code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _get_info(self, host, port, unix_socket, auth): """Return info dict from specified Redis instance :param str host: redis host :param int port: redis port :rtype: dict """ client = self._client(host, port, unix_socket, auth) if client is None: return None info ...
Return info dict from specified Redis instance :param str host: redis host :param int port: redis port :rtype: dict
def calculate_solidity(labels,indexes=None): """Calculate the area of each label divided by the area of its convex hull labels - a label matrix indexes - the indexes of the labels to measure """ if indexes is not None: """ Convert to compat 32bit integer """ indexes = np.array(i...
Calculate the area of each label divided by the area of its convex hull labels - a label matrix indexes - the indexes of the labels to measure
def requires_token_auth(resource): ''' Flask decorator protecting ressources using token scheme ''' @functools.wraps(resource) def decorated(*args, **kwargs): ''' Check provided token ''' token = flask.request.headers.get('Authorization') user = check_token(token) if...
Flask decorator protecting ressources using token scheme
def parse_reports(self): """ Find RSeQC read_duplication reports and parse their data """ # Set up vars self.read_dups = dict() # Go through files and parse data for f in self.find_log_files('rseqc/read_duplication_pos'): if f['f'].startswith('Occurrence UniqReadNumber'): if f[...
Find RSeQC read_duplication reports and parse their data
def addEdge(self, outVertex, inVertex, label): """Creates a new edge @params outVertex: Edge origin Vertex @params inVertex: Edge target vertex @params label: Edge label @returns The created Edge object""" n1 = outVertex.neoelement n2 = inVertex.neoelement ...
Creates a new edge @params outVertex: Edge origin Vertex @params inVertex: Edge target vertex @params label: Edge label @returns The created Edge object
def run_simple(hostname, port, application, use_reloader=False, use_debugger=False, use_evalex=True, extra_files=None, reloader_interval=1, threaded=False, processes=1, request_handler=None, static_files=None, passthrough_errors=False, ssl_context=None): "...
Start an application using wsgiref and with an optional reloader. This wraps `wsgiref` to fix the wrong default reporting of the multithreaded WSGI variable and adds optional multithreading and fork support. This function has a command-line interface too:: python -m werkzeug.serving --help ....
def decrypt(v, key=None, keyfile=None): """ Encrypt an string """ cipher = functions.get_cipher(key, keyfile) return cipher.decrypt(v)
Encrypt an string
def render_revalidation_failure(self, step, form, **kwargs): """ Gets called when a form doesn't validate when rendering the done view. By default, it changed the current step to failing forms step and renders the form. """ self.storage.current_step = step return ...
Gets called when a form doesn't validate when rendering the done view. By default, it changed the current step to failing forms step and renders the form.
def unregister(self, recipe): """ Unregisters a given recipe class. """ recipe = self.get_recipe_instance_from_class(recipe) if recipe.slug in self._registry: del self._registry[recipe.slug]
Unregisters a given recipe class.
def percent_value(self, percent): """ Returns the time value at ``percent`` of this interval. :param percent: the percent :type percent: :class:`~aeneas.exacttiming.Decimal` :raises TypeError: if ``time_point`` is not an instance of ``TimeValue`` :rtype: :class:`~aeneas...
Returns the time value at ``percent`` of this interval. :param percent: the percent :type percent: :class:`~aeneas.exacttiming.Decimal` :raises TypeError: if ``time_point`` is not an instance of ``TimeValue`` :rtype: :class:`~aeneas.exacttiming.TimeValue`
def _named_stream(self, name, binary=False): """ Create an indexed output stream i.e. 'test_00000001.name' :param name: Identifier for the stream :return: A context-managed stream-like object """ with self._store.save_stream(self._named_key(name), binary=binary) as s: ...
Create an indexed output stream i.e. 'test_00000001.name' :param name: Identifier for the stream :return: A context-managed stream-like object
def update_pypsa_load_timeseries(network, loads_to_update=None, timesteps=None): """ Updates load time series in pypsa representation. This function overwrites p_set and q_set of loads_t attribute of pypsa network. Be aware that if you call this function with `times...
Updates load time series in pypsa representation. This function overwrites p_set and q_set of loads_t attribute of pypsa network. Be aware that if you call this function with `timesteps` and thus overwrite current time steps it may lead to inconsistencies in the pypsa network since only load time s...
def delete(self): """ Delete this :term:`Metrics Context` resource. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ self.manager.session.delete(self.ur...
Delete this :term:`Metrics Context` resource. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
def publish(self, channel_id): """ publish: publishes tree to Kolibri Args: channel_id (str): channel's id on Kolibri Studio Returns: None """ payload = { "channel_id":channel_id, } response = config.SESSION.post(config.publish_...
publish: publishes tree to Kolibri Args: channel_id (str): channel's id on Kolibri Studio Returns: None
def add_bboxes_to_image(image, bboxes, color='red', width=1): """ Draw rectangles on the image for the bounding boxes Returns a PIL.Image Arguments: image -- input image bboxes -- bounding boxes in the [((l, t), (r, b)), ...] format Keyword arguments: color -- color to draw the rectangle...
Draw rectangles on the image for the bounding boxes Returns a PIL.Image Arguments: image -- input image bboxes -- bounding boxes in the [((l, t), (r, b)), ...] format Keyword arguments: color -- color to draw the rectangles width -- line width of the rectangles Example: image = Image...
def one_of(self, items): """ Check if the value is contained in a list or generator. >>> Query().f1.one_of(['value 1', 'value 2']) :param items: The list of items to check with """ return self._generate_test( lambda value: value in items, ('one_o...
Check if the value is contained in a list or generator. >>> Query().f1.one_of(['value 1', 'value 2']) :param items: The list of items to check with
def unwatch_source(self, source_id): """ Remove a souce from the watchlist. """ source_id = int(source_id) self._watched_sources.remove(source_id) return (yield from self._send_cmd("WATCH S[%d] OFF" % ( source_id, )))
Remove a souce from the watchlist.
def prepend_child(self, name): """Prepend a child element with the specified name.""" return XMLElement(lib.lsl_prepend_child(self.e, str.encode(name)))
Prepend a child element with the specified name.
def _dict_of_funcs(self, funcs: list) -> pd.Series: """Return a pd.Series of functions with index derived from the function name.""" return {func.__name__: func for func in funcs}
Return a pd.Series of functions with index derived from the function name.
def reduce_l2(attrs, inputs, proto_obj): """Reduce input tensor by l2 normalization.""" new_attrs = translation_utils._fix_attribute_names(attrs, {'axes':'axis'}) return 'norm', new_attrs, inputs
Reduce input tensor by l2 normalization.
def rap(self,analytic=False,pot=None,**kwargs): """ NAME: rap PURPOSE: return the apocenter radius INPUT: analytic - compute this analytically pot - potential to use for analytical calculation OUTPUT: R_ap HISTORY: ...
NAME: rap PURPOSE: return the apocenter radius INPUT: analytic - compute this analytically pot - potential to use for analytical calculation OUTPUT: R_ap HISTORY: 2010-09-20 - Written - Bovy (NYU)
def copy(self, **params): '''Creates the new instance of the Route substituting the requested parameters.''' new_params = dict() for name in ['owner', 'priority', 'key', 'final']: new_params[name] = params.get(name, getattr(self, name)) return Route(**new_params)
Creates the new instance of the Route substituting the requested parameters.
def p_mp_createInstance(p): """mp_createInstance : instanceDeclaration""" inst = p[1] if p.parser.verbose: p.parser.log( _format("Creating instance of {0!A}.", inst.classname)) try: p.parser.handle.CreateInstance(inst) except CIMError as ce: if ce.status_code == C...
mp_createInstance : instanceDeclaration
def getAMFRequest(self, requests): """ Builds an AMF request {LEnvelope<pyamf.remoting.Envelope>} from a supplied list of requests. """ envelope = remoting.Envelope(self.amf_version) if self.logger: self.logger.debug('AMF version: %s' % self.amf_version) ...
Builds an AMF request {LEnvelope<pyamf.remoting.Envelope>} from a supplied list of requests.
def getPageContent(url, session, max_content_bytes=MaxContentBytes): """Get text content of given URL.""" check_robotstxt(url, session) # read page data try: page = urlopen(url, session, max_content_bytes=max_content_bytes) except IOError: page = urlopen(url, session, max_content_byt...
Get text content of given URL.
def create_customer(self, full_name, email): """ Creating customer user :param full_name: str :param email: str :return: New customer """ log.warning('Creating customer...') data = {'fullName': full_name, 'email': email} return self.post('rest/se...
Creating customer user :param full_name: str :param email: str :return: New customer
def get_bond_master(interface): """Returns bond master if interface is bond slave otherwise None. NOTE: the provided interface is expected to be physical """ if interface: iface_path = '/sys/class/net/%s' % (interface) if os.path.exists(iface_path): if '/virtual/' in os.path...
Returns bond master if interface is bond slave otherwise None. NOTE: the provided interface is expected to be physical
def _set_ssm_enable(self, v, load=False): """ Setter method for ssm_enable, mapped from YANG variable /routing_system/router/hide_pim_holder/pim/ssm_enable (container) If this variable is read-only (config: false) in the source YANG file, then _set_ssm_enable is considered as a private method. Backe...
Setter method for ssm_enable, mapped from YANG variable /routing_system/router/hide_pim_holder/pim/ssm_enable (container) If this variable is read-only (config: false) in the source YANG file, then _set_ssm_enable is considered as a private method. Backends looking to populate this variable should do so...
def calc_delay(remainingDrops): ''' Calculate the idle delay Minimum play time for cards to drop is ~20min again. Except for accounts that requested a refund? Re-check every 15 mintes if there are more than 1 card drops remaining. If only one drop remains, check every 5 minutes ...
Calculate the idle delay Minimum play time for cards to drop is ~20min again. Except for accounts that requested a refund? Re-check every 15 mintes if there are more than 1 card drops remaining. If only one drop remains, check every 5 minutes
def save(obj, path=None, name=None, sep=_sep, deep=False, mode='npz', strip=None, compressed=False, verb=True, return_pfe=False): """ Save the ToFu object ToFu provides built-in saving and loading functions for ToFu objects. Specifying saving path ad name is optional (defaults recommended) The...
Save the ToFu object ToFu provides built-in saving and loading functions for ToFu objects. Specifying saving path ad name is optional (defaults recommended) The mode refers to the file format Good practices are: - save all struct objects Parameters ---------- obj : ToFuObjec...
def write_skycatalog(self,filename): """ Write out the all_radec catalog for this image to a file. """ if self.all_radec is None: return ralist = self.all_radec[0]#.tolist() declist = self.all_radec[1]#.tolist() f = open(filename,'w') f.write("#Sky pos...
Write out the all_radec catalog for this image to a file.
def revoke_security_group_deprecated(self, group_name, src_security_group_name=None, src_security_group_owner_id=None, ip_protocol=None, from_port=None, to_...
NOTE: This method uses the old-style request parameters that did not allow a port to be specified when authorizing a group. Remove an existing rule from an existing security group. You need to pass in either src_security_group_name and src_security_group_owner_id OR ...
async def read(cls, *, hostnames: typing.Sequence[str] = None): """List nodes. :param hostnames: Sequence of hostnames to only return. :type hostnames: sequence of `str` """ params = {} if hostnames: params["hostname"] = [ normalize_hostname(h...
List nodes. :param hostnames: Sequence of hostnames to only return. :type hostnames: sequence of `str`
def knuth(data): """ References ---------- .. [1] K. Knuth, "Optimal Data-Based Binning for Histograms", 2006. http://arxiv.org/pdf/physics/0605197v1.pdf """ import scipy.optimize as optimize def f(data): from scipy.special import gamma...
References ---------- .. [1] K. Knuth, "Optimal Data-Based Binning for Histograms", 2006. http://arxiv.org/pdf/physics/0605197v1.pdf
def root(self) -> "GameNode": """Gets the root node, i.e., the game.""" node = self while node.parent: node = node.parent return node
Gets the root node, i.e., the game.
def face_ordering(mesh): """ Triangles with three different length sides are ordered in two ways: [small edge, medium edge, large edge] (SML) [small edge, large edge, medium edge] (SLM) This function returns [-1, 0, 1], depending on whether the triangle is SML or SLM, and 0 if M == L. ...
Triangles with three different length sides are ordered in two ways: [small edge, medium edge, large edge] (SML) [small edge, large edge, medium edge] (SLM) This function returns [-1, 0, 1], depending on whether the triangle is SML or SLM, and 0 if M == L. The reason this is useful as it as a...
def set_network_permission(network_id, usernames, read, write, share,**kwargs): """ Set permissions on a network to a list of users, identifed by their usernames. The read flag ('Y' or 'N') sets read access, the write flag sets write access. If the read flag is 'N', then there is aut...
Set permissions on a network to a list of users, identifed by their usernames. The read flag ('Y' or 'N') sets read access, the write flag sets write access. If the read flag is 'N', then there is automatically no write access or share access.
async def _connect(self): """ Connect to the 'TempDeck' port Planned change- will connect to the correct port in case of multiple TempDecks """ if self._poller: self._poller.join() self._driver.connect(self._port) self._device_info = self._driv...
Connect to the 'TempDeck' port Planned change- will connect to the correct port in case of multiple TempDecks
def get_ext(url): """ Extract an extension from the url. Args: url (str): String representation of a url. Returns: str: Filename extension from a url (without a dot), '' if extension is not present. """ parsed = urllib.parse.urlparse(url) root, ext = os.path.splitext(pars...
Extract an extension from the url. Args: url (str): String representation of a url. Returns: str: Filename extension from a url (without a dot), '' if extension is not present.
def tracking_number(self, service: str = 'usps') -> str: """Generate random tracking number. Supported services: USPS, FedEx and UPS. :param str service: Post service. :return: Tracking number. """ service = service.lower() if service not in ('usps', 'fedex', '...
Generate random tracking number. Supported services: USPS, FedEx and UPS. :param str service: Post service. :return: Tracking number.
def wait_for_provision_state(baremetal_client, node_uuid, provision_state, loops=10, sleep=1): """Wait for a given Provisioning state in Ironic Discoverd Updating the provisioning state is an async operation, we need to wait for it to be completed. :param baremetal_client:...
Wait for a given Provisioning state in Ironic Discoverd Updating the provisioning state is an async operation, we need to wait for it to be completed. :param baremetal_client: Instance of Ironic client :type baremetal_client: ironicclient.v1.client.Client :param node_uuid: The Ironic node UUID ...
def _search_type_in_type_comment(self, code): """ For more info see: https://www.python.org/dev/peps/pep-0484/#type-comments >>> AssignmentProvider()._search_type_in_type_comment('type: int') ['int'] """ for p in self.PEP0484_TYPE_COMMENT_PATTERNS: match = p....
For more info see: https://www.python.org/dev/peps/pep-0484/#type-comments >>> AssignmentProvider()._search_type_in_type_comment('type: int') ['int']
def get_coiledcoil_region(self, cc_number=0, cutoff=7.0, min_kihs=2): """ Assembly containing only assigned regions (i.e. regions with contiguous KnobsIntoHoles. """ g = self.filter_graph(self.graph, cutoff=cutoff, min_kihs=min_kihs) ccs = sorted(networkx.connected_component_subgraphs(g, copy=Tr...
Assembly containing only assigned regions (i.e. regions with contiguous KnobsIntoHoles.
def get_child_models(self): """ Get child models from registered plugins. Fallback to the child model admin and its base model if no plugins are registered. """ child_models = [] for plugin in self.child_model_plugin_class.get_plugins(): child_models.append((p...
Get child models from registered plugins. Fallback to the child model admin and its base model if no plugins are registered.
def extrude_triangulation(vertices, faces, height, **kwargs): """ Turn a 2D triangulation into a watertight Trimesh. Parameters ---------- vertices : (n, 2) float 2D vertices faces : (m, 3) int Triangle in...
Turn a 2D triangulation into a watertight Trimesh. Parameters ---------- vertices : (n, 2) float 2D vertices faces : (m, 3) int Triangle indexes of vertices height : float Distance to extrude triangulation **kwargs: passed to Trimesh Returns --------- mesh...
def list_by_x(prs, key): """ :param key: Grouping key, "type" or "extensions" :return: A list of :class:`Processor` or its children classes grouped by given 'item', [(cid, [:class:`Processor`)]] by default """ if key == "type": kfn = operator.methodcaller(key) res = s...
:param key: Grouping key, "type" or "extensions" :return: A list of :class:`Processor` or its children classes grouped by given 'item', [(cid, [:class:`Processor`)]] by default
def getArguments(parser): "Provides additional validation of the arguments collected by argparse." args = parser.parse_args() # get the number of dimensions in the image if args.example: args.example_image, args.example_header = load(args.example) dimensions = args.example_image.ndim ...
Provides additional validation of the arguments collected by argparse.
def extract_as_epilog(self, text, sections=None, overwrite=False, append=True): """Extract epilog sections from the a docstring Parameters ---------- text The docstring to use sections: list of str The headers of the sections to ...
Extract epilog sections from the a docstring Parameters ---------- text The docstring to use sections: list of str The headers of the sections to extract. If None, the :attr:`epilog_sections` attribute is used overwrite: bool If Tr...
def convert_to_single_placement_group( self, resource_group_name, vm_scale_set_name, active_placement_group_id=None, custom_headers=None, raw=False, **operation_config): """Converts SinglePlacementGroup property to false for a existing virtual machine scale set. :param resource_grou...
Converts SinglePlacementGroup property to false for a existing virtual machine scale set. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param vm_scale_set_name: The name of the virtual machine scale set to create or update. ...
def get_method_description(method): # type: (Callable) -> str """ Retrieves a description of the given method. If possible, the description contains the source file name and line. :param method: A method :return: A description of the method (at least its name) :raise AttributeError: Given o...
Retrieves a description of the given method. If possible, the description contains the source file name and line. :param method: A method :return: A description of the method (at least its name) :raise AttributeError: Given object has no __name__ attribute
def write_newick(rootnode, features=None, format=1, format_root_node=True, is_leaf_fn=None, dist_formatter=None, support_formatter=None, name_formatter=None): """ Iteratively export a tree structure and returns its NHX representation. """ newick = [] leaf = is_leaf_fn if...
Iteratively export a tree structure and returns its NHX representation.
def __extract_file(self, path, fileinfo, destination): """Extracts the specified file to the specified destination. Args: path (str): Relative (to the root of the archive) path of the file to extract. fileinfo (dict): Dictionary c...
Extracts the specified file to the specified destination. Args: path (str): Relative (to the root of the archive) path of the file to extract. fileinfo (dict): Dictionary containing the offset and size of the file (Extract...
def _update_checksum(self): """Update the packet checksum to enable integrity check.""" source_list = [int(octet) for octet in self.source.split(".")] destination_list = [int(octet) for octet in self.destination.split(".")] source_upper = (source_list[0] << 8)...
Update the packet checksum to enable integrity check.
def calc_mass_from_z0(z0, w0): """ Calculates the mass of the particle using the equipartition from the angular frequency of the z signal and the average amplitude of the z signal in nms. Parameters ---------- z0 : float Physical average amplitude of motion in nms w0 : float ...
Calculates the mass of the particle using the equipartition from the angular frequency of the z signal and the average amplitude of the z signal in nms. Parameters ---------- z0 : float Physical average amplitude of motion in nms w0 : float Angular Frequency of z motion Ret...
def _translate_name(name): """Translate the class name to the API endpoint. For example, Car would become cars, FastCar would become fast-cars. Args: name (string): Camel case name (singular) Returns: string: A pluraised, dasherized string. """ ...
Translate the class name to the API endpoint. For example, Car would become cars, FastCar would become fast-cars. Args: name (string): Camel case name (singular) Returns: string: A pluraised, dasherized string.
def url(self): """ The URL to access this preview. """ return reverse('%s:detail' % URL_NAMESPACE, kwargs={ 'module': self.module, 'preview': type(self).__name__, })
The URL to access this preview.
def consumer(self, service, data, to_update, status): """ call the consumer and handle the data :param service: :param data: :param to_update: :param status: :return: status """ # consumer - the service which uses the data ...
call the consumer and handle the data :param service: :param data: :param to_update: :param status: :return: status
def from_json_compatible(schema, dct): "Load from json-encodable" kwargs = {} for key in dct: field_type = schema._fields.get(key) if field_type is None: raise ParseError("Unexpected field encountered in line for record %s: %s" % (schema.__name__, key)) kwargs[key] = fie...
Load from json-encodable
def add_exp_key(self, key, value, ex): "Expired in seconds" return self.c.set(key, value, ex)
Expired in seconds
def _categoryToLabelList(self, category): """ Converts a category number into a list of labels """ if category is None: return [] labelList = [] labelNum = 0 while category > 0: if category % 2 == 1: labelList.append(self.saved_categories[labelNum]) labelNum += 1 ...
Converts a category number into a list of labels
def __merge_nearest_successors(self, node): """! @brief Find nearest sucessors and merge them. @param[in] node (non_leaf_node): Node whose two nearest successors should be merged. @return (bool): True if merging has been successfully performed, otherwise False. ...
! @brief Find nearest sucessors and merge them. @param[in] node (non_leaf_node): Node whose two nearest successors should be merged. @return (bool): True if merging has been successfully performed, otherwise False.
def simple_merge(kls, skeletons): """ Simple concatenation of skeletons into one object without adding edges between them. """ if len(skeletons) == 0: return PrecomputedSkeleton() if type(skeletons[0]) is np.ndarray: skeletons = [ skeletons ] ct = 0 edges = [] for skel...
Simple concatenation of skeletons into one object without adding edges between them.
def run_script_api(module_name): '''API handler. Take script input (from script_input above), run the run() function, and return the results''' filename = '' file_stream = '' #form = {k : try_json(v) for k,v in request.values.items()} form = request.values.to_dict(flat=False) if request.json...
API handler. Take script input (from script_input above), run the run() function, and return the results
def add_tag(context, id, name): """add_tag(context, id, name) Attach a tag to a job. >>> dcictl job-add-tag [OPTIONS] :param string id: ID of the job to attach the tag on [required] :param string tag_name: name of the tag to be attached [required] """ result = job.add_tag(context, id=id,...
add_tag(context, id, name) Attach a tag to a job. >>> dcictl job-add-tag [OPTIONS] :param string id: ID of the job to attach the tag on [required] :param string tag_name: name of the tag to be attached [required]
def setup_step_out(self, frame): """Setup debugger for a "stepOut" """ self.frame_calling = None self.frame_stop = None self.frame_return = frame.f_back self.frame_suspend = False self.pending_stop = True return
Setup debugger for a "stepOut"
def _group_tasks_by_jobid(tasks): """A defaultdict with, for each job, a list of its tasks.""" ret = collections.defaultdict(list) for t in tasks: ret[t.get_field('job-id')].append(t) return ret
A defaultdict with, for each job, a list of its tasks.
def delete_ikepolicy(self, ikepolicy): ''' Deletes the specified IKEPolicy ''' ikepolicy_id = self._find_ikepolicy_id(ikepolicy) ret = self.network_conn.delete_ikepolicy(ikepolicy_id) return ret if ret else True
Deletes the specified IKEPolicy
def record_manifest(self): """ Returns a dictionary representing a serialized state of the service. """ data = {} data['required_packages'] = self.install_required(type=SYSTEM, verbose=False, list_only=True) data['required_packages'].sort() data['custom_packages']...
Returns a dictionary representing a serialized state of the service.
def log_stack(self, signal, frame): """Signal handler to log the stack trace of the current thread. For use with `set_blocking_signal_threshold`. """ gen_log.warning('IOLoop blocked for %f seconds in\n%s', self._blocking_signal_threshold, ...
Signal handler to log the stack trace of the current thread. For use with `set_blocking_signal_threshold`.
def setValue(self, value): """Cast some known data in custom parameters.""" if self.name in self._CUSTOM_INT_PARAMS: value = int(value) elif self.name in self._CUSTOM_FLOAT_PARAMS: value = float(value) elif self.name in self._CUSTOM_BOOL_PARAMS: value ...
Cast some known data in custom parameters.
def _has_valid_abs_ref(self, i, construction_table): """Checks, if ``i`` uses valid absolute references. Checks for each index from first to third row of the ``construction_table``, if the references are colinear. This case has to be specially treated, because the references are...
Checks, if ``i`` uses valid absolute references. Checks for each index from first to third row of the ``construction_table``, if the references are colinear. This case has to be specially treated, because the references are not only atoms (to fix internal degrees of freedom) but also po...
def command(self, *args, **kwargs): """ Attach a command to the current :class:`CLI` object. The function should accept an instance of an :class:`argparse.ArgumentParser` and use it to define extra arguments and options. These options will only affect the specified comma...
Attach a command to the current :class:`CLI` object. The function should accept an instance of an :class:`argparse.ArgumentParser` and use it to define extra arguments and options. These options will only affect the specified command.
def extract_message_info(): """Get information about all messages of interest.""" base_path = BASE_PACKAGE.replace('.', '/') filename = os.path.join(base_path, 'ProtocolMessage.proto') with open(filename, 'r') as file: types_found = False for line in file: stripped = line.l...
Get information about all messages of interest.
def record_get_field_values(rec, tag, ind1=" ", ind2=" ", code="", filter_subfield_code="", filter_subfield_value="", filter_subfield_mode="e"): """Return the list of values for the specified field of the record. List can be fi...
Return the list of values for the specified field of the record. List can be filtered. Use filter_subfield_code and filter_subfield_value to search only in fields that have these values inside them as a subfield. filter_subfield_mode can have 3 different values: 'e' for exact search 's' for sub...
def parse_gene_list(path: str, graph: Graph, anno_type: str = "name") -> list: """Parse a list of genes and return them if they are in the network. :param str path: The path of input file. :param Graph graph: The graph with genes as nodes. :param str anno_type: The type of annotation with two options:n...
Parse a list of genes and return them if they are in the network. :param str path: The path of input file. :param Graph graph: The graph with genes as nodes. :param str anno_type: The type of annotation with two options:name-Entrez ID, symbol-HGNC symbol. :return list: A list of genes, all of which are...
def record(self): # type: () -> bytes ''' A method to generate a string representing this boot info table. Parameters: None. Returns: A string representing this boot info table. ''' if not self._initialized: raise pycdlibexception.Py...
A method to generate a string representing this boot info table. Parameters: None. Returns: A string representing this boot info table.
def prepare_new_dataset(): """prepare_new_dataset""" clean_dir = ev( "OUTPUT_DIR", "/tmp") clean_file = ev( "CLEANED_FILE", "{}/cleaned_attack_scans.csv".format( clean_dir)) fulldata_file = ev( "FULLDATA_FILE", "{}/fulldata_attack_scans.csv".fo...
prepare_new_dataset
def validate_err_calc(val): """Validation function for the :attr:`psy_simple.plotter.FldmeanPlotter.err_calc` formatoption""" try: val = validate_float(val) except (ValueError, TypeError): pass else: if val <= 100 and val >= 0: return val raise ValueError(...
Validation function for the :attr:`psy_simple.plotter.FldmeanPlotter.err_calc` formatoption
def save_lastfile(self, tfi): """Save the taskfile in the config :param tfi: the last selected taskfileinfo :type tfi: class:`jukeboxcore.filesys.TaskFileInfo` :returns: None :rtype: None :raises: None """ tf = models.TaskFile.objects.get(task=tfi.task, v...
Save the taskfile in the config :param tfi: the last selected taskfileinfo :type tfi: class:`jukeboxcore.filesys.TaskFileInfo` :returns: None :rtype: None :raises: None
def plot_irm(fignum, B, M, title): """ function to plot IRM backfield curves Parameters _________ fignum : matplotlib figure number B : list or array of field values M : list or array of magnetizations title : string title for plot """ rpars = {} Mnorm = [] backfield = 0...
function to plot IRM backfield curves Parameters _________ fignum : matplotlib figure number B : list or array of field values M : list or array of magnetizations title : string title for plot
def parse(self, timestr, default=None, ignoretz=False, tzinfos=None, **kwargs): """ Parse the date/time string into a :class:`datetime.datetime` object. :param timestr: Any date/time string using the supported formats. :param default: The default datetime object...
Parse the date/time string into a :class:`datetime.datetime` object. :param timestr: Any date/time string using the supported formats. :param default: The default datetime object, if this is a datetime object and not ``None``, elements specified in ``timestr`` repla...
def WmiQueryFromClient(args): """Run the WMI query and return the data.""" query = args.query base_object = args.base_object or r"winmgmts:\root\cimv2" if not query.upper().startswith("SELECT "): raise RuntimeError("Only SELECT WMI queries allowed.") for response_dict in RunWMIQuery(query, baseobj=base_...
Run the WMI query and return the data.
def get_std_icon(name, size=None): """Get standard platform icon Call 'show_std_icons()' for details""" if not name.startswith('SP_'): name = 'SP_' + name icon = QWidget().style().standardIcon(getattr(QStyle, name)) if size is None: return icon else: return QIcon(icon.pix...
Get standard platform icon Call 'show_std_icons()' for details
def list_agents(self): '''List agents hosted by the agency.''' t = text_helper.Table(fields=("Agent ID", "Agent class", "State"), lengths=(40, 25, 15)) return t.render((a._descriptor.doc_id, a.log_category, a._get_machine_state().name) ...
List agents hosted by the agency.
def scan_for_plugins(directory): """ Scan a directory for modules that contains plugin(s). :param directory: Path of the folder/directory to scan. :return: Dictionary of file (key) and plugins (value), where the key is the path of the module and value is a list of plugins inside that mod...
Scan a directory for modules that contains plugin(s). :param directory: Path of the folder/directory to scan. :return: Dictionary of file (key) and plugins (value), where the key is the path of the module and value is a list of plugins inside that module. :rtype: dict
def is_lti(self): """ Tests whether all filters in the list are linear time invariant (LTI). CascadeFilter and ParallelFilter instances are also LTI if all filters they group are LTI. """ return self.is_linear() and all(filt.is_lti() for filt in self.callables)
Tests whether all filters in the list are linear time invariant (LTI). CascadeFilter and ParallelFilter instances are also LTI if all filters they group are LTI.
def evaluate_trace_request(data, tracer=tracer): """ Evaluate given string trace request. Usage:: Umbra -t "{'umbra.engine' : ('.*', 0), 'umbra.preferences' : (r'.*', 0)}" Umbra -t "['umbra.engine', 'umbra.preferences']" Umbra -t "'umbra.engine, umbra.preferences" :param data:...
Evaluate given string trace request. Usage:: Umbra -t "{'umbra.engine' : ('.*', 0), 'umbra.preferences' : (r'.*', 0)}" Umbra -t "['umbra.engine', 'umbra.preferences']" Umbra -t "'umbra.engine, umbra.preferences" :param data: Trace request. :type data: unicode :param tracer: Tr...
def api2_formula(req): """ A simple `GET`-, URL-based API to OpenFisca, making the assumption of computing formulas for a single person. Combination ----------- You can compute several formulas at once by combining the paths and joining them with `+`. Example: ``` /salaire_super_brut+salaire_net_a_payer?salaire_...
A simple `GET`-, URL-based API to OpenFisca, making the assumption of computing formulas for a single person. Combination ----------- You can compute several formulas at once by combining the paths and joining them with `+`. Example: ``` /salaire_super_brut+salaire_net_a_payer?salaire_de_base=1440 ``` This will com...
def pseudos_with_symbols(self, symbols): """ Return the pseudos with the given chemical symbols. Raises: ValueError if one of the symbols is not found or multiple occurences are present. """ pseudos = self.select_symbols(symbols, ret_list=True) found_symbols ...
Return the pseudos with the given chemical symbols. Raises: ValueError if one of the symbols is not found or multiple occurences are present.
def fmt_angle(val, s1=" ", s2=" ", s3="", pre=3, trunc=False, lower=None, upper=None, b=False, upper_trim=False): """Return sexagesimal string of given angle in degrees or hours. Parameters ---------- val : float The angle (in degrees or hours) that is to be converted into a ...
Return sexagesimal string of given angle in degrees or hours. Parameters ---------- val : float The angle (in degrees or hours) that is to be converted into a sexagesimal string. s1 : str Character to be used between the first and second parts of the the sexagesimal repr...
def to_vars_dict(self): """ Return local state which is relevant for the cluster setup process. """ return { 'gcloud_client_id': self._client_id, 'gcloud_client_secret': self._client_secret, 'gcloud_network': self._network, 'gc...
Return local state which is relevant for the cluster setup process.
def update_reportnumbers(self): """Update reportnumbers.""" report_037_fields = record_get_field_instances(self.record, '037') for field in report_037_fields: subs = field_get_subfields(field) for val in subs.get("a", []): if "arXiv" not in val: ...
Update reportnumbers.
def format_json(event, colored): """ If the event message is a JSON string, then pretty print the JSON with 2 indents and sort the keys. This makes it very easy to visually parse and search JSON data """ try: if event.message.startswith("{"): msg_dict...
If the event message is a JSON string, then pretty print the JSON with 2 indents and sort the keys. This makes it very easy to visually parse and search JSON data
def flatten(dictionary, parent_key=False, separator='.'): """ Turn a nested dictionary into a flattened dictionary :param dictionary: The dictionary to flatten :param parent_key: The string to prepend to dictionary's keys :param separator: The string used to separate flattened keys :retu...
Turn a nested dictionary into a flattened dictionary :param dictionary: The dictionary to flatten :param parent_key: The string to prepend to dictionary's keys :param separator: The string used to separate flattened keys :return: A flattened dictionary
def remove_entry(self, entry = None): """This method can remove entries. The v1Entry-object entry is needed. """ if entry is None or type(entry) is not v1Entry: raise KPError("Need an entry.") elif entry in self.entries: entry.gr...
This method can remove entries. The v1Entry-object entry is needed.
def getToC(doc, simple = True): """Create a table of contents. Args: simple: a bool to control output. Returns a list, where each entry consists of outline level, title, page number and link destination (if simple = False). For details see PyMuPDF's documentation. """ def recurse(olItem, liste...
Create a table of contents. Args: simple: a bool to control output. Returns a list, where each entry consists of outline level, title, page number and link destination (if simple = False). For details see PyMuPDF's documentation.
def get_registered_loggers(hide_children=False, hide_reusables=False): """ Find the names of all loggers currently registered :param hide_children: only return top level logger names :param hide_reusables: hide the reusables loggers :return: list of logger names """ return [logger for logg...
Find the names of all loggers currently registered :param hide_children: only return top level logger names :param hide_reusables: hide the reusables loggers :return: list of logger names
def countdown( seconds=None, block=True, interval=1, daemon=True, tick_callback=None, finish_callback=None, ): """Run a countdown function to wait something, similar to threading.Timer, but will show the detail tick by tick_callback. :: from torequests.utils import countdo...
Run a countdown function to wait something, similar to threading.Timer, but will show the detail tick by tick_callback. :: from torequests.utils import countdown countdown(3) # 3 2 1 # countdown finished [3 seconds]: 2018-06-13 00:12:55 => 2018-06-13 00:12:58. countd...
def hasAttribute(self, attr: str) -> bool: """Return True if this node has ``attr``.""" if attr == 'class': return bool(self.classList) return attr in self.attributes
Return True if this node has ``attr``.
def pipe(maxsize=0, *, loop=None) -> Pipe: """\ A bidirectional pipe of Python objects. >>> async def example1(): ... a, b = pipe() ... a.send_nowait('foo') ... print(await b.recv()) >>> asyncio.run(example1()) foo >>> async def example2(): ... a, b = pipe() ...
\ A bidirectional pipe of Python objects. >>> async def example1(): ... a, b = pipe() ... a.send_nowait('foo') ... print(await b.recv()) >>> asyncio.run(example1()) foo >>> async def example2(): ... a, b = pipe() ... await b.send(eof=True) ... await a...