code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def file_format_name(self): """Return the current format name of the open bdf.""" try: return BfdFormatNamesLong[self.file_format] except IndexError, err: raise BfdException("Invalid format specified (%d)" % self.file_format)
Return the current format name of the open bdf.
def load_config(configfile): """ Load the full config / merge splitted configs if configured """ configfile = os.path.abspath(configfile) config = configobj.ConfigObj(configfile) config_extension = '.conf' ######################################################################### # Loa...
Load the full config / merge splitted configs if configured
def add_remote_candidate(self, remote_candidate): """ Add a remote candidate or signal end-of-candidates. To signal end-of-candidates, pass `None`. """ if self._remote_candidates_end: raise ValueError('Cannot add remote candidate after end-of-candidates.') i...
Add a remote candidate or signal end-of-candidates. To signal end-of-candidates, pass `None`.
def genrepo(**kwargs): ''' Generate package metadata db based on files within the winrepo_source_dir Kwargs: saltenv (str): Salt environment. Default: ``base`` verbose (bool): Return verbose data structure which includes 'success_list', a list of all sls files and ...
Generate package metadata db based on files within the winrepo_source_dir Kwargs: saltenv (str): Salt environment. Default: ``base`` verbose (bool): Return verbose data structure which includes 'success_list', a list of all sls files and the package names contained within....
def prior_const(C, alpha=0.001): """Constant prior of strength alpha. Prior is defined via b_ij=alpha for all i,j Parameters ---------- C : (M, M) ndarray or scipy.sparse matrix Count matrix alpha : float (optional) Value of prior counts Returns ------- B ...
Constant prior of strength alpha. Prior is defined via b_ij=alpha for all i,j Parameters ---------- C : (M, M) ndarray or scipy.sparse matrix Count matrix alpha : float (optional) Value of prior counts Returns ------- B : (M, M) ndarray Prior count mat...
def from_epsg_code(code): """ Load crs object from epsg code, via spatialreference.org. Parses based on the proj4 representation. Arguments: - *code*: The EPSG code as an integer. Returns: - A CS instance of the indicated type. """ # must go online (or look up local table) to ge...
Load crs object from epsg code, via spatialreference.org. Parses based on the proj4 representation. Arguments: - *code*: The EPSG code as an integer. Returns: - A CS instance of the indicated type.
def gnomonicSphereToImage(lon, lat): """ Gnomonic projection (deg). """ # Convert angle to [-180, 180] interval lon = lon - 360.*(lon>180) lon = np.radians(lon) lat = np.radians(lat) r_theta = (180. / np.pi) / np.tan(lat) x = r_theta * np.cos(lon) y = r_theta * np.sin(lon) re...
Gnomonic projection (deg).
def run_archive_cmdlist (archive_cmdlist, verbosity=0): """Run archive command.""" # archive_cmdlist is a command list with optional keyword arguments if isinstance(archive_cmdlist, tuple): cmdlist, runkwargs = archive_cmdlist else: cmdlist, runkwargs = archive_cmdlist, {} return uti...
Run archive command.
def process_json_file(file_name): """Return an EidosProcessor by processing the given Eidos JSON-LD file. This function is useful if the output from Eidos is saved as a file and needs to be processed. Parameters ---------- file_name : str The name of the JSON-LD file to be processed. ...
Return an EidosProcessor by processing the given Eidos JSON-LD file. This function is useful if the output from Eidos is saved as a file and needs to be processed. Parameters ---------- file_name : str The name of the JSON-LD file to be processed. Returns ------- ep : EidosPro...
def bulk_update_resourcedata(scenario_ids, resource_scenarios,**kwargs): """ Update the data associated with a list of scenarios. """ user_id = kwargs.get('user_id') res = None res = {} net_ids = db.DBSession.query(Scenario.network_id).filter(Scenario.id.in_(scenario_ids)).all() i...
Update the data associated with a list of scenarios.
def get_entities_by_components(self, *components): ''' Get entity by list of components All members of components must be of type Component ''' return list(filter(lambda entity: set(components) <= set(map(type, entity.get_comp...
Get entity by list of components All members of components must be of type Component
def get_command_line(self): """ Retrieves the command line with wich the program was started. @rtype: str @return: Command line string. @raise WindowsError: On error an exception is raised. """ (Buffer, MaximumLength) = self.get_command_line_block() Com...
Retrieves the command line with wich the program was started. @rtype: str @return: Command line string. @raise WindowsError: On error an exception is raised.
def dd_docs(self): """Copy and convert various documentation files.""" top = os.path.join(os.path.dirname(__file__)) doc = os.path.join(top, 'doc') # Markdown to ronn to man page man_md = os.path.join(doc, 'authprogs.md') man_ronn = os.path.join(doc, 'authprogs.1.ronn') ...
Copy and convert various documentation files.
def save_to_name_list(dest, name_parts, value): """ Util to save some name sequence to a dict. For instance, `("location","query")` would save to dest["location"]["query"]. """ if len(name_parts) > 1: for part in name_parts[:-1]: if part not in dest: dest[part] = ...
Util to save some name sequence to a dict. For instance, `("location","query")` would save to dest["location"]["query"].
def get_jobs_from_runner(self, outstanding_jids): ''' Given a list of job_ids, return a dictionary of those job_ids that have completed and their results. Query the salt event bus via the jobs runner. jobs.list_job will show a job in progress, jobs.lookup_jid will return a job t...
Given a list of job_ids, return a dictionary of those job_ids that have completed and their results. Query the salt event bus via the jobs runner. jobs.list_job will show a job in progress, jobs.lookup_jid will return a job that has completed. returns a dictionary of job id: re...
def change_custom_host_var(self, host, varname, varvalue): """Change custom host variable Format of the line that triggers function call:: CHANGE_CUSTOM_HOST_VAR;<host_name>;<varname>;<varvalue> :param host: host to edit :type host: alignak.objects.host.Host :param varn...
Change custom host variable Format of the line that triggers function call:: CHANGE_CUSTOM_HOST_VAR;<host_name>;<varname>;<varvalue> :param host: host to edit :type host: alignak.objects.host.Host :param varname: variable name to change :type varname: str :param...
def getModPath(self, *paths): ''' Construct a path relative to this module's working directory. Args: *paths: A list of path strings Notes: This creates the module specific directory if it does not exist. Returns: (str): The full path (or No...
Construct a path relative to this module's working directory. Args: *paths: A list of path strings Notes: This creates the module specific directory if it does not exist. Returns: (str): The full path (or None if no cortex dir is configured).
def _handleSDRClassifierMultiStep(self, patternNZ, inputTSRecordIdx, rawInput): """ Handle the CLA Classifier compute logic when implementing multi-step prediction. This is where the patternNZ is associated with one of the other fields ...
Handle the CLA Classifier compute logic when implementing multi-step prediction. This is where the patternNZ is associated with one of the other fields from the dataset 0 to N steps in the future. This method is used by each type of network (encoder only, SP only, SP +TM) to handle the compute logic thr...
def upload_job_chunk_retreive(self, upload_job_id, chunk_id, **kwargs): # noqa: E501 """Get metadata about a chunk # noqa: E501 Get metadata about a chunk # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchron...
Get metadata about a chunk # noqa: E501 Get metadata about a chunk # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.upload_job_chunk_retreive(upload_job_id, chunk_id, asynchronous...
def _calculateBasalSegmentActivity(connections, activeInput, reducedBasalThresholdCells, connectedPermanence, activationThreshold, minThreshold, reducedBasalThreshold): """ Calculate the active and matching basal segments for this timestep. Th...
Calculate the active and matching basal segments for this timestep. The difference with _calculateApicalSegmentActivity is that cells with active apical segments (collected in reducedBasalThresholdCells) have a lower activation threshold for their basal segments (set by reducedBasalThreshold parameter)...
def fromtree(cls, tree): """ Create a METS from an ElementTree or Element. :param ElementTree tree: ElementTree to build a METS document from. """ mets = cls() mets.tree = tree mets._parse_tree(tree) return mets
Create a METS from an ElementTree or Element. :param ElementTree tree: ElementTree to build a METS document from.
def _live_entity_map(self, entity_type): """Return an id:Entity map of all the living entities of type ``entity_type``. """ return { entity_id: self.get_entity(entity_type, entity_id) for entity_id, history in self.state.get(entity_type, {}).items() i...
Return an id:Entity map of all the living entities of type ``entity_type``.
def waitfor(self, relist, timeout=None, cleanup=None): """Read until one from a list of a regular expressions matches. The first argument is a list of regular expressions, either compiled (re.RegexObject instances) or uncompiled (strings). The optional second argument is a timeout, in s...
Read until one from a list of a regular expressions matches. The first argument is a list of regular expressions, either compiled (re.RegexObject instances) or uncompiled (strings). The optional second argument is a timeout, in seconds; default is no timeout. Return a tuple of ...
def _singleframe_to_nifti(grouped_dicoms, output_file): """ This function will convert a philips singleframe series to a nifti """ # Create mosaic block logger.info('Creating data block') full_block = _singleframe_to_block(grouped_dicoms) logger.info('Creating affine') # Create the nif...
This function will convert a philips singleframe series to a nifti
def quokka_heatmap(size=None, extract=None): """ Returns a heatmap (here: depth map) for the standard example quokka image. Parameters ---------- size : None or float or tuple of int, optional See :func:`imgaug.quokka`. extract : None or 'square' or tuple of number or imgaug.BoundingBo...
Returns a heatmap (here: depth map) for the standard example quokka image. Parameters ---------- size : None or float or tuple of int, optional See :func:`imgaug.quokka`. extract : None or 'square' or tuple of number or imgaug.BoundingBox or imgaug.BoundingBoxesOnImage See :func:`imgau...
def get_scan_plot(self, coords=None): """ Get a matplotlib plot of the potential energy surface. Args: coords: internal coordinate name to use as abcissa. """ from pymatgen.util.plotting import pretty_plot plt = pretty_plot(12, 8) d = self.read_scan...
Get a matplotlib plot of the potential energy surface. Args: coords: internal coordinate name to use as abcissa.
def compute(self, function): """Evaluate the passed function with the supplied data. Stores result in self.out. Parameters ---------- function: str Name of the :mod:`allantools` function to evaluate Returns ------- result: dict T...
Evaluate the passed function with the supplied data. Stores result in self.out. Parameters ---------- function: str Name of the :mod:`allantools` function to evaluate Returns ------- result: dict The results of the calculation.
def makeServoIDPacket(curr_id, new_id): """ Given the current ID, returns a packet to set the servo to a new ID """ pkt = Packet.makeWritePacket(curr_id, xl320.XL320_ID, [new_id]) return pkt
Given the current ID, returns a packet to set the servo to a new ID
def set_primary(self, **params): """https://developers.coinbase.com/api/v2#set-account-as-primary""" data = self.api_client.set_primary_account(self.id, **params) self.update(data) return data
https://developers.coinbase.com/api/v2#set-account-as-primary
def log_path(self, new_path): """Setter for `log_path`, use with caution.""" if self.has_active_service: raise DeviceError( self, 'Cannot change `log_path` when there is service running.') old_path = self._log_path if new_path == old_path: ...
Setter for `log_path`, use with caution.
def markov_mobility(p, measure="P", ini=None): """ Markov-based mobility index. Parameters ---------- p : array (k, k), Markov transition probability matrix. measure : string If measure= "P", :math:`M_{P} = \\frac{m-\sum_{i=1}^m P_{ii}}{m-1}`; ...
Markov-based mobility index. Parameters ---------- p : array (k, k), Markov transition probability matrix. measure : string If measure= "P", :math:`M_{P} = \\frac{m-\sum_{i=1}^m P_{ii}}{m-1}`; if measure = "D", :math:`M_{D} = 1...
def _amp3d_to_2d(self, amp, sigma_x, sigma_y): """ converts 3d density into 2d density parameter :param amp: :param sigma_x: :param sigma_y: :return: """ return amp * np.sqrt(np.pi) * np.sqrt(sigma_x * sigma_y * 2)
converts 3d density into 2d density parameter :param amp: :param sigma_x: :param sigma_y: :return:
def end_point_to_center_parameters(x1, y1, x2, y2, fA, fS, rx, ry, phi=0): ''' See http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes F.6.5 note that we reduce phi to zero outside this routine ''' rx = fabs(rx) ry = fabs(ry) # step 1 if phi: phi_rad = radians(phi) ...
See http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes F.6.5 note that we reduce phi to zero outside this routine
def start(self): """ Start the connection. This should be called after all listeners have been registered. If this method is not called, no frames will be received by the connection. """ self.running = True self.attempt_connection() receiver_thread = self....
Start the connection. This should be called after all listeners have been registered. If this method is not called, no frames will be received by the connection.
def get_selective_mirrors(self, number=None, pop_sorted=None): """get mirror genotypic directions of the `number` worst solution, based on ``pop_sorted`` attribute (from last iteration). Details: Takes the last ``number=sp.lam_mirr`` entries in ``pop_sorted=self.pop_sort...
get mirror genotypic directions of the `number` worst solution, based on ``pop_sorted`` attribute (from last iteration). Details: Takes the last ``number=sp.lam_mirr`` entries in ``pop_sorted=self.pop_sorted`` as solutions to be mirrored.
def is_component(self, path): '''Is the node pointed to by @ref path a component?''' node = self.get_node(path) if not node: return False return node.is_component
Is the node pointed to by @ref path a component?
def execute(self, conn, block_id="", transaction=False): """ simple execute """ if not conn: dbsExceptionHandler("dbsException-db-conn-failed", "Oracle/FileBuffer/List. Expects db connection from upper layer.") sql = self.sql binds = { "block_id" : block_id} cursor...
simple execute
def set_group_bond(self, atom_index_one, atom_index_two, bond_order): """Add bonds within a group. :param atom_index_one: the integer atom index (in the group) of the first partner in the bond :param atom_index_two: the integer atom index (in the group) of the second partner in the bond ...
Add bonds within a group. :param atom_index_one: the integer atom index (in the group) of the first partner in the bond :param atom_index_two: the integer atom index (in the group) of the second partner in the bond :param bond_order: the integer bond order
def _collect_plugin(self, plugin): '''Wraps the collect_plugin() method so we can apply a timeout against the plugin as a whole''' with ThreadPoolExecutor(1) as pool: try: t = pool.submit(self.collect_plugin, plugin) # Re-type int 0 to NoneType, as oth...
Wraps the collect_plugin() method so we can apply a timeout against the plugin as a whole
def complete_config(self, text, line, begidx, endidx): ''' Tab-complete config command ''' return [i for i in PsiturkShell.config_commands if i.startswith(text)]
Tab-complete config command
def get_feed(self, datasource_id): """ Получение настроек для фида :param datasource_id: идентификатор фида :return: FeedDataSource """ info = self.__metadb.one( """ SELECT to_json(ds) as datasource , to_json(fc) as connector ...
Получение настроек для фида :param datasource_id: идентификатор фида :return: FeedDataSource
def initialize(self, all_options): """Create run_info and relevant directories, and return the run id. Must be called before `start`. """ if self.run_info: raise AssertionError('RunTracker.initialize must not be called multiple times.') # Initialize the run. # Select a globally unique I...
Create run_info and relevant directories, and return the run id. Must be called before `start`.
def plot(self, phi, r, **kwargs): """Add a data series to the plot. :param phi: array containing phi-values, should be in degrees (or radians). :param r: array containing r-values. For further options see the plot function of the super class. """ if...
Add a data series to the plot. :param phi: array containing phi-values, should be in degrees (or radians). :param r: array containing r-values. For further options see the plot function of the super class.
def addRegistration(self, key, registration): """ Binds an IoC registration to a given key. It should be used if you introduce custom registrations; otherwise, registerTransient() and registerSingleton() are usually shorter and simpler. Registering a key twice raises a KeyError. ...
Binds an IoC registration to a given key. It should be used if you introduce custom registrations; otherwise, registerTransient() and registerSingleton() are usually shorter and simpler. Registering a key twice raises a KeyError.
def to_json(self, filename=None): """ Exports statistical data to a JSON formatted file Parameters ---------- filename: output file that holds statistics data """ def json_encoder(obj): if isinstance(obj, pd.DataFrame) or isinstance(obj, pd.Series)...
Exports statistical data to a JSON formatted file Parameters ---------- filename: output file that holds statistics data
def validate_protoquil(program: Program) -> None: """ Ensure that a program is valid ProtoQuil, otherwise raise a ValueError. Protoquil is a subset of Quil which excludes control flow and classical instructions. :param program: The Quil program to validate. """ valid_instruction_types = tuple([...
Ensure that a program is valid ProtoQuil, otherwise raise a ValueError. Protoquil is a subset of Quil which excludes control flow and classical instructions. :param program: The Quil program to validate.
def flags(self, index): """ Reimplements the :meth:`QAbstractItemModel.flags` method. :param index: Index. :type index: QModelIndex :return: Flags. ( Qt.ItemFlags ) """ if not index.isValid(): return Qt.NoItemFlags node = self.get_node(index...
Reimplements the :meth:`QAbstractItemModel.flags` method. :param index: Index. :type index: QModelIndex :return: Flags. ( Qt.ItemFlags )
def upgradeExplicitOid(store): """ Upgrade a store to use explicit oid columns. This allows VACUUMing the database without corrupting it. This requires copying all of axiom_objects and axiom_types, as well as all item tables that have not yet been upgraded. Consider VACUUMing the database...
Upgrade a store to use explicit oid columns. This allows VACUUMing the database without corrupting it. This requires copying all of axiom_objects and axiom_types, as well as all item tables that have not yet been upgraded. Consider VACUUMing the database afterwards to reclaim space.
def is_method(arg): """Checks whether given object is a method.""" if inspect.ismethod(arg): return True if isinstance(arg, NonInstanceMethod): return True # Unfortunately, there is no disctinction between instance methods # that are yet to become part of a class, and regular functi...
Checks whether given object is a method.
def do_create(self, params): """ \x1b[1mNAME\x1b[0m create - Creates a znode \x1b[1mSYNOPSIS\x1b[0m create <path> <value> [ephemeral] [sequence] [recursive] [async] \x1b[1mOPTIONS\x1b[0m * ephemeral: make the znode ephemeral (default: false) * sequence: make the znode sequentia...
\x1b[1mNAME\x1b[0m create - Creates a znode \x1b[1mSYNOPSIS\x1b[0m create <path> <value> [ephemeral] [sequence] [recursive] [async] \x1b[1mOPTIONS\x1b[0m * ephemeral: make the znode ephemeral (default: false) * sequence: make the znode sequential (default: false) * recursive: r...
def check_vlan_type_driver_commands(self): """Checks the validity of CLI commands for Arista's VLAN type driver. This method tries to execute the commands used exclusively by the arista_vlan type driver and stores the commands if they succeed. """ cmd = ['show openstack re...
Checks the validity of CLI commands for Arista's VLAN type driver. This method tries to execute the commands used exclusively by the arista_vlan type driver and stores the commands if they succeed.
def ValidateIapJwtFromComputeEngine(iap_jwt, cloud_project_number, backend_service_id): """Validates an IAP JWT for your (Compute|Container) Engine service. Args: iap_jwt: The contents of the X-Goog-IAP-JWT-Assertion header. cloud_project_number: The project *number* for...
Validates an IAP JWT for your (Compute|Container) Engine service. Args: iap_jwt: The contents of the X-Goog-IAP-JWT-Assertion header. cloud_project_number: The project *number* for your Google Cloud project. This is returned by 'gcloud projects describe $PROJECT_ID', or in the Project Info card i...
def _extract_prop_set(line): """ Extract the (key, value)-tuple from a string like: >>> 'set foo = "bar"' :param line: :return: tuple (key, value) """ token = ' = "' line = line[4:] pos = line.find(token) return line[:pos], line[pos + 4:-1]
Extract the (key, value)-tuple from a string like: >>> 'set foo = "bar"' :param line: :return: tuple (key, value)
def _is_target_valid(self, cfg, target): # pylint:disable=no-self-use """ Check if the resolved target is valid. :param cfg: The CFG analysis object. :param int target: The target to check. :return: True if the target is valid. False otherwise. :rtyp...
Check if the resolved target is valid. :param cfg: The CFG analysis object. :param int target: The target to check. :return: True if the target is valid. False otherwise. :rtype: bool
def view(cls, database, viewname, **options): """Execute a CouchDB named view and map the result values back to objects of this mapping. Note that by default, any properties of the document that are not included in the values of the view will be treated as if they were missing f...
Execute a CouchDB named view and map the result values back to objects of this mapping. Note that by default, any properties of the document that are not included in the values of the view will be treated as if they were missing from the document. If you want to load the full document f...
def run(self): """ Executes a started pipeline by pulling results from it's output ``Pipers``. Processing nodes i.e. ``Pipers`` with the ``track`` attribute set ``True`` will have their returned results stored within the ``Dagger.stats['pipers_tracked']`` dictionary. A running...
Executes a started pipeline by pulling results from it's output ``Pipers``. Processing nodes i.e. ``Pipers`` with the ``track`` attribute set ``True`` will have their returned results stored within the ``Dagger.stats['pipers_tracked']`` dictionary. A running pipeline can be paused.
def load_parameters(self, filename, ctx=None, allow_missing=False, ignore_extra=False): """Load parameters from file previously saved by `save_parameters`. Parameters ---------- filename : str Path to parameter file. ctx : Context or list of C...
Load parameters from file previously saved by `save_parameters`. Parameters ---------- filename : str Path to parameter file. ctx : Context or list of Context, default cpu() Context(s) to initialize loaded parameters on. allow_missing : bool, default Fals...
def align(self, other): """ Align two time series so that len(self) == len(other) and self.timstamps == other.timestamps. :return: :tuple:(`TimeSeries` object(the aligned self), `TimeSeries` object(the aligned other)) """ if isinstance(other, TimeSeries): aligned, ot...
Align two time series so that len(self) == len(other) and self.timstamps == other.timestamps. :return: :tuple:(`TimeSeries` object(the aligned self), `TimeSeries` object(the aligned other))
def _render(self): """Create a Message version of this ErrorMessage Args: none Returns: the Message instance of this ErrorMessage Raises: Errors are propagated """ message = Message() message.add(Heading(tr('Problem'), **ORAN...
Create a Message version of this ErrorMessage Args: none Returns: the Message instance of this ErrorMessage Raises: Errors are propagated
def run(self): """ Usage: containment run """ run_command = ( settings.project_customization.runfile.read_text().split() ) chmod_string = ( "chmod +x " + settings.project_customization.runfile.absolute().as_posix() ) ...
Usage: containment run
def install_monitor(self, monitor_pattern: str, monitor_stat_func_name: str): """ Installs an MXNet monitor onto the underlying module. :param monitor_pattern: Pattern string. :param monitor_stat_func_name: Name of monitor statistics function. """ self._monitor = mx.moni...
Installs an MXNet monitor onto the underlying module. :param monitor_pattern: Pattern string. :param monitor_stat_func_name: Name of monitor statistics function.
def delete_file(self, secure_data_path): """Delete a file at the given secure data path""" secret_resp = delete_with_retry(self.cerberus_url + '/v1/secure-file/' + secure_data_path, headers=self.HEADERS) throw_if_bad_response(secret_resp) return secr...
Delete a file at the given secure data path
def rec_merge(d1, d2): """ Recursively merge two dictionaries Update two dicts of dicts recursively, if either mapping has leaves that are non-dicts, the second's leaf overwrites the first's. import collections import functools e.g. functools.reduce(rec_merge, (d1, d2, d3, d4)) """ ...
Recursively merge two dictionaries Update two dicts of dicts recursively, if either mapping has leaves that are non-dicts, the second's leaf overwrites the first's. import collections import functools e.g. functools.reduce(rec_merge, (d1, d2, d3, d4))
def decodeElem(self, bytes, index, raw=False): """Decodes a single element at array[index] from a sequence bytes that contain data for the entire array. """ self._assertIndex(index) start = index * self.type.nbytes stop = start + self.type.nbytes if stop > len(b...
Decodes a single element at array[index] from a sequence bytes that contain data for the entire array.
def _pick_or_create_inserted_op_moment_index( self, splitter_index: int, op: ops.Operation, strategy: InsertStrategy) -> int: """Determines and prepares where an insertion will occur. Args: splitter_index: The index to insert at. op: The operation that wi...
Determines and prepares where an insertion will occur. Args: splitter_index: The index to insert at. op: The operation that will be inserted. strategy: The insertion strategy. Returns: The index of the (possibly new) moment where the insertion should ...
def get_membership(self): """ Alternative representation of group membership - creates a list with one tuple per group; each tuple contains the indices of its members Example: partition = (0,0,0,1,0,1,2,2) membership = [(0,1,2,4), (3,5), (6,7)] :return:...
Alternative representation of group membership - creates a list with one tuple per group; each tuple contains the indices of its members Example: partition = (0,0,0,1,0,1,2,2) membership = [(0,1,2,4), (3,5), (6,7)] :return: list of tuples giving group memberships by in...
def point_to_polygon_distance(polygon, pxx, pyy): """ Calculate the distance to polygon for each point of the collection on the 2d Cartesian plane. :param polygon: Shapely "Polygon" geometry object. :param pxx: List or numpy array of abscissae values of points to calculate t...
Calculate the distance to polygon for each point of the collection on the 2d Cartesian plane. :param polygon: Shapely "Polygon" geometry object. :param pxx: List or numpy array of abscissae values of points to calculate the distance from. :param pyy: Same structure as ``...
def register_outgoing_conn(self, conn): """Add outgoing connection into the heap.""" assert conn, "conn is required" conn.set_outbound_pending_change_callback(self._on_conn_change) self.connections.append(conn) self._set_on_close_cb(conn) self._on_conn_change()
Add outgoing connection into the heap.
def DataProcessorsDelete(self, dataProcessorId): """ Delete a data processor in CommonSense. @param dataProcessorId - The id of the data processor that will be deleted. @return (bool) - Boolean indicating whether GroupsP...
Delete a data processor in CommonSense. @param dataProcessorId - The id of the data processor that will be deleted. @return (bool) - Boolean indicating whether GroupsPost was successful.
def decodeString(encoded): ''' Decodes an UTF-8 string from an encoded MQTT bytearray. Returns the decoded string and renaining bytearray to be parsed ''' length = encoded[0]*256 + encoded[1] return (encoded[2:2+length].decode('utf-8'), encoded[2+length:])
Decodes an UTF-8 string from an encoded MQTT bytearray. Returns the decoded string and renaining bytearray to be parsed
def simulate_paths(is_returns, num_days, starting_value=1, num_samples=1000, random_seed=None): """ Gnerate alternate paths using available values from in-sample returns. Parameters ---------- is_returns : pandas.core.frame.DataFrame Non-cumulative in-sample returns. ...
Gnerate alternate paths using available values from in-sample returns. Parameters ---------- is_returns : pandas.core.frame.DataFrame Non-cumulative in-sample returns. num_days : int Number of days to project the probability cone forward. starting_value : int or float Starti...
def run(extension=None, name=None, description=None, salt_dir=None, merge=False, temp_dir=None): ''' A template factory for extending the salt ecosystem :param extension: The extension type, e.g. 'module', 'state', if omitted, user will be prompted :type extension: ``str`` :param name: Python-fri...
A template factory for extending the salt ecosystem :param extension: The extension type, e.g. 'module', 'state', if omitted, user will be prompted :type extension: ``str`` :param name: Python-friendly name for the module, if omitted, user will be prompted :type name: ``str`` :param description...
def ConsumeString(self): """Consumes a string value. Returns: The string parsed. Raises: ParseError: If a string value couldn't be consumed. """ the_bytes = self.ConsumeByteString() try: return six.text_type(the_bytes, 'utf-8') except UnicodeDecodeError as e: raise ...
Consumes a string value. Returns: The string parsed. Raises: ParseError: If a string value couldn't be consumed.
def get_colors(stylename): """Construct the keys to be used building the base stylesheet from a templatee.""" style = get_style_by_name(stylename) fgcolor = style.style_for_token(Token.Text)['color'] or '' if len(fgcolor) in (3,6): # could be 'abcdef' or 'ace' hex, which needs '#' prefix ...
Construct the keys to be used building the base stylesheet from a templatee.
def dasrfr(handle, lenout=_default_len_out): """ Return the contents of the file record of a specified DAS file. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dasrfr_c.html :param handle: DAS file handle. :type handle: int :param lenout: length of output strs :type lenout: ...
Return the contents of the file record of a specified DAS file. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dasrfr_c.html :param handle: DAS file handle. :type handle: int :param lenout: length of output strs :type lenout: str :return: ID word, DAS internal file name, Number ...
def loadFromFile(self, path): """ Load JSON config file from disk at the given path :param str path: path to config file """ if '~' in path: path = os.path.expanduser(path) f = open(path) body = f.read() f.close() self._path = path ...
Load JSON config file from disk at the given path :param str path: path to config file
def calc_hessian(beta, design, alt_IDs, rows_to_obs, rows_to_alts, utility_transform, transform_first_deriv_c, transform_first_deriv_v, transform_deriv_alpha, block_ma...
Parameters ---------- beta : 1D ndarray. All elements should by ints, floats, or longs. Should have 1 element for each utility coefficient being estimated (i.e. num_features). design : 2D ndarray. There should be one row per observation per available alternative. There should...
def _in_git_repo(): """Returns True if inside a git repo, False otherwise""" ret = temple.utils.shell('git rev-parse', stderr=subprocess.DEVNULL, check=False) return ret.returncode == 0
Returns True if inside a git repo, False otherwise
def get(self, client_id, code): """Get the Grant object with the given client ID and code :param client_id: ID of the client :param code: """ return self.query.filter_by(client_id=client_id, code=code).first()
Get the Grant object with the given client ID and code :param client_id: ID of the client :param code:
def to_tensor(X, device, accept_sparse=False): """Turn input data to torch tensor. Parameters ---------- X : input data Handles the cases: * PackedSequence * numpy array * torch Tensor * scipy sparse CSR matrix * list or tuple of one of the former *...
Turn input data to torch tensor. Parameters ---------- X : input data Handles the cases: * PackedSequence * numpy array * torch Tensor * scipy sparse CSR matrix * list or tuple of one of the former * dict with values of one of the former device : s...
def create_fork(self, organization=None): """Create a fork of this repository. :param str organization: (required), login for organization to create the fork under :returns: :class:`Repository <Repository>` if successful, else None """ url = self._build_url('forks', ...
Create a fork of this repository. :param str organization: (required), login for organization to create the fork under :returns: :class:`Repository <Repository>` if successful, else None
def calc_lfp(self): """ Sum all the LFP contributions from every cell type. """ LFParray = np.array([]) LFPdict = {} i = 0 for y in self.y: fil = os.path.join(self.populations_path, self.output_file.format(y, 'LFP.h5')) ...
Sum all the LFP contributions from every cell type.
def prepare_prop_defs(prop_defs, prop_name, cls_names): """ Examines and adds any missing defs to the prop_defs dictionary for use with the RdfPropertyMeta.__prepare__ method Args: ----- prop_defs: the defintions from the rdf vocabulary defintion prop_name: the property name ...
Examines and adds any missing defs to the prop_defs dictionary for use with the RdfPropertyMeta.__prepare__ method Args: ----- prop_defs: the defintions from the rdf vocabulary defintion prop_name: the property name cls_names: the name of the associated classes Returns: ---...
def asn(self, ip, announce_date=None): """ Give an IP, maybe a date, get the ASN. This is the fastest command. :param ip: IP address to search for :param announce_date: Date of the announcement :rtype: String, ASN. """ assignations, ...
Give an IP, maybe a date, get the ASN. This is the fastest command. :param ip: IP address to search for :param announce_date: Date of the announcement :rtype: String, ASN.
def add_default_module_dir(self): """ Add directory to store built-in plugins to `module_dir` parameter. Default directory to store plugins is `BLACKBIRD_INSTALL_DIR/plugins`. :rtype: None :return: None """ default_module_dir = os.path.join( os.path.ab...
Add directory to store built-in plugins to `module_dir` parameter. Default directory to store plugins is `BLACKBIRD_INSTALL_DIR/plugins`. :rtype: None :return: None
def _copySchemaFile(self, src, dst): """ Copy a proto file to the temporary directory, with appropriate line replacements """ with open(src) as srcFile, open(dst, 'w') as dstFile: srcLines = srcFile.readlines() for srcLine in srcLines: toWr...
Copy a proto file to the temporary directory, with appropriate line replacements
def _url_open(self, method, bucket_name=None, object_name=None, query=None, body=None, headers={}, content_sha256=None, preload_content=True): """ Open a url wrapper around signature version '4' and :meth:`urllib3.PoolManager.urlopen` """ # ...
Open a url wrapper around signature version '4' and :meth:`urllib3.PoolManager.urlopen`
async def async_get(self, url): """Get an arbitrary page. This resets the iterator and then fully consumes it to return the specific page **only**. :param str url: URL to arbitrary page results. """ self.reset() self.next_link = url return await self.asy...
Get an arbitrary page. This resets the iterator and then fully consumes it to return the specific page **only**. :param str url: URL to arbitrary page results.
def standardize_genes(self, inplace=False): """Standardize the expression of each gene (row).""" matrix = self.center_genes(inplace=inplace) matrix.X[:,:] = matrix.X / \ np.tile(np.std(matrix.X, axis=1, ddof=1), (matrix.n, 1)).T return matrix
Standardize the expression of each gene (row).
def has_c_library(library, extension=".c"): """Check whether a C/C++ library is available on the system to the compiler. Parameters ---------- library: str The library we want to check for e.g. if we are interested in FFTW3, we want to check for `fftw3.h`, so this parameter will be `fft...
Check whether a C/C++ library is available on the system to the compiler. Parameters ---------- library: str The library we want to check for e.g. if we are interested in FFTW3, we want to check for `fftw3.h`, so this parameter will be `fftw3`. extension: str If we want to check...
def get_descriptions(config, exam_lex, lexer): """ based on the configuration settings determines which windows to include """ if config.BOOLEAN_STATES[config.config.get('Layout', 'command_description')]: if config.BOOLEAN_STATES[config.config.get('Layout', 'param_description')]: return VSpl...
based on the configuration settings determines which windows to include
def trace_generator(trace, start=0, stop=None, step=1): """Return a generator returning values from the object's trace. Ex: T = trace_generator(theta.trace) T.next() for t in T:... """ i = start stop = stop or np.inf size = min(trace.length(), stop) while i < size: index...
Return a generator returning values from the object's trace. Ex: T = trace_generator(theta.trace) T.next() for t in T:...
def process_date_created(self, text): """Set date_created to the oldest date (date created).""" date = parse(text) if self.date_created == 'N/A': self.date_created = date if date < self.date_created: self.date_created = date
Set date_created to the oldest date (date created).
def quadrature_expectation(p, obj1, obj2=None, num_gauss_hermite_points=None): """ Compute the expectation <obj1(x) obj2(x)>_p(x) Uses Gauss-Hermite quadrature for approximate integration. :type p: (mu, cov) tuple or a `ProbabilityDistribution` object :type obj1: kernel, mean function, (kernel, fea...
Compute the expectation <obj1(x) obj2(x)>_p(x) Uses Gauss-Hermite quadrature for approximate integration. :type p: (mu, cov) tuple or a `ProbabilityDistribution` object :type obj1: kernel, mean function, (kernel, features), or None :type obj2: kernel, mean function, (kernel, features), or None :par...
def compile_entity_feature_generator(): """ Given optional arguments, returns a generator function which accepts an xml root and a list of indexes for a mention, and will generate relation features for this entity. """ BASIC_ATTRIBS_REL = ["lemma", "dep_label"] m = Mention(0) # Basic ...
Given optional arguments, returns a generator function which accepts an xml root and a list of indexes for a mention, and will generate relation features for this entity.
def pack_field(self, value): """ Pack single field (string or integer value) <field> ::= <int32_varint><data> :param value: value to be packed :type value: bytes, str, int or long :return: packed value :rtype: bytes """ if isinstance(value, str):...
Pack single field (string or integer value) <field> ::= <int32_varint><data> :param value: value to be packed :type value: bytes, str, int or long :return: packed value :rtype: bytes
def update_device_list(self, sessions): """ Update device list. """ if sessions is None: _LOGGER.error('Error updating Emby devices.') return new_devices = [] active_devices = [] dev_update = False for device in sessions: dev_name = '{...
Update device list.
def stream_agent_show(self, metric_key, department_id=None, **kwargs): "https://developer.zendesk.com/rest_api/docs/chat/apis#get-single-agent-status" api_path = "/stream/agents/{metric_key}" api_path = api_path.format(metric_key=metric_key) api_query = {} if "query" in kwargs.ke...
https://developer.zendesk.com/rest_api/docs/chat/apis#get-single-agent-status
def properties_changed(self, sender, changed_properties, invalidated_properties): """ Called when a device property has changed or got invalidated. """ if 'Connected' in changed_properties: if changed_properties['Connected']: self.connect_succeeded() ...
Called when a device property has changed or got invalidated.
def chkaddhdr(self, line): """If this line contains desired header info, save it.""" mtch = self.cmpline.search(line) if mtch: self.gpadhdr.append(mtch.group(1))
If this line contains desired header info, save it.