code
stringlengths
51
2.38k
docstring
stringlengths
4
15.2k
def get_column(self, name): import ibis.expr.operations as ops ref = ops.TableColumn(name, self) return ref.to_expr()
Get a reference to a single column from the table Returns ------- column : array expression
def _log(self): self._log_platform() self._log_app_data() self._log_python_version() self._log_tcex_version() self._log_tc_proxy()
Send System and App data to logs.
def top_segment_proportions(mtx, ns): if not (max(ns) <= mtx.shape[1] and min(ns) > 0): raise IndexError("Positions outside range of features.") if issparse(mtx): if not isspmatrix_csr(mtx): mtx = csr_matrix(mtx) return top_segment_proportions_sparse_csr(mtx.data, mtx.indptr,...
Calculates total percentage of counts in top ns genes. Parameters ---------- mtx : `Union[np.array, sparse.spmatrix]` Matrix, where each row is a sample, each column a feature. ns : `Container[Int]` Positions to calculate cumulative proportion at. Values are considered 1-indexed...
def get_objective_banks_by_objective(self, objective_id): mgr = self._get_provider_manager('LEARNING', local=True) lookup_session = mgr.get_objective_bank_lookup_session(proxy=self._proxy) return lookup_session.get_objective_banks_by_ids( self.get_objective_bank_ids_by_objective(obje...
Gets the list of ``ObjectiveBanks`` mapped to an ``Objective``. arg: objective_id (osid.id.Id): ``Id`` of an ``Objective`` return: (osid.learning.ObjectiveBankList) - list of objective banks raise: NotFound - ``objective_id`` is not found raise: NullArgument - ``obj...
def convert_iso_stamp(t, tz=None): if t is None: return None dt = dateutil.parser.parse(t) if tz is not None: timezone = pytz.timezone(tz) if dt.tzinfo is None: dt = timezone.localize(dt) return dt
Convert a string in ISO8601 form into a Datetime object. This is mainly used for converting timestamps sent from the TempoDB API, which are assumed to be correct. :param string t: the timestamp to convert :rtype: Datetime object
def _ProcessHistogram(self, tag, wall_time, step, histo): histo = self._ConvertHistogramProtoToTuple(histo) histo_ev = HistogramEvent(wall_time, step, histo) self.histograms.AddItem(tag, histo_ev) self.compressed_histograms.AddItem(tag, histo_ev, self._CompressHistogram)
Processes a proto histogram by adding it to accumulated state.
def _read_payload(socket, payload_size): remaining = payload_size while remaining > 0: data = read(socket, remaining) if data is None: continue if len(data) == 0: break remaining -= len(data) yield data
From the given socket, reads and yields payload of the given size. With sockets, we don't receive all data at once. Therefore this method will yield each time we read some data from the socket until the payload_size has reached or socket has no more data. Parameters ---------- socket Socket...
def hash(self): hash_request = etcdrpc.HashRequest() return self.maintenancestub.Hash(hash_request).hash
Return the hash of the local KV state. :returns: kv state hash :rtype: int
def _rmv_pkg(self, package): removes = [] if GetFromInstalled(package).name() and package not in self.skip: ver = GetFromInstalled(package).version() removes.append(package + ver) self._removepkg(package) return removes
Remove one signle package
def runm(): signal.signal(signal.SIGINT, signal_handler) count = int(sys.argv.pop(1)) processes = [Process(target=run, args=()) for x in range(count)] try: for p in processes: p.start() except KeyError: pass finally: for p in processes: p.join()
This is super minimal and pretty hacky, but it counts as a first pass.
def base64url_to_long(data): _data = as_bytes(data) _d = base64.urlsafe_b64decode(_data + b'==') if [e for e in [b'+', b'/', b'='] if e in _data]: raise ValueError("Not base64url encoded") return intarr2long(struct.unpack('%sB' % len(_d), _d))
Stricter then base64_to_long since it really checks that it's base64url encoded :param data: The base64 string :return:
def get_instance_route53_names(self, instance): instance_attributes = [ 'public_dns_name', 'private_dns_name', 'ip_address', 'private_ip_address' ] name_list = set() for attrib in instance_attributes: try: value = getattr(instance, attr...
Check if an instance is referenced in the records we have from Route53. If it is, return the list of domain names pointing to said instance. If nothing points to it, return an empty list.
def get_list_of_applications(): apps = mod_prg.Programs('Applications', 'C:\\apps') fl = mod_fl.FileList(['C:\\apps'], ['*.exe'], ["\\bk\\"]) for f in fl.get_list(): apps.add(f, 'autogenerated list') apps.list() apps.save()
Get list of applications
def _updateConstructorAndMembers(self): syntheticMetaData = self._syntheticMetaData() constructor = self._constructorFactory.makeConstructor(syntheticMetaData.originalConstructor(), syntheticMetaData.syntheticMemberList(), ...
We overwrite constructor and accessors every time because the constructor might have to consume all members even if their decorator is below the "synthesizeConstructor" decorator and it also might need to update the getters and setters because the naming convention has changed.
def get_tag_html(tag_id): tag_data = get_lazy_tag_data(tag_id) tag = tag_data['tag'] args = tag_data['args'] kwargs = tag_data['kwargs'] lib, tag_name = get_lib_and_tag_name(tag) args_str = '' if args: for arg in args: if isinstance(arg, six.string_types): ...
Returns the Django HTML to load the tag library and render the tag. Args: tag_id (str): The tag id for the to return the HTML for.
def _get_complex_agents(self, complex_id): agents = [] components = self._recursively_lookup_complex(complex_id) for c in components: db_refs = {} name = uniprot_client.get_gene_name(c) if name is None: db_refs['SIGNOR'] = c else: ...
Returns a list of agents corresponding to each of the constituents in a SIGNOR complex.
def add_properties(self, properties): if isinstance(properties, dict): self._properties.update(properties)
Updates the framework properties dictionary :param properties: New framework properties to add
def draw_chimera_embedding(G, *args, **kwargs): draw_embedding(G, chimera_layout(G), *args, **kwargs)
Draws an embedding onto the chimera graph G, according to layout. If interaction_edges is not None, then only display the couplers in that list. If embedded_graph is not None, the only display the couplers between chains with intended couplings according to embedded_graph. Parameters ---------- ...
def convert_npdist(self, node): with context(self.fname, node): npdist = [] for np in node.nodalPlaneDist: prob, strike, dip, rake = ( np['probability'], np['strike'], np['dip'], np['rake']) npdist.append((prob, geo.NodalPlane(strike, d...
Convert the given node into a Nodal Plane Distribution. :param node: a nodalPlaneDist node :returns: a :class:`openquake.hazardlib.geo.NodalPlane` instance
def shared_databases(self): endpoint = '/'.join(( self.server_url, '_api', 'v2', 'user', 'shared_databases')) resp = self.r_session.get(endpoint) resp.raise_for_status() data = response_to_json_dict(resp) return data.get('shared_databases', [])
Retrieves a list containing the names of databases shared with this account. :returns: List of database names
def _getBlobFromURL(cls, url, exists=False): bucketName = url.netloc fileName = url.path if fileName.startswith('/'): fileName = fileName[1:] storageClient = storage.Client() bucket = storageClient.get_bucket(bucketName) blob = bucket.blob(bytes(fileName)) ...
Gets the blob specified by the url. caution: makes no api request. blob may not ACTUALLY exist :param urlparse.ParseResult url: the URL :param bool exists: if True, then syncs local blob object with cloud and raises exceptions if it doesn't exist remotely :return: the blob re...
def clean(self): data = super(PublishingAdminForm, self).clean() cleaned_data = self.cleaned_data instance = self.instance unique_fields_set = instance.get_unique_together() if not unique_fields_set: return data for unique_fields in unique_fields_set: ...
Additional clean data checks for path and keys. These are not cleaned in their respective methods e.g. `clean_slug` as they depend upon other field data. :return: Cleaned data.
def block(seed): num = SAMPLE_RATE * BLOCK_SIZE rng = RandomState(seed % 2**32) variance = SAMPLE_RATE / 2 return rng.normal(size=num, scale=variance**0.5)
Return block of normal random numbers Parameters ---------- seed : {None, int} The seed to generate the noise.sd Returns -------- noise : numpy.ndarray Array of random numbers
def _validate_publish_parameters(body, exchange, immediate, mandatory, properties, routing_key): if not compatibility.is_string(body): raise AMQPInvalidArgument('body should be a string') elif not compatibility.is_string(routing_key): raise AM...
Validate Publish Parameters. :param bytes|str|unicode body: Message payload :param str routing_key: Message routing key :param str exchange: The exchange to publish the message to :param dict properties: Message properties :param bool mandatory: Requires the message is published...
def has_datastore(self): success, result = self._read_from_hdx('datastore', self.data['id'], 'resource_id', self.actions()['datastore_search']) if not success: logger.debug(result) else: if result: return True ...
Check if the resource has a datastore. Returns: bool: Whether the resource has a datastore or not
def list_bandwidth_limit_rules(self, policy_id, retrieve_all=True, **_params): return self.list('bandwidth_limit_rules', self.qos_bandwidth_limit_rules_path % policy_id, retrieve_all, **_params)
Fetches a list of all bandwidth limit rules for the given policy.
def _call(self, resource_url, params=None): url = "%s%s" % (self._endpoint(), resource_url) if params: url += "?%s&%s" % (params, self._auth()) else: url += "?%s" % self._auth() return requests.get(url)
Calls the Marvel API endpoint :param resource_url: url slug of the resource :type resource_url: str :param params: query params to add to endpoint :type params: str :returns: response -- Requests response
def drop(verbose): click.secho('Dropping all tables!', fg='red', bold=True) with click.progressbar(reversed(_db.metadata.sorted_tables)) as bar: for table in bar: if verbose: click.echo(' Dropping table {0}'.format(table)) table.drop(bind=_db.engine, checkfirst=Tr...
Drop tables.
def exit(self, code=0, message=None): if self._parser: if code > 0: self.parser.error(message) else: self.parser.exit(code, message) else: if message is not None: if code > 0: sys.stderr.write(message...
Exit the console program sanely.
def create(labels=None, **kw): if labels is not None: kw[u'labels'] = encoding.PyValueToMessage(MetricValue.LabelsValue, labels) return MetricValue(**kw)
Constructs a new metric value. This acts as an alternate to MetricValue constructor which simplifies specification of labels. Rather than having to create a MetricValue.Labels instance, all that's necessary to specify the required string. Args: labels (dict([string, [string]]): **kw: ...
def _validate_list_type(self, name, obj, *args): if obj is None: return if isinstance(obj, list): for i in obj: self._validate_type_not_null(name, i, *args) else: self._validate_type(name, obj, *args)
Helper function that checks the input object type against each in a list of classes, or if the input object is a list, each value that it contains against that list. :param name: Name of the object. :param obj: Object to check the type of. :param args: List of classes. :raises T...
def open(self): if self.flag == "w": check_call(_LIB.MXRecordIOWriterCreate(self.uri, ctypes.byref(self.handle))) self.writable = True elif self.flag == "r": check_call(_LIB.MXRecordIOReaderCreate(self.uri, ctypes.byref(self.handle))) self.writable = False...
Opens the record file.
def get_body(self): body = copy.deepcopy(self.errors) for error in body: for key in error.keys(): if key not in self.ERROR_OBJECT_FIELDS: del error[key] return json.dumps({'errors': body})
Return a HTTPStatus compliant body attribute Be sure to purge any unallowed properties from the object. TIP: At the risk of being a bit slow we copy the errors instead of mutating them since they may have key/vals like headers that are useful elsewhere.
def create_qgis_template_output(output_path, layout): dirname = os.path.dirname(output_path) if not os.path.exists(dirname): os.makedirs(dirname) context = QgsReadWriteContext() context.setPathResolver(QgsProject.instance().pathResolver()) layout.saveAsTemplate(output_path, context) retu...
Produce QGIS Template output. :param output_path: The output path. :type output_path: str :param composition: QGIS Composition object to get template. values :type composition: qgis.core.QgsLayout :return: Generated output path. :rtype: str
def from_fits_images(cls, path_l, max_norder): moc = MOC() for path in path_l: header = fits.getheader(path) current_moc = MOC.from_image(header=header, max_norder=max_norder) moc = moc.union(current_moc) return moc
Loads a MOC from a set of FITS file images. Parameters ---------- path_l : [str] A list of path where the fits image are located. max_norder : int The MOC resolution. Returns ------- moc : `~mocpy.moc.MOC` The union of all the...
def generate_random_string(number_of_random_chars=8, character_set=string.ascii_letters): return u('').join(random.choice(character_set) for _ in range(number_of_random_chars))
Generate a series of random characters. Kwargs: number_of_random_chars (int) : Number of characters long character_set (str): Specify a character set. Default is ASCII
def _make_request(self, method, url, post_data=None, body=None): if not self.connection: self._connect() try: self.connection.close() except: pass self.connection.connect() headers = {} if self.auth_header: headers["Authoriz...
Make a request on this connection
def _is_ascii_stl(first_bytes): is_ascii = False if 'solid' in first_bytes.decode("utf-8").lower(): is_ascii = True return is_ascii
Determine if this is an ASCII based data stream, simply by checking the bytes for the word 'solid'.
def _get_errors(self): errors = self.json.get('data').get('failures') if errors: logger.error(errors) return errors
Gets errors from HTTP response
def _key_values(self, sn: "SequenceNode") -> Union[EntryKeys, EntryValue]: try: keys = self.up_to("/") except EndOfInput: keys = self.remaining() if not keys: raise UnexpectedInput(self, "entry value or keys") if isinstance(sn, LeafListNode): ...
Parse leaf-list value or list keys.
def pad_zeroes(addr, n_zeroes): if len(addr) < n_zeroes: return pad_zeroes("0" + addr, n_zeroes) return addr
Padds the address with zeroes
def review_score(self, reviewer, product): return self._g.retrieve_review(reviewer, product).score
Find a review score from a given reviewer to a product. Args: reviewer: Reviewer i.e. an instance of :class:`ria.bipartite.Reviewer`. product: Product i.e. an instance of :class:`ria.bipartite.Product`. Returns: A review object representing the review from the reviewer to...
def prefixes_to_fns(self, prefixes: List[str]) -> Tuple[List[str], List[str]]: feat_fns = [str(self.feat_dir / ("%s.%s.npy" % (prefix, self.feat_type))) for prefix in prefixes] label_fns = [str(self.label_dir / ("%s.%s" % (prefix, self.label_type))) for prefix i...
Fetches the file paths to the features files and labels files corresponding to the provided list of features
def reconstruct(self, b, X=None): if X is None: X = self.getcoef() Xf = sl.rfftn(X, None, self.cbpdn.cri.axisN) slc = (slice(None),)*self.dimN + \ (slice(self.chncs[b], self.chncs[b+1]),) Sf = np.sum(self.cbpdn.Df[slc] * Xf, axis=self.cbpdn.cri.axisM) re...
Reconstruct representation of signal b in signal set.
def valid_any_uri(item): try: part = urlparse(item) except Exception: raise NotValid("AnyURI") if part[0] == "urn" and part[1] == "": return True return True
very simplistic, ...
def set_storage(self, storage): if isinstance(storage, BaseStorage): self.storage = storage elif isinstance(storage, dict): if 'backend' not in storage and 'root_dir' in storage: storage['backend'] = 'FileSystem' try: backend_cls = geta...
Set storage backend for downloader For full list of storage backend supported, please see :mod:`storage`. Args: storage (dict or BaseStorage): storage backend configuration or instance
def minver_error(pkg_name): print( 'ERROR: specify minimal version of "{}" using ' '">=" or "=="'.format(pkg_name), file=sys.stderr ) sys.exit(1)
Report error about missing minimum version constraint and exit.
def _load_config(self): self._config = ConfigParser.SafeConfigParser() self._config.read(self.config_path)
Read the configuration file and load it into memory.
def _get_at_pos(self, pos): if pos < 0: return None, None if len(self.lines) > pos: return self.lines[pos], pos if self.file is None: return None, None assert pos == len(self.lines), "out of order request?" self.read_next_line() return ...
Return a widget for the line number passed.
def _getSectionForDataDirectoryEntry(self, data_directory_entry, sections): for section in sections: if data_directory_entry.VirtualAddress >= section.header.VirtualAddress and \ data_directory_entry.VirtualAddress < section.header.VirtualAddress + section.header.SizeOfRawData : ...
Returns the section which contains the data of DataDirectory
def _terminate_procs(procs): logging.warn("Stopping all remaining processes") for proc, g in procs.values(): logging.debug("[%s] SIGTERM", proc.pid) try: proc.terminate() except OSError as e: if e.errno != errno.ESRCH: raise sys.exit(1)
Terminate all processes in the process dictionary
def play(self, filename, translate=False): if translate: with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as f: fname = f.name with audioread.audio_open(filename) as f: with contextlib.closing(wave.open(fname, 'w')) as of: ...
Plays the sounds. :filename: The input file name :translate: If True, it runs it through audioread which will translate from common compression formats to raw WAV.
def datetimeparse(s): try: dt = dateutil.parser.parse(s) except ValueError: return None return utc_dt(dt)
Parse a string date time to a datetime object. Suitable for dates serialized with .isoformat() :return: None, or an aware datetime instance, tz=UTC.
def load_cli_plugins(cli, config_dir=None): from .config import load_master_config config = load_master_config(config_dir=config_dir) plugins = discover_plugins(config.Plugins.dirs) for plugin in plugins: if not hasattr(plugin, 'attach_to_cli'): continue logger.debug("Attach ...
Load all plugins and attach them to a CLI object.
def init_conv_weight(layer): n_filters = layer.filters filter_shape = (layer.kernel_size,) * get_n_dim(layer) weight = np.zeros((n_filters, n_filters) + filter_shape) center = tuple(map(lambda x: int((x - 1) / 2), filter_shape)) for i in range(n_filters): filter_weight = np.zeros((n_filters,...
initilize conv layer weight.
def _magic(header, footer, mime, ext=None): if not header: raise ValueError("Input was empty") info = _identify_all(header, footer, ext)[0] if mime: return info.mime_type return info.extension if not \ isinstance(info.extension, list) else info[0].extension
Discover what type of file it is based on the incoming string
def run(self): "Run cli, processing arguments and executing subcommands." arguments = self.argument_parser.parse_args() argspec = inspect.getargspec(arguments.func) vargs = [] for arg in argspec.args: vargs.append(getattr(arguments, arg)) if argspec.varargs: ...
Run cli, processing arguments and executing subcommands.
def load_local_translationtable(self, name): localtt_file = 'translationtable/' + name + '.yaml' try: with open(localtt_file): pass except IOError: with open(localtt_file, 'w') as write_yaml: yaml.dump({name: name}, write_yaml) fina...
Load "ingest specific" translation from whatever they called something to the ontology label we need to map it to. To facilitate seeing more ontology lables in dipper ingests a reverse mapping from ontology lables to external strings is also generated and available as a dict localtcid
def parse_binary(self): self.mimetype = self.resource.rdf.graph.value( self.resource.uri, self.resource.rdf.prefixes.ebucore.hasMimeType).toPython() self.data = self.resource.repo.api.http_request( 'GET', self.resource.uri, data=None, headers={'Content-Type':self.resource.mimetype}, is_rdf=Fals...
when retrieving a NonRDF resource, parse binary data and make available via generators
def add_instance(self, instance): assert isinstance(instance, dict) item = defaults["common"].copy() item.update(defaults["instance"]) item.update(instance["data"]) item.update(instance) item["itemType"] = "instance" item["isToggled"] = instance["data"].get("publi...
Append `instance` to model Arguments: instance (dict): Serialised instance Schema: instance.json
def _sumindex(self, index=None): try: ndim = len(index) except TypeError: index = (index,) ndim = 1 if len(self.shape) != ndim: raise ValueError("Index to %d-dimensional array %s has too %s dimensions" % (len(self.shape), self.name,...
Convert tuple index to 1-D index into value
def close(self): if VERBOSE: _print_out('\nDummy_serial: Closing port\n') if not self._isOpen: raise IOError('Dummy_serial: The port is already closed') self._isOpen = False self.port = None
Close a port on dummy_serial.
def to_float_with_default(value, default_value): result = FloatConverter.to_nullable_float(value) return result if result != None else default_value
Converts value into float or returns default when conversion is not possible. :param value: the value to convert. :param default_value: the default value. :return: float value or default value when conversion is not supported.
def get_system(self, twig=None, **kwargs): if twig is not None: kwargs['twig'] = twig kwargs['context'] = 'system' return self.filter(**kwargs)
Filter in the 'system' context :parameter str twig: twig to use for filtering :parameter **kwargs: any other tags to do the filter (except twig or context) :return: :class:`phoebe.parameters.parameters.Parameter` or :class:`phoebe.parameters.parameters.ParameterSet`
def compute_pairwise_similarity_score(self): pairs = [] all_scores = [] for i, unit in enumerate(self.parsed_response): for j, other_unit in enumerate(self.parsed_response): if i != j: pair = (i, j) rev_pair = (j, i) ...
Computes the average pairwise similarity score between all pairs of Units. The pairwise similarity is calculated as the sum of similarity scores for all pairwise word pairs in a response -- except any pair composed of a word and itself -- divided by the total number of words in an attempt. I.e....
def get_stats(self): resp = requests.get('%s/api/stats.json' % self.url) assert(resp.status_code == 200) return resp.json()
Get kitty stats as a dictionary
def save_feedback(rdict): if not os.path.exists(_feedback_dir): os.makedirs(_feedback_dir) jcont = json.dumps(rdict) f = open(_feedback_file, 'w') f.write(jcont) f.close()
Save feedback file
def nfa(self): finalstate = State(final=True) nextstate = finalstate for tokenexpr in reversed(self): state = tokenexpr.nfa(nextstate) nextstate = state return NFA(state)
convert the expression into an NFA
def retrieve_object_query(self, view_kwargs, filter_field, filter_value): return self.session.query(self.model).filter(filter_field == filter_value)
Build query to retrieve object :param dict view_kwargs: kwargs from the resource view :params sqlalchemy_field filter_field: the field to filter on :params filter_value: the value to filter with :return sqlalchemy query: a query from sqlalchemy
def default(self): if self.MUTABLE: return copy.deepcopy(self._default) else: return self._default
Returns the static value that this defaults to.
def add_from_existing(self, resource, timeout=-1): uri = self.URI + "/from-existing" return self._client.create(resource, uri=uri, timeout=timeout)
Adds a volume that already exists in the Storage system Args: resource (dict): Object to create. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView, just stop waiting for i...
def remove(config, username, filename, force): client = Client() client.prepare_connection() user_api = UserApi(client) key_api = API(client) key_api.remove(username, user_api, filename, force)
Remove user's SSH public key from their LDAP entry.
def generation(self): with self._lock: if self.state is not MemberState.STABLE: return None return self._generation
Get the current generation state if the group is stable. Returns: the current generation or None if the group is unjoined/rebalancing
def _generate_attrs(self): attrs = {} if ismodule(self.doubled_obj): for name, func in getmembers(self.doubled_obj, is_callable): attrs[name] = Attribute(func, 'toplevel', self.doubled_obj) else: for attr in classify_class_attrs(self.doubled_obj_type): ...
Get detailed info about target object. Uses ``inspect.classify_class_attrs`` to get several important details about each attribute on the target object. :return: The attribute details dict. :rtype: dict
def select_action(self, **kwargs): setattr(self.inner_policy, self.attr, self.get_current_value()) return self.inner_policy.select_action(**kwargs)
Choose an action to perform # Returns Action to take (int)
def remove_adapter(widget_class, flavour=None): for it,tu in enumerate(__def_adapter): if (widget_class == tu[WIDGET] and flavour == tu[FLAVOUR]): del __def_adapter[it] return True return False
Removes the given widget class information from the default set of adapters. If widget_class had been previously added by using add_adapter, the added adapter will be removed, restoring possibly previusly existing adapter(s). Notice that this function will remove only *one* adapter about given wige...
def ParseAgeSpecification(cls, age): try: return (0, int(age)) except (ValueError, TypeError): pass if age == NEWEST_TIME: return data_store.DB.NEWEST_TIMESTAMP elif age == ALL_TIMES: return data_store.DB.ALL_TIMESTAMPS elif len(age) == 2: start, end = age return ...
Parses an aff4 age and returns a datastore age specification.
def sound_pressure_low(self): self._ensure_mode(self.MODE_DBA) return self.value(0) * self._scale('DBA')
A measurement of the measured sound pressure level, as a percent. Uses A-weighting, which focuses on levels up to 55 dB.
def draw(self): for fig in self.figs2draw: fig.canvas.draw() self._figs2draw.clear()
Draw the figures and those that are shared and have been changed
def _ParseCachedEntryVista(self, value_data, cached_entry_offset): try: cached_entry = self._ReadStructureFromByteStream( value_data[cached_entry_offset:], cached_entry_offset, self._cached_entry_data_type_map) except (ValueError, errors.ParseError) as exception: raise errors.Par...
Parses a Windows Vista cached entry. Args: value_data (bytes): value data. cached_entry_offset (int): offset of the first cached entry data relative to the start of the value data. Returns: AppCompatCacheCachedEntry: cached entry. Raises: ParseError: if the value data co...
def return_input_paths(job, work_dir, ids, *args): paths = OrderedDict() for name in args: if not os.path.exists(os.path.join(work_dir, name)): file_path = job.fileStore.readGlobalFile(ids[name], os.path.join(work_dir, name)) else: file_path = os.path.join(work_dir, name)...
Returns the paths of files from the FileStore Input1: Toil job instance Input2: Working directory Input3: jobstore id dictionary Input4: names of files to be returned from the jobstore Returns: path(s) to the file(s) requested -- unpack these!
def color_stream_mt(istream=sys.stdin, n=config.N_PROCESSES, **kwargs): queue = multiprocessing.Queue(1000) lock = multiprocessing.Lock() pool = [multiprocessing.Process(target=color_process, args=(queue, lock), kwargs=kwargs) for i in range(n)] for p in pool: p.start() block = [...
Read filenames from the input stream and detect their palette using multiple processes.
def python_sidebar_help(python_input): token = 'class:sidebar.helptext' def get_current_description(): i = 0 for category in python_input.options: for option in category.options: if i == python_input.selected_option_index: return option.description...
Create the `Layout` for the help text for the current item in the sidebar.
def compute_K_factors(self, spacing=None, configs=None, numerical=False, elem_file=None, elec_file=None): if configs is None: use_configs = self.configs else: use_configs = configs if numerical: settings = { 'elem': el...
Compute analytical geometrical factors. TODO: use real electrode positions from self.grid
def get_loader(module_or_name): if module_or_name in sys.modules: module_or_name = sys.modules[module_or_name] if isinstance(module_or_name, ModuleType): module = module_or_name loader = getattr(module, '__loader__', None) if loader is not None: return loader ...
Get a PEP 302 "loader" object for module_or_name If the module or package is accessible via the normal import mechanism, a wrapper around the relevant part of that machinery is returned. Returns None if the module cannot be found or imported. If the named module is not already imported, its containing...
def delete_user(self, username): path = Client.urls['users_by_name'] % username return self._call(path, 'DELETE')
Deletes a user from the server. :param string username: Name of the user to delete from the server.
def pix2vec(nside, ipix, nest=False): lon, lat = healpix_to_lonlat(ipix, nside, order='nested' if nest else 'ring') return ang2vec(*_lonlat_to_healpy(lon, lat))
Drop-in replacement for healpy `~healpy.pixelfunc.pix2vec`.
def from_list(cls, l): if len(l) == 3: x, y, z = map(float, l) return cls(x, y, z) elif len(l) == 2: x, y = map(float, l) return cls(x, y) else: raise AttributeError
Return a Point instance from a given list
def instruction_PAGE(self, opcode): op_address, opcode2 = self.read_pc_byte() paged_opcode = opcode * 256 + opcode2 self.call_instruction_func(op_address - 1, paged_opcode)
call op from page 2 or 3
def preserve_context(f): action = current_action() if action is None: return f task_id = action.serialize_task_id() called = threading.Lock() def restore_eliot_context(*args, **kwargs): if not called.acquire(False): raise TooManyCalls(f) with Action.continue_task(...
Package up the given function with the current Eliot context, and then restore context and call given function when the resulting callable is run. This allows continuing the action context within a different thread. The result should only be used once, since it relies on L{Action.serialize_task_id} who...
def get_lr_scheduler(learning_rate, lr_refactor_step, lr_refactor_ratio, num_example, batch_size, begin_epoch): assert lr_refactor_ratio > 0 iter_refactor = [int(r) for r in lr_refactor_step.split(',') if r.strip()] if lr_refactor_ratio >= 1: return (learning_rate, None) els...
Compute learning rate and refactor scheduler Parameters: --------- learning_rate : float original learning rate lr_refactor_step : comma separated str epochs to change learning rate lr_refactor_ratio : float lr *= ratio at certain steps num_example : int number o...
def get_dimension_index(self, dimension): if isinstance(dimension, int): if (dimension < (self.ndims + len(self.vdims)) or dimension < len(self.dimensions())): return dimension else: return IndexError('Dimension index out of bounds') ...
Get the index of the requested dimension. Args: dimension: Dimension to look up by name or by index Returns: Integer index of the requested dimension
def request(self, hostport=None, service=None, arg_scheme=None, retry=None, **kwargs): return self.peers.request(hostport=hostport, service=service, arg_scheme=arg_...
Initiate a new request through this TChannel. :param hostport: Host to which the request will be made. If unspecified, a random known peer will be picked. This is not necessary if using Hyperbahn. :param service: The name of a service available on Hyperb...
def load_cli_config(args): default_cli_config = _load_default_cli_config() toml_config = _load_toml_cli_config() for config in (toml_config, default_cli_config): for key, val in config.items(): if key in args and getattr(args, key) is not None: pass else: ...
Modifies ARGS in-place to have the attributes defined in the CLI config file if it doesn't already have them. Certain default values are given if they are not in ARGS or the config file.
def get_col(self, col_name, filter = lambda _ : True): if col_name not in self._headers: raise ValueError("{} not found! Model has headers: {}".format(col_name, self._headers)) col = [] for i in range(self.num_rows): row = self._table[i + 1] val = row[col_name...
Return all values in the column corresponding to col_name that satisfies filter, which is a function that takes in a value of the column's type and returns True or False Parameters ---------- col_name : str Name of desired column filter : function, optional ...
def find(self, pattern): pos = self.current_segment.data.find(pattern) if pos == -1: return -1 return pos + self.current_position
Searches for a pattern in the current memory segment
def norm_join(prefix, suffix): if (prefix is None) and (suffix is None): return "." if prefix is None: return os.path.normpath(suffix) if suffix is None: return os.path.normpath(prefix) return os.path.normpath(os.path.join(prefix, suffix))
Join ``prefix`` and ``suffix`` paths and return the resulting path, normalized. :param string prefix: the prefix path :param string suffix: the suffix path :rtype: string
def PopAllChildren(self): indexes = self.GetChildrenIndexes() children = [] for c in indexes: child = self.PopChild(c) children.append(child) return children
Method to remove and return all children of current node :return: list of children
def _build_brokers(self, brokers): for broker_id, metadata in six.iteritems(brokers): self.brokers[broker_id] = self._create_broker(broker_id, metadata)
Build broker objects using broker-ids.
def get_cmdclass(): cmdclass = versioneer.get_cmdclass() try: from wheel.bdist_wheel import bdist_wheel except ImportError: bdist_wheel = None if bdist_wheel is not None: cmdclass["bdist_wheel"] = bdist_wheel return cmdclass
A ``cmdclass`` that works around a setuptools deficiency. There is no need to build wheels when installing a package, however some versions of setuptools seem to mandate this. This is a hacky workaround that modifies the ``cmdclass`` returned by versioneer so that not having wheel installed is not a fa...