code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def map_column(self, value): """ Applied to each column of every row returned by `rows`. Default behaviour is to escape special characters and identify any self.null_values. """ if value in self.null_values: return r'\\N' else: return default_esca...
Applied to each column of every row returned by `rows`. Default behaviour is to escape special characters and identify any self.null_values.
def load_data_and_model(items_as_dict, **context): """ Loads every file in a dictionary {key: filename}. The extension is either *pkl* and *onnx* and determines how it it loaded. If the value is not a string, the function assumes it was already loaded. """ res = {} for k, v in items_as_d...
Loads every file in a dictionary {key: filename}. The extension is either *pkl* and *onnx* and determines how it it loaded. If the value is not a string, the function assumes it was already loaded.
def content( self): """*The text content of this object (excluding title)* Much like the `raw_content` of an object, but does not include a title or tags. The initial indentation is also removed. For a document object the `content` is synonymous with `raw_content`. **Usage:** ...
*The text content of this object (excluding title)* Much like the `raw_content` of an object, but does not include a title or tags. The initial indentation is also removed. For a document object the `content` is synonymous with `raw_content`. **Usage:** .. code-block:: python ...
def fcoe_get_interface_input_fcoe_intf_rbridge_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") fcoe_get_interface = ET.Element("fcoe_get_interface") config = fcoe_get_interface input = ET.SubElement(fcoe_get_interface, "input") fcoe_in...
Auto Generated Code
def attach_run_command(cmd): """ Run a command when attaching Please do not call directly, this will execvp the command. This is to be used in conjunction with the attach method of a container. """ if isinstance(cmd, tuple): return _lxc.attach_run_command(cmd) el...
Run a command when attaching Please do not call directly, this will execvp the command. This is to be used in conjunction with the attach method of a container.
def as_batch_body(self): ''' return the current message as expected by batch body format''' if sys.version_info >= (3,) and isinstance(self.body, bytes): # It HAS to be string to be serialized in JSON body = self.body.decode('utf-8') else: # Python 2.7 people ...
return the current message as expected by batch body format
def _get_scalexy(self, ims_width, ims_height): """Returns scale_x, scale_y for bitmap display""" # Get cell attributes cell_attributes = self.code_array.cell_attributes[self.key] angle = cell_attributes["angle"] if abs(angle) == 90: scale_x = self.rect[3] / float(im...
Returns scale_x, scale_y for bitmap display
def generate_bond_subgraphs_from_break(bond_graph, atom1, atom2): """Splits the bond graph between two atoms to producing subgraphs. Notes ----- This will not work if there are cycles in the bond graph. Parameters ---------- bond_graph: networkx.Graph Graph of covalent bond network...
Splits the bond graph between two atoms to producing subgraphs. Notes ----- This will not work if there are cycles in the bond graph. Parameters ---------- bond_graph: networkx.Graph Graph of covalent bond network atom1: isambard.ampal.Atom First atom in the bond. atom2...
def import_locations(self, gpx_file): """Import GPX data files. ``import_locations()`` returns a series of lists representing track segments with :class:`Trackpoint` objects as contents. It expects data files in GPX format, as specified in `GPX 1.1 Schema Documentation`_, which...
Import GPX data files. ``import_locations()`` returns a series of lists representing track segments with :class:`Trackpoint` objects as contents. It expects data files in GPX format, as specified in `GPX 1.1 Schema Documentation`_, which is XML such as:: <?xml version="1.0...
def translate(self, word): """ pass in a word string that you would like to see probable matches for. """ if (word not in self.transmissions): raise NoMatchError('no matches found') else: trans = self.transmissions[word] # print out a s...
pass in a word string that you would like to see probable matches for.
def resolve(self, component_type, **kwargs): """ Resolves an instance of the component type. :param component_type: The type of the component (e.g. a class). :param kwargs: Overriding arguments to use (by name) instead of resolving them. :return: An instance of the component. ...
Resolves an instance of the component type. :param component_type: The type of the component (e.g. a class). :param kwargs: Overriding arguments to use (by name) instead of resolving them. :return: An instance of the component.
def delete_bundle(self, bundleId): """Returns success(True) or failure(False) on deleting a specific bundle present in the Globalization pipeline""" if not bundleId: return None url = self.__get_base_bundle_url() + "/" + bundleId response = self.__perform_res...
Returns success(True) or failure(False) on deleting a specific bundle present in the Globalization pipeline
def log(self, sequence, infoarray) -> None: """Pass the given |IoSequence| to a suitable instance of a |NetCDFVariableBase| subclass. When writing data, the second argument should be an |InfoArray|. When reading data, this argument is ignored. Simply pass |None|. (1) We prepare...
Pass the given |IoSequence| to a suitable instance of a |NetCDFVariableBase| subclass. When writing data, the second argument should be an |InfoArray|. When reading data, this argument is ignored. Simply pass |None|. (1) We prepare some devices handling some sequences by applying ...
def get_datetime_issue_in_progress(self, issue): """ If the issue is in progress, gets that most recent time that the issue became 'In Progress' """ histories = issue.changelog.histories for history in reversed(histories): history_items = history.items for...
If the issue is in progress, gets that most recent time that the issue became 'In Progress'
def port_profile_vlan_profile_switchport_trunk_trunk_vlan_classification_allowed_vlan_add_trunk_ctag_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") port_profile = ET.SubElement(config, "port-profile", xmlns="urn:brocade.com:mgmt:brocade-port-profile") ...
Auto Generated Code
def delete(self, model_class, **where): ''' Session().delete(Employee, id=1, name='John Doe') ''' assert hasattr(model_class, '_fields'), 'Not a valid class' table = model_class.__name__.lower() with Session() as conn: SQL = f'DELETE FROM {table} WHERE' ...
Session().delete(Employee, id=1, name='John Doe')
async def vc_check(ctx: commands.Context): # pylint: disable=unused-argument """ Check for whether VC is available in this bot. """ if not discord.voice_client.has_nacl: raise commands.CheckFailure("voice cannot be used because PyNaCl is not loaded") if not discord.opus.is_loaded(): ...
Check for whether VC is available in this bot.
def batch(iterable, length): """ Returns a series of iterators across the inputted iterable method, broken into chunks based on the inputted length. :param iterable | <iterable> | (list, tuple, set, etc.) length | <int> :credit http://en.sharejs.com/python/14362...
Returns a series of iterators across the inputted iterable method, broken into chunks based on the inputted length. :param iterable | <iterable> | (list, tuple, set, etc.) length | <int> :credit http://en.sharejs.com/python/14362 :return <generator> ...
def add_edge(self, fr, to): """ Add an outward edge to a vertex :param fr: The source vertex. :param to: The name of the outward edge. """ if fr not in set(self.graph.vs): # ToDo: find out why item can be in set but not dict raise ValueError('can not connect unknown...
Add an outward edge to a vertex :param fr: The source vertex. :param to: The name of the outward edge.
def get_induced_subhypergraph(self, nodes): """Gives a new hypergraph that is the subhypergraph of the current hypergraph induced by the provided set of nodes. That is, the induced subhypergraph's node set corresponds precisely to the nodes provided, and the coressponding hyperedges in t...
Gives a new hypergraph that is the subhypergraph of the current hypergraph induced by the provided set of nodes. That is, the induced subhypergraph's node set corresponds precisely to the nodes provided, and the coressponding hyperedges in the subhypergraph are only those from the origin...
def changeTarget(self, vehID, edgeID): """changeTarget(string, string) -> None The vehicle's destination edge is set to the given edge id. The route is rebuilt. """ self._connection._sendStringCmd( tc.CMD_SET_VEHICLE_VARIABLE, tc.CMD_CHANGETARGET, vehID, edgeID)
changeTarget(string, string) -> None The vehicle's destination edge is set to the given edge id. The route is rebuilt.
def plot_number_observer_with_matplotlib(*args, **kwargs): """ Generate a plot from NumberObservers and show it on IPython notebook with matplotlib. Parameters ---------- obs : NumberObserver (e.g. FixedIntervalNumberObserver) fmt : str, optional opt : dict, optional matplotlib ...
Generate a plot from NumberObservers and show it on IPython notebook with matplotlib. Parameters ---------- obs : NumberObserver (e.g. FixedIntervalNumberObserver) fmt : str, optional opt : dict, optional matplotlib plot options. Examples -------- >>> plot_number_observer(o...
def setCollapsable(self, state): """ Sets whether or not this toolbar is collapsable. :param state | <bool> """ if self._collapsable == state: return self._collapsable = state self.clear()
Sets whether or not this toolbar is collapsable. :param state | <bool>
def qteCloseQtmacs(self): """ Close Qtmacs. First kill all applets, then shut down Qtmacs. |Args| * **None** |Returns| * **None** |Raises| * **None** """ # Announce the shutdown. msgObj = QtmacsMessage() msgOb...
Close Qtmacs. First kill all applets, then shut down Qtmacs. |Args| * **None** |Returns| * **None** |Raises| * **None**
def adev(data, rate=1.0, data_type="phase", taus=None): """ Allan deviation. Classic - use only if required - relatively poor confidence. .. math:: \\sigma^2_{ADEV}(\\tau) = { 1 \\over 2 \\tau^2 } \\langle ( {x}_{n+2} - 2x_{n+1} + x_{n} )^2 \\rangle = { 1 \\over 2 (N-2) \\tau^2...
Allan deviation. Classic - use only if required - relatively poor confidence. .. math:: \\sigma^2_{ADEV}(\\tau) = { 1 \\over 2 \\tau^2 } \\langle ( {x}_{n+2} - 2x_{n+1} + x_{n} )^2 \\rangle = { 1 \\over 2 (N-2) \\tau^2 } \\sum_{n=1}^{N-2} ( {x}_{n+2} - 2x_{n+1} + x_{n} )^2 ...
def locked_put(self, credentials): """Write a credentials to the SQLAlchemy datastore. Args: credentials: :class:`oauth2client.Credentials` """ filters = {self.key_name: self.key_value} query = self.session.query(self.model_class).filter_by(**filters) entity ...
Write a credentials to the SQLAlchemy datastore. Args: credentials: :class:`oauth2client.Credentials`
def set_attributes(self, session_key, attributes): """ :type attributes: dict """ session = self._lookup_required_session(session_key) session.set_attributes(attributes) self.session_handler.on_change(session)
:type attributes: dict
def _guess_type_from_validator(validator): """ Utility method to return the declared type of an attribute or None. It handles _OptionalValidator and _AndValidator in order to unpack the validators. :param validator: :return: the type of attribute declared in an inner 'instance_of' validator (if any...
Utility method to return the declared type of an attribute or None. It handles _OptionalValidator and _AndValidator in order to unpack the validators. :param validator: :return: the type of attribute declared in an inner 'instance_of' validator (if any is found, the first one is used) or None if no inn...
def connect(self): """ Connect socket connection to Chromecast device. Must only be called if the worker thread will not be started. """ try: self.initialize_connection() except ChromecastConnectionError: self._report_connection_status( ...
Connect socket connection to Chromecast device. Must only be called if the worker thread will not be started.
def _add_foreign_key_constraint(self, constraint): """ Adds a foreign key constraint. :param constraint: The constraint to add :type constraint: ForeignKeyConstraint :rtype: Table """ constraint.set_local_table(self) if constraint.get_name(): ...
Adds a foreign key constraint. :param constraint: The constraint to add :type constraint: ForeignKeyConstraint :rtype: Table
def loop(self, callback=None, daemonize=False, **args): """ Events are read only one time every min(read_freq, timeout) seconds at best and only if the size to read is >= threshold. After this method returns it must not be called again for the same instance. @param callb...
Events are read only one time every min(read_freq, timeout) seconds at best and only if the size to read is >= threshold. After this method returns it must not be called again for the same instance. @param callback: Functor called after each event processing iteration. ...
def preprocess(lat,lon,sla, N_min=None, per_min=15.0, max_gap=None, leave_gaps=False, remove_edges=True, interp_over_continents=False, truncate_if_continents=True, discard_continental_gaps = T...
Preprocessing of the SLA data :: * process positions : * interpolate over gaps * find continents (extend the positions over continents to get the discontinuity) * find track edges * find gap lengths * clean SLA data:: * Remove gaps greater than ma...
def customWalker(node, space=''): """ A convenience function to ease debugging. It will print the node structure that's returned from CommonMark The usage would be something like: >>> content = Parser().parse('Some big text block\n===================\n\nwith content\n') >>> customWalker(content) ...
A convenience function to ease debugging. It will print the node structure that's returned from CommonMark The usage would be something like: >>> content = Parser().parse('Some big text block\n===================\n\nwith content\n') >>> customWalker(content) document heading text S...
def contrast_rms(data, *kwargs): """ Compute RMS contrast norm of an image """ av = np.average(data, *kwargs) mal = 1 / (data.shape[0] * data.shape[1]) return np.sqrt(mal * np.sum(np.square(data - av)))
Compute RMS contrast norm of an image
def Items(cls): """non-class attributes ordered by alphabetical order. :: >>> class MyClass(Constant): ... a = 1 # non-class attributre ... b = 2 # non-class attributre ... ... class C(Constant): ... pass ...
non-class attributes ordered by alphabetical order. :: >>> class MyClass(Constant): ... a = 1 # non-class attributre ... b = 2 # non-class attributre ... ... class C(Constant): ... pass ... ... ...
def get_template_field(env, fullname): """ Gets template fields for specific operator class. :param fullname: Full path to operator class. For example: ``airflow.contrib.operators.gcp_vision_operator.CloudVisionProductSetCreateOperator`` :return: List of template field :rtype: list[str] ...
Gets template fields for specific operator class. :param fullname: Full path to operator class. For example: ``airflow.contrib.operators.gcp_vision_operator.CloudVisionProductSetCreateOperator`` :return: List of template field :rtype: list[str]
def analyze(self, handle, filename): """Submit a file for analysis. :type handle: File handle :param handle: Handle to file to upload for analysis. :type filename: str :param filename: File name. :rtype: str :return: File ID as a string """ ...
Submit a file for analysis. :type handle: File handle :param handle: Handle to file to upload for analysis. :type filename: str :param filename: File name. :rtype: str :return: File ID as a string
def regular_index(*dfs): """ Change & restore the indices of dataframes Dataframe with duplicate values can be hard to work with. When split and recombined, you cannot restore the row order. This can be the case even if the index has unique but irregular/unordered. This contextmanager resets th...
Change & restore the indices of dataframes Dataframe with duplicate values can be hard to work with. When split and recombined, you cannot restore the row order. This can be the case even if the index has unique but irregular/unordered. This contextmanager resets the unordered indices of any datafr...
def get_languages(self): """ Returns a list of all language options available in TheTVDB. :return: a python dictionary with either the result of the search or an error from TheTVDB. """ raw_response = requests_util.run_request('get', self.API_BASE_URL + '/languages', ...
Returns a list of all language options available in TheTVDB. :return: a python dictionary with either the result of the search or an error from TheTVDB.
def get_os_file_names(files): """ returns file names :param files: list of strings and\\or :class:`file_configuration_t` instances. :type files: list """ fnames = [] for f in files: if utils.is_str(f): fnames.app...
returns file names :param files: list of strings and\\or :class:`file_configuration_t` instances. :type files: list
def with_sql_context(application_name, conf=None): """Context manager for a spark context Returns ------- sc : SparkContext sql_context: SQLContext Examples -------- Used within a context manager >>> with with_sql_context("MyApplication") as (sc, sql_context): ... import py...
Context manager for a spark context Returns ------- sc : SparkContext sql_context: SQLContext Examples -------- Used within a context manager >>> with with_sql_context("MyApplication") as (sc, sql_context): ... import pyspark ... # Do stuff ... pass
def removeAll(self): """ Remove all selectables, and return a list of them. """ rv = self._removeAll(self._reads, self._writes) return rv
Remove all selectables, and return a list of them.
def check_access(self, item, context): """Checks whether a current user has an access to a certain item. :param TreeItemBase item: :param Context context: :rtype: bool """ if hasattr(self.current_request.user.is_authenticated, '__call__'): authenticated = sel...
Checks whether a current user has an access to a certain item. :param TreeItemBase item: :param Context context: :rtype: bool
def calc_qv_v1(self): """Calculate the discharge of both forelands after Manning-Strickler. Required control parameters: |EKV| |SKV| |Gef| Required flux sequence: |AV| |UV| Calculated flux sequence: |lstream_fluxes.QV| Examples: For appropriate strict...
Calculate the discharge of both forelands after Manning-Strickler. Required control parameters: |EKV| |SKV| |Gef| Required flux sequence: |AV| |UV| Calculated flux sequence: |lstream_fluxes.QV| Examples: For appropriate strictly positive values: ...
def probe(self, axis: str, distance: float) -> Dict[str, float]: """ Run a probe and return the new position dict """ return self._smoothie_driver.probe_axis(axis, distance)
Run a probe and return the new position dict
def get_metrics_data_queue(self, name, queue_name, metric, rollup, filter_expresssion): ''' Retrieves the list of supported metrics for this namespace and queue name: Name of the service bus namespace. queue_name: Name of the service bus queue in this namespace. ...
Retrieves the list of supported metrics for this namespace and queue name: Name of the service bus namespace. queue_name: Name of the service bus queue in this namespace. metric: name of a supported metric rollup: name of a supported rollu...
def active_pixmap(self, value): """ Setter for **self.__active_pixmap** attribute. :param value: Attribute value. :type value: QPixmap """ if value is not None: assert type(value) is QPixmap, "'{0}' attribute: '{1}' type is not 'QPixmap'!".format( ...
Setter for **self.__active_pixmap** attribute. :param value: Attribute value. :type value: QPixmap
def stream_parameters(streams, no_duplicates=True, exclude=['name']): """ Given a list of streams, return a flat list of parameter name, excluding those listed in the exclude list. If no_duplicates is enabled, a KeyError will be raised if there are parameter name clashes across the streams. """...
Given a list of streams, return a flat list of parameter name, excluding those listed in the exclude list. If no_duplicates is enabled, a KeyError will be raised if there are parameter name clashes across the streams.
def itemfreq(inlist): """ Returns a list of pairs. Each pair consists of one of the scores in inlist and it's frequency count. Assumes a 1D list is passed. Usage: litemfreq(inlist) Returns: a 2D frequency table (col [0:n-1]=scores, col n=frequencies) """ scores = pstat.unique(inlist) scores.sort() ...
Returns a list of pairs. Each pair consists of one of the scores in inlist and it's frequency count. Assumes a 1D list is passed. Usage: litemfreq(inlist) Returns: a 2D frequency table (col [0:n-1]=scores, col n=frequencies)
def iter_acgt_geno(self): """Iterates over genotypes (ACGT format). Returns: tuple: The name of the marker as a string, and its genotypes as a :py:class:`numpy.ndarray` (ACGT format). """ # Need to iterate over itself, and modify the actual genotypes for...
Iterates over genotypes (ACGT format). Returns: tuple: The name of the marker as a string, and its genotypes as a :py:class:`numpy.ndarray` (ACGT format).
def delete_speaker(self, speaker_uri): """Delete an speaker from a collection :param speaker_uri: the URI that references the speaker :type speaker_uri: String :rtype: Boolean :returns: True if the speaker was deleted :raises: APIError if the request was not successful...
Delete an speaker from a collection :param speaker_uri: the URI that references the speaker :type speaker_uri: String :rtype: Boolean :returns: True if the speaker was deleted :raises: APIError if the request was not successful
def _insert_matplotlib_configs(c): """Add configurations related to matplotlib's plot directive to the state. """ if 'extensions' not in c: c['extensions'] = [] try: import matplotlib.sphinxext.plot_directive c['extensions'] += [matplotlib.sphinxext.plot_directive.__name__] ...
Add configurations related to matplotlib's plot directive to the state.
def wait(self, cadence=2, sendspec=None): """Does not return until all background commands are completed. """ shutit = self.shutit shutit.log('In wait.', level=logging.DEBUG) if sendspec: cadence = sendspec.wait_cadence shutit.log('Login stack is:\n' + str(self.login_stack), level=logging.DEBUG) while ...
Does not return until all background commands are completed.
def encode(cls, value): """ take an integer and turn it into a string representation to write into redis. :param value: int :return: str """ try: coerced = int(value) if coerced + 0 == value: return repr(coerced) e...
take an integer and turn it into a string representation to write into redis. :param value: int :return: str
def connect_to_database(host=None, port=None, connect=False, **kwargs): """ Explicitly begins a database connection for the application (if this function is not called, a connection is created when it is first needed). Takes arguments identical to pymongo.MongoClient.__init__ @param host: ...
Explicitly begins a database connection for the application (if this function is not called, a connection is created when it is first needed). Takes arguments identical to pymongo.MongoClient.__init__ @param host: the hostname to connect to @param port: the port to connect to @param connec...
def get_filter_pillar(filter_name, pillar_key='acl', pillarenv=None, saltenv=None): ''' Helper that can be used inside a state SLS, in order to get the filter configuration given its name. filter_name The name of the filter. ...
Helper that can be used inside a state SLS, in order to get the filter configuration given its name. filter_name The name of the filter. pillar_key The root key of the whole policy config. pillarenv Query the master to generate fresh pillar data on the fly, specificall...
def post(self, request, *args, **kwargs): """ Handles POST requests. """ return self.subscribe(request, *args, **kwargs)
Handles POST requests.
def read(path, saltenv='base'): ''' Read the contents of a text file, if the file is binary then ''' # Return a dict of paths + content ret = [] files = find(path, saltenv) for fn_ in files: full = next(six.iterkeys(fn_)) form = fn_[full] if form == 'txt': ...
Read the contents of a text file, if the file is binary then
def tryCppComment(self, block): """C++ comment checking. when we want to insert slashes: #, #/, #! #/<, #!< and ##... return: filler string or null, if not in a star comment NOTE: otherwise comments get skipped generally and we use the last code-line """ if not block.prev...
C++ comment checking. when we want to insert slashes: #, #/, #! #/<, #!< and ##... return: filler string or null, if not in a star comment NOTE: otherwise comments get skipped generally and we use the last code-line
def _get_content_range(start: Optional[int], end: Optional[int], total: int) -> str: """Returns a suitable Content-Range header: >>> print(_get_content_range(None, 1, 4)) bytes 0-0/4 >>> print(_get_content_range(1, 3, 4)) bytes 1-2/4 >>> print(_get_content_range(None, None, 4)) bytes 0-3/4 ...
Returns a suitable Content-Range header: >>> print(_get_content_range(None, 1, 4)) bytes 0-0/4 >>> print(_get_content_range(1, 3, 4)) bytes 1-2/4 >>> print(_get_content_range(None, None, 4)) bytes 0-3/4
async def wasAdded(self, node): ''' Fire the onAdd() callbacks for node creation. ''' for func in self.onadds: try: retn = func(node) if s_coro.iscoro(retn): await retn except asyncio.CancelledError: ...
Fire the onAdd() callbacks for node creation.
def get_device_category(self, cat): """Return the device category and name given the category id""" if cat in self.device_categories: return self.device_categories[cat] else: return False
Return the device category and name given the category id
def get_temp_tag_for_repo_creation(self): """ If not already cached, fetch the creation date of the repo, cache it and return the special value indicating the creation of the repo. :rtype: str :return: value indicating the creation """ tag_date = self.tag_times_d...
If not already cached, fetch the creation date of the repo, cache it and return the special value indicating the creation of the repo. :rtype: str :return: value indicating the creation
def update(self, client=None): """Sends all properties in a PUT request. Updates the ``_properties`` with the response from the backend. If :attr:`user_project` is set, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ...
Sends all properties in a PUT request. Updates the ``_properties`` with the response from the backend. If :attr:`user_project` is set, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client:...
def get_context_data(cls, instance): ''' Generate a Context Parameters object based on the instance's configuration. We do not use the hlapi currently, but the rfc3413.oneliner.cmdgen accepts Context Engine Id (always None for now) and Context Name parameters. ''' ...
Generate a Context Parameters object based on the instance's configuration. We do not use the hlapi currently, but the rfc3413.oneliner.cmdgen accepts Context Engine Id (always None for now) and Context Name parameters.
def setup(app): """Sphinx extension: run sphinx-apidoc.""" event = 'builder-inited' if six.PY3 else b'builder-inited' app.connect(event, on_init)
Sphinx extension: run sphinx-apidoc.
def get_dashboard_info(adapter, institute_id=None, slice_query=None): """Returns cases with phenotype If phenotypes are provided search for only those Args: adapter(adapter.MongoAdapter) institute_id(str): an institute _id slice_query(str): query to filter cases to obtain stat...
Returns cases with phenotype If phenotypes are provided search for only those Args: adapter(adapter.MongoAdapter) institute_id(str): an institute _id slice_query(str): query to filter cases to obtain statistics for. Returns: data(dict): Dictionary with relevant inform...
def draw_boxes(im, boxes, labels=None, color=None): """ Args: im (np.ndarray): a BGR image in range [0,255]. It will not be modified. boxes (np.ndarray): a numpy array of shape Nx4 where each row is [x1, y1, x2, y2]. labels: (list[str] or None) color: a 3-tuple BGR color (in rang...
Args: im (np.ndarray): a BGR image in range [0,255]. It will not be modified. boxes (np.ndarray): a numpy array of shape Nx4 where each row is [x1, y1, x2, y2]. labels: (list[str] or None) color: a 3-tuple BGR color (in range [0, 255]) Returns: np.ndarray: a new image.
def cleanup_custom_options(id, weakref=None): """ Cleans up unused custom trees if all objects referencing the custom id have been garbage collected or tree is otherwise unreferenced. """ try: if Store._options_context: return weakrefs = Store._weakrefs.get(id, []) ...
Cleans up unused custom trees if all objects referencing the custom id have been garbage collected or tree is otherwise unreferenced.
def convert_to_str(input_string): """ Returns a string of the input compatible between py2 and py3 :param input_string: :return: """ if sys.version < '3': if isinstance(input_string, str) \ or isinstance(input_string, unicode): # pragma: no cover py3 return i...
Returns a string of the input compatible between py2 and py3 :param input_string: :return:
def nominal_step(x=None): """Return nominal step""" if x is None: return 1.0 return np.log1p(np.abs(x)).clip(min=1.0)
Return nominal step
def new(cls, access_token, environment='prod'): '''Creates a new cross-service client.''' return cls( storage_client=StorageClient.new(access_token, environment=environment))
Creates a new cross-service client.
def columnize(items, width=None, file=sys.stdout): """ Smart display width handling when showing a list of stuff. """ if not items: return if width is None: width = shutil.get_terminal_size()[0] if file is sys.stdout else 80 items = [rendering.vtmlrender(x) for x in items] maxcol = m...
Smart display width handling when showing a list of stuff.
def compile(self, ctx, args, dependency_classpath, upstream_analysis, settings, compiler_option_sets, zinc_file_manager, javac_plugin_map, scalac_plugin_map): """Invoke the compiler. Subclasses must implement. Must raise TaskError on compile failure. :param CompileContext ctx: ...
Invoke the compiler. Subclasses must implement. Must raise TaskError on compile failure. :param CompileContext ctx: A CompileContext for the target to compile. :param list args: Arguments to the compiler (such as javac or zinc). :param list dependency_classpath: List of classpath entries of type Class...
def query_image_content(self, image, content_type=""): '''**Description** Find the image with the tag <image> and return its content. **Arguments** - image: Input image can be in the following formats: registry/repo:tag - content_type: The content type can be one of ...
**Description** Find the image with the tag <image> and return its content. **Arguments** - image: Input image can be in the following formats: registry/repo:tag - content_type: The content type can be one of the following types: - os: Operating System Packag...
def mousePressEvent( self, event ): """ Make sure on a mouse release event that we have a current item. If no item is current, then our edit item will become current. :param event | <QMouseReleaseEvent> """ item = self.itemAt(event.pos()) ...
Make sure on a mouse release event that we have a current item. If no item is current, then our edit item will become current. :param event | <QMouseReleaseEvent>
def _decrement_current_byte(self): """ Decrements the value of the current byte at the pointer. If the result is below 0, then it will overflow to 255 """ # If the current byte is uninitialized, then decrementing it will make it the max cell size # Otherwise, if it's alre...
Decrements the value of the current byte at the pointer. If the result is below 0, then it will overflow to 255
def generate_timestamp(fmt=None): """ Generate a timestamp to mark when this file was last modified. :param str fmt: Special format instructions :return str: YYYY-MM-DD format, or specified format """ if fmt: time = dt.datetime.now().strftime(fmt) else: time = dt.date.today(...
Generate a timestamp to mark when this file was last modified. :param str fmt: Special format instructions :return str: YYYY-MM-DD format, or specified format
def run(self): """ Wrapper function for TUN and serial port monitoring Wraps the necessary functions to loop over until self._isRunning threading.Event() is set(). This checks for data on the TUN/serial interfaces and then sends data over the appropriate interface. This ...
Wrapper function for TUN and serial port monitoring Wraps the necessary functions to loop over until self._isRunning threading.Event() is set(). This checks for data on the TUN/serial interfaces and then sends data over the appropriate interface. This function is automatically run when ...
def slice(self, start_time, end_time, strict=False): ''' Slice the annotation and return as a new `Annotation` object. Slicing has the same effect as trimming (see `Annotation.trim`) except that while trimming does not modify the start time of the annotation or the observations ...
Slice the annotation and return as a new `Annotation` object. Slicing has the same effect as trimming (see `Annotation.trim`) except that while trimming does not modify the start time of the annotation or the observations it contains, slicing will set the new annotation's start time to ...
def move_stage(self, stage, new_index, edit_version=None, **kwargs): ''' :param stage: A number for the stage index (for the nth stage, starting from 0), or a string of the stage index, name, or ID :type stage: int or string :param new_index: The new position in the order of stages that ...
:param stage: A number for the stage index (for the nth stage, starting from 0), or a string of the stage index, name, or ID :type stage: int or string :param new_index: The new position in the order of stages that the specified stage should have (where 0 indicates the first stage) :type new_ind...
def _read_certificates(self): """ Reads end-entity and intermediate certificate information from the TLS session """ cert_context_pointer_pointer = new(crypt32, 'CERT_CONTEXT **') result = secur32.QueryContextAttributesW( self._context_handle_pointer, ...
Reads end-entity and intermediate certificate information from the TLS session
def _transform(self, q): """ exp(i q.r(i)) v(i)""" s2p = self._primitive.get_supercell_to_primitive_map() p2s = self._primitive.get_primitive_to_supercell_map() num_s = self._supercell.get_number_of_atoms() num_p = self._primitive.get_number_of_atoms() v = self._velocit...
exp(i q.r(i)) v(i)
def clear_empty(self): """Remove flair that is not visible or has been set to empty.""" for flair in self.current_flair(): if not flair['flair_text'] and not flair['flair_css_class']: print(self.reddit.flair.update(flair['user'])) print('Removed flair for {0}'...
Remove flair that is not visible or has been set to empty.
def connection(self, name=None): """return a named connection. This function will return a named connection by either finding one in its pool by the name or creating a new one. If no name is given, it will use the name of the current executing thread as the name of the connecti...
return a named connection. This function will return a named connection by either finding one in its pool by the name or creating a new one. If no name is given, it will use the name of the current executing thread as the name of the connection. parameters: name - ...
def individual(self, ind_id=None): """Return a individual object Args: ind_id (str): A individual id Returns: individual (puzzle.models.individual) """ for ind_obj in self.individuals: if ind_obj.ind_id == ...
Return a individual object Args: ind_id (str): A individual id Returns: individual (puzzle.models.individual)
def array(shape, dtype=_np.float64, autolock=False): """Factory method for shared memory arrays supporting all numpy dtypes.""" assert _NP_AVAILABLE, "To use the shared array object, numpy must be available!" if not isinstance(dtype, _np.dtype): dtype = _np.dtype(dtype) # Not bothering to transl...
Factory method for shared memory arrays supporting all numpy dtypes.
def permittivity_IAPWS(T, rho): r'''Calculate the relative permittivity of pure water as a function of. temperature and density. Assumes the 1997 IAPWS [1]_ formulation. .. math:: \epsilon(\rho, T) =\frac{1 + A + 5B + (9 + 2A + 18B + A^2 + 10AB + 9B^2)^{0.5}}{4(1-B)} A(\rh...
r'''Calculate the relative permittivity of pure water as a function of. temperature and density. Assumes the 1997 IAPWS [1]_ formulation. .. math:: \epsilon(\rho, T) =\frac{1 + A + 5B + (9 + 2A + 18B + A^2 + 10AB + 9B^2)^{0.5}}{4(1-B)} A(\rho, T) = \frac{N_A\mu^2\rho g}{M\epsi...
async def join(self, ctx): """Sends you the bot invite link.""" perms = discord.Permissions.none() perms.read_messages = True perms.send_messages = True perms.manage_messages = True perms.embed_links = True perms.read_message_history = True perms.attach_fi...
Sends you the bot invite link.
def save_form(self, commit=True): """ This calls Django's ``ModelForm.save()``. It only takes care of saving this actual form, and leaves the nested forms and formsets alone. We separate this out of the :meth:`~django_superform.forms.SuperModelForm.save` method to make ...
This calls Django's ``ModelForm.save()``. It only takes care of saving this actual form, and leaves the nested forms and formsets alone. We separate this out of the :meth:`~django_superform.forms.SuperModelForm.save` method to make extensibility easier.
def make(base_classes=(), have_mt=False): """Use this static method to build a model class that possibly derives from other classes. If have_mt is True, then returned class will take into account multi-threading issues when dealing with observable properties.""" good_bc = ModelF...
Use this static method to build a model class that possibly derives from other classes. If have_mt is True, then returned class will take into account multi-threading issues when dealing with observable properties.
def add_arguments(self, parser): """ Command arguments. """ super(Command, self).add_arguments(parser) parser.add_argument('--badges', action='store', dest='badges', type=str) parser.add...
Command arguments.
def set_app_data(self, tnum, tdata): """set the values of the tag.""" if not isinstance(tdata, str): raise TypeError("tag data must be str") self.tagClass = Tag.applicationTagClass self.tagNumber = tnum self.tagLVT = len(tdata) self.tagData = tdata
set the values of the tag.
def run_protocol(protocol_code: Any = None, protocol_json: Dict[Any, Any] = None, simulate: bool = False, context: ProtocolContext = None): """ Create a ProtocolRunner instance from one of a variety of protocol sources. :param protocol_bytes: If the protoc...
Create a ProtocolRunner instance from one of a variety of protocol sources. :param protocol_bytes: If the protocol is a Python protocol, pass the file contents here. :param protocol_json: If the protocol is a json file, pass the contents here. :param simulate: True to simulate; False to execute...
def _set_ipv6_address(self, v, load=False): """ Setter method for ipv6_address, mapped from YANG variable /interface/fortygigabitethernet/ipv6/ipv6_config/address/ipv6_address (list) If this variable is read-only (config: false) in the source YANG file, then _set_ipv6_address is considered as a private ...
Setter method for ipv6_address, mapped from YANG variable /interface/fortygigabitethernet/ipv6/ipv6_config/address/ipv6_address (list) If this variable is read-only (config: false) in the source YANG file, then _set_ipv6_address is considered as a private method. Backends looking to populate this variable s...
def cublasDsbmv(handle, uplo, n, k, alpha, A, lda, x, incx, beta, y, incy): """ Matrix-vector product for real symmetric-banded matrix. """ status = _libcublas.cublasDsbmv_v2(handle, _CUBLAS_FILL_MODE[uplo], n, k, ctypes.byr...
Matrix-vector product for real symmetric-banded matrix.
def primary_measures(self): """Iterate over the primary columns, columns which do not have a parent Also sets the property partition_stats to the stats collection for the partition and column. """ from ambry.valuetype.core import ROLE for c in self.columns: if not ...
Iterate over the primary columns, columns which do not have a parent Also sets the property partition_stats to the stats collection for the partition and column.
def flush(self): """Flush tables and arrays to disk""" self.log.info('Flushing tables and arrays to disk...') for tab in self._tables.values(): tab.flush() self._write_ndarrays_cache_to_disk()
Flush tables and arrays to disk
def draw_video(self, underlay, overlay, out, x, y): """ Draws one video over another @param underlay : video file on bottom @param overlay : video file to render on top @param out : output file @param start : starting position of overlay @param end : end position ...
Draws one video over another @param underlay : video file on bottom @param overlay : video file to render on top @param out : output file @param start : starting position of overlay @param end : end position of overlay @param x : x position of overlay @param y : y...
def _coeff4(N, a0, a1, a2, a3): """a common internal function to some window functions with 4 coeffs For the blackmna harris for instance, the results are identical to octave if N is odd but not for even values...if n =0 whatever N is, the w(0) must be equal to a0-a1+a2-a3, which is the case here, but...
a common internal function to some window functions with 4 coeffs For the blackmna harris for instance, the results are identical to octave if N is odd but not for even values...if n =0 whatever N is, the w(0) must be equal to a0-a1+a2-a3, which is the case here, but not in octave...