code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def pointSampler(actor, distance=None): poly = actor.polydata(True) pointSampler = vtk.vtkPolyDataPointSampler() if not distance: distance = actor.diagonalSize() / 100.0 pointSampler.SetDistance(distance) pointSampler.SetInputData(poly) pointSampler.Update() uactor = Actor(pointSampl...
Algorithm to generate points the specified distance apart.
def response_hook(self, r, **kwargs): if r.status_code == 401: www_authenticate = r.headers.get('www-authenticate', '').lower() auth_type = _auth_type_from_header(www_authenticate) if auth_type is not None: return self.retry_using_http_NTLM_auth( ...
The actual hook handler.
def com_google_fonts_check_name_version_format(ttFont): from fontbakery.utils import get_name_entry_strings import re def is_valid_version_format(value): return re.match(r'Version\s0*[1-9]+\.\d+', value) failed = False version_entries = get_name_entry_strings(ttFont, NameID.VERSION_STRING) if len(versio...
Version format is correct in 'name' table?
def req_cycle(req): cls = req.__class__ seen = {req.name} while isinstance(req.comes_from, cls): req = req.comes_from if req.name in seen: return True else: seen.add(req.name) return False
is this requirement cyclic?
def roughsize(size, above=20, mod=10): if size < above: return str(size) return "{:d}+".format(size - size % mod)
6 -> '6' 15 -> '15' 134 -> '130+'.
def _is_free_link_end(self, this, next): after, ctx = self._read(2), self._context equal_sign_contexts = contexts.TEMPLATE_PARAM_KEY | contexts.HEADING return (this in (self.END, "\n", "[", "]", "<", ">") or this == next == "'" or (this == "|" and ctx & contexts.T...
Return whether the current head is the end of a free link.
def first(self): if self.total and self.limit < self.total: return {'page[offset]': 0, 'page[limit]': self.limit} else: return None
Generate query parameters for the first page
def _flush(self): t1, t2 = str(time.time()).split(".") state_path = os.path.join(self.ep_directory, "state_{}_{}.npz".format(t1, t2)) if hasattr(self.env, "unwrapped"): env_name = self.env.unwrapped.__class__.__name__ else: env_name = self.env.__class__.__name__ ...
Method to flush internal state to disk.
def format_close(code: int, reason: str) -> str: if 3000 <= code < 4000: explanation = "registered" elif 4000 <= code < 5000: explanation = "private use" else: explanation = CLOSE_CODES.get(code, "unknown") result = f"code = {code} ({explanation}), " if reason: result...
Display a human-readable version of the close code and reason.
def languages(self, key, value): languages = self.get('languages', []) values = force_list(value.get('a')) for value in values: for language in RE_LANGUAGE.split(value): try: name = language.strip().capitalize() languages.append(pycountry.languages.get(nam...
Populate the ``languages`` key.
def legend_title_header_element(feature, parent): _ = feature, parent header = legend_title_header['string_format'] return header.capitalize()
Retrieve legend title header string from definitions.
def _createConnectivity(self, linkList, connectList): for idx, link in enumerate(linkList): connectivity = connectList[idx] for upLink in connectivity['upLinks']: upstreamLink = UpstreamLink(upstreamLinkID=int(upLink)) upstreamLink.streamLink = link ...
Create GSSHAPY Connect Object Method
def distance(vec1, vec2): if isinstance(vec1, Vector2) \ and isinstance(vec2, Vector2): dist_vec = vec2 - vec1 return dist_vec.length() else: raise TypeError("vec1 and vec2 must be Vector2's")
Calculate the distance between two Vectors
def sendResult(self, future): future.greenlet = None assert future._ended(), "The results are not valid" self.socket.sendResult(future)
Send back results to broker for distribution to parent task.
def mav_param(self): compid = self.settings.target_component if compid == 0: compid = 1 sysid = (self.settings.target_system, compid) if not sysid in self.mav_param_by_sysid: self.mav_param_by_sysid[sysid] = mavparm.MAVParmDict() return self.mav_param_by_s...
map mav_param onto the current target system parameters
def _designspace_locations(self, designspace): maps = [] for elements in (designspace.sources, designspace.instances): location_map = {} for element in elements: path = _normpath(element.path) location_map[path] = element.location maps....
Map font filenames to their locations in a designspace.
def instance_contains(container, item): return item in (member for _, member in inspect.getmembers(container))
Search into instance attributes, properties and return values of no-args methods.
def rpm_info(rpm_path): ts = rpm.TransactionSet() ts.setVSFlags(rpm._RPMVSF_NOSIGNATURES) rpm_info = {} rpm_fd = open(rpm_path, 'rb') pkg = ts.hdrFromFdno(rpm_fd) rpm_info['name'] = pkg['name'] rpm_info['version'] = pkg['version'] rpm_info['release'] = pkg['release'] rpm_info['epoch'...
Query information about the RPM at `rpm_path`.
def discover(self, details = False): 'Discover API definitions. Set details=true to show details' if details and not (isinstance(details, str) and details.lower() == 'false'): return copy.deepcopy(self.discoverinfo) else: return dict((k,v.get('description', '')) for k,v i...
Discover API definitions. Set details=true to show details
def EncodeMessageList(cls, message_list, packed_message_list): uncompressed_data = message_list.SerializeToString() packed_message_list.message_list = uncompressed_data compressed_data = zlib.compress(uncompressed_data) if len(compressed_data) < len(uncompressed_data): packed_message_list.compress...
Encode the MessageList into the packed_message_list rdfvalue.
def insert_file(self, f, namespace, timestamp): doc = f.get_metadata() doc["content"] = f.read() self.doc_dict[f._id] = Entry(doc=doc, ns=namespace, ts=timestamp)
Inserts a file to the doc dict.
def complete(self): if self.scan_limit is not None and self.scan_limit == 0: return True if self.item_limit is not None and self.item_limit == 0: return True return False
Return True if the limit has been reached
def upload_rabbitmq_conf(template_name=None, context=None, restart=True): template_name = template_name or u'rabbitmq/rabbitmq.config' destination = u'/etc/rabbitmq/rabbitmq.config' upload_template(template_name, destination, context=context, use_sudo=True) if restart: restart_service(u'rabbitmq...
Upload RabbitMQ configuration from a template.
def serve(self, host='', port=8000, no_documentation=False, display_intro=True): if no_documentation: api = self.server(None) else: api = self.server() if display_intro: print(INTRO) httpd = make_server(host, port, api) print("Serving on {0}:{1...
Runs the basic hug development server against this API
def make_country_nationality_list(cts, ct_file): countries = pd.read_csv(ct_file) nationality = dict(zip(countries.nationality,countries.alpha_3_code)) both_codes = {**nationality, **cts} return both_codes
Combine list of countries and list of nationalities
def _get_timezone(self, tz): if tz == "Local": try: return tzlocal.get_localzone() except pytz.UnknownTimeZoneError: return "?" if len(tz) == 2: try: zones = pytz.country_timezones(tz) except KeyError: ...
Find and return the time zone if possible
def hourly_relative_humidity(self): dpt_data = self._humidity_condition.hourly_dew_point_values( self._dry_bulb_condition) rh_data = [rel_humid_from_db_dpt(x, y) for x, y in zip( self._dry_bulb_condition.hourly_values, dpt_data)] return self._get_daily_data_collections( ...
A data collection containing hourly relative humidity over they day.
def _get_mainchain(df, invert): if invert: mc = df[(df['atom_name'] != 'C') & (df['atom_name'] != 'O') & (df['atom_name'] != 'N') & (df['atom_name'] != 'CA')] else: mc = df[(df['atom_name'] == 'C') | ...
Return only main chain atom entries from a DataFrame
def check_password(password: str, encrypted: str) -> bool: if encrypted.startswith("{crypt}"): encrypted = "{CRYPT}" + encrypted[7:] return pwd_context.verify(password, encrypted)
Check a plaintext password against a hashed password.
def _validate_platforms_in_image(self, image): expected_platforms = get_platforms(self.workflow) if not expected_platforms: self.log.info('Skipping validation of available platforms ' 'because expected platforms are unknown') return if len(expect...
Ensure that the image provides all platforms expected for the build.
def write_yara(self, output_file): fout = open(output_file, 'wb') fout.write('\n') for iocid in self.yara_signatures: signature = self.yara_signatures[iocid] fout.write(signature) fout.write('\n') fout.close() return True
Write out yara signatures to a file.
def from_str(string): match = re.match(r'^ADD (\w+)$', string) if match: return AddEvent(match.group(1)) else: raise EventParseError
Generate a `AddEvent` object from a string
def __clean_rouge_args(self, rouge_args): if not rouge_args: return quot_mark_pattern = re.compile('"(.+)"') match = quot_mark_pattern.match(rouge_args) if match: cleaned_args = match.group(1) return cleaned_args else: return rouge_...
Remove enclosing quotation marks, if any.
def localDirPath(self): rootDirPath = os.environ[self.rootDirPathEnvName] return os.path.join(rootDirPath, self.contentHash)
The path to the directory containing the resource on the worker.
def rq_job(self): if not self.rq_id or not self.rq_origin: return try: return RQJob.fetch(self.rq_id, connection=get_connection(self.rq_origin)) except NoSuchJobError: return
The last RQ Job this ran on
def _sync(timeout=None): evt = WeakEvent(auto_reset=False) Callback(evt.Signal) evt.Wait(timeout=timeout) evt.Reset() wait4 = set(_handlers) _handlers.clear() _handlers.add(evt) try: WaitForAll(wait4, timeout=timeout) except Exception as e: evt.SignalException(e) ...
I will wait until all pending handlers cothreads have completed
def tqdm(self): with utils.async_tqdm( total=0, desc='Extraction completed...', unit=' file') as pbar_path: self._pbar_path = pbar_path yield
Add a progression bar for the current extraction.
def createDashboardOverlay(self, pchOverlayKey, pchOverlayFriendlyName): fn = self.function_table.createDashboardOverlay pMainHandle = VROverlayHandle_t() pThumbnailHandle = VROverlayHandle_t() result = fn(pchOverlayKey, pchOverlayFriendlyName, byref(pMainHandle), byref(pThumbnailHandle)...
Creates a dashboard overlay and returns its handle
def connect(self, **settings): if not settings: settings = self.connection_settings connection_key = ':'.join([str(settings[k]) for k in sorted(settings)]) if connection_key not in self._connections: self._connections[connection_key] = redis.StrictRedis( ...
Connect to redis and cache the new connection
def getPhotos(self, tags='', per_page='', page=''): method = 'flickr.groups.pools.getPhotos' data = _doget(method, group_id=self.id, tags=tags,\ per_page=per_page, page=page) photos = [] for photo in data.rsp.photos.photo: photos.append(_parse_photo(phot...
Get a list of photo objects for this group
def push(self, instance, action, success, idxs=_marker): uid = api.get_uid(instance) info = self.objects.get(uid, {}) idx = [] if idxs is _marker else idxs info[action] = {'success': success, 'idxs': idx} self.objects[uid] = info
Adds an instance into the pool, to be reindexed on resume
def _backup_pb_gui(self, dirs): import PySimpleGUI as sg with ZipFile(self.zip_filename, 'w') as backup_zip: for count, path in enumerate(dirs): backup_zip.write(path, path[len(self.source):len(path)]) if not sg.OneLineProgressMeter('Writing Zip Files', count ...
Create a zip backup with a GUI progress bar.
def enable_scanners_by_group(self, group): if group == 'all': self.logger.debug('Enabling all scanners') return self.zap.ascan.enable_all_scanners() try: scanner_list = self.scanner_group_map[group] except KeyError: raise ZAPError( ...
Enables the scanners in the group if it matches one in the scanner_group_map.
def fixpath(path): return os.path.normpath(os.path.realpath(os.path.expanduser(path)))
Uniformly format a path.
def make(self, apps): for subreport in self.subreports: logger.debug('Make subreport "{0}"'.format(subreport.name)) subreport.make(apps) for subreport in self.subreports: subreport.compact_tables()
Create the report from application results
def image_to_texture(image): vtex = vtk.vtkTexture() vtex.SetInputDataObject(image) vtex.Update() return vtex
Converts ``vtkImageData`` to a ``vtkTexture``
def certs(self): certstack = libcrypto.CMS_get1_certs(self.ptr) if certstack is None: raise CMSError("getting certs") return StackOfX509(ptr=certstack, disposable=True)
List of the certificates contained in the structure
def use_comparative_assessment_view(self): self._object_views['assessment'] = COMPARATIVE for session in self._get_provider_sessions(): try: session.use_comparative_assessment_view() except AttributeError: pass
Pass through to provider AssessmentLookupSession.use_comparative_assessment_view
def render_template(template_name, **context): tmpl = jinja_env.get_template(template_name) context["url_for"] = url_for return Response(tmpl.render(context), mimetype="text/html")
Render a template into a response.
def edit_history(self): ret = self._db.session\ .query(Config)\ .filter(Config.type == 'buildstate')\ .filter(Config.group == 'access')\ .filter(Config.key == 'last')\ .order_by(Config.modified.desc())\ .all() return ret
Return config record information about the most recent bundle accesses and operations
def clear_last_lines(self, n): self.term.stream.write( self.term.move_up * n + self.term.clear_eos) self.term.stream.flush()
Clear last N lines of terminal output.
def as_sql(self, compiler, connection): sql, params = super().as_sql(compiler, connection) params.append(self.path) return sql, params
Compile SQL for this function.
def write_file_to_manifest(file_name, width, manifest_fh): manifest_fh.write("%s,%s\n" % (file_name, str(width))) logging.debug("Wrote file %s to manifest", file_name)
Write the given file in manifest.
def validate_authentication(self, username, password, handler): user = authenticate( **{self.username_field: username, 'password': password} ) account = self.get_account(username) if not (user and account): raise AuthenticationFailed("Authentication failed.")
authenticate user with password
def receive_promise(self, msg): self.observe_proposal(msg.proposal_id) if not self.leader and msg.proposal_id == self.proposal_id and msg.from_uid not in self.promises_received: self.promises_received.add(msg.from_uid) if self.highest_accepted_id is None or msg.last_accepted_id >...
Returns an Accept messages if a quorum of Promise messages is achieved
def _openapi_json(self): from pprint import pprint pprint(self.to_dict()) return current_app.response_class(json.dumps(self.to_dict(), indent=4), mimetype='application/json')
Serve JSON spec file
def featurize(*features): from functools import cmp_to_key def compare_subclass(left, right): if issubclass(left, right): return -1 elif issubclass(right, left): return 1 return 0 sorted_features = sorted(features, key=cmp_to_key(compare_subclass)) name = ...
Put features into proper MRO order.
def split_interface(intf_name): head = intf_name.rstrip(r"/\0123456789. ") tail = intf_name[len(head) :].lstrip() return (head, tail)
Split an interface name based on first digit, slash, or space match.
def update_control_board_calibration(control_board, fitted_params): control_board.a0_series_resistance = fitted_params['fitted R'].values control_board.a0_series_capacitance = fitted_params['fitted C'].values
Update the control board with the specified fitted parameters.
def _update_header_size(self): column_count = self.table_header.model().columnCount() for index in range(0, column_count): if index < column_count: column_width = self.dataTable.columnWidth(index) self.table_header.setColumnWidth(index, column_width) ...
Update the column width of the header.
def read_flash(self, addr=0xFF, page=0x00): buff = bytearray() page_size = self.targets[addr].page_size for i in range(0, int(math.ceil(page_size / 25.0))): pk = None retry_counter = 5 while ((not pk or pk.header != 0xFF or struct.unpack('<...
Read back a flash page from the Crazyflie and return it
def _force_force_on_start(self): if self.force_on_start in self.available_combinations: self.displayed = self.force_on_start self._choose_what_to_display(force_refresh=True) self._apply(force=True) self.py3.update() self.force_on_start = None
Force the user configured mode on start.
def print(self): print("TOTALS -------------------------------------------") print(json.dumps(self.counts, indent=4, sort_keys=True)) if self.sub_total: print("\nSUB TOTALS --- based on '%s' ---------" % self.sub_total) print(json.dumps(self.sub_counts, indent=4, sort_key...
prints to terminal the summray statistics
def exists_course_list(curriculum_abbr, course_number, section_id, quarter, year, joint=False): return exists(get_course_list_name(curriculum_abbr, course_number, section_id, quarter, year, joint))
Return True if the corresponding mailman list exists for the course
def parametric_mean_function(max_iters=100, optimize=True, plot=True): mf = GPy.core.Mapping(1,1) mf.f = np.sin X = np.linspace(0,10,50).reshape(-1,1) Y = np.sin(X) + 0.5*np.cos(3*X) + 0.1*np.random.randn(*X.shape) + 3*X mf = GPy.mappings.Linear(1,1) k =GPy.kern.RBF(1) lik = GPy.likelihoods....
A linear mean function with parameters that we'll learn alongside the kernel
def client_status(self, config_path): c = self.client_for(config_path) status = "stopped" if not c or not c.ensime: status = 'unloaded' elif c.ensime.is_ready(): status = 'ready' elif c.ensime.is_running(): status = 'startup' elif c.ens...
Get status of client for a project, given path to its config.
def update(self, vts): for vt in vts.versioned_targets: vt.ensure_legal() if not vt.valid: self._invalidator.update(vt.cache_key) vt.valid = True self._artifact_write_callback(vt) if not vts.valid: vts.ensure_legal() self._invalidator.update(vts.cache_key) v...
Mark a changed or invalidated VersionedTargetSet as successfully processed.
def handler(self): if hasNTLM: if self._handler is None: passman = request.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, self._parsed_org_url, self._login_username, self._password) self._handler = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(...
gets the security handler for the class
def google(self): tms_x, tms_y = self.tms return tms_x, (2 ** self.zoom - 1) - tms_y
Gets the tile in the Google format, converted from TMS
def load_conf(cfg_path): global config try: cfg = open(cfg_path, 'r') except Exception as ex: if verbose: print("Unable to open {0}".format(cfg_path)) print(str(ex)) return False cfg_json = cfg.read() cfg.close() try: config = json.loads(cf...
Try to load the given conf file.
def _setup_message(self): if self.content == 'html': self._message = MIMEMultipart('alternative') part = MIMEText(self.body, 'html', 'UTF-8') else: self._message = MIMEMultipart() part = MIMEText(self.body, 'plain', 'UTF-8') self._message.preamble ...
Constructs the actual underlying message with provided values
def _remove_add_key(self, key): if not hasattr(self, '_queue'): return if key in self._queue: self._queue.remove(key) self._queue.append(key) if self.maxsize == 0: return while len(self._queue) > self.maxsize: del self[self._queue[0...
Move a key to the end of the linked list and discard old entries.
def related_lua_args(self): related = self.queryelem.select_related if related: meta = self.meta for rel in related: field = meta.dfields[rel] relmodel = field.relmodel bk = self.backend.basekey(relmodel._meta) if relmodel el...
Generator of load_related arguments
def apply_attributes(self, nc, table, prefix=''): for name, value in sorted(table.items()): if name in nc.ncattrs(): LOG.debug('already have a value for %s' % name) continue if value is not None: setattr(nc, name, value) else: ...
apply fixed attributes, or look up attributes needed and apply them
def code(self, text, lang=None): with self.paragraph(stylename='code'): lines = text.splitlines() for line in lines[:-1]: self._code_line(line) self.linebreak() self._code_line(lines[-1])
Add a code block.
def dispatch_hook(cls, _pkt=None, *args, **kargs): if _pkt: attr_type = orb(_pkt[0]) return cls.registered_attributes.get(attr_type, cls) return cls
Returns the right RadiusAttribute class for the given data.
def temporary_directory(): dir_name = tempfile.mkdtemp() yield dir_name if os.path.exists(dir_name): shutil.rmtree(dir_name)
make a temporary directory, yeild its name, cleanup on exit
def loop(self): if not self._loop: self._loop = IOLoop.current() return self._loop return self._loop
Lazy event loop initialization
def func(self): fn = self.engine.query.sense_func_get( self.observer.name, self.sensename, *self.engine._btt() ) if fn is not None: return SenseFuncWrap(self.observer, fn)
Return the function most recently associated with this sense.
def peer_address(self): if not self._peer_address: self._peer_address = self.proto.reader._transport.get_extra_info('peername') if len(self._peer_address) == 4: self._peer_address = self._peer_address[:2] return self._peer_address
Peer endpoint address as a tuple
async def on_open(self): self.__ensure_barrier() while self.connected: try: if self.__lastping > self.__lastpong: raise IOError("Last ping remained unanswered") self.send_message("2") self.send_ack() self.__l...
DingDongmaster the connection is open
def motion_sensor(self, enabled): if enabled is True: value = CONST.SETTINGS_MOTION_POLICY_ON elif enabled is False: value = CONST.SETTINGS_MOTION_POLICY_OFF else: raise SkybellException(ERROR.INVALID_SETTING_VALUE, (CONST.SE...
Set the motion sensor state.
def _get_stripped_marker(marker, strip_func): if not marker: return None marker = _ensure_marker(marker) elements = marker._markers strip_func(elements) if elements: return marker return None
Build a new marker which is cleaned according to `strip_func`
def _run(method, cmd, cwd=None, shell=True, universal_newlines=True, stderr=STDOUT): if not cmd: error_msg = 'Passed empty text or list' raise AttributeError(error_msg) if isinstance(cmd, six.string_types): cmd = str(cmd) if shell: if ...
Internal wrapper for `call` amd `check_output`
def visit_call(self, node): expr_str = self._precedence_parens(node, node.func) args = [arg.accept(self) for arg in node.args] if node.keywords: keywords = [kwarg.accept(self) for kwarg in node.keywords] else: keywords = [] args.extend(keywords) re...
return an astroid.Call node as string
def to_unit_cell(self, in_place=False): frac_coords = np.mod(self.frac_coords, 1) if in_place: self.frac_coords = frac_coords else: return PeriodicSite(self.species, frac_coords, self.lattice, properties=self.properties)
Move frac coords to within the unit cell cell.
def parse_keyring(self, namespace=None): results = {} if not keyring: return results if not namespace: namespace = self.prog for option in self._options: secret = keyring.get_password(namespace, option.name) if secret: resul...
Find settings from keyring.
def csrf_protect_all_post_and_cross_origin_requests(): success = None if is_cross_origin(request): logger.warning("Received cross origin request. Aborting") abort(403) if request.method in ["POST", "PUT"]: token = session.get("csrf_token") if token == request.form.get("csrf_t...
returns None upon success
def replace_keys(record: Mapping, key_map: Mapping) -> dict: return {key_map[k]: v for k, v in record.items() if k in key_map}
New record with renamed keys including keys only found in key_map.
async def _register(self): if self.registered: return self._registration_attempts += 1 self.connection.throttle = False if self.password: await self.rawmsg('PASS', self.password) await self.set_nickname(self._attempt_nicknames.pop(0)) await self.ra...
Perform IRC connection registration.
def copy_plus(orig, new): for ext in ["", ".idx", ".gbi", ".tbi", ".bai"]: if os.path.exists(orig + ext) and (not os.path.lexists(new + ext) or not os.path.exists(new + ext)): shutil.copyfile(orig + ext, new + ext)
Copy a fils, including biological index files.
def _simplify_shape(self, alist, rec=0): if rec != 0: if len(alist) == 1: return alist[-1] return alist if len(alist) == 1: return self._simplify_shape(alist[-1], 1) return [self._simplify_shape(al, 1) for al in alist]
Reduce the alist dimension if needed
def add_param(self, param_key, param_val): self.params.append([param_key, param_val]) if param_key == '__success_test': self.success = param_val
adds parameters as key value pairs
def find(self,cell_designation,cell_filter=lambda x,c: 'c' in x and x['c'] == c): if 'parent' in self.meta: return (self.meta['parent'],self.meta['parent'].find(cell_designation,cell_filter=cell_filter))
finds spike containers in multi spike containers collection offspring
def getDbNames(self): request = [] request.append(uu({'-dbnames': '' })) result = self._doRequest(request) result = FMResultset.FMResultset(result) dbNames = [] for dbName in result.resultset: dbNames.append(string.lower(dbName['DATABASE_NAME'])) return dbNames
This function returns the list of open databases
async def set_heating_level(self, level, duration=0): url = '{}/devices/{}'.format(API_URL, self.device.deviceid) level = 10 if level < 10 else level level = 100 if level > 100 else level if self.side == 'left': data = { 'leftHeatingDuration': duration, ...
Update heating data json.
def included_length(self): return sum([shot.length for shot in self.shots if shot.is_included])
Surveyed length, not including "excluded" shots
def run(self): self._finished.clear() for line in iter(self.pipeReader.readline, ''): logging.log(self.level, line.strip('\n')) self.pipeReader.close() self._finished.set()
Run the thread, logging everything.
async def cancel_watchdog(self): if self._watchdog_task is not None: _LOGGER.debug("Canceling Watchdog task.") self._watchdog_task.cancel() try: await self._watchdog_task except asyncio.CancelledError: self._watchdog_task = None
Cancel the watchdog task and related variables.
def factory_object(self, index, doc_type, data=None, id=None): data = data or {} obj = self.model() obj._meta.index = index obj._meta.type = doc_type obj._meta.connection = self if id: obj._meta.id = id if data: obj.update(data) ret...
Create a stub object to be manipulated