code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def check_dataset_metadata(client): old_metadata = list(_dataset_metadata_pre_0_3_4(client)) if not old_metadata: return True click.secho( WARNING + 'There are metadata files in the old location.' '\n (use "renku migrate datasets" to move them)\n\n\t' + '\n\t'.join( clic...
Check location of dataset metadata.
def file_names(self) -> Iterable[str]: if self.is_sharded(): yield from ShardedFile(self.filename_spec).get_filenames() elif self.filename_spec: yield self.filename_spec
Generates all file names that are used to generate file_handles.
def snapshot(self): return dict((n, self._slots[n].get()) for n in self._slots.keys())
Return a dictionary of current slots by reference.
def move_to_pat(pat: str, offset: (float, float)=None, tolerance: int=0) -> None: with tempfile.NamedTemporaryFile() as f: subprocess.call( + f.name, shell=True) loc = visgrep(f.name, pat, tolerance) pat_size = get_png_dim(pat) if offset is None: x, y = [l + ps//2 for l, ps in zip(lo...
See help for click_on_pat
def build_where_stmt(self, ident, filters, q_filters=None, source_class=None): if q_filters is not None: stmts = self._parse_q_filters(ident, q_filters, source_class) if stmts: self._ast['where'].append(stmts) else: stmts = [] for row in fi...
construct a where statement from some filters
def sunionstore(self, destkey, key, *keys): return self.execute(b'SUNIONSTORE', destkey, key, *keys)
Add multiple sets and store the resulting set in a key.
def kml(self): url = self._url + "/kml" return _kml.KML(url=url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port, initialize=True)
returns the kml functions for server
def _writeblocks(cls, blocks, available, cont_size, padding_func): data = bytearray() for block in blocks: if isinstance(block, Padding): continue data += cls._writeblock(block) blockssize = len(data) padding_block = Padding() blockssize +=...
Render metadata block as a byte string.
def _search_vals(self, compiled_pattern, fld_val): matches = [] if isinstance(fld_val, set): for val in fld_val: self._search_val(matches, compiled_pattern, val) elif isinstance(fld_val, str): self._search_val(matches, compiled_pattern, fld_val) re...
Search for user-regex in scalar or iterable data values.
def asJSON(self): value = self._json if value is None: value = json.dumps(self.asDictionary, default=_date_handler) self._json = value return self._json
returns a geometry as JSON
def parse(self, obj): for k, default in obj.__class__.defaults.items(): typ = type(default) if typ is str: continue v = getattr(obj, k) if typ is int: setattr(obj, k, int(v or default)) elif typ is float: ...
Parse the object's properties according to its default types.
def _get_monitoring_heartbeat(self): target = self.uri + '/monitoring/heartbeat' response = self.session.get(target) return response
Tests whether or not the ACS service being monitored is alive.
def closeEvent(self, event): max_dataset_history = self.value('max_dataset_history') keep_recent_datasets(max_dataset_history, self.info) settings.setValue('window/geometry', self.saveGeometry()) settings.setValue('window/state', self.saveState()) event.accept()
save the name of the last open dataset.
def _workaround_no_vector_images(project): RED = (255, 0, 0) PLACEHOLDER = kurt.Image.new((32, 32), RED) for scriptable in [project.stage] + project.sprites: for costume in scriptable.costumes: if costume.image.format == "SVG": yield "%s - %s" % (scriptable.name, costume....
Replace vector images with fake ones.
def _cert_file(name, cert_type): return os.path.join(LE_LIVE, name, '{0}.pem'.format(cert_type))
Return expected path of a Let's Encrypt live cert
def register_templatetags(): from turboengine.conf import settings from google.appengine.ext.webapp import template for python_file in settings.TEMPLATE_PATH: template.register_template_library(python_file)
Register templatetags defined in settings as basic templatetags
def handle_command_line(): phrase = ' '.join(sys.argv[1:]) or 'random' try: giphy = get_random_giphy(phrase) except ValueError: sys.stderr.write('Unable to find any GIFs for {!r}\n'.format(phrase)) sys.exit(1) display(fetch_image(giphy))
Display an image for the phrase in sys.argv, if possible
def use_plenary_log_view(self): self._log_view = PLENARY for session in self._get_provider_sessions(): try: session.use_plenary_log_view() except AttributeError: pass
Pass through to provider LogEntryLogSession.use_plenary_log_view
def _associate_placeable(self, location): if not location: return placeable, _ = unpack_location(location) self.previous_placeable = placeable if not self.placeables or (placeable != self.placeables[-1]): self.placeables.append(placeable)
Saves a reference to a placeable
def build_event_graph(graph, tree, node): if node_key(node) in graph: return type = get_type(node) text = get_text(node) label = '%s (%s)' % (type, text) graph.add_node(node_key(node), type=type, label=label, text=text) args = get_args(node) for arg_role, (arg_id, arg_tag) in args.it...
Return a DiGraph of a specific event structure, built recursively
def chunks(self, num_chunks=100, chunk_size=2, random_state=np.random): chunks = -np.ones_like(self.known_label_idx, dtype=int) uniq, lookup = np.unique(self.known_labels, return_inverse=True) all_inds = [set(np.where(lookup==c)[0]) for c in xrange(len(uniq))] idx = 0 while idx < num_chunks and all_...
the random state object to be passed must be a numpy random seed
def dataReceived(self, data): self.bytes_in += (len(data)) self.buffer_in = self.buffer_in + data while self.CheckDataReceived(): pass
Called from Twisted whenever data is received.
def load_file(self, cursor, target, fname, options): "Parses and loads a single file into the target table." with open(fname) as fin: log.debug("opening {0} in {1} load_file".format(fname, __name__)) encoding = options.get('encoding', 'utf-8') if target in self.proces...
Parses and loads a single file into the target table.
def loginfo(method): def loginfo_method(self, rinput): klass = rinput.__class__ for key in klass.stored(): val = getattr(rinput, key) if isinstance(val, DataFrame): self.logger.debug("DataFrame %s", info.gather_info_dframe(val)) elif isinstance(val...
Log the contents of Recipe Input
def cgi_method_is_post(environ: Dict[str, str]) -> bool: method = environ.get("REQUEST_METHOD", None) if not method: return False return method.upper() == "POST"
Determines if the CGI method was ``POST``, given the CGI environment.
def retrieve(self, request, *args, **kwargs): when_param = get_query_params(self.request).get("preview", None) pk = self.kwargs["pk"] when = None if when_param: try: when = parse_date(when_param) except ValueError: when = None ...
Retrieve pzone as a preview or applied if no preview is provided.
def _reduce_sizes(self, bbox_list): return [BBox(self._intersection_area(bbox).bounds, self.crs).transform(bbox.crs) for bbox in bbox_list]
Reduces sizes of bounding boxes
def finalize_options(self): install.finalize_options(self) if self.prefix is None: man_dir = None else: man_dir = os.path.join(self.prefix, "share", "man", "man1") if self.root is not None: man_dir = os.path.join(self.root, man_dir[1:]) ...
Alter the installation path.
def conditions_met(self, instance, state): transition = self.get_transition(state) if transition is None: return False elif transition.conditions is None: return True else: return all(map(lambda condition: condition(instance), transition.conditions))
Check if all conditions have been met
def main(): if len(sys.argv) != 2: raise RuntimeError('Usage: python3 async_send.py <json config>') sip_logging.init_logger(show_thread=False) spead_config = json.loads(sys.argv[1]) try: _path = os.path.dirname(os.path.abspath(__file__)) schema_path = os.path.join(_path, 'config_...
Main function for SPEAD sender module.
def close(self): if not self._closed: with self._lock: if not self._closed: self._closed = True self._worker.stop() self._writer.flush() self._writer.close()
Closes the underlying writer, flushing any pending writes first.
def start(self, *msg): self.start_time = datetime.datetime.now() label = colors.purple("START") self._msg(label, *msg)
Prints an start message
def delete_row(self, key, value): self.rows = filter(lambda x: x.get(key) != value, self.rows)
Deletes the rows where key = value.
def patch_clean_fields(model): old_clean_fields = model.clean_fields def new_clean_fields(self, exclude=None): if hasattr(self, '_mt_form_pending_clear'): for field_name, value in self._mt_form_pending_clear.items(): field = self._meta.get_field(field_name) or...
Patch clean_fields method to handle different form types submission.
def postOptions(self): if self.portIdentifiers: store = self.parent.parent.getStore() store.transact(self._delete, store, self.portIdentifiers) print "Deleted." raise SystemExit(0) else: self.opt_help()
Delete the ports specified with the port-identifier option.
def get(self, stream, fmt='txt', **kwargs): sel = ''.join(["&{0}={1}".format(k, v) for (k, v) in kwargs.items()]) url = "streamds/{0}.{1}?{2}".format(stream, fmt, sel[1:]) data = self._db._get_content(url) if not data: log.error("No data found at URL '%s'." % url) ...
Get the data for a given stream manually
def extractContent(self, text): m = self.nextValidComment(text) return '' if m is None else m.group(1)
Extract the content of comment text.
def run_once(func): def wrapper(*args, **kwargs): if not wrapper.has_run: wrapper.has_run = True return func(*args, **kwargs) wrapper.has_run = False return wrapper
Decorator for making sure a method can only be executed once
def hash_dir(path): dir_hash = {} for root, dirs, files in os.walk(path, topdown=False): f_hash = ((f, hash_file(join(root, f))) for f in files) d_hash = ((d, dir_hash[join(root, d)]) for d in dirs) dir_hash[join(*split(root))] = _mktree(f_hash, d_hash) return dir_hash[path]
Write directory at path to Git index, return its SHA1 as a string.
def debug_query_result(rows: Sequence[Any]) -> None: log.info("Retrieved {} rows", len(rows)) for i in range(len(rows)): log.info("Row {}: {}", i, rows[i])
Writes a query result to the log.
def _counts(self): rolling_dim = utils.get_temp_dimname(self.obj.dims, '_rolling_dim') counts = (self.obj.notnull() .rolling(center=self.center, **{self.dim: self.window}) .construct(rolling_dim, fill_value=False) .sum(dim=rolling_dim, skipna=False))...
Number of non-nan entries in each rolling window.
def hook(module): if "INSTANA_DEV" in os.environ: print("==============================================================") print("Instana: Running flask hook") print("==============================================================") wrapt.wrap_function_wrapper('flask', 'Flask.__init__', wr...
Hook method to install the Instana middleware into Flask
def _element_str(self): if isinstance(self.element, CIMProperty): return _format("property {0!A} in class {1!A} (in {2!A})", self.propname, self.classname, self.namespace) elif isinstance(self.element, CIMMethod): return _format("method {0!A} in class {...
Return a string that identifies the value-mapped element.
def read_buffer(io, print_output=False, print_func=None): def _print(line): if print_output: if print_func: formatted_line = print_func(line) else: formatted_line = line encoded_line = unicode(formatted_line).encode('utf-8') pri...
Reads a file-like buffer object into lines and optionally prints the output.
def needed(name, required): return [ relative_field(r, name) if r and startswith_field(r, name) else None for r in required ]
RETURN SUBSET IF name IN REQUIRED
def intersection(a, b, scale=1): try: a1, a2 = a except TypeError: a1 = a.start a2 = a.stop try: b1, b2 = b except TypeError: b1 = b.start b2 = b.stop if a2 <= b1: return None if a1 >= b2: return None if a2 <= b2: if a1 ...
Intersection between two segments.
def split_source(source_code): eol_chars = get_eol_chars(source_code) if eol_chars: return source_code.split(eol_chars) else: return [source_code]
Split source code into lines
def __fetch_heatmap_data_from_profile(self): with open(self.pyfile.path, "r") as file_to_read: for line in file_to_read: self.pyfile.lines.append(" " + line.strip("\n")) self.pyfile.length = len(self.pyfile.lines) line_profiles = self.__get_line_profile_data() ...
Method to create heatmap data from profile information.
def fixpix2(data, mask, iterations=3, out=None): out = out if out is not None else data.copy() binry = mask != 0 lblarr, labl = ndimage.label(binry) stct = ndimage.generate_binary_structure(2, 2) back = lblarr == 0 for idx in range(1, labl + 1): segm = lblarr == idx dilmask = num...
Substitute pixels in mask by a bilinear least square fitting.
def gauge(self, *args, **kwargs): orig_gauge = super(Nagios, self).gauge if 'timestamp' in kwargs and 'timestamp' not in getargspec(orig_gauge).args: del kwargs['timestamp'] orig_gauge(*args, **kwargs)
Compatability wrapper for Agents that do not submit gauge metrics with custom timestamps
def _get_token_encoder(vocab_dir, vocab_name, filename): vocab_path = os.path.join(vocab_dir, vocab_name) if not tf.gfile.Exists(vocab_path): _build_vocab(filename, vocab_path, 10000) return text_encoder.TokenTextEncoder(vocab_path)
Reads from file and returns a `TokenTextEncoder` for the vocabulary.
def _parse(self, date_str, format='%Y-%m-%d'): rv = pd.to_datetime(date_str, format=format) if hasattr(rv, 'to_pydatetime'): rv = rv.to_pydatetime() return rv
helper function for parsing FRED date string into datetime
def find_archive_program (format, command, program=None): commands = ArchivePrograms[format] programs = [] if program is not None: programs.append(program) for key in (None, command): if key in commands: programs.extend(commands[key]) if not programs: raise util.P...
Find suitable archive program for given format and mode.
def validate(self): if not isinstance(self.fold_scope_location, FoldScopeLocation): raise TypeError(u'Expected FoldScopeLocation fold_scope_location, got: {} {}'.format( type(self.fold_scope_location), self.fold_scope_location)) if self.fold_scope_location.field != COUNT_META...
Validate that the FoldCountContextField is correctly representable.
def loadJson(self, data): if not isinstance(data, dict): data = json.loads(data) self.__dict__.update(data) self.inflate() return self
convert the json data into updating this obj's attrs
def check_credentials(client): pid, uid, gid = get_peercred(client) euid = os.geteuid() client_name = "PID:%s UID:%s GID:%s" % (pid, uid, gid) if uid not in (0, euid): raise SuspiciousClient("Can't accept client with %s. It doesn't match the current EUID:%s or ROOT." % ( client_name,...
Checks credentials for given socket.
def _check_users(users): messg = '' valid = True for user, user_details in six.iteritems(users): if not user_details: valid = False messg += 'Please provide details for username {user}.\n'.format(user=user) continue if not (isinstance(user_details.get('lev...
Checks if the input dictionary of users is valid.
def build_trainer(nn, ds, verbosity=1): return pb.supervised.trainers.rprop.RPropMinusTrainer(nn, dataset=ds, batchlearning=True, verbose=bool(verbosity))
Configure neural net trainer from a pybrain dataset
def login(self): if self.args.snmp_force: self.client_mode = 'snmp' else: if not self._login_glances(): return False if self.client_mode == 'snmp': if not self._login_snmp(): return False logger.debug("Load limits from t...
Logon to the server.
def find_object(self, key, layers): state = self.state if layers is None or layers == '': layers = state.layers.keys() for layer in layers: if key in state.layers[layer]: return state.layers[layer][key] return None
find an object to be modified
def clean(self): self.feed() if self.current_parent_element['tag'] != '': self.cleaned_html += '</{}>'.format(self.current_parent_element['tag']) self.cleaned_html = re.sub(r'(</[u|o]l>)<p></p>', r'\g<1>', self.cleaned_html) self._remove_pre_formatting() return self.c...
Goes through the txt input and cleans up any problematic HTML.
def dump(self): subtoken_strings = [(i, s) for s, i in six.iteritems(self._subtoken_string_to_id)] print(u", ".join(u"{0} : '{1}'".format(i, s) for i, s in sorted(subtoken_strings)))
Debugging dump of the current subtoken vocabulary.
def _environment_sanity_check(environment): assert issubclass(environment.undefined, Undefined), 'undefined must ' \ 'be a subclass of undefined because filters depend on it.' assert environment.block_start_string != \ environment.variable_start_string != \ environment.comment_start_stri...
Perform a sanity check on the environment.
def _loadcache(cachefile): cache = {} if os.path.exists(cachefile): with open(cachefile) as f: for line in f: line = line.split() if len(line) == 2: try: cache[int(line[0])] = float(line[1]) excep...
Returns a dictionary resulting from reading a likelihood cachefile
def check_program_compression(archive, command, program, compression): program = os.path.basename(program) if compression: if not program_supports_compression(program, compression): if command == 'create': comp_command = command else: comp_command ...
Check if a program supports the given compression.
def stream_data(self, host=HOST, port=GPSD_PORT, enable=True, gpsd_protocol=PROTOCOL, devicepath=None): self.socket.connect(host, port) self.socket.watch(enable, gpsd_protocol, devicepath)
Connect and command, point and shoot, flail and bail
def find_in_path(name, path): "Find a file in a search path" for dir in path.split(os.pathsep): binpath = os.path.join(dir, name) if os.path.exists(binpath): return os.path.abspath(binpath) return None
Find a file in a search path
def convert_unicode(text): if isPython2: h = HTMLParser() s = h.unescape(text) else: try: s = unescape(text) except Exception: s = HTMLParser().unescape(text) return s
converts unicode HTML to real Unicode
def _is_physical_entity(pe): val = isinstance(pe, _bp('PhysicalEntity')) or \ isinstance(pe, _bpimpl('PhysicalEntity')) return val
Return True if the element is a physical entity
def rotate_in_plane(chi, phase): v = chi.T sp = np.sin(phase) cp = np.cos(phase) res = 1.*v res[0] = v[0]*cp + v[1]*sp res[1] = v[1]*cp - v[0]*sp return res.T
For transforming spins between the coprecessing and coorbital frames
def _process_cell(i, state, finite=False): op_1 = state[i - 1] op_2 = state[i] if i == len(state) - 1: if finite: op_3 = state[0] else: op_3 = 0 else: op_3 = state[i + 1] result = 0 for i, val in enumerate([op_3, op_2, op_1]): if val: ...
Process 3 cells and return a value from 0 to 7.
def transform_streams_for_comparison(outputs): new_outputs = [] for output in outputs: if (output.output_type == 'stream'): new_outputs.append({ 'output_type': 'stream', output.name: output.text, }) else: new_outputs.append(outp...
Makes failure output for streams better by having key be the stream name
def sinterstore(self, destkey, key, *keys): return self.execute(b'SINTERSTORE', destkey, key, *keys)
Intersect multiple sets and store the resulting set in a key.
def parse_arglist(args): args = 'f({})'.format(args) tree = ast.parse(args) funccall = tree.body[0].value args = [ast.literal_eval(arg) for arg in funccall.args] kwargs = {arg.arg: ast.literal_eval(arg.value) for arg in funccall.keywords} if len(args) > 2: raise TypeError( ...
Parses an arglist into arguments for Image, as a kwargs dict
def to_string(self, value): self._warn_deprecated_outside_JSONField() value = json.dumps( self.to_json(value), indent=2, sort_keys=True, separators=(',', ': '), ) return value
Return a JSON serialized string representation of the value.
def query_all(self): return self.query_model(self.model, self.condition, order_by=self.order_by, group_by=self.group_by, having=self.having)
Query all records without limit and offset.
def sub(pattern, repl, string, *args, **kwargs): flags = args[4] if len(args) > 4 else kwargs.get('flags', 0) is_replace = _is_replace(repl) is_string = isinstance(repl, (str, bytes)) if is_replace and repl.use_format: raise ValueError("Compiled replace cannot be a format object!") pattern =...
Apply `sub` after applying backrefs.
def standardize(): def f(G, bim): G_out = standardize_snps(G) return G_out, bim return f
return variant standarize function
def computeRange(corners): x = corners[:, 0] y = corners[:, 1] _xrange = (np.minimum.reduce(x), np.maximum.reduce(x)) _yrange = (np.minimum.reduce(y), np.maximum.reduce(y)) return _xrange, _yrange
Determine the range spanned by an array of pixel positions.
def image_get(request, image_id): image = glanceclient(request).images.get(image_id) return Image(image)
Returns an Image object populated with metadata for a given image.
def _process_score(self, model_name, dependency_cache=None): version = self[model_name].version start = time.time() feature_values = self._solve_features(model_name, dependency_cache) logger.debug("Extracted features for {0}:{1}:{2} in {3} secs" .format(self.name, mo...
Generates a score for a given model using the `dependency_cache`.
def from_json_file(cls, json_file): with open(json_file, "r", encoding="utf-8") as reader: text = reader.read() return cls.from_dict(json.loads(text))
Constructs a `GPT2Config` from a json file of parameters.
def addSquigglyAnnot(self, rect): CheckParent(self) val = _fitz.Page_addSquigglyAnnot(self, rect) if not val: return val.thisown = True val.parent = weakref.proxy(self) self._annot_refs[id(val)] = val return val
Wavy underline content in a rectangle or quadrilateral.
def img2img_transformer2d_base(): hparams = image_transformer2d_base() hparams.layer_preprocess_sequence = "n" hparams.layer_postprocess_sequence = "da" hparams.learning_rate = 0.2 hparams.layer_prepostprocess_dropout = 0.1 hparams.learning_rate_warmup_steps = 12000 hparams.filter_size = 2048 hparams.nu...
Base params for img2img 2d attention.
def interp(net, layers): for l in layers: m, k, h, w = net.params[l][0].data.shape if m != k and k != 1: print 'input + output channels need to be the same or |output| == 1' raise if h != w: print 'filters need to be square' raise filt ...
Set weights of each layer in layers to bilinear kernels for interpolation.
def create(self, ignore=None): ignore = ignore or [] def _create(tree_or_filename, alias=None): for name, value in tree_or_filename.items(): if isinstance(value, dict): for result in _create(value, alias=name): yield result ...
Yield tuple with created index name and responses from a client.
def patch(callback=None, path=None, method=Method.PATCH, resource=None, tags=None, summary="Patch specified resource.", middleware=None): def inner(c): op = ResourceOperation(c, path or PathParam('{key_field}'), method, resource, tags, summary, middleware, full_clean...
Decorator to configure an operation that patches a resource.
def data(self): means = [] table = self._slice.as_array() products = self._inner_prods(table, self.values) for axis, product in enumerate(products): if product is None: means.append(product) continue valid_indices = self._valid_indi...
list of mean numeric values of categorical responses.
def compute_edge_reduction(self) -> float: nb_init_edge = self.init_edge_number() nb_poweredge = self.edge_number() return (nb_init_edge - nb_poweredge) / (nb_init_edge)
Compute the edge reduction. Costly computation
def disable_notebook(): try: from IPython.core.getipython import get_ipython except ImportError: raise ImportError('This feature requires IPython 1.0+') ip = get_ipython() f = ip.display_formatter.formatters['text/html'] f.type_printers.pop(np.ndarray, None)
Disable automatic visualization of NumPy arrays in the IPython Notebook.
def gen_lazy_function(self): if self._value is None: if self._random is not None: self.value = self._random(**self._parents.value) else: raise ValueError( 'Stochastic ' + self.__name__ + "'s value...
Will be called by Node at instantiation.
def time_signature_event(self, meter=(4, 4)): numer = a2b_hex('%02x' % meter[0]) denom = a2b_hex('%02x' % int(log(meter[1], 2))) return self.delta_time + META_EVENT + TIME_SIGNATURE + '\x04' + numer\ + denom + '\x18\x08'
Return a time signature event for meter.
def initialize(self, io_loop): self._loop = io_loop for app_context in self._applications.values(): app_context._loop = self._loop self._clients = set() self._stats_job = PeriodicCallback(self._log_stats, self._stats_log_frequency_mi...
Start a Bokeh Server Tornado Application on a given Tornado IOLoop.
def parse_eggs_list(path): with open(path, 'r') as script: data = script.readlines() start = 0 end = 0 for counter, line in enumerate(data): if not start: if 'sys.path[0:0]' in line: start = counter + 1 if counter >= start a...
Parse eggs list from the script at the given path
def modified_lines(self, r, file_name): cmd = self.file_diff_cmd(r, file_name) diff = shell_out_ignore_exitcode(cmd, cwd=self.root) return list(self.modified_lines_from_diff(diff))
Returns the line numbers of a file which have been changed.
def strip_command(self, command_string, output): output_list = output.split(command_string) return self.RESPONSE_RETURN.join(output_list)
Strip command_string from output string.
def valid_level(value): value = value.upper() if getattr(logging, value, None) is None: raise argparse.ArgumentTypeError("%s is not a valid level" % value) return value
Validation function for parser, logging level argument.
def _ordered(self, odict): ndict = OrderedDict() if isinstance(odict, CatDict) or isinstance(odict, Entry): key = odict.sort_func else: key = None nkeys = list(sorted(odict.keys(), key=key)) for key in nkeys: if isinstance(odict[key], OrderedDi...
Convert the object into a plain OrderedDict.
def quit(self): self.receive_thread.stopped = True self.message_thread.stopped = True self.receive_thread.join() _LOGGER.info('receive_thread exited') self.message_thread.join() _LOGGER.info('message_thread exited') self.socket.close()
Close threads and socket.
def delete(self, name): obj = self._get_object(name) if obj: return self.driver.delete_object(obj)
Delete object on remote