code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def get_labels(self, depth=None): """ Returns a list of labels created by this reference. Parameters ---------- depth : integer or ``None`` If not ``None``, defines from how many reference levels to retrieve labels from. Returns ------- ...
Returns a list of labels created by this reference. Parameters ---------- depth : integer or ``None`` If not ``None``, defines from how many reference levels to retrieve labels from. Returns ------- out : list of ``Label`` List contai...
def show_compatibility_message(self, message): """ Show compatibility message. """ messageBox = QMessageBox(self) messageBox.setWindowModality(Qt.NonModal) messageBox.setAttribute(Qt.WA_DeleteOnClose) messageBox.setWindowTitle('Compatibility Check') messag...
Show compatibility message.
def pop_configuration(self): """ Pushes the currently active configuration from the stack of configurations managed by this mapping. :raises IndexError: If there is only one configuration in the stack. """ if len(self.__configurations) == 1: raise IndexError(...
Pushes the currently active configuration from the stack of configurations managed by this mapping. :raises IndexError: If there is only one configuration in the stack.
def get_plaintext_document_body(fpath, keep_layout=False): """Given a file-path to a full-text, return a list of unicode strings whereby each string is a line of the fulltext. In the case of a plain-text document, this simply means reading the contents in from the file. In the case of a PDF how...
Given a file-path to a full-text, return a list of unicode strings whereby each string is a line of the fulltext. In the case of a plain-text document, this simply means reading the contents in from the file. In the case of a PDF however, this means converting the document to plaintext. ...
def unsubscribe_from_candles(self, pair, timeframe=None, **kwargs): """Unsubscribe to the passed pair's OHLC data channel. :param timeframe: str, {1m, 5m, 15m, 30m, 1h, 3h, 6h, 12h, 1D, 7D, 14D, 1M} :param kwargs: :return: """ valid_tfs =...
Unsubscribe to the passed pair's OHLC data channel. :param timeframe: str, {1m, 5m, 15m, 30m, 1h, 3h, 6h, 12h, 1D, 7D, 14D, 1M} :param kwargs: :return:
def _invert(self): """ Invert coverage data from {test_context: {file: line}} to {file: {test_context: line}} """ result = defaultdict(dict) for test_context, src_context in six.iteritems(self.data): for src, lines in six.iteritems(src_context): ...
Invert coverage data from {test_context: {file: line}} to {file: {test_context: line}}
def decompress(databasepath, database_name, compression, compressed_file): """ Decompress the provided file using the appropriate library :param databasepath: Name and path of where the database files are to be downloaded :param database_name: Name of the database e.g. sipprverse ...
Decompress the provided file using the appropriate library :param databasepath: Name and path of where the database files are to be downloaded :param database_name: Name of the database e.g. sipprverse :param compression: STR MOB-suite databases are .zip files, while OLC databases are .tar.gz ...
def annual_heating_design_day_990(self): """A design day object representing the annual 99.0% heating design day.""" if bool(self._winter_des_day_dict) is True: return DesignDay.from_ashrae_dict_heating( self._winter_des_day_dict, self.location, True, self._st...
A design day object representing the annual 99.0% heating design day.
def delete_namespaced_limit_range(self, name, namespace, **kwargs): """ delete a LimitRange This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_namespaced_limit_range(name, namespace, as...
delete a LimitRange This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_namespaced_limit_range(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool :...
def get_mockup_motor(self, motor): """ Gets the equivalent :class:`~pypot.primitive.primitive.MockupMotor`. """ return next((m for m in self.robot.motors if m.name == motor.name), None)
Gets the equivalent :class:`~pypot.primitive.primitive.MockupMotor`.
def run_container(image, name=None, skip_translate=None, ignore_collisions=False, validate_ip_addrs=True, client_timeout=salt.utils.docker.CLIENT_TIMEOUT, bg=False, replace=False, ...
.. versionadded:: 2018.3.0 Equivalent to ``docker run`` on the Docker CLI. Runs the container, waits for it to exit, and returns the container's logs when complete. .. note:: Not to be confused with :py:func:`docker.run <salt.modules.dockermod.run>`, which provides a :py:func:`cmd.run ...
def _dict_subset(keys, master_dict): ''' Return a dictionary of only the subset of keys/values specified in keys ''' return dict([(k, v) for k, v in six.iteritems(master_dict) if k in keys])
Return a dictionary of only the subset of keys/values specified in keys
def commit_transaction(self): """Commit a multi-statement transaction. .. versionadded:: 3.7 """ self._check_ended() retry = False state = self._transaction.state if state is _TxnState.NONE: raise InvalidOperation("No transaction started") eli...
Commit a multi-statement transaction. .. versionadded:: 3.7
def next(self): """Next point in iteration """ x, y = next(self.scan) xr = -x if self.rx else x yr = -y if self.ry else y return xr, yr
Next point in iteration
def hostinterface_update(interfaceid, **kwargs): ''' .. versionadded:: 2016.3.0 Update host interface .. note:: This function accepts all standard hostinterface: keyword argument names differ depending on your zabbix version, see here__. .. __: https://www.zabbix.com/documenta...
.. versionadded:: 2016.3.0 Update host interface .. note:: This function accepts all standard hostinterface: keyword argument names differ depending on your zabbix version, see here__. .. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_inter...
def masks(list_of_index_lists, n): """Make an array in which rows store 1d mask arrays from list of index lists. Parameters ---------- n : int Maximal index / number of samples. """ # make a list of mask arrays, it's easier to store # as there is a hdf5 equivalent for il,l in en...
Make an array in which rows store 1d mask arrays from list of index lists. Parameters ---------- n : int Maximal index / number of samples.
def list_open_buffers(self): """ Return a `OpenBufferInfo` list that gives information about the open buffers. """ active_eb = self.active_editor_buffer visible_ebs = self.active_tab.visible_editor_buffers() def make_info(i, eb): return OpenBufferInfo...
Return a `OpenBufferInfo` list that gives information about the open buffers.
async def create_new_pump_async(self, partition_id, lease): """ Create a new pump thread with a given lease. :param partition_id: The partition ID. :type partition_id: str :param lease: The lease to be used. :type lease: ~azure.eventprocessorhost.lease.Lease """ ...
Create a new pump thread with a given lease. :param partition_id: The partition ID. :type partition_id: str :param lease: The lease to be used. :type lease: ~azure.eventprocessorhost.lease.Lease
def main(): """Generate a TPIP report.""" parser = argparse.ArgumentParser(description='Generate a TPIP report as a CSV file.') parser.add_argument('output_filename', type=str, metavar='output-file', help='the output path and filename', nargs='?') parser.add_argument('--only', ty...
Generate a TPIP report.
def _get_user_class(self, name): """Get or create a user class of the given type.""" self._user_classes.setdefault(name, _make_user_class(self, name)) return self._user_classes[name]
Get or create a user class of the given type.
def get_coordination_symmetry_measures_optim(self, only_minimum=True, all_csms=True, nb_set=None, optimization=None): """ Returns the continuous symmetry measures of the current local geometry in a dictionary. :return: the continuous symmetry meas...
Returns the continuous symmetry measures of the current local geometry in a dictionary. :return: the continuous symmetry measures of the current local geometry in a dictionary.
def check_exports(mod, specs, renamings): ''' Does nothing but raising PythranSyntaxError if specs references an undefined global ''' functions = {renamings.get(k, k): v for k, v in specs.functions.items()} mod_functions = {node.name: node for node in mod.body if isinstance...
Does nothing but raising PythranSyntaxError if specs references an undefined global
def seek(self, rev): """Arrange the caches to help look up the given revision.""" # TODO: binary search? Perhaps only when one or the other # stack is very large? if not self: return if type(rev) is not int: raise TypeError("rev must be int") past ...
Arrange the caches to help look up the given revision.
def deleteFeatures(self, objectIds="", where="", geometryFilter=None, gdbVersion=None, rollbackOnFailure=True ): """ removes 1:n features based on a sql statement ...
removes 1:n features based on a sql statement Input: objectIds - The object IDs of this layer/table to be deleted where - A where clause for the query filter. Any legal SQL where clause operating on the fields in the layer is allowed. F...
def add_user( self, user, first_name=None, last_name=None, email=None, password=None ): """ Add a new user. Args: user (string): User name. first_name (optional[string]): User's first name. Defaults to None. last_n...
Add a new user. Args: user (string): User name. first_name (optional[string]): User's first name. Defaults to None. last_name (optional[string]): User's last name. Defaults to None. email: (optional[string]): User's email address. Defaults to None. ...
def get_coordinate_systems( self, token: dict = None, srs_code: str = None, prot: str = "https" ) -> dict: """Get available coordinate systems in Isogeo API. :param str token: API auth token :param str srs_code: code of a specific coordinate system :param str prot: https [DE...
Get available coordinate systems in Isogeo API. :param str token: API auth token :param str srs_code: code of a specific coordinate system :param str prot: https [DEFAULT] or http (use it only for dev and tracking needs).
def _autoinsert_quotes(self, key): """Control how to automatically insert quotes in various situations.""" char = {Qt.Key_QuoteDbl: '"', Qt.Key_Apostrophe: '\''}[key] line_text = self.editor.get_text('sol', 'eol') line_to_cursor = self.editor.get_text('sol', 'cursor') cursor = s...
Control how to automatically insert quotes in various situations.
def run_model(self, op_list, num_steps, feed_vars=(), feed_data=None, print_every=100, allow_initialize=True): """Runs `op_list` for `num_steps`. Args: op_list: A list of ops to run. num_steps: Number of...
Runs `op_list` for `num_steps`. Args: op_list: A list of ops to run. num_steps: Number of steps to run this for. If feeds are used, this is a maximum. `None` can be used to signal "forever". feed_vars: The variables to feed. feed_data: An iterator that feeds data tuples. prin...
def set_cmap(self, cmap, callback=True): """ Set the color map used by this RGBMapper. `cmap` specifies a ColorMap object. If `callback` is True, then any callbacks associated with this change will be invoked. """ self.cmap = cmap with self.suppress_changed: ...
Set the color map used by this RGBMapper. `cmap` specifies a ColorMap object. If `callback` is True, then any callbacks associated with this change will be invoked.
def countthai(text: str, ignore_chars: str = _DEFAULT_IGNORE_CHARS) -> float: """ :param str text: input text :return: float, proportion of characters in the text that is Thai character """ if not text or not isinstance(text, str): return 0 if not ignore_chars: ignore_chars = ""...
:param str text: input text :return: float, proportion of characters in the text that is Thai character
def string2identifier(s): """Turn a string into a valid python identifier. Currently only allows ASCII letters and underscore. Illegal characters are replaced with underscore. This is slightly more opinionated than python 3 itself, and may be refactored in future (see PEP 3131). Parameters ---...
Turn a string into a valid python identifier. Currently only allows ASCII letters and underscore. Illegal characters are replaced with underscore. This is slightly more opinionated than python 3 itself, and may be refactored in future (see PEP 3131). Parameters ---------- s : string st...
def quantile(data, num_breaks): """ Calculate quantile breaks. Arguments: data -- Array of values to classify. num_breaks -- Number of breaks to perform. """ def scipy_mquantiles(a, prob=list([.25,.5,.75]), alphap=.4, betap=.4, axis=None, limit=()): """ function copied from scipy 0...
Calculate quantile breaks. Arguments: data -- Array of values to classify. num_breaks -- Number of breaks to perform.
def visit_AugAssign(self, node): """ AugAssigned value depend on r-value type dependencies. It is valid for subscript, `a[i] += foo()` means `a` type depend on `foo` return type and previous a types too. """ args = (self.naming[get_variable(node.target).id], ...
AugAssigned value depend on r-value type dependencies. It is valid for subscript, `a[i] += foo()` means `a` type depend on `foo` return type and previous a types too.
def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_rx_vlan_disc_req(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") fcoe_get_interface = ET.Element("fcoe_get_interface") config = fcoe_get_interface output = ET.SubElement(fcoe_get_interface, "...
Auto Generated Code
def readFLOAT16(self): """ Read a 2 byte float """ self.reset_bits_pending() word = self.readUI16() sign = -1 if ((word & 0x8000) != 0) else 1 exponent = (word >> 10) & 0x1f significand = word & 0x3ff if exponent == 0: if significand == 0: ...
Read a 2 byte float
def _configure_io_handler(self, handler): """Register an io-handler at the polling object.""" if self.check_events(): return if handler in self._unprepared_handlers: old_fileno = self._unprepared_handlers[handler] prepared = self._prepare_io_handler(handler) ...
Register an io-handler at the polling object.
def search(self, pattern, minAddr = None, maxAddr = None): """ Search for the given pattern within the process memory. @type pattern: str, compat.unicode or L{Pattern} @param pattern: Pattern to search for. It may be a byte string, a Unicode string, or an instance of ...
Search for the given pattern within the process memory. @type pattern: str, compat.unicode or L{Pattern} @param pattern: Pattern to search for. It may be a byte string, a Unicode string, or an instance of L{Pattern}. The following L{Pattern} subclasses are provided...
def url2domain(url): """ extract domain from url """ parsed_uri = urlparse.urlparse(url) domain = '{uri.netloc}'.format(uri=parsed_uri) domain = re.sub("^.+@", "", domain) domain = re.sub(":.+$", "", domain) return domain
extract domain from url
def _detect_xerial_stream(payload): """Detects if the data given might have been encoded with the blocking mode of the xerial snappy library. This mode writes a magic header of the format: +--------+--------------+------------+---------+--------+ | Marker | Magic String | Nu...
Detects if the data given might have been encoded with the blocking mode of the xerial snappy library. This mode writes a magic header of the format: +--------+--------------+------------+---------+--------+ | Marker | Magic String | Null / Pad | Version | Compat | +...
def queries(self, request): '''Multiple Database Queries''' queries = self.get_queries(request) worlds = [] with self.mapper.begin() as session: for _ in range(queries): world = session.query(World).get(randint(1, MAXINT)) worlds.append(self.ge...
Multiple Database Queries
def read(self, auth, resource, options, defer=False): """ Read value(s) from a dataport. Calls a function that builds a request to read the dataport specified by an alias or rid and returns timeseries data as defined by the options. Args: auth: Takes the device cik ...
Read value(s) from a dataport. Calls a function that builds a request to read the dataport specified by an alias or rid and returns timeseries data as defined by the options. Args: auth: Takes the device cik resource: Takes the dataport alias or rid. options...
def get_pic(self, playingsong, tempfile_path): '''获取专辑封面''' url = playingsong['picture'].replace('\\', '') for _ in range(3): try: urllib.urlretrieve(url, tempfile_path) logger.debug('Get cover art success!') return True exc...
获取专辑封面
def get_balance(self): """Check the balance fot this account. Returns a dictionary containing: account_type: The account type balance: The balance remaining on the account currency: The currency used for the account balance. Assume GBP in not set""" xml_root ...
Check the balance fot this account. Returns a dictionary containing: account_type: The account type balance: The balance remaining on the account currency: The currency used for the account balance. Assume GBP in not set
def _get_padded(data, start, end): """Return `data[start:end]` filling in with zeros outside array bounds Assumes that either `start<0` or `end>len(data)` but not both. """ if start < 0 and end > data.shape[0]: raise RuntimeError() if start < 0: start_zeros = np.zeros((-start, data...
Return `data[start:end]` filling in with zeros outside array bounds Assumes that either `start<0` or `end>len(data)` but not both.
def _resolve_paths(self, *paths): """ Resolve paths into a set of filenames (no directories) to check. External tools will handle directories as arguments differently, so for consistency we just want to pass them filenames. This method will recursively walk all directories and ...
Resolve paths into a set of filenames (no directories) to check. External tools will handle directories as arguments differently, so for consistency we just want to pass them filenames. This method will recursively walk all directories and filter out any paths that match self.options.i...
def init(cls, path=None, mkdir=True, odbt=GitCmdObjectDB, expand_vars=True, **kwargs): """Initialize a git repository at the given path if specified :param path: is the full path to the repo (traditionally ends with /<name>.git) or None in which case the repository will be creat...
Initialize a git repository at the given path if specified :param path: is the full path to the repo (traditionally ends with /<name>.git) or None in which case the repository will be created in the current working directory :param mkdir: if specified wi...
def exists(config): """ Check whether the .wily/ directory exists. :param config: The configuration :type config: :class:`wily.config.WilyConfig` :return: Whether the .wily directory exists :rtype: ``boolean`` """ exists = ( pathlib.Path(config.cache_path).exists() and...
Check whether the .wily/ directory exists. :param config: The configuration :type config: :class:`wily.config.WilyConfig` :return: Whether the .wily directory exists :rtype: ``boolean``
def DynamicCmd(name, plugins): """ Returns a cmd with the added plugins, :param name: TODO: :param plugins: list of plugins """ exec('class %s(cmd.Cmd):\n prompt="cm> "' % name) plugin_objects = [] for plugin in plugins: classprefix = plugin['class'] plugin_list =...
Returns a cmd with the added plugins, :param name: TODO: :param plugins: list of plugins
def get_hubs(self): """Get a list of hubs names. Returns ------- hubs : list List of hub names """ # Use helm to get a list of hubs. output = helm( 'list', '-q' ) # Check if an error occurred. if...
Get a list of hubs names. Returns ------- hubs : list List of hub names
def insert_file(self, file): """insert_file(file) Load resources entries from FILE, and insert them into the database. FILE can be a filename (a string)or a file object. """ if type(file) is bytes: file = open(file, 'r') self.insert_string(file.read())
insert_file(file) Load resources entries from FILE, and insert them into the database. FILE can be a filename (a string)or a file object.
def set_dhw_on(self, until=None): """Sets the DHW on until a given time, or permanently.""" if until is None: data = {"Mode": "PermanentOverride", "State": "On", "UntilTime": None} else: data = {"Mode": "TemporaryOverride", ...
Sets the DHW on until a given time, or permanently.
async def _upload_chunks( cls, rfile: BootResourceFile, content: io.IOBase, chunk_size: int, progress_callback=None): """Upload the `content` to `rfile` in chunks using `chunk_size`.""" content.seek(0, io.SEEK_SET) upload_uri = urlparse( cls._handler.uri)._rep...
Upload the `content` to `rfile` in chunks using `chunk_size`.
def predicate_type(self, pred: URIRef) -> URIRef: """ Return the type of pred :param pred: predicate to map :return: """ return self._o.value(pred, RDFS.range)
Return the type of pred :param pred: predicate to map :return:
def plot_poles(map_axis, plon, plat, A95, label='', color='k', edgecolor='k', marker='o', markersize=20, legend='no'): """ This function plots paleomagnetic poles and A95 error ellipses on a cartopy map axis. Before this function is called, a plot needs to be initialized with code such as that in the m...
This function plots paleomagnetic poles and A95 error ellipses on a cartopy map axis. Before this function is called, a plot needs to be initialized with code such as that in the make_orthographic_map function. Examples ------- >>> plons = [200, 180, 210] >>> plats = [60, 40, 35] >>> A95 =...
def _get(self, url, params={}): """Wrapper around request.get() to use the API prefix. Returns a JSON response.""" req = self._session.get(self._api_prefix + url, params=params) return self._action(req)
Wrapper around request.get() to use the API prefix. Returns a JSON response.
def _get_argv(index, default=None): ''' get the argv input argument defined by index. Return the default attribute if that argument does not exist ''' return _sys.argv[index] if len(_sys.argv) > index else default
get the argv input argument defined by index. Return the default attribute if that argument does not exist
def load_plume_package(package, plume_dir, accept_defaults): """Loads a canari package into Plume.""" from canari.commands.load_plume_package import load_plume_package load_plume_package(package, plume_dir, accept_defaults)
Loads a canari package into Plume.
def is_attacked_by(self, color: Color, square: Square) -> bool: """ Checks if the given side attacks the given square. Pinned pieces still count as attackers. Pawns that can be captured en passant are **not** considered attacked. """ return bool(self.attackers_mask(color...
Checks if the given side attacks the given square. Pinned pieces still count as attackers. Pawns that can be captured en passant are **not** considered attacked.
def svm_train(arg1, arg2=None, arg3=None): """ svm_train(y, x [, options]) -> model | ACC | MSE y: a list/tuple/ndarray of l true labels (type must be int/double). x: 1. a list/tuple of l training instances. Feature vector of each training instance is a list/tuple or dictionary. 2. an l * n numpy ndar...
svm_train(y, x [, options]) -> model | ACC | MSE y: a list/tuple/ndarray of l true labels (type must be int/double). x: 1. a list/tuple of l training instances. Feature vector of each training instance is a list/tuple or dictionary. 2. an l * n numpy ndarray or scipy spmatrix (n: number of features). ...
def places_photo(client, photo_reference, max_width=None, max_height=None): """ Downloads a photo from the Places API. :param photo_reference: A string identifier that uniquely identifies a photo, as provided by either a Places search or Places detail request. :type photo_reference: string ...
Downloads a photo from the Places API. :param photo_reference: A string identifier that uniquely identifies a photo, as provided by either a Places search or Places detail request. :type photo_reference: string :param max_width: Specifies the maximum desired width, in pixels. :type max_width: ...
def fetch(**kwargs): ''' .. versionadded:: 2016.3.4 freebsd-update fetch wrapper. Based on the currently installed world and the configuration options set, fetch all available binary updates. kwargs: Parameters of freebsd-update command. ''' # fetch continues when no controlling te...
.. versionadded:: 2016.3.4 freebsd-update fetch wrapper. Based on the currently installed world and the configuration options set, fetch all available binary updates. kwargs: Parameters of freebsd-update command.
def quad_info(name, quad, pretty): '''Get information for a specific mosaic quad''' cl = clientv1() mosaic, = cl.get_mosaic_by_name(name).items_iter(1) echo_json_response(call_and_wrap(cl.get_quad_by_id, mosaic, quad), pretty)
Get information for a specific mosaic quad
def from_vertices_and_edges(vertices, edges, vertex_name_key='name', vertex_id_key='id', edge_foreign_keys=('source', 'target'), directed=True): """ This representation assumes that vertices and edges are encoded in two lists, each list containing a Python dict for each vertex an...
This representation assumes that vertices and edges are encoded in two lists, each list containing a Python dict for each vertex and each edge, respectively. A distinguished element of the vertex dicts contain a vertex ID which is used in the edge dicts to refer to source and target vertices. All the re...
def render(obj): """Convienently render strings with the fabric context""" def get_v(v): return v % env if isinstance(v, basestring) else v if isinstance(obj, types.StringType): return obj % env elif isinstance(obj, types.TupleType) or isinstance(obj, types.ListType): rv = [] ...
Convienently render strings with the fabric context
def get_relevant_policy_section(self, policy_name, group=None): """ Look up the policy corresponding to the provided policy name and group (optional). Log any issues found during the look up. """ policy_bundle = self._operation_policies.get(policy_name) if not policy_bun...
Look up the policy corresponding to the provided policy name and group (optional). Log any issues found during the look up.
def validate(self, key, value): """Validation function run before setting. Uses function from __init__.""" if self._validator is not None: self._validator(key, value)
Validation function run before setting. Uses function from __init__.
def assert_satisfies(v, cond, message=None): """ Assert that variable satisfies the provided condition. :param v: variable to check. Its value is only used for error reporting. :param bool cond: condition that must be satisfied. Should be somehow related to the variable ``v``. :param message: messa...
Assert that variable satisfies the provided condition. :param v: variable to check. Its value is only used for error reporting. :param bool cond: condition that must be satisfied. Should be somehow related to the variable ``v``. :param message: message string to use instead of the default.
def close(self): """ Close the connection. """ if not self._closed: if self.protocol_version >= 3: log_debug("[#%04X] C: GOODBYE", self.local_port) self._append(b"\x02", ()) try: self.send() except S...
Close the connection.
def invert_projection(self, X, identities): """ Calculate the inverted projection. The inverted projectio of a SOM is created by association each weight with the input which matches it the most, thus giving a good approximation of the "influence" of each input item. Wor...
Calculate the inverted projection. The inverted projectio of a SOM is created by association each weight with the input which matches it the most, thus giving a good approximation of the "influence" of each input item. Works best for symbolic (instead of continuous) input data. ...
def plotRatePSD(include=['allCells', 'eachPop'], timeRange=None, binSize=5, maxFreq=100, NFFT=256, noverlap=128, smooth=0, overlay=True, ylim = None, popColors = {}, fontSize=12, figSize=(10,8), saveData=None, saveFig=None, showFig=True): ''' Plot firing rate power spectral density (PSD) - include...
Plot firing rate power spectral density (PSD) - include (['all',|'allCells','allNetStims',|,120,|,'E1'|,('L2', 56)|,('L5',[4,5,6])]): List of data series to include. Note: one line per item, not grouped (default: ['allCells', 'eachPop']) - timeRange ([start:stop]): Time range of spikes show...
def convert_la_to_rgba(self, row, result): """Convert a grayscale image with alpha to RGBA.""" for i in range(len(row) // 3): for j in range(3): result[(4 * i) + j] = row[2 * i] result[(4 * i) + 3] = row[(2 * i) + 1]
Convert a grayscale image with alpha to RGBA.
def PostRegistration(method): # pylint: disable=C0103 """ The service post-registration callback decorator is called after a service of the component has been registered to the framework. The decorated method must accept the :class:`~pelix.framework.ServiceReference` of the registered servi...
The service post-registration callback decorator is called after a service of the component has been registered to the framework. The decorated method must accept the :class:`~pelix.framework.ServiceReference` of the registered service as argument:: @PostRegistration def callback_method(...
def content(): """Helper method that returns just the content. This method was added so that the text could be reused in the dock_help module. .. versionadded:: 3.2.2 :returns: A message object without brand element. :rtype: safe.messaging.message.Message """ message = m.Message() ...
Helper method that returns just the content. This method was added so that the text could be reused in the dock_help module. .. versionadded:: 3.2.2 :returns: A message object without brand element. :rtype: safe.messaging.message.Message
def check_dupl_sources(self): # used in print_csm_info """ Extracts duplicated sources, i.e. sources with the same source_id in different source groups. Raise an exception if there are sources with the same ID which are not duplicated. :returns: a list of list of sources, order...
Extracts duplicated sources, i.e. sources with the same source_id in different source groups. Raise an exception if there are sources with the same ID which are not duplicated. :returns: a list of list of sources, ordered by source_id
def get_data(self): "Get SNMP values from host" alarm_oids = [netsnmp.Varbind(alarms[alarm_id]['oid']) for alarm_id in self.models[self.modem_type]['alarms']] metric_oids = [netsnmp.Varbind(metrics[metric_id]['oid']) for metric_id in self.models[self.modem_type]['metrics']] response = se...
Get SNMP values from host
def start(self): """ Start downloading, handling auto retry, download resume and path moving """ if not self.auto_retry: self.curl() return while not self.is_finished: try: self.curl() except pycurl.error as ...
Start downloading, handling auto retry, download resume and path moving
def remove_target(self, target_name: str): """Remove (unregister) a `target` from this build context. Removes the target instance with the given name, if it exists, from both the `targets` map and the `targets_by_module` map. Doesn't do anything if no target with that name is found. ...
Remove (unregister) a `target` from this build context. Removes the target instance with the given name, if it exists, from both the `targets` map and the `targets_by_module` map. Doesn't do anything if no target with that name is found. Doesn't touch the target graph, if it exists.
def subn_filter(s, find, replace, count=0): """A non-optimal implementation of a regex filter""" return re.gsub(find, replace, count, s)
A non-optimal implementation of a regex filter
def remove_last(ol,value,**kwargs): ''' from elist.elist import * ol = [1,'a',3,'a',5,'a'] id(ol) new = remove_last(ol,'a') ol new id(ol) id(new) #### ol = [1,'a',3,'a',5,'a'] id(ol) rslt = remove_last(ol,'a',mode="origi...
from elist.elist import * ol = [1,'a',3,'a',5,'a'] id(ol) new = remove_last(ol,'a') ol new id(ol) id(new) #### ol = [1,'a',3,'a',5,'a'] id(ol) rslt = remove_last(ol,'a',mode="original") ol rslt id(ol) ...
def _adjust_auto(self, real_wave_mfcc, algo_parameters): """ AUTO (do not modify) """ self.log(u"Called _adjust_auto") self.log(u"Nothing to do, return unchanged")
AUTO (do not modify)
def start(self): """Creates a TCP connection to Device Cloud and sends a ConnectionRequest message""" self.log.info("Starting Insecure Session for Monitor %s" % self.monitor_id) if self.socket is not None: raise Exception("Socket already established for %s." % self) try: ...
Creates a TCP connection to Device Cloud and sends a ConnectionRequest message
def after_unassign(duplicate_analysis): """Removes the duplicate from the system """ analysis_events.after_unassign(duplicate_analysis) parent = duplicate_analysis.aq_parent logger.info("Removing duplicate '{}' from '{}'" .format(duplicate_analysis.getId(), parent.getId())) paren...
Removes the duplicate from the system
def create_oracle(username, password, host, port, database, **kwargs): # pragma: no cover """ create an engine connected to a oracle database using cx_oracle. """ return create_engine( _create_oracle(username, password, host, port, database), **kwargs )
create an engine connected to a oracle database using cx_oracle.
def payload_class_for_element_name(element_name): """Return a payload class for given element name.""" logger.debug(" looking up payload class for element: {0!r}".format( element_name)) logger.debug(" known: {0!r}".format(STANZA_PAYLOAD_CLASSE...
Return a payload class for given element name.
def _set_gbc(self, v, load=False): """ Setter method for gbc, mapped from YANG variable /brocade_interface_ext_rpc/get_media_detail/output/interface/gbc (container) If this variable is read-only (config: false) in the source YANG file, then _set_gbc is considered as a private method. Backends lookin...
Setter method for gbc, mapped from YANG variable /brocade_interface_ext_rpc/get_media_detail/output/interface/gbc (container) If this variable is read-only (config: false) in the source YANG file, then _set_gbc is considered as a private method. Backends looking to populate this variable should do so vi...
def get_workflow(self): """Returns the instantiated workflow class.""" extra_context = self.get_initial() entry_point = self.request.GET.get("step", None) workflow = self.workflow_class(self.request, context_seed=extra_context, ...
Returns the instantiated workflow class.
def preferred_width(self, cli, max_available_width): """ Report the width of the longest meta text as the preferred width of this control. It could be that we use less width, but this way, we're sure that the layout doesn't change when we select another completion (E.g. that com...
Report the width of the longest meta text as the preferred width of this control. It could be that we use less width, but this way, we're sure that the layout doesn't change when we select another completion (E.g. that completions are suddenly shown in more or fewer columns.)
def _get_adjusted_merge_area(self, attrs, insertion_point, no_to_insert, axis): """Returns updated merge area Parameters ---------- attrs: Dict \tCell attribute dictionary that shall be adjusted insertion_point: Integer \tPont on ...
Returns updated merge area Parameters ---------- attrs: Dict \tCell attribute dictionary that shall be adjusted insertion_point: Integer \tPont on axis, before which insertion takes place no_to_insert: Integer >= 0 \tNumber of rows/cols/tabs that shall be...
def get_variants(data, include_germline=False): """Retrieve set of variant calls to use for heterogeneity analysis. """ data = utils.deepish_copy(data) supported = ["precalled", "vardict", "vardict-java", "vardict-perl", "freebayes", "octopus", "strelka2"] # Right now mutect2 and mu...
Retrieve set of variant calls to use for heterogeneity analysis.
def _count_leading(line, ch): """ Return number of `ch` characters at the start of `line`. Example: >>> _count_leading(' abc', ' ') 3 """ i, n = 0, len(line) while i < n and line[i] == ch: i += 1 return i
Return number of `ch` characters at the start of `line`. Example: >>> _count_leading(' abc', ' ') 3
def create(self): """Create tracking collection. Does nothing if tracking collection already exists. """ if self._track is None: self._track = self.db[self.tracking_collection_name]
Create tracking collection. Does nothing if tracking collection already exists.
def from_file(filepath, delimiter='', blanklines=False): """Imports userdata from a file. :type filepath: string :param filepath The absolute path to the file. :type delimiter: string :param: delimiter Delimiter to use with the troposphere.Join(). :type blanklines: boolean :param bla...
Imports userdata from a file. :type filepath: string :param filepath The absolute path to the file. :type delimiter: string :param: delimiter Delimiter to use with the troposphere.Join(). :type blanklines: boolean :param blanklines If blank lines shoud be ignored rtype: troposphere...
def map_(input_layer, fn): """Maps the given function across this sequence. To map an entire template across the sequence, use the `as_fn` method on the template. Args: input_layer: The input tensor. fn: A function of 1 argument that is applied to each item in the sequence. Returns: A new sequen...
Maps the given function across this sequence. To map an entire template across the sequence, use the `as_fn` method on the template. Args: input_layer: The input tensor. fn: A function of 1 argument that is applied to each item in the sequence. Returns: A new sequence Pretty Tensor. Raises: ...
async def send_from_directory( directory: FilePath, file_name: str, *, mimetype: Optional[str]=None, as_attachment: bool=False, attachment_filename: Optional[str]=None, add_etags: bool=True, cache_timeout: Optional[int]=None, conditional: bool=True...
Send a file from a given directory. Arguments: directory: Directory that when combined with file_name gives the file path. file_name: File name that when combined with directory gives the file path. See :func:`send_file` for the other arguments.
def build_global(self, global_node): """parse `global` section, and return the config.Global Args: global_node (TreeNode): `global` section treenode Returns: config.Global: an object """ config_block_lines = self.__build_config_block( globa...
parse `global` section, and return the config.Global Args: global_node (TreeNode): `global` section treenode Returns: config.Global: an object
def get_first_node( node, node_not_to_step_past ): """ This is a super hacky way of getting the first node after a statement. We do this because we visit a statement and keep on visiting and get something in return that is rarely the first node. So we loop and loop backwards until we...
This is a super hacky way of getting the first node after a statement. We do this because we visit a statement and keep on visiting and get something in return that is rarely the first node. So we loop and loop backwards until we hit the statement or there is nothing to step back to.
def get_reviews(self, user_id): """ Get reviews for a particular user """ url = _REVIEWS_USER.format(c_api=_C_API_BEGINNING, api=_API_VERSION, user_id=user_id, at=s...
Get reviews for a particular user
def conn_aws(cred, crid): """Establish connection to AWS service.""" driver = get_driver(Provider.EC2) try: aws_obj = driver(cred['aws_access_key_id'], cred['aws_secret_access_key'], region=cred['aws_default_region']) except SSLError as e: ...
Establish connection to AWS service.
def uninstall(self, auto_confirm=False): """ Uninstall the distribution currently satisfying this requirement. Prompts before removing or modifying files unless ``auto_confirm`` is True. Refuses to delete or modify files outside of ``sys.prefix`` - thus uninstallation w...
Uninstall the distribution currently satisfying this requirement. Prompts before removing or modifying files unless ``auto_confirm`` is True. Refuses to delete or modify files outside of ``sys.prefix`` - thus uninstallation within a virtual environment can only modify that virt...
def inbox(request, template_name='django_messages/inbox.html'): """ Displays a list of received messages for the current user. Optional Arguments: ``template_name``: name of the template to use. """ message_list = Message.objects.inbox_for(request.user) return render(request, template_na...
Displays a list of received messages for the current user. Optional Arguments: ``template_name``: name of the template to use.