Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
358,100
def cli(ctx, feature_id, description, organism="", sequence=""): return ctx.gi.annotations.set_description(feature_id, description, organism=organism, sequence=sequence)
Set a feature's description Output: A standard apollo feature dictionary ({"features": [{...}]})
358,101
def addField(self, name, fieldParams, encoderParams): assert fieldParams is not None and in fieldParams dataClassName = fieldParams.pop() try: dataClass=eval(dataClassName)(fieldParams) except TypeError, e: print (" "some required constructor parameters. Parameters " ...
Add a single field to the dataset. Parameters: ------------------------------------------------------------------- name: The user-specified name of the field fieldSpec: A list of one or more dictionaries specifying parameters to be used for dataClass initializati...
358,102
def _apply_uncertainty_to_mfd(self, mfd, value): if self.uncertainty_type == : a, b = value mfd.modify(, dict(a_val=a, b_val=b)) elif self.uncertainty_type == : mfd.modify(, dict(value=value)) elif self.uncertainty_type == : mfd.modify(,...
Modify ``mfd`` object with uncertainty value ``value``.
358,103
def ColumnToIndex (col): ndx = 0 for c in col: ndx = ndx * 26 + ord(c.upper()) - 64 return ndx
convert column to index. Eg: ConvertInIndex("AB") = 28
358,104
def init_associations(self, hdr_only=False, prt=sys.stdout): import timeit import datetime associations = [] tic = timeit.default_timer() if self.filename is None: return associations ver = None ntgpadobj_make = None hdrobj = GpadHdr()...
Read GPAD file. HTTP address okay. GZIPPED/BZIPPED file okay.
358,105
def AsHandler(request=None, modules=None, **kw): ps = ParsedSoap(request) kw[] = request _Dispatch(ps, modules, _ModPythonSendXML, _ModPythonSendFault, **kw)
Dispatch from within ModPython.
358,106
def recognize_byte(self, image, timeout=10): result = [] alpr = subprocess.Popen( self._cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL ) try: stdout, stderr = alpr....
Process a byte image buffer.
358,107
def sklearn2pmml(pipeline, pmml, user_classpath = [], with_repr = False, debug = False, java_encoding = "UTF-8"): if debug: java_version = _java_version(java_encoding) if java_version is None: java_version = ("java", "N/A") print("python: {0}".format(platform.python_version())) print("sklearn: {0}".format...
Converts a fitted Scikit-Learn pipeline to PMML. Parameters: ---------- pipeline: PMMLPipeline The pipeline. pmml: string The path to where the PMML document should be stored. user_classpath: list of strings, optional The paths to JAR files that provide custom Transformer, Selector and/or Estimator conver...
358,108
def string_xor(a, b): if sys.version_info[0] < 3: return .join((chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b))) else: return bytes(x ^ y for (x, y) in zip(a, b))
Computes the XOR operator between two byte strings. If the strings are of different lengths, the result string is as long as the shorter.
358,109
def set_storage_account( self, vault_base_url, storage_account_name, resource_id, active_key_name, auto_regenerate_key, regeneration_period=None, storage_account_attributes=None, tags=None, custom_headers=None, raw=False, **operation_config): parameters = models.StorageAccountCreateParamete...
Creates or updates a new storage account. This operation requires the storage/set permission. :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. :type vault_base_url: str :param storage_account_name: The name of the storage account. :typ...
358,110
def _run(broker, graph=None, root=None, context=None, inventory=None): if not root: context = context or HostContext broker[context] = context() return dr.run(graph, broker=broker) if os.path.isdir(root): return process_dir(broker, root, graph, context, inventory=inventory...
run is a general interface that is meant for stand alone scripts to use when executing insights components. Args: root (str): None will causes a host collection in which command and file specs are run. A directory or archive path will cause collection from the directory or archi...
358,111
def decrypt(payload, private_key): cipher = PKCS1_v1_5.new(private_key) aes_key_str = cipher.decrypt(b64decode(payload.get("aes_key")), sentinel=None) aes_key = json.loads(aes_key_str.decode("utf-8")) key = b64decode(aes_key.get("key")) iv = b64decode(aes_key.get("iv")) ...
Decrypt an encrypted JSON payload and return the Magic Envelope document inside.
358,112
def create_vacation(body): arequest = requests.post(VACATIONS_URL, headers=HEADERS, data=json.dumps(body)) status_code = str(arequest.status_code) if status_code != : _LOGGER.error("Failed to create vacation. " + status_code) _LOGGER.error(arequest.json()) ...
Create a vacation.
358,113
def _apply_final_rules(self, phonetic, final_rules, language_arg, strip): if not final_rules: return phonetic phonetic = self._expand_alternates(phonetic) phonetic_array = phonetic.split() for k in range(len(phonetic_array)): phonetic ...
Apply a set of final rules to the phonetic encoding. Parameters ---------- phonetic : str The term to which to apply the final rules final_rules : tuple The set of final phonetic transform regexps language_arg : int An integer representing the...
358,114
def delete(self, album, **kwds): return self._client.post("/album/%s/delete.json" % self._extract_id(album), **kwds)["result"]
Endpoint: /album/<id>/delete.json Deletes an album. Returns True if successful. Raises a TroveboxError if not.
358,115
def cleaned_date(day, keep_datetime=False): if not isinstance(day, (date, datetime)): raise UnsupportedDateType( "`{}` is of unsupported type ({})".format(day, type(day))) if not keep_datetime: if hasattr(day, ) and callable(day.date): day = day.date() return day
Return a "clean" date type. * keep a `date` unchanged * convert a datetime into a date, * convert any "duck date" type into a date using its `date()` method.
358,116
def find(im_source, im_search): r = find_all(im_source, im_search, maxcnt=1) return r[0] if r else None
Only find maximum one object
358,117
def restore(self): clean_beam, beam_params = beam_fit(self.psf_data, self.cdelt1, self.cdelt2) if np.all(np.array(self.psf_data_shape)==2*np.array(self.dirty_data_shape)): self.restored = np.fft.fftshift(np.fft.irfft2(np.fft.rfft2(conv.pad_array(self.model))*np.fft.rfft2(clean_beam...
This method constructs the restoring beam and then adds the convolution to the residual.
358,118
def annotate(self, records, **kwargs): self.annotator_params.update(**kwargs) chunk_size = self.annotator_params.get(, self.CHUNK_SIZE) chunk = [] for i, record in enumerate(records): chunk.append(record) if (i + 1) % chunk_size == 0: ...
Annotate a set of records with stored fields. Args: records: A list or iterator (can be a Query object) chunk_size: The number of records to annotate at once (max 500). Returns: A generator that yields one annotated record at a time.
358,119
def fetch_query_from_pgdb(self, qname, query, con, cxn, limit=None, force=False): if con is None and cxn is None: LOG.error("ERROR: you need to supply connection information") return if con is None and cxn is not None: con = psycopg2.connect( ...
Supply either an already established connection, or connection parameters. The supplied connection will override any separate cxn parameter :param qname: The name of the query to save the output to :param query: The SQL query itself :param con: The already-established connection ...
358,120
def register(name=EopDb.DEFAULT_DBNAME): if isinstance(name, str): def wrapper(klass): EopDb.register(klass, name) return klass return wrapper else: klass = name EopDb.register...
Decorator for registering an Eop Database Example: .. code-block:: python @register class SqliteEnvDatabase: # sqlite implementation # this database will be known as 'default' @register('json') class JsonEnvDatabase: # JSON implementation ...
358,121
def get_forced_variation(self, experiment_key, user_id): if not self.is_valid: self.logger.error(enums.Errors.INVALID_DATAFILE.format()) return None if not validator.is_non_empty_string(experiment_key): self.logger.error(enums.Errors.INVALID_INPUT_ERROR.format()) return None ...
Gets the forced variation for a given user and experiment. Args: experiment_key: A string key identifying the experiment. user_id: The user ID. Returns: The forced variation key. None if no forced variation key.
358,122
def get_term_category_frequencies(self, scatterchartdata): term_ranker = scatterchartdata.term_ranker(self) if scatterchartdata.use_non_text_features: term_ranker.use_non_text_features() return term_ranker.get_ranks()
Applies the ranker in scatterchartdata to term-category frequencies. Parameters ---------- scatterchartdata : ScatterChartData Returns ------- pd.DataFrame
358,123
def __shpFileLength(self): start = self.shp.tell() self.shp.seek(0,2) size = self.shp.tell() size //= 2 self.shp.seek(start) return size
Calculates the file length of the shp file.
358,124
def append(self,*args,toSection=None,**kwargs): if not toSection and toSection is not 0: s = Section(*args,**kwargs) self.subs.append(s) self.lastSection = s s._parentSection = self s._reportSection = self._reportSection else: ...
Append a new section If toSection is None, section is appended to the main section/subs list. Else if toSection is int or (int,int,...), it gets added to the subs (subsection) list of the specified section. *args* and *kwargs* are processed by Section class initiation
358,125
def extractblocks(img, blksz, stpsz=None): if isinstance(img, tuple): img = np.stack(img, axis=-1) if stpsz is None: stpsz = (1,) * len(blksz) imgsz = img.shape numblocks = tuple(int(np.floor((a - b) / c) + 1) for a, b, c in zip_longest(...
Extract blocks from an ndarray signal into an ndarray. Parameters ---------- img : ndarray or tuple of ndarrays nd array of images, or tuple of images blksz : tuple tuple of block sizes, blocks are taken starting from the first index of img stpsz : tuple, optional (default None, c...
358,126
def any_shared(enum_one, enum_two): if not is_collection(enum_one) or not is_collection(enum_two): return False enum_one = enum_one if isinstance(enum_one, (set, dict)) else set(enum_one) enum_two = enum_two if isinstance(enum_two, (set, dict)) else set(enum_two) return any(e in enum_...
Truthy if any element in enum_one is present in enum_two
358,127
def to_sparse(self, fill_value=None, kind=): from pandas.core.sparse.api import SparseDataFrame return SparseDataFrame(self._series, index=self.index, columns=self.columns, default_kind=kind, default_fill_value=fill_value)
Convert to SparseDataFrame. Implement the sparse version of the DataFrame meaning that any data matching a specific value it's omitted in the representation. The sparse DataFrame allows for a more efficient storage. Parameters ---------- fill_value : float, default None...
358,128
def get_update_io_tiles(self, params, values): otile = self.get_update_tile(params, values) if otile is None: return [None]*3 ptile = self.get_padding_size(otile) or util.Tile(0, dim=otile.dim) otile = util.Tile.intersection(otile, self.oshape) if ...
Get the tiles corresponding to a particular section of image needed to be updated. Inputs are the parameters and values. Returned is the padded tile, inner tile, and slicer to go between, but accounting for wrap with the edge of the image as necessary.
358,129
def replace(self, resource, id_, document): args = self._es_args(resource, refresh=True) document.pop(, None) document.pop(, None) self._update_parent_args(resource, args, document) return self.elastic(resource).index(body=document, id=id_, **args)
Replace document in index.
358,130
def filter_noexpand_columns(columns): prefix_len = len(NOEXPAND_PREFIX) noexpand = [c[prefix_len:] for c in columns if c.startswith(NOEXPAND_PREFIX)] other = [c for c in columns if not c.startswith(NOEXPAND_PREFIX)] return other, noexpand
Return columns not containing and containing the noexpand prefix. Parameters ---------- columns: sequence of str A sequence of strings to be split Returns ------- Two lists, the first containing strings without the noexpand prefix, the second containing those that do with the pre...
358,131
def _get_pc_covered_str(self): pc = self.pc_covered if 0 < pc < self._near0: pc = self._near0 elif self._near100 < pc < 100: pc = self._near100 else: pc = round(pc, self._precision) return "%.*f" % (self._precision, pc)
Returns the percent covered, as a string, without a percent sign. Note that "0" is only returned when the value is truly zero, and "100" is only returned when the value is truly 100. Rounding can never result in either "0" or "100".
358,132
def align_circulation_with_z(self, circulation=None): if circulation is None: circulation = self.circulation() circulation = atleast_2d(circulation, insert_axis=1) cart = self.cartesian pos = cart.xyz vel = np.vstack((cart.v_x.value[None], ...
If the input orbit is a tube orbit, this function aligns the circulation axis with the z axis and returns a copy. Parameters ---------- circulation : array_like (optional) Array of bits that specify the axis about which the orbit circulates. If not provided, will...
358,133
def current() -> : curr = greenlet.getcurrent() if not isinstance(curr, Process): raise TypeError("Current greenlet does not correspond to a Process instance.") return cast(Process, greenlet.getcurrent())
Returns the instance of the process that is executing at the current moment.
358,134
def set(self, value: int): if not isinstance(value, int): raise self.exception("{} is not an integer".format(value)) if self.lsb0 and self.value % 2 == 1: raise self.exception("{} not power of two".format(value)) if not self.signed and value < 0: rais...
Set the immediate to a value. This function checks if the value is valid and will raise an :class:`InvalidImmediateException` if it doesn't. :param value: Value to set the immediate to :type value: int :raises InvalidImmediateException: value does not match immediate
358,135
def make_into_gene(self): for reverse in [True, False]: for frame in range(3): new_seq = copy.copy(self) if reverse: new_seq.revcomp() new_seq.seq = new_seq[frame:] if len(new_seq) % 3: n...
Tries to make into a gene sequence. Tries all three reading frames and both strands. Returns a tuple (new sequence, strand, frame) if it was successful. Otherwise returns None.
358,136
def init_UI(self): dw, dh = wx.DisplaySize() r1 = dw/1210. r2 = dw/640. self.GUI_RESOLUTION = min(r1, r2, 1) top_bar_2v_space = 5 top_bar_h_space = 10 spec_button_space = 10 side_bar_v_space = 10 ...
Set display variables (font, resolution of GUI, sizer proportions) then builds the Side bar panel, Top bar panel, and Plots scrolleing panel which are then placed placed together in a sizer and fit to the GUI wx.Frame
358,137
def import_string(name): mod = fp = None try: return sys.modules[name] except KeyError: pass try: fp, pathname, desc = imp.find_module(name) mod = imp.load_module(name, fp, pathname, desc) except ImportError: mod = None finally: ...
import module
358,138
def get(name=None): if name is None or name == : return _DEFAULT_PALETTE if isinstance(name, str): return PROJECT_PALETTES.get(name) or BUILT_IN_PALETTES.get(name)
Return a named Palette, or None if no such name exists. If ``name`` is omitted, the default value is used.
358,139
def register(app_name, modules): global INSTALLED_APPS_REGISTER mod_list = INSTALLED_APPS_REGISTER.get(app_name, []) if isinstance(modules, basestring): mod_list.append(modules) elif is_iterable(modules): mod_list.extend(modules) INSTALLED_APPS_REGISTER[app_name] = mod_list
simple module registering for later usage we don't want to import admin.py in models.py
358,140
def _mirbase_stats(data, out_dir): utils.safe_makedir(out_dir) out_file = os.path.join(out_dir, "%s_bcbio_mirbase.txt" % dd.get_sample_name(data)) out_file_novel = os.path.join(out_dir, "%s_bcbio_mirdeeep2.txt" % dd.get_sample_name(data)) mirbase_fn = data.get("seqbuster", None) if mirbase_fn: ...
Create stats from miraligner
358,141
def NewFromCmy(c, m, y, alpha=1.0, wref=_DEFAULT_WREF): return Color(Color.CmyToRgb(c, m, y), , alpha, wref)
Create a new instance based on the specifed CMY values. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: ...
358,142
def search(self, **kwargs): return super(ApiV4IPv6, self).get(self.prepare_url(, kwargs))
Method to search ipv6's based on extends search. :param search: Dict containing QuerySets to find ipv6's. :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. :param fields: Array containing fields to override d...
358,143
def upload_from_url_sync(cls, url, timeout=30, interval=0.3, until_ready=False, store=None, filename=None): ffu = cls.upload_from_url(url, store, filename) return ffu.wait(timeout=timeout, interval=interval, until_ready=until_ready)
Uploads file from given url and returns ``File`` instance. Args: - url (str): URL of file to upload to - store (Optional[bool]): Should the file be automatically stored upon upload. Defaults to None. - False - do not store file - True - st...
358,144
def from_compact_str(cls, str_pauli_term): coef_str, str_pauli_term = str_pauli_term.split() try: coef = int(coef_str) except ValueError: try: coef = float(coef_str) except ValueError: coef = complex(coef_str) ...
Construct a PauliTerm from the result of str(pauli_term)
358,145
def block_cm(cm): if np.any(cm.sum(1) == 0): return True if np.all(cm.sum(1) == 1): return True outputs = list(range(cm.shape[1])) def outputs_of(nodes): return np.where(cm[nodes, :].sum(0))[0] def inputs_to(nodes): return np.where(cm[:,...
Return whether ``cm`` can be arranged as a block connectivity matrix. If so, the corresponding mechanism/purview is trivially reducible. Technically, only square matrices are "block diagonal", but the notion of connectivity carries over. We test for block connectivity by trying to grow a block of node...
358,146
def resolve(str_or_obj): from rope.base.utils.pycompat import string_types if not isinstance(str_or_obj, string_types): return str_or_obj if not in str_or_obj: str_or_obj += mod_name, obj_name = str_or_obj.rsplit(, 1) __import__(mod_name) mod = sys.modules[mod_name] re...
Returns object from string
358,147
def internal_error(exception, template_path, is_admin, db=None): if db: try: db.session.rollback() except: pass title = str(exception) message = traceback.format_exc() preformat = True log.error(.format(title, message)) if current_app.config.get...
Render an "internal error" page. The following variables will be populated when rendering the template: title: The page title message: The body of the error message to display to the user preformat: Boolean stating whether to wrap the error message in a pre As well as rendering the error mess...
358,148
def update_journals(self): for field in record_get_field_instances(self.record, ): subs = field_get_subfield_instances(field) new_subs = [] volume_letter = "" journal_name = "" for idx, (key, value) in enumerate(subs): if key =...
773 journal translations.
358,149
def vertex_neighbors(self): graph = self.vertex_adjacency_graph neighbors = [list(graph.neighbors(i)) for i in range(len(self.vertices))] return np.array(neighbors)
The vertex neighbors of each vertex of the mesh, determined from the cached vertex_adjacency_graph, if already existent. Returns ---------- vertex_neighbors : (len(self.vertices),) int Represents immediate neighbors of each vertex along the edge of a triangle ...
358,150
def listEverything(matching=False): pages=pageNames() if matching: pages=[x for x in pages if matching in x] for i,page in enumerate(pages): pages[i]="%s%s (%s)"%(pageFolder(page),page,getPageType(page)) print("\n".join(sorted(pages)))
Prints every page in the project to the console. Args: matching (str, optional): if given, only return names with this string in it
358,151
def molecular_diameter(Tc=None, Pc=None, Vc=None, Zc=None, omega=None, Vm=None, Vb=None, CASRN=, AvailableMethods=False, Method=None): rs L-J molecular diameter. Values are available from one source with lookup based on CASRNs, or can be estimated from 9 CSP methods. Will automatically select ...
r'''This function handles the retrieval or calculation a chemical's L-J molecular diameter. Values are available from one source with lookup based on CASRNs, or can be estimated from 9 CSP methods. Will automatically select a data source to use if no Method is provided; returns None if the data is not a...
358,152
def _parse_desc(node): desc = if len(node) == 0: return + node.text + for n in node: if n.tag == : desc += + _join_lines(n.text) + elif n.tag == or n.tag == : desc += for c in n: if c.tag == : desc +=...
A quick'n'dirty description parser
358,153
def isTrackedDeviceConnected(self, unDeviceIndex): fn = self.function_table.isTrackedDeviceConnected result = fn(unDeviceIndex) return result
Returns true if there is a device connected in this slot.
358,154
def process_IN_IGNORED(self, raw_event): event_ = self.process_default(raw_event) self._watch_manager.del_watch(raw_event.wd) return event_
The watch descriptor raised by this event is now ignored (forever), it can be safely deleted from the watch manager dictionary. After this event we can be sure that neither the event queue nor the system will raise an event associated to this wd again.
358,155
def cached_path(self, path_or_url): assert path_or_url, "Expected non-empty string for path_or_url" remote_filename = split(path_or_url)[1] if self.is_url_format(path_or_url): local_filename = datacache.build_local_filename( ...
When downloading remote files, the default behavior is to name local files the same as their remote counterparts.
358,156
def unpacktar(tarfile, destdir): nullfd = open(os.devnull, "w") tarfile = cygpath(os.path.abspath(tarfile)) log.debug("unpack tar %s into %s", tarfile, destdir) try: check_call([TAR, , tarfile], cwd=destdir, stdout=nullfd, preexec_fn=_noumask) except Exception: ...
Unpack given tarball into the specified dir
358,157
def to_bytes(self): self.sanitize() bitstream = BitArray( % self.message_type) bitstream += BitArray( % self.proxy_map_reply) bitstream += self._reserved1 has_xtr_site_id = bool(self.xtr_id or self.site_id or self.for_rtr)...
Create bytes from properties
358,158
def next_tick(date, interval=15): now = dt.datetime.now(pytz.utc) live = False while now < date: time.sleep(interval) now = dt.datetime.now(pytz.utc) live = True return live
Only return when we reach given datetime
358,159
def clearAndSetComboBoxes(self, axesNames): logger.debug("Collector clearAndSetComboBoxes: {}".format(axesNames)) check_is_a_sequence(axesNames) row = 0 self._deleteComboBoxes(row) self.clear() self._setAxesNames(axesNames) self._createComboBoxes(row) ...
Removes all comboboxes.
358,160
def check_package(self, package, package_dir): try: return self.packages_checked[package] except KeyError: pass init_py = orig.build_py.check_package(self, package, package_dir) self.packages_checked[package] = init_py if not init_py or not self...
Check namespace packages' __init__ for declare_namespace
358,161
def disable(self): self._enabled = False for child in self.children: if isinstance(child, (Container, Widget)): child.disable()
Disable all the widgets in this container
358,162
def multipart_etag(digests): etag = hashlib.md5() count = 0 for dig in digests: count += 1 etag.update(binascii.a2b_hex(dig)) return .format(etag.hexdigest(), count)
Computes etag for multipart uploads :type digests: list of hex-encoded md5 sums (string) :param digests: The list of digests for each individual chunk. :rtype: string :returns: The etag computed from the individual chunks.
358,163
def draw_rand_pos(self, radius, z_min, z_max, min_r=np.array([0]), min_cell_interdist=10., **args): x = (np.random.rand(self.POPULATION_SIZE)-0.5)*radius*2 y = (np.random.rand(self.POPULATION_SIZE)-0.5)*radius*2 z = np.random.rand(self.POPULATION_SIZE)*(z_max - z_m...
Draw some random location within radius, z_min, z_max, and constrained by min_r and the minimum cell interdistance. Returned argument is a list of dicts [{'xpos', 'ypos', 'zpos'},]. Parameters ---------- radius : float Radius of population. z_min : float ...
358,164
def run_command(self, command, shell=True, env=None, execute=, return_code=None): self.log.info(, command) if env is None: env = os.environ if self.debug is False: stdout = open(os.devnull, ) else: stdout = subprocess.PIP...
Run a shell command. The options available: * ``shell`` to be enabled or disabled, which provides the ability to execute arbitrary stings or not. if disabled commands must be in the format of a ``list`` * ``env`` is an environment override and or manipulati...
358,165
def get_checkers(self): return [self] + [ c for _checkers in self._checkers.values() for c in _checkers if c is not self ]
return all available checkers as a list
358,166
def friendships(user_id, level=2): logging.info("getting friends for user %s", user_id) level -= 1 try: for friend_id in t.friend_ids(user_id): yield (user_id, friend_id) if level > 0: yield from friendships(friend_id, level) except requests.exceptio...
Pass in a user_id and you will be returned a generator of friendship tuples (user_id, friend_id). By default it will return the friend of a friend network (level=2), but you can expand this by settings the level parameter to either another number. But beware, it could run for a while!
358,167
def detach(self, listener): if listener in self.listeners: self.listeners.remove(listener)
Detach a listening object so that it won't receive any events anymore.
358,168
def add_account(self, account): if account.account_cookie not in self.account_list: if self.cash_available > account.init_cash: account.portfolio_cookie = self.portfolio_cookie account.user_cookie = self.user_cookie self.cash.append(self.cash_...
portfolio add a account/stratetgy
358,169
def reduce_(self): r new_nodes = _curve_helpers.reduce_pseudo_inverse(self._nodes) return Curve(new_nodes, self._degree - 1, _copy=False)
r"""Return a degree-reduced version of the current curve. .. _pseudo-inverse: https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_pseudoinverse Does this by converting the current nodes :math:`v_0, \ldots, v_n` to new nodes :math:`w_0, \ldots, w_{n - 1}` that correspond to ...
358,170
def complete(self): if self._possible is None: self._possible = [] for possible in self.names: c = Completion(self.context, self.names[possible], len(self.context.symbol)) self._possible.append(c) return self._possible
Gets a list of completion objects for the symbol under the cursor.
358,171
def as_id_dict(self): d = {} for row in self: if row.experiment_id not in d: d[row.experiment_id] = {} if (row.time_slide_id, row.veto_def_name, row.datatype, row.sim_proc_id) in d[row.experiment_id]: raise KeyError("duplicate entries in experiment_summary table") d[row.experiment_id][(row....
Return table as a dictionary mapping experiment_id, time_slide_id, veto_def_name, and sim_proc_id (if it exists) to the expr_summ_id.
358,172
def register_for_json(*args, **kwargs) -> Any: if DEBUG: print("register_for_json: args = {}".format(repr(args))) print("register_for_json: kwargs = {}".format(repr(kwargs))) if len(args) == 1 and len(kwargs) == 0 and c...
Class decorator to register classes with our JSON system. - If method is ``'provides_init_args_kwargs'``, the class provides a function .. code-block:: python def init_args_kwargs(self) -> Tuple[List[Any], Dict[str, Any]] that returns an ``(args, kwargs)`` tuple, suitable for passing t...
358,173
def energy(self): result = 0.0 for index1 in range(self.numc): for index2 in range(index1): if self.scaling[index1, index2] > 0: for se, ve in self.yield_pair_energies(index1, index2): result += se*ve*self.scaling[index1, i...
Compute the energy of the system
358,174
def common_parent_go_ids(goids, godag): rec = godag[goids[0]] candidates = rec.get_all_parents() candidates.update({goids[0]}) for goid in goids[1:]: rec = godag[goid] parents = rec.get_all_parents() parents.update({goid}) candidates.intersection...
This function finds the common ancestors in the GO tree of the list of goids in the input.
358,175
def ip_rtm_config_route_static_route_oif_vrf_static_route_next_vrf_dest(self, **kwargs): config = ET.Element("config") ip = ET.SubElement(config, "ip", xmlns="urn:brocade.com:mgmt:brocade-common-def") rtm_config = ET.SubElement(ip, "rtm-config", xmlns="urn:brocade.com:mgmt:brocade-rtm")...
Auto Generated Code
358,176
def block_resource_fitnesses(self, block: block.Block): node_fitnesses[node][resource.describe()] = False else: if max_fit - min_fit: node_fitnesses[node][resource.describe()] = (fitness - min_fit) / ...
Returns a map of nodename to average fitness value for this block. Assumes that required resources have been checked on all nodes.
358,177
def get_dimensions(js_dict, naming): dimensions = [] dim_names = [] if check_version_2(js_dict): dimension_dict = js_dict else: dimension_dict = js_dict[] for dim in dimension_dict[]: dim_name = js_dict[][dim][] if not dim_name: dim_name = dim ...
Get dimensions from input data. Args: js_dict (dict): dictionary containing dataset data and metadata. naming (string, optional): dimension naming. Possible values: 'label' \ or 'id'. Returns: dimensions (list): list of pandas data frames with dimension \ ...
358,178
async def genKeys(self, schemaId: ID, p_prime=None, q_prime=None) -> ( PublicKey, RevocationPublicKey): pk, sk = await self._primaryIssuer.genKeys(schemaId, p_prime, q_prime) pkR, skR = await self._nonRevocationIssuer.genRevocationKeys() pk = await self.wallet.submitPublicKe...
Generates and submits keys (both public and secret, primary and non-revocation). :param schemaId: The schema ID (reference to claim definition schema) :param p_prime: optional p_prime parameter :param q_prime: optional q_prime parameter :return: Submitted Public keys (bo...
358,179
def after_feature(context, feature): context.pctl.stop_all() shutil.rmtree(os.path.join(context.pctl.patroni_path, )) context.dcs_ctl.cleanup_service_tree() if feature.status == : shutil.copytree(context.pctl.output_dir, context.pctl.output_dir + )
stop all Patronis, remove their data directory and cleanup the keys in etcd
358,180
def _get_pkg_info(*packages, **kwargs): packages kwargs = salt.utils.args.clean_kwargs(**kwargs) failhard = kwargs.pop(, True) if kwargs: salt.utils.args.invalid_kwargs(kwargs) if __grains__[] == and __grains__[] < (12, 4): bin_var = else: bin_var = ret = [] ...
Return list of package information. If 'packages' parameter is empty, then data about all installed packages will be returned. :param packages: Specified packages. :param failhard: Throw an exception if no packages found. :return:
358,181
def Levenshtein_Distance(w1, w2): m, n = len(w1), len(w2) v1 = [i for i in range(n + 1)] v2 = [0 for i in range(n + 1)] for i in range(m): v2[0] = i + 1 for j in range(n): delCost = v1[j + 1] + 1 insCost = v2[j] + 1 ...
Computes Levenshtein Distance between two words Args: :param w1: str :param w2: str :return: int Examples: >>> Levenshtein.Levenshtein_Distance('noctis', 'noctem') 2 >>> Levenshtein.Levenshtein_Distance('nox', 'nochem') ...
358,182
def attach_virtual_server(self, ticket_id=None, virtual_id=None): return self.ticket.addAttachedVirtualGuest(virtual_id, id=ticket_id)
Attach a virtual server to a ticket. :param integer ticket_id: the id of the ticket to attach to :param integer virtual_id: the id of the virtual server to attach :returns: dict -- The new ticket attachment
358,183
def extension_supported(extension_name, request): for ext in list_extensions(request): if ext.name == extension_name: return True return False
Determine if nova supports a given extension name. Example values for the extension_name include AdminActions, ConsoleOutput, etc.
358,184
def wrapJobFn(fn, *args, **kwargs): if PromisedRequirement.convertPromises(kwargs): return PromisedRequirementJobFunctionWrappingJob.create(fn, *args, **kwargs) else: return JobFunctionWrappingJob(fn, *args, **kwargs)
Makes a Job out of a job function. \ Convenience function for constructor of :class:`toil.job.JobFunctionWrappingJob`. :param fn: Job function to be run with ``*args`` and ``**kwargs`` as arguments. \ See toil.job.JobFunctionWrappingJob for reserved keyword arguments used \ to specify r...
358,185
def _set_ethernet_interface(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=ethernet_interface.ethernet_interface, is_container=, presence=False, yang_name="ethernet-interface", rest_name="", parent=self, choice=(u, u), path_helper=self._path_helper, ...
Setter method for ethernet_interface, mapped from YANG variable /rbridge_id/router/router_bgp/router_bgp_attributes/neighbor/neighbor_ips/neighbor_addr/update_source/ethernet_interface (container) If this variable is read-only (config: false) in the source YANG file, then _set_ethernet_interface is considered a...
358,186
def reqAccountSummary(self, reqId, groupName, tags): return _swigibpy.EClient_reqAccountSummary(self, reqId, groupName, tags)
reqAccountSummary(EClient self, int reqId, IBString const & groupName, IBString const & tags)
358,187
def invoke(awsclient, function_name, payload, invocation_type=None, alias_name=ALIAS_NAME, version=None, outfile=None): log.debug(, function_name) client_lambda = awsclient.get_client() if invocation_type is None: invocation_type = if payload.startswith(): log.debug( % p...
Send a ping request to a lambda function. :param awsclient: :param function_name: :param payload: :param invocation_type: :param alias_name: :param version: :param outfile: write response to file :return: ping response payload
358,188
def combine_quantities(data, units=, magnitude=, list_of_dicts=False): try: from pint import UnitRegistry ureg = UnitRegistry() except ImportError: raise ImportError() list_of_dicts = if list_of_dicts else None data_flatten2d = flatten2d(data, list...
combine <unit,magnitude> pairs into pint.Quantity objects Parameters ---------- data : dict units : str name of units key magnitude : str name of magnitude key list_of_dicts: bool treat list of dicts as additional branches Examples -------- >>> from pprint i...
358,189
def is_lock(lock): if lock is None: return False for attr in "acquire", "release", "__enter__", "__exit__": if not hasattr(lock, attr): return False return True
Tests if the given lock is an instance of a lock class
358,190
def enable(name, start_type=, start_delayed=False, **kwargs): * modify(name, start_type=start_type, start_delayed=start_delayed) svcstat = info(name) if start_type.lower() == : return svcstat[].lower() == start_type.lower() and svcstat[] == start_delayed else: return svcstat[].lower...
Enable the named service to start at boot Args: name (str): The name of the service to enable. start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that...
358,191
def structured_mesh(shape = (2,2,2), dim = (1.,1.,1.)): shape = np.array(shape) dim = np.array(dim) Ne = shape.prod() Nn = (shape + 1).prod() nindex = np.arange(Nn) + 1 eindex = np.arange(Ne) + 1 coords = [ np.linspace(0., dim[i], shape[i] + 1) for i in range(len(shape...
Returns a structured mesh. :arg shape: 2 or 3 integers (eg: shape = (10, 10, 10)). :type shape: tuple :arg dim: 2 or 3 floats (eg: dim = (4., 2., 1.)) :type dim: tuple .. note:: This function does not use GMSH for mesh generation. >>> import argiope as ag >>> mesh =...
358,192
def search_exoplanet(exoplanet): base_url = "http://star-api.herokuapp.com/api/v1/exo_planets/" if not isinstance(exoplanet, str): raise ValueError( "The exoplanet arg you provided is not the type of str") else: base_url += exoplanet return dispatch_http_get(base_url)
It is also possible to query the exoplanets by label, here is an example of querying for the exoplanet labeled as 11 Com http://star-api.herokuapp.com/api/v1/exo_planets/11 Com
358,193
def _assert_relation_does_not_exists(self): relations = self.database._relations[self.related_to] existing = [r for r in relations if r[2] == self.related_name] if existing: error = ("The related name defined for the field , named , already exists " "on ...
Check if a relation with the current related_name doesn't already exists for the related model
358,194
def set_rate(self, rate): self._rate = self._player_interface_property(, dbus.Double(rate)) return self._rate
Set the playback rate of the video as a multiple of the default playback speed Examples: >>> player.set_rate(2) # Will play twice as fast as normal speed >>> player.set_rate(0.5) # Will play half speed
358,195
def wnsumd(window): assert isinstance(window, stypes.SpiceCell) assert window.dtype == 1 meas = ctypes.c_double() avg = ctypes.c_double() stddev = ctypes.c_double() shortest = ctypes.c_int() longest = ctypes.c_int() libspice.wnsumd_c(ctypes.byref(window), ctypes.byref(meas), ...
Summarize the contents of a double precision window. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnsumd_c.html :param window: Window to be summarized. :type window: spiceypy.utils.support_types.SpiceCell :return: Total measure of intervals in window, Average measur...
358,196
def get_smtlib_script_satisfiability(self, extra_constraints=(), extra_variables=()): try: e_csts = self._solver_backend.convert_list(extra_constraints + tuple(self.constraints)) e_variables = self._solver_backend.convert_list(extra_variables) variables, csts = self...
Return an smt-lib script that check the satisfiability of the current constraints :return string: smt-lib script
358,197
def fig_to_src(figure, image_format=, dpi=80): if image_format == : f = io.BytesIO() figure.savefig(f, format=image_format, dpi=dpi) f.seek(0) return png_to_src(f.read()) elif image_format == : f = io.StringIO() figure.savefig(f, format=image_format, dpi=dpi...
Convert a matplotlib figure to an inline HTML image. :param matplotlib.figure.Figure figure: Figure to display. :param str image_format: png (default) or svg :param int dpi: dots-per-inch for raster graphics. :rtype: str
358,198
def maybe_reexec_pex(compatibility_constraints): if os.environ.pop(, None): os.execve(target, cmdline, ENV.copy())
Handle environment overrides for the Python interpreter to use when executing this pex. This function supports interpreter filtering based on interpreter constraints stored in PEX-INFO metadata. If PEX_PYTHON is set in a pexrc, it attempts to obtain the binary location of the interpreter specified by PEX_PYTHON....
358,199
def platform_config_dir(): if LINUX: dpath_ = os.environ.get(, ) elif DARWIN: dpath_ = elif WIN32: dpath_ = os.environ.get(, ) else: raise NotImplementedError( % (sys.platform,)) dpath = normpath(expanduser(dpath_)) return dpath
Returns a directory which should be writable for any application This should be used for persistent configuration files. Returns: PathLike : path to the cahce dir used by the current operating system