code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def list_taxa(pdb_list, sleep_time=.1): '''Given a list of PDB IDs, look up their associated species This function digs through the search results returned by the get_all_info() function and returns any information on taxonomy included within the description. The PDB website description of each en...
Given a list of PDB IDs, look up their associated species This function digs through the search results returned by the get_all_info() function and returns any information on taxonomy included within the description. The PDB website description of each entry includes the name of the species (and s...
def _get_tmp_gcs_bucket(cls, writer_spec): """Returns bucket used for writing tmp files.""" if cls.TMP_BUCKET_NAME_PARAM in writer_spec: return writer_spec[cls.TMP_BUCKET_NAME_PARAM] return cls._get_gcs_bucket(writer_spec)
Returns bucket used for writing tmp files.
def pow(base, exp): """Returns element-wise result of base element raised to powers from exp element. Both inputs can be Symbol or scalar number. Broadcasting is not supported. Use `broadcast_pow` instead. `sym.pow` is being deprecated, please use `sym.power` instead. Parameters --------- ...
Returns element-wise result of base element raised to powers from exp element. Both inputs can be Symbol or scalar number. Broadcasting is not supported. Use `broadcast_pow` instead. `sym.pow` is being deprecated, please use `sym.power` instead. Parameters --------- base : Symbol or scalar ...
def dropEvent(self, event): """ Listens for query's being dragged and dropped onto this tree. :param event | <QDropEvent> """ # overload the current filtering options data = event.mimeData() if data.hasFormat('application/x-orb-table') and \ ...
Listens for query's being dragged and dropped onto this tree. :param event | <QDropEvent>
def describe_numeric_1d(series, **kwargs): """Compute summary statistics of a numerical (`TYPE_NUM`) variable (a Series). Also create histograms (mini an full) of its distribution. Parameters ---------- series : Series The variable to describe. Returns ------- Series T...
Compute summary statistics of a numerical (`TYPE_NUM`) variable (a Series). Also create histograms (mini an full) of its distribution. Parameters ---------- series : Series The variable to describe. Returns ------- Series The description of the variable as a Series with in...
def to_dict(self): """Return common list python object. :returns: Dictionary of groups and data :rtype: dict """ list_data = [] for key, value in list(self.data.items()): row = list(key) row.append(value) list_data.append(row) r...
Return common list python object. :returns: Dictionary of groups and data :rtype: dict
def mptt_before_update(mapper, connection, instance): """ Based on this example: http://stackoverflow.com/questions/889527/move-node-in-nested-set """ node_id = getattr(instance, instance.get_pk_name()) table = _get_tree_table(mapper) db_pk = instance.get_pk_column() default_level = inst...
Based on this example: http://stackoverflow.com/questions/889527/move-node-in-nested-set
def pad_sequence_to_length(sequence: List, desired_length: int, default_value: Callable[[], Any] = lambda: 0, padding_on_right: bool = True) -> List: """ Take a list of objects and pads it to the desired length, returning the padde...
Take a list of objects and pads it to the desired length, returning the padded list. The original list is not modified. Parameters ---------- sequence : List A list of objects to be padded. desired_length : int Maximum length of each sequence. Longer sequences are truncated to thi...
def _add_devices_from_config(args): """ Add devices from config. """ config = _parse_config(args.config) for device in config['devices']: if args.default: if device == "default": raise ValueError('devicename "default" in config is not allowed if default param is set') ...
Add devices from config.
def get_time(self): """Time of the TIFF file Currently, only the file modification time is supported. Note that the modification time of the TIFF file is dependent on the file system and may have temporal resolution as low as 3 seconds. """ if isinstance(self.pat...
Time of the TIFF file Currently, only the file modification time is supported. Note that the modification time of the TIFF file is dependent on the file system and may have temporal resolution as low as 3 seconds.
def where(self, where: str) -> 'SASdata': """ This method returns a clone of the SASdata object, with the where attribute set. The original SASdata object is not affected. :param where: the where clause to apply :return: SAS data object """ sd = SASdata(self.sas, self.li...
This method returns a clone of the SASdata object, with the where attribute set. The original SASdata object is not affected. :param where: the where clause to apply :return: SAS data object
def reassign(self, user_ids, requester): """Reassign this incident to a user or list of users :param user_ids: A non-empty list of user ids :param requester: The email address of individual requesting reassign """ path = '{0}'.format(self.collection.name) assignments = [...
Reassign this incident to a user or list of users :param user_ids: A non-empty list of user ids :param requester: The email address of individual requesting reassign
def Ctrl_c(self, dl = 0): """Ctrl + c 复制 """ self.Delay(dl) self.keyboard.press_key(self.keyboard.control_key) self.keyboard.tap_key("c") self.keyboard.release_key(self.keyboard.control_key)
Ctrl + c 复制
def API_GET(self, courseid=None): # pylint: disable=arguments-differ """ List courses available to the connected client. Returns a dict in the form :: { "courseid1": { "name": "Name of the course", #th...
List courses available to the connected client. Returns a dict in the form :: { "courseid1": { "name": "Name of the course", #the name of the course "require_password": False, #indicates if t...
def get_path(self, temp_ver): """ Get the path of the given version in this store Args: temp_ver TemplateVersion: version to look for Returns: str: The path to the template version inside the store Raises: RuntimeError: if the template is no...
Get the path of the given version in this store Args: temp_ver TemplateVersion: version to look for Returns: str: The path to the template version inside the store Raises: RuntimeError: if the template is not in the store
def get_current_qualification_score(self, name, worker_id): """Return the current score for a worker, on a qualification with the provided name. """ qtype = self.get_qualification_type_by_name(name) if qtype is None: raise QualificationNotFoundException( ...
Return the current score for a worker, on a qualification with the provided name.
def _is_prime(bit_size, n): """ An implementation of Miller–Rabin for checking if a number is prime. :param bit_size: An integer of the number of bits in the prime number :param n: An integer, the prime number :return: A boolean """ r = 0 s = n - 1 while s...
An implementation of Miller–Rabin for checking if a number is prime. :param bit_size: An integer of the number of bits in the prime number :param n: An integer, the prime number :return: A boolean
def remove_gaps(A, B): """ skip column if either is a gap """ a_seq, b_seq = [], [] for a, b in zip(list(A), list(B)): if a == '-' or a == '.' or b == '-' or b == '.': continue a_seq.append(a) b_seq.append(b) return ''.join(a_seq), ''.join(b_seq)
skip column if either is a gap
def get_table_cache_key(db_alias, table): """ Generates a cache key from a SQL table. :arg db_alias: Alias of the used database :type db_alias: str or unicode :arg table: Name of the SQL table :type table: str or unicode :return: A cache key :rtype: int """ cache_key = '%s:%s' %...
Generates a cache key from a SQL table. :arg db_alias: Alias of the used database :type db_alias: str or unicode :arg table: Name of the SQL table :type table: str or unicode :return: A cache key :rtype: int
def domain_search(auth=None, **kwargs): ''' Search domains CLI Example: .. code-block:: bash salt '*' keystoneng.domain_search salt '*' keystoneng.domain_search name=domain1 ''' cloud = get_operator_cloud(auth) kwargs = _clean_kwargs(**kwargs) return cloud.search_domai...
Search domains CLI Example: .. code-block:: bash salt '*' keystoneng.domain_search salt '*' keystoneng.domain_search name=domain1
def add_update_user(self, user, capacity=None): # type: (Union[hdx.data.user.User,Dict,str],Optional[str]) -> None """Add new or update existing user in organization with new metadata. Capacity eg. member, admin must be supplied either within the User object or dictionary or using the capacity a...
Add new or update existing user in organization with new metadata. Capacity eg. member, admin must be supplied either within the User object or dictionary or using the capacity argument (which takes precedence). Args: user (Union[User,Dict,str]): Either a user id or user metadata ei...
def scale_vmss(access_token, subscription_id, resource_group, vmss_name, capacity): '''Change the instance count of an existing VM Scale Set. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource ...
Change the instance count of an existing VM Scale Set. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of the virtual machine scale set. capacit...
def parse_env(envlist): '''parse_env will parse a single line (with prefix like ENV removed) to a list of commands in the format KEY=VALUE For example: ENV PYTHONBUFFER 1 --> [PYTHONBUFFER=1] ::Notes Docker: https://docs.docker.com/engine/reference/builder/#env ''' if not isinstance...
parse_env will parse a single line (with prefix like ENV removed) to a list of commands in the format KEY=VALUE For example: ENV PYTHONBUFFER 1 --> [PYTHONBUFFER=1] ::Notes Docker: https://docs.docker.com/engine/reference/builder/#env
def ready(self): """Auto load Trionyx""" models_config.auto_load_configs() self.auto_load_app_modules(['layouts', 'signals']) app_menu.auto_load_model_menu() auto_register_search_models() tabs.auto_generate_missing_tabs()
Auto load Trionyx
def check_key(self, key, raise_error=True, *args, **kwargs): """ Checks whether the key is a valid formatoption Parameters ---------- %(check_key.parameters.no_possible_keys|name)s Returns ------- %(check_key.returns)s Raises ------ ...
Checks whether the key is a valid formatoption Parameters ---------- %(check_key.parameters.no_possible_keys|name)s Returns ------- %(check_key.returns)s Raises ------ %(check_key.raises)s
def relpath_to_modname(relpath): """Convert relative path to module name Within a project, a path to the source file is uniquely identified with a module name. Relative paths of the form 'foo/bar' are *not* converted to module names 'foo.bar', because (1) they identify directories, not regular file...
Convert relative path to module name Within a project, a path to the source file is uniquely identified with a module name. Relative paths of the form 'foo/bar' are *not* converted to module names 'foo.bar', because (1) they identify directories, not regular files, and (2) already 'foo/bar/__init__.py'...
def cosine_similarity(sent1: str, sent2: str) -> float: """ Calculates cosine similarity between 2 sentences/documents. Thanks to @vpekar, see http://goo.gl/ykibJY """ WORD = re.compile(r'\w+') def get_cosine(vec1, vec2): intersection = set(vec1.keys()) & set(vec2.keys()) numera...
Calculates cosine similarity between 2 sentences/documents. Thanks to @vpekar, see http://goo.gl/ykibJY
def _create_tag_lowlevel(self, tag_name, message=None, force=True, patch=False): """Create a tag on the toplevel or patch repo If the tag exists, and force is False, no tag is made. If force is True, and a tag exists, but it is a direct ancestor of the current commi...
Create a tag on the toplevel or patch repo If the tag exists, and force is False, no tag is made. If force is True, and a tag exists, but it is a direct ancestor of the current commit, and there is no difference in filestate between the current commit and the tagged commit, no tag is ma...
def save_series(self) -> None: """Save time series data as defined by the actual XML `writer` element. >>> from hydpy.core.examples import prepare_full_example_1 >>> prepare_full_example_1() >>> from hydpy import HydPy, TestIO, XMLInterface >>> hp = HydPy('LahnH') ...
Save time series data as defined by the actual XML `writer` element. >>> from hydpy.core.examples import prepare_full_example_1 >>> prepare_full_example_1() >>> from hydpy import HydPy, TestIO, XMLInterface >>> hp = HydPy('LahnH') >>> with TestIO(): ... hp.p...
def endpoint_delete(auth=None, **kwargs): ''' Delete an endpoint CLI Example: .. code-block:: bash salt '*' keystoneng.endpoint_delete id=3bee4bd8c2b040ee966adfda1f0bfca9 ''' cloud = get_operator_cloud(auth) kwargs = _clean_kwargs(**kwargs) return cloud.delete_endpoint(**kwarg...
Delete an endpoint CLI Example: .. code-block:: bash salt '*' keystoneng.endpoint_delete id=3bee4bd8c2b040ee966adfda1f0bfca9
def plot_options(cls, obj, percent_size): """ Given a holoviews object and a percentage size, apply heuristics to compute a suitable figure size. For instance, scaling layouts and grids linearly can result in unwieldy figure sizes when there are a large number of elements. As ad ...
Given a holoviews object and a percentage size, apply heuristics to compute a suitable figure size. For instance, scaling layouts and grids linearly can result in unwieldy figure sizes when there are a large number of elements. As ad hoc heuristics are used, this functionality is kept se...
def handle_signature(self, sig, signode): """Parse the signature *sig* into individual nodes and append them to the *signode*. If ValueError is raises, parsing is aborted and the whole *sig* string is put into a single desc_name node. The return value is the value that identifies the ob...
Parse the signature *sig* into individual nodes and append them to the *signode*. If ValueError is raises, parsing is aborted and the whole *sig* string is put into a single desc_name node. The return value is the value that identifies the object. IOW, it is the identifier that will be ...
def reindex_like(self, other, method=None, copy=True, limit=None, tolerance=None): """ Return an object with matching indices as other object. Conform the object to the same index on all axes. Optional filling logic, placing NaN in locations having no value ...
Return an object with matching indices as other object. Conform the object to the same index on all axes. Optional filling logic, placing NaN in locations having no value in the previous index. A new object is produced unless the new index is equivalent to the current one and copy=False...
def find_ent_space_price(package, category, size, tier_level): """Find the space price for the given category, size, and tier :param package: The Enterprise (Endurance) product package :param category: The category of space (endurance, replication, snapshot) :param size: The size for which a price is d...
Find the space price for the given category, size, and tier :param package: The Enterprise (Endurance) product package :param category: The category of space (endurance, replication, snapshot) :param size: The size for which a price is desired :param tier_level: The endurance tier for which a price is ...
def fromXml(cls, elem): """ Converts the inputted element to a Python object by looking through the IO addons for the element's tag. :param elem | <xml.etree.ElementTree.Element> :return <variant> """ if elem is None: return ...
Converts the inputted element to a Python object by looking through the IO addons for the element's tag. :param elem | <xml.etree.ElementTree.Element> :return <variant>
def mtr_tr_dense(sz): """Series of machine translation models. All models are trained on sequences of 256 tokens. You can use the dataset translate_enfr_wmt32k_packed. 154000 steps = 3 epochs. Args: sz: an integer Returns: a hparams """ n = 2 ** sz hparams = mtf_bitransformer_base() hpar...
Series of machine translation models. All models are trained on sequences of 256 tokens. You can use the dataset translate_enfr_wmt32k_packed. 154000 steps = 3 epochs. Args: sz: an integer Returns: a hparams
def distance_to_closest(self, ps: Union["Units", List["Point2"], Set["Point2"]]) -> Union[int, float]: """ This function assumes the 2d distance is meant """ assert ps closest_distance_squared = math.inf for p2 in ps: if not isinstance(p2, Point2): p2 = p2.pos...
This function assumes the 2d distance is meant
def metrics(self): """ Calculate and return the metrics. """ masterThrp, backupThrp = self.getThroughputs(self.instances.masterId) r = self.instance_throughput_ratio(self.instances.masterId) m = [ ("{} Monitor metrics:".format(self), None), ("Delta...
Calculate and return the metrics.
def set_dash(self, dashes, offset=0): """Sets the dash pattern to be used by :meth:`stroke`. A dash pattern is specified by dashes, a list of positive values. Each value provides the length of alternate "on" and "off" portions of the stroke. :obj:`offset` specifies an offset into...
Sets the dash pattern to be used by :meth:`stroke`. A dash pattern is specified by dashes, a list of positive values. Each value provides the length of alternate "on" and "off" portions of the stroke. :obj:`offset` specifies an offset into the pattern at which the stroke begins. ...
def search_cloud_integration_deleted_for_facet(self, facet, **kwargs): # noqa: E501 """Lists the values of a specific facet over the customer's deleted cloud integrations # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP ...
Lists the values of a specific facet over the customer's deleted cloud integrations # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.search_cloud_integration_deleted_fo...
def add_permission(self, name): """ Adds a permission to the backend, model permission :param name: name of the permission: 'can_add','can_edit' etc... """ perm = self.find_permission(name) if perm is None: try: perm = ...
Adds a permission to the backend, model permission :param name: name of the permission: 'can_add','can_edit' etc...
def zeros_coefs(nmax, mmax, coef_type=scalar): """Returns a ScalarCoefs object or a VectorCoeffs object where each of the coefficients is set to 0. The structure is such that *nmax* is th largest *n* can be in c[n, m], and *mmax* is the largest *m* can be for any *n*. (See *ScalarCoefs* and *Vecto...
Returns a ScalarCoefs object or a VectorCoeffs object where each of the coefficients is set to 0. The structure is such that *nmax* is th largest *n* can be in c[n, m], and *mmax* is the largest *m* can be for any *n*. (See *ScalarCoefs* and *VectorCoefs* for details.) Examples:: ...
def xmoe_2d(): """Two-dimensional hierarchical mixture of 16 experts.""" hparams = xmoe_top_2() hparams.decoder_layers = ["att", "hmoe"] * 4 hparams.mesh_shape = "b0:2;b1:4" hparams.outer_batch_size = 4 hparams.layout = "outer_batch:b0;inner_batch:b1,expert_x:b1,expert_y:b0" hparams.moe_num_experts = [4, ...
Two-dimensional hierarchical mixture of 16 experts.
def constraint_present(name, constraint_id, constraint_type, constraint_options=None, cibname=None): ''' Ensure that a constraint is created Should be run on one cluster node only (there may be races) Can only be run on a node with a functional pacemaker/corosync name Irrelevant, not u...
Ensure that a constraint is created Should be run on one cluster node only (there may be races) Can only be run on a node with a functional pacemaker/corosync name Irrelevant, not used (recommended: {{formulaname}}__constraint_present_{{constraint_id}}) constraint_id name for the c...
def bezier(self, points): """Draw a Bezier-curve. :param points: ex.) ((5, 5), (6, 6), (7, 7)) :type points: list """ coordinates = pgmagick.CoordinateList() for point in points: x, y = float(point[0]), float(point[1]) coordinates.append(pgmagick....
Draw a Bezier-curve. :param points: ex.) ((5, 5), (6, 6), (7, 7)) :type points: list
def delete(self, refobj): """Delete the content of the given refobj :param refobj: the refobj that represents the content that should be deleted :type refobj: refobj :returns: None :rtype: None :raises: None """ refobjinter = self.get_refobjinter() ...
Delete the content of the given refobj :param refobj: the refobj that represents the content that should be deleted :type refobj: refobj :returns: None :rtype: None :raises: None
def ebrisk(rupgetter, srcfilter, param, monitor): """ :param rupgetter: a RuptureGetter instance :param srcfilter: a SourceFilter instance :param param: a dictionary of parameters :param monitor: :class:`openquake.baselib.performance.Monitor` instance :returns: ...
:param rupgetter: a RuptureGetter instance :param srcfilter: a SourceFilter instance :param param: a dictionary of parameters :param monitor: :class:`openquake.baselib.performance.Monitor` instance :returns: an ArrayWrapper with shape (E, L, T, ...)
def _get_seal_key_ntlm2(negotiate_flags, exported_session_key, magic_constant): """ 3.4.5.3 SEALKEY Calculates the seal_key used to seal (encrypt) messages. This for authentication where NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY has been negotiated. Will weaken the keys if NTLMSSP_NEGOTIATE_128 is ...
3.4.5.3 SEALKEY Calculates the seal_key used to seal (encrypt) messages. This for authentication where NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY has been negotiated. Will weaken the keys if NTLMSSP_NEGOTIATE_128 is not negotiated, will try NEGOTIATE_56 and then will default to the 40-bit key @para...
def _stop_trial(self, trial, error=False, error_msg=None, stop_logger=True): """Stops this trial. Stops this trial, releasing all allocating resources. If stopping the trial fails, the run will be marked as terminated in error, but no exception will be thrown. ...
Stops this trial. Stops this trial, releasing all allocating resources. If stopping the trial fails, the run will be marked as terminated in error, but no exception will be thrown. Args: error (bool): Whether to mark this trial as terminated in error. error_msg ...
def p_factor_unary_operators(self, p): """ term : SUB factor | ADD factor """ p[0] = p[2] if p[1] == '-': p[0] = Instruction('-x', context={'x': p[0]})
term : SUB factor | ADD factor
def prep_cwl(samples, workflow_fn, out_dir, out_file, integrations=None, add_container_tag=None): """Output a CWL description with sub-workflows and steps. """ if add_container_tag is None: container_tags = None elif add_container_tag.lower() == "quay_lookup": container_tags...
Output a CWL description with sub-workflows and steps.
def charge_parent(self, mol, skip_standardize=False): """Return the charge parent of a given molecule. The charge parent is the uncharged version of the fragment parent. :param mol: The input molecule. :type mol: rdkit.Chem.rdchem.Mol :param bool skip_standardize: Set to True i...
Return the charge parent of a given molecule. The charge parent is the uncharged version of the fragment parent. :param mol: The input molecule. :type mol: rdkit.Chem.rdchem.Mol :param bool skip_standardize: Set to True if mol has already been standardized. :returns: The charge...
def check_expected_infos(self, test_method): """ This method is called after each test. It will read decorated informations and check if there are expected infos. You can set expected infos by decorators :py:func:`.expected_info_messages` and :py:func:`.allowed_info_messages`. ...
This method is called after each test. It will read decorated informations and check if there are expected infos. You can set expected infos by decorators :py:func:`.expected_info_messages` and :py:func:`.allowed_info_messages`.
def server_add(s_name, s_ip, s_state=None, **connection_args): ''' Add a server Note: The default server state is ENABLED CLI Example: .. code-block:: bash salt '*' netscaler.server_add 'serverName' 'serverIpAddress' salt '*' netscaler.server_add 'serverName' 'serverIpAddress' 'se...
Add a server Note: The default server state is ENABLED CLI Example: .. code-block:: bash salt '*' netscaler.server_add 'serverName' 'serverIpAddress' salt '*' netscaler.server_add 'serverName' 'serverIpAddress' 'serverState'
def _set_tcp_keepalive(sock, opts): ''' Ensure that TCP keepalives are set for the socket. ''' if hasattr(socket, 'SO_KEEPALIVE'): if opts.get('tcp_keepalive', False): sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) if hasattr(socket, 'SOL_TCP'): ...
Ensure that TCP keepalives are set for the socket.
def validation_step(self, Xi, yi, **fit_params): """Perform a forward step using batched data and return the resulting loss. The module is set to be in evaluation mode (e.g. dropout is not applied). Parameters ---------- Xi : input data A batch of the ...
Perform a forward step using batched data and return the resulting loss. The module is set to be in evaluation mode (e.g. dropout is not applied). Parameters ---------- Xi : input data A batch of the input data. yi : target data A batch of t...
def combine_dictionaries(a, b): """ returns the combined dictionary. a's values preferentially chosen """ c = {} for key in list(b.keys()): c[key]=b[key] for key in list(a.keys()): c[key]=a[key] return c
returns the combined dictionary. a's values preferentially chosen
def request_generic(self, act, coro, perform, complete): """ Performs an overlapped request (via `perform` callable) and saves the token and the (`overlapped`, `perform`, `complete`) trio. """ overlapped = OVERLAPPED() overlapped.object = act self.add_token...
Performs an overlapped request (via `perform` callable) and saves the token and the (`overlapped`, `perform`, `complete`) trio.
def compute_absolute_error(self, predicted_data, record, dataframe_record): '''Calculate the absolute error for this case.''' absolute_error = abs(record['DDG'] - predicted_data[self.ddg_analysis_type]) dataframe_record['AbsoluteError'] = absolute_error
Calculate the absolute error for this case.
def teleport(self, agent_name, location=None, rotation=None): """Teleports the target agent to any given location, and applies a specific rotation. Args: agent_name (str): The name of the agent to teleport. location (np.ndarray or list): XYZ coordinates (in meters) for the agent...
Teleports the target agent to any given location, and applies a specific rotation. Args: agent_name (str): The name of the agent to teleport. location (np.ndarray or list): XYZ coordinates (in meters) for the agent to be teleported to. If no location is given, it isn't t...
def close(self): """ Closes the project, but keep information on disk """ project_nodes_id = set([n.id for n in self.nodes]) for module in self.compute(): module_nodes_id = set([n.id for n in module.instance().nodes]) # We close the project only for the ...
Closes the project, but keep information on disk
def __clear_buffer_watch(self, bw): """ Used by L{dont_watch_buffer} and L{dont_stalk_buffer}. @type bw: L{BufferWatch} @param bw: Buffer watch identifier. """ # Get the PID and the start and end addresses of the buffer. pid = bw.pid start = bw.start ...
Used by L{dont_watch_buffer} and L{dont_stalk_buffer}. @type bw: L{BufferWatch} @param bw: Buffer watch identifier.
def get_roles(self): """ Returns: Role instances according to task definition. """ if self.role.exist: # return explicitly selected role return [self.role] else: roles = [] if self.role_query_code: # use...
Returns: Role instances according to task definition.
def list_pr_comments(repo: GithubRepository, pull_id: int ) -> List[Dict[str, Any]]: """ References: https://developer.github.com/v3/issues/comments/#list-comments-on-an-issue """ url = ("https://api.github.com/repos/{}/{}/issues/{}/comments" "?access_token={}".fo...
References: https://developer.github.com/v3/issues/comments/#list-comments-on-an-issue
def get_http_method_arg_name(self): """ Return the HTTP function to call and the params/data argument name """ if self.method == 'get': arg_name = 'params' else: arg_name = 'data' return getattr(requests, self.method), arg_name
Return the HTTP function to call and the params/data argument name
def dateadd(value: fields.DateTime(), addend: fields.Int(validate=Range(min=1)), unit: fields.Str(validate=OneOf(['minutes', 'days']))='days'): """Add a value to a date.""" value = value or dt.datetime.utcnow() if unit == 'minutes': delta = dt.timedelta(minutes=addend) el...
Add a value to a date.
def _profile_module(self): """Runs statistical profiler on a module.""" with open(self._run_object, 'rb') as srcfile, _StatProfiler() as prof: code = compile(srcfile.read(), self._run_object, 'exec') prof.base_frame = inspect.currentframe() try: exec(c...
Runs statistical profiler on a module.
def diff(new, old): """ Compute the difference in items of two revisioned collections. If only `new' is specified, it is assumed it is not an update. If both are set, the removed items are returned first. Otherwise, the updated and edited ones are returned. :param set new: Set of new objects ...
Compute the difference in items of two revisioned collections. If only `new' is specified, it is assumed it is not an update. If both are set, the removed items are returned first. Otherwise, the updated and edited ones are returned. :param set new: Set of new objects :param set old: Set of old obj...
def get_translation_lookup(identifier, field, value): """ Mapper that takes a language field, its value and returns the related lookup for Translation model. """ # Split by transformers parts = field.split("__") # Store transformers transformers = parts[1:] if len(parts) > 1 else None ...
Mapper that takes a language field, its value and returns the related lookup for Translation model.
def _augment_url_with_version(auth_url): """Optionally augment auth_url path with version suffix. Check if path component already contains version suffix and if it does not, append version suffix to the end of path, not erasing the previous path contents, since keystone web endpoint (like /identity) co...
Optionally augment auth_url path with version suffix. Check if path component already contains version suffix and if it does not, append version suffix to the end of path, not erasing the previous path contents, since keystone web endpoint (like /identity) could be there. Keystone version needs to be a...
def django(line): ''' >>> import pprint >>> input_line1 = '[23/Aug/2017 11:35:25] INFO [app.middleware_log_req:50]View func called:{"exception": null,"processing_time": 0.00011801719665527344, "url": "<url>",host": "localhost", "user": "testing", "post_contents": "", "method": "POST" }' >>> output_line1...
>>> import pprint >>> input_line1 = '[23/Aug/2017 11:35:25] INFO [app.middleware_log_req:50]View func called:{"exception": null,"processing_time": 0.00011801719665527344, "url": "<url>",host": "localhost", "user": "testing", "post_contents": "", "method": "POST" }' >>> output_line1 = django(input_line1) >>>...
def ekopw(fname): """ Open an existing E-kernel file for writing. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekopw_c.html :param fname: Name of EK file. :type fname: str :return: Handle attached to EK file. :rtype: int """ fname = stypes.stringToCharP(fname) handle...
Open an existing E-kernel file for writing. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekopw_c.html :param fname: Name of EK file. :type fname: str :return: Handle attached to EK file. :rtype: int
def check_read_inputs(self, sampfrom, sampto, channels, physical, smooth_frames, return_res): """ Ensure that input read parameters (from rdsamp) are valid for the record """ # Data Type Check if not hasattr(sampfrom, '__index__'): ...
Ensure that input read parameters (from rdsamp) are valid for the record
def switch_window(self, window_id: int): """ Switches currently active tmux window for given task. 0 is the default window Args: window_id: integer id of tmux window to use """ # windows are numbered sequentially 0, 1, 2, ... # create any missing windows and make them point to the same di...
Switches currently active tmux window for given task. 0 is the default window Args: window_id: integer id of tmux window to use
def transfer_config_dict(soap_object, data_dict): """ This is a utility function used in the certification modules to transfer the data dicts above to SOAP objects. This avoids repetition and allows us to store all of our variable configuration here rather than in each certification script. """ ...
This is a utility function used in the certification modules to transfer the data dicts above to SOAP objects. This avoids repetition and allows us to store all of our variable configuration here rather than in each certification script.
def version_range(guid, version, before=None, app_versions=None): """Returns all values after (and including) `version` for the app `guid`""" if app_versions is None: app_versions = validator.constants.APPROVED_APPLICATIONS app_key = None # Support for shorthand instead of full GUIDs. for ...
Returns all values after (and including) `version` for the app `guid`
def pip_install(self, reqs): """Install dependencies into this env by calling pip in a subprocess""" if not reqs: return log.info('Calling pip to install %s', reqs) check_call([ sys.executable, '-m', 'pip', 'install', '--ignore-installed', '--prefix', ...
Install dependencies into this env by calling pip in a subprocess
def slugable(self): """ A node is slugable in following cases: 1 - Node doesn't have children. 2 - Node has children but its page doesn't have a regex. 3 - Node has children, its page has regex but it doesn't show it. 4 - Node has children, its page shows his regex and no...
A node is slugable in following cases: 1 - Node doesn't have children. 2 - Node has children but its page doesn't have a regex. 3 - Node has children, its page has regex but it doesn't show it. 4 - Node has children, its page shows his regex and node has a default value for regex. ...
def setup_plugins(extra_plugin_dir=None): """Loads any additional plugins.""" if os.path.isdir(PLUGINS_DIR): load_plugins([PLUGINS_DIR]) if extra_plugin_dir: load_plugins(extra_plugin_dir)
Loads any additional plugins.
def authenticate_user(username, password): """ Authenticate a username and password against our database :param username: :param password: :return: authenticated username """ user_model = Query() user = db.get(user_model.username == username) if not user: logger.warning("Use...
Authenticate a username and password against our database :param username: :param password: :return: authenticated username
def mft_mirror_offset(self): """ Returns: int: Mirror MFT Table offset from the beginning of the partition \ in bytes """ return self.bpb.bytes_per_sector * \ self.bpb.sectors_per_cluster * self.extended_bpb.mft_mirror_cluster
Returns: int: Mirror MFT Table offset from the beginning of the partition \ in bytes
def __process_by_ccore(self): """! @brief Performs processing using CCORE (C/C++ part of pyclustering library). """ ccore_metric = metric_wrapper.create_instance(self.__metric) self.__score = wrapper.silhoeutte(self.__data, self.__clusters, ccore_metric.get_pointer())
! @brief Performs processing using CCORE (C/C++ part of pyclustering library).
def _get_boolean(data, position, dummy0, dummy1): """Decode a BSON true/false to python True/False.""" end = position + 1 return data[position:end] == b"\x01", end
Decode a BSON true/false to python True/False.
def _CollapseStrings(elided): """Collapses strings and chars on a line to simple "" or '' blocks. We nix strings first so we're not fooled by text like '"http://"' Args: elided: The line being processed. Returns: The line with collapsed strings. """ if _RE_PATTERN_INCLUDE.match(el...
Collapses strings and chars on a line to simple "" or '' blocks. We nix strings first so we're not fooled by text like '"http://"' Args: elided: The line being processed. Returns: The line with collapsed strings.
def get_variables(self) -> Set[str]: """Find all the variables specified in a format string. This returns a list of all the different variables specified in a format string, that is the variables inside the braces. """ variables = set() for cmd in self._cmd: ...
Find all the variables specified in a format string. This returns a list of all the different variables specified in a format string, that is the variables inside the braces.
def can_user_access_build(param_name): """Determines if the current user can access the build ID in the request. Args: param_name: Parameter name to use for getting the build ID from the request. Will fetch from GET or POST requests. Returns: The build the user has access to. ...
Determines if the current user can access the build ID in the request. Args: param_name: Parameter name to use for getting the build ID from the request. Will fetch from GET or POST requests. Returns: The build the user has access to.
def to_python(self, value): """Convert the value to the appropriate timezone.""" # pylint: disable=newstyle value = super(LinkedTZDateTimeField, self).to_python(value) if not value: return value return value.astimezone(self.timezone)
Convert the value to the appropriate timezone.
def _get_metricsmgr_cmd(self, metricsManagerId, sink_config_file, port): ''' get the command to start the metrics manager processes ''' metricsmgr_main_class = 'org.apache.heron.metricsmgr.MetricsManager' metricsmgr_cmd = [os.path.join(self.heron_java_home, 'bin/java'), # We could not...
get the command to start the metrics manager processes
def generate_ast(path): """Generate an Abstract Syntax Tree using the ast module. Args: path(str): The path to the file e.g. example/foo/bar.py """ if os.path.isfile(path): with open(path, 'r') as f: try: tree = ast.parse(f.read()) ret...
Generate an Abstract Syntax Tree using the ast module. Args: path(str): The path to the file e.g. example/foo/bar.py
def set_params(w, src): """ Set source parameters. """ params = extract_source_params(src) # this is done because for characteristic sources geometry is in # 'surface' attribute params.update(extract_geometry_params(src)) mfd_pars, rate_pars = extract_mfd_params(src) params.update(m...
Set source parameters.
def make_cashed(self): """ Включает кэширование запросов к descend """ self._descendance_cash = [dict() for _ in self.graph] self.descend = self._descend_cashed
Включает кэширование запросов к descend
def verify_file_exists(file_name, file_location): """ Function to verify if a file exists Args: file_name: The name of file to check file_location: The location of the file, derive from the os module Returns: returns boolean True or False """ return __os.path.isfile(__os.path.j...
Function to verify if a file exists Args: file_name: The name of file to check file_location: The location of the file, derive from the os module Returns: returns boolean True or False
def deactivate_lvm_volume_group(block_device): ''' Deactivate any volume gruop associated with an LVM physical volume. :param block_device: str: Full path to LVM physical volume ''' vg = list_lvm_volume_group(block_device) if vg: cmd = ['vgchange', '-an', vg] check_call(cmd)
Deactivate any volume gruop associated with an LVM physical volume. :param block_device: str: Full path to LVM physical volume
def list_vdirs(site, app=_DEFAULT_APP): ''' Get all configured IIS virtual directories for the specified site, or for the combination of site and application. Args: site (str): The IIS site name. app (str): The IIS application. Returns: dict: A dictionary of the virtual dir...
Get all configured IIS virtual directories for the specified site, or for the combination of site and application. Args: site (str): The IIS site name. app (str): The IIS application. Returns: dict: A dictionary of the virtual directory names and properties. CLI Example: ...
def generate_property_names(self): """ Means that keys of object must to follow this definition. .. code-block:: python { 'propertyNames': { 'maxLength': 3, }, } Valid keys of object for this definition are fo...
Means that keys of object must to follow this definition. .. code-block:: python { 'propertyNames': { 'maxLength': 3, }, } Valid keys of object for this definition are foo, bar, ... but not foobar for example.
def encode(self, sequence): """Returns a tuple (binary reprensentation, default sequence, polymorphisms list)""" polymorphisms = [] defaultSequence = '' binSequence = array.array(self.forma.typecode) b = 0 i = 0 trueI = 0 #not inc in case if poly poly = set() while i < len(sequence)-1: b = b | ...
Returns a tuple (binary reprensentation, default sequence, polymorphisms list)
def from_dict(cls, pref, prefix = None): """ Create a Prefix object from a dict. Suitable for creating Prefix objects from XML-RPC input. """ if prefix is None: prefix = Prefix() prefix.id = pref['id'] if pref['vrf_id'] is not None: # VRF is not mandato...
Create a Prefix object from a dict. Suitable for creating Prefix objects from XML-RPC input.
def validate(retval, func, args): # type: (int, Any, Tuple[Any, Any]) -> Optional[Tuple[Any, Any]] """ Validate the returned value of a Xlib or XRANDR function. """ if retval != 0 and not ERROR.details: return args err = "{}() failed".format(func.__name__) details = {"retval": retval, "arg...
Validate the returned value of a Xlib or XRANDR function.
def raw(self, module, method='GET', data=None): ''' Submits or requsts raw input ''' request = self.session url = 'http://%s:%s/%s' % (self.host, self.port, module) if self.verbose: print data if method=='GET': response = request.get(url) ...
Submits or requsts raw input
def update_subscription(self, update_parameters, subscription_id): """UpdateSubscription. [Preview API] Update an existing subscription. Depending on the type of subscription and permissions, the caller can update the description, filter settings, channel (delivery) settings and more. :param :cl...
UpdateSubscription. [Preview API] Update an existing subscription. Depending on the type of subscription and permissions, the caller can update the description, filter settings, channel (delivery) settings and more. :param :class:`<NotificationSubscriptionUpdateParameters> <azure.devops.v5_0.notificatio...