code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def gate_angle(gate0: Gate, gate1: Gate) -> bk.BKTensor: return fubini_study_angle(gate0.vec, gate1.vec)
The Fubini-Study angle between gates
def _list_available_rest_versions(self): url = "https://{0}/api/api_version".format(self._target) data = self._request("GET", url, reestablish_session=False) return data["version"]
Return a list of the REST API versions supported by the array
def check_rdn_deposits(raiden, user_deposit_proxy: UserDeposit): while True: rei_balance = user_deposit_proxy.effective_balance(raiden.address, "latest") rdn_balance = to_rdn(rei_balance) if rei_balance < MIN_REI_THRESHOLD: click.secho( ( f'WAR...
Check periodically for RDN deposits in the user-deposits contract
def main(): arguments = docopt(__doc__, version=__version__) if arguments['on']: print 'Mr. Wolfe is at your service' print 'If any of your programs run into an error' print 'use wolfe $l' print 'To undo the changes made by mr wolfe in your bashrc, do wolfe off' on() elif arguments['off']: ...
i am winston wolfe, i solve problems
def distribution(self, limit=1024): res = self._qexec("%s, count(*) as __cnt" % self.name(), group="%s" % self.name(), order="__cnt DESC LIMIT %d" % limit) dist = [] cnt = self._table.size() for i, r in enumerate(res): dist.append(list(r) + [i, r[1] ...
Build the distribution of distinct values
def _save_token_cache(self, new_cache): 'Write out to the filesystem a cache of the OAuth2 information.' logging.debug('Looking to write to local authentication cache...') if not self._check_token_cache_type(new_cache): logging.error('Attempt to save a bad value: %s', new_cache) ...
Write out to the filesystem a cache of the OAuth2 information.
def from_gene_ids_and_names(cls, gene_names: Dict[str, str]): genes = [ExpGene(id_, name=name) for id_, name in gene_names.items()] return cls.from_genes(genes)
Initialize instance from gene IDs and names.
def _path_to_keys(cls, path): keys = _BaseFrame._path_to_keys_cache.get(path) if keys is None: keys = _BaseFrame._path_to_keys_cache[path] = path.split('.') return keys
Return a list of keys for a given path
def delete_email_marketing_campaign(self, email_marketing_campaign): url = self.api.join('/'.join([ self.EMAIL_MARKETING_CAMPAIGN_URL, str(email_marketing_campaign.constant_contact_id)])) response = url.delete() self.handle_response_status(response) return respons...
Deletes a Constant Contact email marketing campaign.
def volume_up(self): try: return bool(self.send_get_command(self._urls.command_volume_up)) except requests.exceptions.RequestException: _LOGGER.error("Connection error: volume up command not sent.") return False
Volume up receiver via HTTP get command.
def bk_cyan(cls): "Make the text background color cyan." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.BACKGROUND_MASK wAttributes |= win32.BACKGROUND_CYAN cls._set_text_attributes(wAttributes)
Make the text background color cyan.
def json_loads(data): try: return json.loads(data, encoding='utf-8') except TypeError: return json.loads(data.decode('utf-8'))
python-version-safe json.loads
def preLoad(self): logging.getLogger().debug("Preloading segment '%s'" % (self)) real_url = self.buildUrl() cache_url = self.buildUrl(cache_friendly=True) audio_data = self.download(real_url) assert(audio_data) __class__.cache[cache_url] = audio_data
Store audio data in cache for fast playback.
def __initialize_ui(self): self.viewport().installEventFilter(ReadOnlyFilter(self)) if issubclass(type(self), QListView): super(type(self), self).setUniformItemSizes(True) elif issubclass(type(self), QTreeView): super(type(self), self).setUniformRowHeights(True)
Initializes the View ui.
def sources(self): def set_bundle(s): s._bundle = self return s return list(set_bundle(s) for s in self.dataset.sources)
Iterate over downloadable sources
def _save_one(self, model, ctx): assert isinstance(ctx, ResourceQueryContext) self._orm.add(model) self._orm.flush()
Saves the created instance.
def _set(self, key, value, identity='image'): if identity == 'image': s = serialize_image_file(value) else: s = serialize(value) self._set_raw(add_prefix(key, identity), s)
Serializing, prefix wrapper for _set_raw
def db(self, connection_string=None): connection_string = connection_string or self.settings["db"] if not hasattr(self, "_db_conns"): self._db_conns = {} if not connection_string in self._db_conns: self._db_conns[connection_string] = oz.sqlalchemy.session(connection_strin...
Gets the SQLALchemy session for this request
def write_ensemble(ensemble, options): size = len(ensemble) filename = '%s_%s_queries.csv' % (options.outname, size) file = os.path.join(os.getcwd(), filename) f = open(file, 'w') out = ', '.join(ensemble) f.write(out) f.close()
Prints out the ensemble composition at each size
def to_vec4(self, isPoint): vec4 = Vector4() vec4.x = self.x vec4.y = self.y vec4.z = self.z if isPoint: vec4.w = 1 else: vec4.w = 0 return vec4
Converts this vector3 into a vector4 instance.
def init_db(self): db_path = self.get_data_file("data.sqlite") self.db = sqlite3.connect(db_path) self.cursor = self.db.cursor() self.db_exec( )
Init database and prepare tables
def characteristics_resolved(self): self._disconnect_characteristic_signals() characteristics_regex = re.compile(self._path + '/char[0-9abcdef]{4}$') managed_characteristics = [ char for char in self._object_manager.GetManagedObjects().items() if characteristics_regex.mat...
Called when all service's characteristics got resolved.
def _get_sorted_mosaics(dicom_input): sorted_mosaics = sorted(dicom_input, key=lambda x: x.AcquisitionNumber) for index in range(0, len(sorted_mosaics) - 1): if sorted_mosaics[index].AcquisitionNumber >= sorted_mosaics[index + 1].AcquisitionNumber: raise ConversionValidationError("INCONSISTE...
Search all mosaics in the dicom directory, sort and validate them
def _create_body(self, name, flavor=None, volume=None, databases=None, users=None, version=None, type=None): if flavor is None: flavor = 1 flavor_ref = self.api._get_flavor_ref(flavor) if volume is None: volume = 1 if databases is None: dat...
Used to create the dict required to create a Cloud Database instance.
def dataset_exists(dataset_name): dataset_dir = os.path.join(LIB_DIR, 'datasets') dataset_path = os.path.join(dataset_dir, dataset_name) return dataset_path if os.path.isdir(dataset_path) else None
If a dataset with the given name exists, return its absolute path; otherwise return None
def post_deploy_assume_role(assume_role_config, context): if isinstance(assume_role_config, dict): if assume_role_config.get('post_deploy_env_revert'): context.restore_existing_iam_env_vars()
Revert to previous credentials, if necessary.
def search_function(root1, q, s, f, l, o='g'): global links links = search(q, o, s, f, l) root1.destroy() root1.quit()
function to get links
def sagemaker_timestamp(): moment = time.time() moment_ms = repr(moment).split('.')[1][:3] return time.strftime("%Y-%m-%d-%H-%M-%S-{}".format(moment_ms), time.gmtime(moment))
Return a timestamp with millisecond precision.
def data_filler_detailed_registration(self, number_of_rows, db): try: detailed_registration = db data_list = list() for i in range(0, number_of_rows): post_det_reg = { "id": rnd_id_generator(self), "email": self.faker.sa...
creates and fills the table with detailed regis. information
def init_discrete_hmm_ml(C_full, nstates, reversible=True, stationary=True, active_set=None, P=None, eps_A=None, eps_B=None, separate=None): raise NotImplementedError('ML-initialization not yet implemented')
Initializes discrete HMM using maximum likelihood of observation counts
def GenerateDSP(dspfile, source, env): version_num = 6.0 if 'MSVS_VERSION' in env: version_num, suite = msvs_parse_version(env['MSVS_VERSION']) if version_num >= 10.0: g = _GenerateV10DSP(dspfile, source, env) g.Build() elif version_num >= 7.0: g = _GenerateV7DSP(dspfile,...
Generates a Project file based on the version of MSVS that is being used
def frame2expnum(frameid): result = {} parts = re.search('(?P<expnum>\d{7})(?P<type>\S)(?P<ccd>\d\d)', frameid) assert parts is not None result['expnum'] = parts.group('expnum') result['ccd'] = parts.group('ccd') result['version'] = parts.group('type') return result
Given a standard OSSOS frameid return the expnum, version and ccdnum as a dictionary.
def yesno(self, s, yesno_callback, casual=False): self.write(s) self.yesno_callback = yesno_callback self.yesno_casual = casual
Ask a question and prepare to receive a yes-or-no answer.
def pid_exists(pid): try: os.kill(pid, 0) except OSError as exc: return exc.errno == errno.EPERM else: return True
Determines if a system process identifer exists in process table.
def _is_protein(pe): val = isinstance(pe, _bp('Protein')) or \ isinstance(pe, _bpimpl('Protein')) or \ isinstance(pe, _bp('ProteinReference')) or \ isinstance(pe, _bpimpl('ProteinReference')) return val
Return True if the element is a protein
def _clean_doc(self, doc=None): if doc is None: doc = self.doc resources = doc['Resources'] for arg in ['startline', 'headerlines', 'encoding']: for e in list(resources.args): if e.lower() == arg: resources.args.remove(e) for te...
Clean the doc before writing it, removing unnecessary properties and doing other operations.
def _process_get_status(self, data): status = self._parse_status(data, self.cast_type) is_new_app = self.app_id != status.app_id and self.app_to_launch self.status = status self.logger.debug("Received status: %s", self.status) self._report_status() if is_new_app and self....
Processes a received STATUS message and notifies listeners.
def _setup_xauth(self): handle, filename = tempfile.mkstemp(prefix='PyVirtualDisplay.', suffix='.Xauthority') self._xauth_filename = filename os.close(handle) self._old_xauth = {} self._old_xauth['AUTHFILE'] = os.getenv('AUTHFILE') ...
Set up the Xauthority file and the XAUTHORITY environment variable.
def _pullMessage(self): data = { "msgs_recv": 0, "sticky_token": self._sticky, "sticky_pool": self._pool, "clientid": self._client_id, "state": "active" if self._markAlive else "offline", } return self._get(self.req_url.STICKY, data, fi...
Call pull api with seq value to get message data.
def messages(self): return int(math.floor(((self.limit.unit_value - self.level) / self.limit.unit_value) * self.limit.value))
Return remaining messages before limiting.
def getIRThreshold(self): command = '$GO' threshold = self.sendCommand(command) if threshold[0] == 'NK': return 0 else: return float(threshold[2])/10
Returns the IR temperature threshold in degrees Celcius, or 0 if no Threshold is set
def destroy(self): self._teardown_features() focus_registry.unregister(self.widget) widget = self.widget if widget is not None: del self.widget super(QtGraphicsItem, self).destroy() del self._widget_action
Destroy the underlying QWidget object.
def extract_zipfile(archive_name, destpath): "Unpack a zip file" archive = zipfile.ZipFile(archive_name) archive.extractall(destpath)
Unpack a zip file
def create_package_set_from_installed(**kwargs): if kwargs == {}: kwargs = {"local_only": False, "skip": ()} package_set = {} problems = False for dist in get_installed_distributions(**kwargs): name = canonicalize_name(dist.project_name) try: package_set[name] = Packa...
Converts a list of distributions into a PackageSet.
def add_rollback_panels(self): from wagtailplus.utils.edit_handlers import add_panel_to_edit_handler from wagtailplus.wagtailrollbacks.edit_handlers import HistoryPanel for model in self.applicable_models: add_panel_to_edit_handler(model, HistoryPanel, _(u'History'))
Adds rollback panel to applicable model class's edit handlers.
def check(self, instance): self.log.debug("Running instance: %s", instance) custom_tags = instance.get('tags', []) if not instance or self.PROC_NAME not in instance: raise GUnicornCheckError("instance must specify: %s" % self.PROC_NAME) proc_name = instance.get(self.PROC_NAME...
Collect metrics for the given gunicorn instance.
def create_gnu_header(self, info, encoding, errors): info["magic"] = GNU_MAGIC buf = b"" if len(info["linkname"]) > LENGTH_LINK: buf += self._create_gnu_long_header(info["linkname"], GNUTYPE_LONGLINK, encoding, errors) if len(info["name"]) > LENGTH_NAME: buf += se...
Return the object as a GNU header block sequence.
def itemlist(item, sep, suppress_trailing=True): return condense(item + ZeroOrMore(addspace(sep + item)) + Optional(sep.suppress() if suppress_trailing else sep))
Create a list of items seperated by seps.
def add_function(self, function): function = self.build_function(function) if function.name in self.functions: raise FunctionAlreadyRegistered(function.name) self.functions[function.name] = function
Adds the function to the list of registered functions.
def compile_path(self, path, write=True, package=None, *args, **kwargs): path = fixpath(path) if not isinstance(write, bool): write = fixpath(write) if os.path.isfile(path): if package is None: package = False destpath = self.compile_file(path,...
Compile a path and returns paths to compiled files.
def find_closest_match(target_track, tracks): track = None tracks_with_match_ratio = [( track, get_similarity(target_track.artist, track.artist), get_similarity(target_track.name, track.name), ) for track in tracks] sorted_tracks = sorted( tracks_with_match_ratio, ...
Return closest match to target track
def process_casefile(cls, workdir): record = cls(None, workdir) obj = {} with open(os.path.join(workdir, 'frames', 'frames.json')) as f: obj = json.load(f) record.device_info = obj['device'] record.frames = obj['frames'] casedir = os.path.join(workdir, ...
generate code from case.json
def _parse_chat(self, chat): if chat.data['type'] == 'chat': if chat.data['player'] in [p.player_name for i, p in self._players()]: self._chat.append(chat.data) elif chat.data['type'] == 'ladder': self._ladder = chat.data['ladder'] elif chat.data['type'] =...
Parse a chat message.
def compute(self, *args, **kwargs)->[Any, None]: return super().compute( self.compose, *args, **kwargs )
Compose and evaluate the function.
def timeit(func): @wraps(func) def timer_wrapper(*args, **kwargs): with Timer() as timer: result = func(*args, **kwargs) return result, timer return timer_wrapper
Returns the number of seconds that a function took along with the result
def mk_travis_config(): t = dedent( ) jobs = [env for env in parseconfig(None, 'tox').envlist if not env.startswith('cov-')] jobs += 'coverage', print(t.format(jobs=('\n'.join((' - TOX_JOB=' + job) for job in jobs))))
Generate configuration for travis.
def clone_workspace(self) -> None: def clone_clicked(text): if text: command = Workspace.CloneWorkspaceCommand(self, text) command.perform() self.document_controller.push_undo_command(command) self.pose_get_string_message_box(caption=_("Enter a...
Pose a dialog to name and clone a workspace.
def _recurse_config_to_dict(t_data): if not isinstance(t_data, type(None)): if isinstance(t_data, list): t_list = [] for i in t_data: t_list.append(_recurse_config_to_dict(i)) return t_list elif isinstance(t_data, dict): t_dict = {} ...
helper function to recurse through a vim object and attempt to return all child objects
def list_apis(awsclient): client_api = awsclient.get_client('apigateway') apis = client_api.get_rest_apis()['items'] for api in apis: print(json2table(api))
List APIs in account.
def _input_handler_decorator(self, data): input_handler = getattr(self, self.__InputHandler) input_parts = [ self.Parameters['taxonomy_file'], input_handler(data), self.Parameters['training_set_id'], self.Parameters['taxonomy_version'], self.Pa...
Adds positional parameters to selected input_handler's results.
def supported_auth_methods(self) -> List[str]: return [auth for auth in self.AUTH_METHODS if auth in self.server_auth_methods]
Get all AUTH methods supported by the both server and by us.
def __manage_connections(self, ccallbacks=None): _logger.info("Running client.") if self.__message_handler_cls is not None: self.__message_handler = self.__message_handler_cls( self.__election, ccallbacks) ...
This runs as the main connection management greenlet.
def _decode_sensor_data(properties): b64_input = "" for s in properties.get('payload'): b64_input += s decoded = base64.b64decode(b64_input) data = zlib.decompress(decoded) points = [] i = 0 while i < len(data): points.append({ ...
Decode, decompress, and parse the data from the history API
def count_discussions_handler(sender, **kwargs): if kwargs.get('instance') and kwargs.get('created'): return comment = 'comment' in kwargs and kwargs['comment'] or kwargs['instance'] entry = comment.content_object if isinstance(entry, Entry): entry.comment_count = entry.comments.count() ...
Update the count of each type of discussion on an entry.
def doi_uri_to_doi(value): "Strip the uri schema from the start of DOI URL strings" if value is None: return value replace_values = ['http://dx.doi.org/', 'https://dx.doi.org/', 'http://doi.org/', 'https://doi.org/'] for replace_value in replace_values: value = valu...
Strip the uri schema from the start of DOI URL strings
def current_ime(self): dumpout = self.adb_shell(['dumpsys', 'input_method']) m = _INPUT_METHOD_RE.search(dumpout) if m: return m.group(1)
Get current input method
def _deserialize(self, value, attr, data): if value: value = self._format_phone_number(value, attr) return super(PhoneNumberField, self)._deserialize(value, attr, data)
Format and validate the phone number using libphonenumber.
def build_single(mode): if mode == 'force': amode = ['-a'] else: amode = [] if executable.endswith('uwsgi'): _executable = executable[:-5] + 'python' else: _executable = executable p = subprocess.Popen([_executable, '-m', 'nikola', 'build'] + amode, ...
Build, in the single-user mode.
def retrieve_records(self, timeperiod, include_running, include_processed, include_noop, include_failed, include_disabled): resp = dict() try: query = unit_of_work_dao.QUERY_GET_FREERUN_SINCE(timeperiod, include_running, ...
method looks for suitable UOW records and returns them as a dict
def translate_gitlab_exception(func): @functools.wraps(func) def _wrapper(*args, **kwargs): try: return func(*args, **kwargs) except gitlab.GitlabError as e: status_to_exception = { 401: UnauthorizedError, 404: NotFoundError, } ...
Decorator to catch GitLab-specific exceptions and raise them as GitClientError exceptions.
def encrypt_file(file_path, sender, recipients): "Returns encrypted binary file content if successful" for recipient_key in recipients: crypto.assert_type_and_length('recipient_key', recipient_key, (str, crypto.UserLock)) crypto.assert_type_and_length("sender_key", sender, crypto.UserLock) if (n...
Returns encrypted binary file content if successful
def add_sparql_line_nums(sparql): lines = sparql.split("\n") return "\n".join(["%s %s" % (i + 1, line) for i, line in enumerate(lines)])
Returns a sparql query with line numbers prepended
def setReturnParameter(self, name, type, namespace=None, element_type=0): parameter = ParameterInfo(name, type, namespace, element_type) self.retval = parameter return parameter
Set the return parameter description for the call info.
def arg_name(self): if self.constraint is bool and self.value: return '--no-%s' % self.name.replace('_', '-') return '--%s' % self.name.replace('_', '-')
Returns the name of the parameter as a command line flag
def unwraplist(v): if is_list(v): if len(v) == 0: return None elif len(v) == 1: return unwrap(v[0]) else: return unwrap(v) else: return unwrap(v)
LISTS WITH ZERO AND ONE element MAP TO None AND element RESPECTIVELY
def load_key_file(self): self.client_key = None if self.key_file_path: key_file_path = self.key_file_path else: key_file_path = self._get_key_file_path() key_dict = {} logger.debug('load keyfile from %s', key_file_path); if os.path.isfile(key_file_...
Try to load the client key for the current ip.
def print_violations(self, violations): for v in violations: line_nr = v.line_nr if v.line_nr else "-" self.display.e(u"{0}: {1}".format(line_nr, v.rule_id), exact=True) self.display.ee(u"{0}: {1} {2}".format(line_nr, v.rule_id, v.message), exact=True) if v.conten...
Print a given set of violations to the standard error output
def _parse_tokenize(self, rule): for token in self._TOKENIZE_RE.split(rule): if not token or token.isspace(): continue clean = token.lstrip('(') for i in range(len(token) - len(clean)): yield '(', '(' if not clean: c...
Tokenizer for the policy language.
def circ_permutation(items): permutations = [] for i in range(len(items)): permutations.append(items[i:] + items[:i]) return permutations
Calculate the circular permutation for a given list of items.
def multi_iter(iterable, count=2): if not isinstance( iterable, ( list, tuple, set, FutureChainResults, collections.Sequence, collections.Set, collections.Mapping, collections.MappingView )): iterable = SafeTee(i...
Return `count` independent, thread-safe iterators for `iterable`
def start(self): self._useV2 = self.cf.platform.get_protocol_version() >= 4 logger.debug('[%d]: Using V2 protocol: %d', self.port, self._useV2) logger.debug('[%d]: Start fetching...', self.port) self.cf.add_port_callback(self.port, self._new_packet_cb) self.state = GET_TOC_INFO ...
Initiate fetching of the TOC.
def compiled_init_func(self): def get_column_assignment(column_name): return ALCHEMY_TEMPLATES.col_assignment.safe_substitute(col_name=column_name) def get_compiled_args(arg_name): return ALCHEMY_TEMPLATES.func_arg.safe_substitute(arg_name=arg_name) join_string = "\n" + s...
Returns compiled init function
def parse_config(config_file): try: with open(config_file, 'r') as f: return yaml.load(f) except IOError: print "Configuration file {} not found or not readable.".format(config_file) raise
Parse a YAML configuration file
def expand_models(self, target, data): if isinstance(data, dict): data = data.values() for chunk in data: if target in chunk: yield self.init_target_object(target, chunk) else: for key, item in chunk.items(): yield s...
Generates all objects from given data.
def _selectedRepoRow(self): selectedModelIndexes = \ self.reposTableWidget.selectionModel().selectedRows() for index in selectedModelIndexes: return index.row()
Return the currently select repo
def collect(self, name, arr): name = py_str(name) if self.include_layer is not None and not self.include_layer(name): return handle = ctypes.cast(arr, NDArrayHandle) arr = NDArray(handle, writable=False).copyto(cpu()) if self.logger is not None: self.logge...
Callback function for collecting layer output NDArrays.
def transitions(accountable): transitions = accountable.issue_transitions().get('transitions') headers = ['id', 'name'] if transitions: rows = [[v for k, v in sorted(t.items()) if k in headers] for t in transitions] rows.insert(0, headers) print_table(SingleTable(rows...
List all possible transitions for a given issue.
def _draw_tile_layer(self, tile, layer_name, c_filters, colour, t_filters, x, y, bg): left = (x + self._screen.width // 4) * 2 top = y + self._screen.height // 2 if (left > self._screen.width or left + self._size * 2 < 0 or top > self._screen.height or top + self._size < 0): ...
Draw the visible geometry in the specified map tile.
def dot_format(out, graph, name="digraph"): out.write("digraph %s {\n" % name) for step, deps in each_step(graph): for dep in deps: out.write(" \"%s\" -> \"%s\";\n" % (step, dep)) out.write("}\n")
Outputs the graph using the graphviz "dot" format.
def remove_overlaps(self, ufos, glyph_filter=lambda g: len(g)): from booleanOperations import union, BooleanOperationsError for ufo in ufos: font_name = self._font_name(ufo) logger.info("Removing overlaps for " + font_name) for glyph in ufo: if not gly...
Remove overlaps in UFOs' glyphs' contours.
def save_resource(self, name, resource, pushable=False): 'Saves an object such that it can be used by other tests.' if pushable: self.pushable_resources[name] = resource else: self.resources[name] = resource
Saves an object such that it can be used by other tests.
def add_relation(app_f, app_t, weight=1): recs = TabRel.select().where( (TabRel.post_f_id == app_f) & (TabRel.post_t_id == app_t) ) if recs.count() > 1: for record in recs: MRelation.delete(record.uid) if recs.count() == 0: uid = tools....
Adding relation between two posts.
def clean(self): return Text(self.__text_cleaner.clean(self[TEXT]), **self.__kwargs)
Return a copy of this Text instance with invalid characters removed.
def _op(self, _, obj, app): if obj.responses == None: return tmp = {} for k, v in six.iteritems(obj.responses): if isinstance(k, six.integer_types): tmp[str(k)] = v else: tmp[k] = v obj.update_field('responses', tmp)
convert status code in Responses from int to string
def _generate_SAX(self): sections = {} self.value_min = self.time_series.min() self.value_max = self.time_series.max() section_height = (self.value_max - self.value_min) / self.precision for section_number in range(self.precision): sections[section_number] = self.valu...
Generate SAX representation for all values of the time series.
def contents(self): data = find_dataset_path( self.name, data_home=self.data_home, ext=None ) return os.listdir(data)
Contents returns a list of the files in the data directory.
def url(url: str, method: str): try: url_rule, params = (current_app.url_map.bind('localhost') .match(url, method=method, return_rule=True)) except (NotFound, MethodNotAllowed)\ as e: click.secho(str(e), fg='white', bg='red') else: headings = (...
Show details for a specific URL.
def _sync_tasks(self, tasks_json): for task_json in tasks_json: task_id = task_json['id'] project_id = task_json['project_id'] if project_id not in self.projects: continue project = self.projects[project_id] self.tasks[task_id] = Task(t...
Populate the user's tasks from a JSON encoded list.
def detectEncodingMeta(self): buffer = self.rawStream.read(self.numBytesMeta) assert isinstance(buffer, bytes) parser = EncodingParser(buffer) self.rawStream.seek(0) encoding = parser.getEncoding() if encoding is not None and encoding.name in ("utf-16be", "utf-16le"): ...
Report the encoding declared by the meta element
def find_all(self, string, callback): for index, output in self.iter(string): callback(index, output)
Wrapper on iter method, callback gets an iterator result