code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def validate(self, instance, value): """Checks if value is a boolean""" if self.cast: value = bool(value) if not isinstance(value, BOOLEAN_TYPES): self.error(instance, value) return value
Checks if value is a boolean
def base_path(main_path, fmt): """Given a path and options for a format (ext, suffix, prefix), return the corresponding base path""" if not fmt: return os.path.splitext(main_path)[0] fmt = long_form_one_format(fmt) fmt_ext = fmt['extension'] suffix = fmt.get('suffix') prefix = fmt.get('...
Given a path and options for a format (ext, suffix, prefix), return the corresponding base path
def get_bin(self): """Gets the ``Bin`` at this node. return: (osid.resource.Bin) - the bin represented by this node *compliance: mandatory -- This method must be implemented.* """ if self._lookup_session is None: mgr = get_provider_manager('RESOURCE', runtime=self._...
Gets the ``Bin`` at this node. return: (osid.resource.Bin) - the bin represented by this node *compliance: mandatory -- This method must be implemented.*
def isqrt(n): ''' given a non-negative integer n, return a pair (a,b) such that n = a * a * b where b is a square-free integer. If n is a perfect square, then a is its square root and b is one. ''' # TODO: replace with a more efficient implementation if n == 0: return n, 1 ...
given a non-negative integer n, return a pair (a,b) such that n = a * a * b where b is a square-free integer. If n is a perfect square, then a is its square root and b is one.
def get_security_group_dict(): """Returns dictionary of named security groups {name: securitygroup}.""" client = get_ec2_client() response = client.describe_security_groups() assert is_good_response(response) result = OrderedDict() ec2 = get_ec2_resource() for security_group_response in response['Securi...
Returns dictionary of named security groups {name: securitygroup}.
def solve_quadratic(a, b, c): ''' >>> solve_quadratic(1.0, 2.0, 1.0) (-1.0, -1.0) ''' discRoot = math.sqrt((b * b) - 4 * a * c) root1 = (-b - discRoot) / (2 * a) root2 = (-b + discRoot) / (2 * a) return (root1, root2)
>>> solve_quadratic(1.0, 2.0, 1.0) (-1.0, -1.0)
def bit_string_index(text): """Return the index of a string of 0s and 1s.""" n = len(text) k = text.count("1") if text.count("0") != n - k: raise VisualizationError("s must be a string of 0 and 1") ones = [pos for pos, char in enumerate(text) if char == "1"] return lex_index(n, k, ones)
Return the index of a string of 0s and 1s.
def scale_dict_wet(C): """To account for the fact that arXiv:Jenkins:2017jig uses a flavour non-redundant basis in contrast to WCxf, symmetry factors of two have to be introduced in several places for operators that are symmetric under the interchange of two currents.""" return {k: v / _scale_dict[k...
To account for the fact that arXiv:Jenkins:2017jig uses a flavour non-redundant basis in contrast to WCxf, symmetry factors of two have to be introduced in several places for operators that are symmetric under the interchange of two currents.
def filter_keys(d, keys, use_wildcards=False, list_of_dicts=False, deepcopy=True): """ filter dict by certain keys Parameters ---------- d : dict keys: list use_wildcards : bool if true, can use * (matches everything) and ? (matches any single character) list...
filter dict by certain keys Parameters ---------- d : dict keys: list use_wildcards : bool if true, can use * (matches everything) and ? (matches any single character) list_of_dicts: bool treat list of dicts as additional branches deepcopy: bool deepcopy valu...
def find_substring(substring, suffix_tree, edge_repo): """Returns the index if substring in tree, otherwise -1. """ assert isinstance(substring, str) assert isinstance(suffix_tree, SuffixTree) assert isinstance(edge_repo, EventSourcedRepository) if not substring: return -1 if suffix_...
Returns the index if substring in tree, otherwise -1.
def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, ...
Returns the user and group that the disk images should be owned by
def get_default_user_groups(self, **kwargs): # noqa: E501 """Get default user groups customer preferences # 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.get_...
Get default user groups customer preferences # 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.get_default_user_groups(async_req=True) >>> result = thread.get() ...
def extract_files(filename, includes): """ Extract the files to be added based on the includes """ # Load the execution strace log lines = open(filename).readlines() # Extract only open files - whether for read or write. You often # want to capture the json/ini configuration file as well ...
Extract the files to be added based on the includes
def broadcast(self, command, *args, **kwargs): """ Notifies each user with a specified command. """ criterion = kwargs.pop('criterion', self.BROADCAST_FILTER_ALL) for index, user in items(self.users()): if criterion(user, command, *args, **kwargs): sel...
Notifies each user with a specified command.
def _extract_image_urls(arg: Message_T) -> List[str]: """Extract all image urls from a message-like object.""" arg_as_msg = Message(arg) return [s.data['url'] for s in arg_as_msg if s.type == 'image' and 'url' in s.data]
Extract all image urls from a message-like object.
def _log_prefix(self, prefix, request): """ Returns a formatted prefix for logging for the given request. """ # After a celery task runs, the request cache is cleared. So if celery # tasks are running synchronously (CELERY_ALWAYS _EAGER), "guid_key" # will no longer be in...
Returns a formatted prefix for logging for the given request.
def create(self, bucket, descriptor, force=False): """https://github.com/frictionlessdata/tableschema-pandas-py#storage """ # Make lists buckets = bucket if isinstance(bucket, six.string_types): buckets = [bucket] descriptors = descriptor if isinstanc...
https://github.com/frictionlessdata/tableschema-pandas-py#storage
def get_issue(self, number): """ :calls: `GET /repos/:owner/:repo/issues/:number <http://developer.github.com/v3/issues>`_ :param number: integer :rtype: :class:`github.Issue.Issue` """ assert isinstance(number, (int, long)), number headers, data = self._requester...
:calls: `GET /repos/:owner/:repo/issues/:number <http://developer.github.com/v3/issues>`_ :param number: integer :rtype: :class:`github.Issue.Issue`
def _fit_and_score(est, x, y, scorer, train_index, test_index, parameters, fit_params, predict_params): """Train survival model on given data and return its score on test data""" X_train, y_train = _safe_split(est, x, y, train_index) train_params = fit_params.copy() # Training est.set_params(**para...
Train survival model on given data and return its score on test data
def MigrateArtifacts(): """Migrates Artifacts from AFF4 to REL_DB.""" # First, delete all existing artifacts in REL_DB. artifacts = data_store.REL_DB.ReadAllArtifacts() if artifacts: logging.info("Deleting %d artifacts from REL_DB.", len(artifacts)) for artifact in data_store.REL_DB.ReadAllArtifacts():...
Migrates Artifacts from AFF4 to REL_DB.
def delete_subscription(self, subscription_id): """ Delete single subscription """ url = self.SUBSCRIPTIONS_ID_URL % subscription_id connection = Connection(self.token) connection.set_url(self.production, url) return connection.delete_request()
Delete single subscription
def locale_negotiator(request): """Locale negotiator base on the `Accept-Language` header""" locale = 'en' if request.accept_language: locale = request.accept_language.best_match(LANGUAGES) locale = LANGUAGES.get(locale, 'en') return locale
Locale negotiator base on the `Accept-Language` header
def _unarmor(pem_bytes): """ Convert a PEM-encoded byte string into one or more DER-encoded byte strings :param pem_bytes: A byte string of the PEM-encoded data :raises: ValueError - when the pem_bytes do not appear to be PEM-encoded bytes :return: A generator of 3-element...
Convert a PEM-encoded byte string into one or more DER-encoded byte strings :param pem_bytes: A byte string of the PEM-encoded data :raises: ValueError - when the pem_bytes do not appear to be PEM-encoded bytes :return: A generator of 3-element tuples in the format: (object_type, ...
def _njobs(self): """%(InteractiveBase._njobs)s""" ret = super(self.__class__, self)._njobs or [0] ret[0] += 1 return ret
%(InteractiveBase._njobs)s
def isobaric_expansion_l(self): r'''Isobaric (constant-pressure) expansion of the liquid phase of the chemical at its current temperature and pressure, in units of [1/K]. .. math:: \beta = \frac{1}{V}\left(\frac{\partial V}{\partial T} \right)_P Utilizes the temperature-der...
r'''Isobaric (constant-pressure) expansion of the liquid phase of the chemical at its current temperature and pressure, in units of [1/K]. .. math:: \beta = \frac{1}{V}\left(\frac{\partial V}{\partial T} \right)_P Utilizes the temperature-derivative method of :obj:`thermo.v...
def getOneMessage ( self ): """ I pull one complete message off the buffer and return it decoded as a dict. If there is no complete message in the buffer, I return None. Note that the buffer can contain more than once message. You should therefore call me in a loop until...
I pull one complete message off the buffer and return it decoded as a dict. If there is no complete message in the buffer, I return None. Note that the buffer can contain more than once message. You should therefore call me in a loop until I return None.
def setProperty(self, prop, *args, **kwargs): """ Set the value of a property by sending an event on the root window. See the corresponding method for the required arguments. For example, for the property _NET_WM_STATE, look for :meth:`setWmState` """ f = self.__setAttrs....
Set the value of a property by sending an event on the root window. See the corresponding method for the required arguments. For example, for the property _NET_WM_STATE, look for :meth:`setWmState`
def symlink_to(self, target, target_is_directory=False): """ Make this path a symlink pointing to the given path. Note the order of arguments (self, target) is the reverse of os.symlink's. """ if self._closed: self._raise_closed() self._accessor.symlin...
Make this path a symlink pointing to the given path. Note the order of arguments (self, target) is the reverse of os.symlink's.
def fill_tree(comments): """ Insert extra comments in the comments list, so that the root path of the first comment is always visible. Use this in comments' pagination to fill in the tree information. The inserted comments have an ``added_path`` attribute. """ if not comments: return ...
Insert extra comments in the comments list, so that the root path of the first comment is always visible. Use this in comments' pagination to fill in the tree information. The inserted comments have an ``added_path`` attribute.
def get_new_working_set(self): """ Get a new list of IPs to work with from the queue. This returns None if there is no update. Read all the messages from the queue on which we get the IP addresses that we have to monitor. We will ignore all of them, except the last one,...
Get a new list of IPs to work with from the queue. This returns None if there is no update. Read all the messages from the queue on which we get the IP addresses that we have to monitor. We will ignore all of them, except the last one, since maybe we received two updates in a row, but ...
def save_and_close_attributes(self): ''' Performs the same function as save_attributes but also closes the attribute file. ''' if not self.saveable(): raise AttributeError("Cannot save attribute file without a valid file") if not self._db_closed: s...
Performs the same function as save_attributes but also closes the attribute file.
async def get_state_json( self, rr_state_builder: Callable[['Verifier', str, int], Awaitable[Tuple[str, int]]], fro: int, to: int) -> (str, int): """ Get rev reg state json, and its timestamp on the distributed ledger, from cached rev reg state fra...
Get rev reg state json, and its timestamp on the distributed ledger, from cached rev reg state frames list or distributed ledger, updating cache as necessary. Raise BadRevStateTime if caller asks for a state in the future. On return of any previously existing rev reg state frame, alway...
def tridiag(below=None, diag=None, above=None, name=None): """Creates a matrix with values set above, below, and on the diagonal. Example: ```python tridiag(below=[1., 2., 3.], diag=[4., 5., 6., 7.], above=[8., 9., 10.]) # ==> array([[ 4., 8., 0., 0.], # [ 1., 5., ...
Creates a matrix with values set above, below, and on the diagonal. Example: ```python tridiag(below=[1., 2., 3.], diag=[4., 5., 6., 7.], above=[8., 9., 10.]) # ==> array([[ 4., 8., 0., 0.], # [ 1., 5., 9., 0.], # [ 0., 2., 6., 10.], # ...
def detectUbuntuTablet(self): """Return detection of an Ubuntu Mobile OS tablet Detects a tablet running the Ubuntu Mobile OS. """ if UAgentInfo.deviceUbuntu in self.__userAgent \ and UAgentInfo.deviceTablet in self.__userAgent: return True return False
Return detection of an Ubuntu Mobile OS tablet Detects a tablet running the Ubuntu Mobile OS.
def get_reference(self, refobj): """Return the reference node that the reftrack node is connected to or None if it is imported. :param refobj: the reftrack node to query :type refobj: str :returns: the reference node :rtype: str | None :raises: None """ c...
Return the reference node that the reftrack node is connected to or None if it is imported. :param refobj: the reftrack node to query :type refobj: str :returns: the reference node :rtype: str | None :raises: None
def d2gauss(x,m_y,sigma): '''returns the second derivative of the gaussian with mean m_y, and standard deviation sigma, calculated at the points of x.''' return gauss(x,m_y,sigma)*[-1/sigma**2 + (n-m_y)**2/sigma**4 for n in x]
returns the second derivative of the gaussian with mean m_y, and standard deviation sigma, calculated at the points of x.
def search_list(kb, value=None, match_type=None, page=None, per_page=None, unique=False): """Search "mappings to" for knowledge.""" # init page = page or 1 per_page = per_page or 10 if kb.kbtype == models.KnwKB.KNWKB_TYPES['written_as']: # get the...
Search "mappings to" for knowledge.
def create_unclaimed_draft(self, test_mode=False, files=None, file_urls=None, draft_type=None, subject=None, message=None, signers=None, cc_email_addresses=None, signing_redirect_url=None, form_fields_per_document=None, metadata=None, use_preexisting_fields=False, allow_decline=False): ''' Creates a new Draft t...
Creates a new Draft that can be claimed using the claim URL Creates a new Draft that can be claimed using the claim URL. The first authenticated user to access the URL will claim the Draft and will be shown either the "Sign and send" or the "Request signature" page with the Draft loaded...
def columnize(items, separator=' ', displaywidth=80): """ Transform a list of strings into a single string with columns. Parameters ---------- items : sequence of strings The strings to process. separator : str, optional [default is two spaces] The string that separates columns. ...
Transform a list of strings into a single string with columns. Parameters ---------- items : sequence of strings The strings to process. separator : str, optional [default is two spaces] The string that separates columns. displaywidth : int, optional [default is 80] Width ...
def normalize(rp_pyxb): """Normalize a ReplicationPolicy PyXB type in place. The preferred and blocked lists are sorted alphabetically. As blocked nodes override preferred nodes, and any node present in both lists is removed from the preferred list. Args: rp_pyxb : ReplicationPolicy PyXB obj...
Normalize a ReplicationPolicy PyXB type in place. The preferred and blocked lists are sorted alphabetically. As blocked nodes override preferred nodes, and any node present in both lists is removed from the preferred list. Args: rp_pyxb : ReplicationPolicy PyXB object The object will be ...
def reload_using_spawn_wait(self): """ Spawn a subprocess and wait until it finishes. :return: None. """ # Create command parts cmd_parts = [sys.executable] + sys.argv # Get env dict copy env_copy = os.environ.copy() # Send interrupt...
Spawn a subprocess and wait until it finishes. :return: None.
def lte(max_value): """ Validates that a field value is less than or equal to the value given to this validator. """ def validate(value): if value > max_value: return e("{} is not less than or equal to {}", value, max_value) return validate
Validates that a field value is less than or equal to the value given to this validator.
def _WriteResponses(self, responses, cursor): """Builds the writes to store the given responses in the db.""" query = ("INSERT IGNORE INTO flow_responses " "(client_id, flow_id, request_id, response_id, " "response, status, iterator, timestamp) VALUES ") templates = [] args =...
Builds the writes to store the given responses in the db.
def get_asset_spatial_assignment_session_for_repository(self, repository_id, proxy): """Gets the session for assigning spatial coverage of an asset for the given repository. arg: repository_id (osid.id.Id): the Id of the repository arg proxy (osid.proxy.Proxy): a proxy re...
Gets the session for assigning spatial coverage of an asset for the given repository. arg: repository_id (osid.id.Id): the Id of the repository arg proxy (osid.proxy.Proxy): a proxy return: (osid.repository.AssetSpatialAssignmentSession) - an AssetSpatialAssignmen...
def process_hit_event(self, frame): """Return (stop_state, delete_temporary) at a breakpoint hit event.""" if not self.enabled: return False, False # Count every hit when breakpoint is enabled. self.hits += 1 # A conditional breakpoint. if self.cond: ...
Return (stop_state, delete_temporary) at a breakpoint hit event.
def select(self, name): ''' Returns a new PluginSet that has only the plugins in this that are named `name`. ''' return PluginSet(self.group, name, [ plug for plug in self.plugins if plug.name == name])
Returns a new PluginSet that has only the plugins in this that are named `name`.
def getCollapseRequestsFn(self): """Helper function to determine which collapseRequests function to use from L{_collapseRequests}, or None for no merging""" # first, seek through builder, global, and the default collapseRequests_fn = self.config.collapseRequests if collapseReques...
Helper function to determine which collapseRequests function to use from L{_collapseRequests}, or None for no merging
def logstart(self, logfname=None, loghead=None, logmode=None, log_output=False, timestamp=False, log_raw_input=False): """Generate a new log-file with a default header. Raises RuntimeError if the log has already been started""" if self.logfile is not None: raise Ru...
Generate a new log-file with a default header. Raises RuntimeError if the log has already been started
def format(self, altitude=None, deg_char='', min_char='m', sec_char='s'): """ Format decimal degrees (DD) to degrees minutes seconds (DMS) """ latitude = "%s %s" % ( format_degrees(abs(self.latitude), symbols={ 'deg': deg_char, 'arcmin': min_char, 'arcsec': se...
Format decimal degrees (DD) to degrees minutes seconds (DMS)
def calculate_weights(correlation_matrix, min_wt): ''' Calculate a weight for each profile based on its correlation to other replicates. Negative correlations are clipped to 0, and weights are clipped to be min_wt at the least. Args: correlation_matrix (pandas df): Correlations between all replicat...
Calculate a weight for each profile based on its correlation to other replicates. Negative correlations are clipped to 0, and weights are clipped to be min_wt at the least. Args: correlation_matrix (pandas df): Correlations between all replicates min_wt (float): Minimum raw weight when calculating ...
def sha1(self): """SHA1 hash of the config file itself.""" with open(self.path, 'rb') as f: return hashlib.sha1(f.read()).hexdigest()
SHA1 hash of the config file itself.
def load_npy_to_any(path='', name='file.npy'): """Load `.npy` file. Parameters ------------ path : str Path to the file (optional). name : str File name. Examples --------- - see tl.files.save_any_to_npy() """ file_path = os.path.join(path, name) try: ...
Load `.npy` file. Parameters ------------ path : str Path to the file (optional). name : str File name. Examples --------- - see tl.files.save_any_to_npy()
def AddUser(self, uid, username, active): '''Convenience method to add a user. Return the object path of the new user. ''' user_path = '/org/freedesktop/login1/user/%i' % uid if user_path in mockobject.objects: raise dbus.exceptions.DBusException('User %i already exists' % uid, ...
Convenience method to add a user. Return the object path of the new user.
def kld(p1, p2): """Compute Kullback-Leibler divergence between p1 and p2. It assumes that p1 and p2 are already normalized that each of them sums to 1. """ return np.sum(np.where(p1 != 0, p1 * np.log(p1 / p2), 0))
Compute Kullback-Leibler divergence between p1 and p2. It assumes that p1 and p2 are already normalized that each of them sums to 1.
def get_credentials(cmd_args): """ :return: The email and api_key to use to connect to TagCube. This function will try to get the credentials from: * Command line arguments * Environment variables * Configuration file ...
:return: The email and api_key to use to connect to TagCube. This function will try to get the credentials from: * Command line arguments * Environment variables * Configuration file It will return the first match, in the ord...
def calculate_ef_diff(ef_structure1, ef_structure2, fpf): """ returns the absolute value of the difference in enrichment factors and corresponding statistics. specifically, |ef1 - ef2|, the 95% confidence interval, and the 2-sided p-value :param score_structure_1: list [(id, best_score, best_query, stat...
returns the absolute value of the difference in enrichment factors and corresponding statistics. specifically, |ef1 - ef2|, the 95% confidence interval, and the 2-sided p-value :param score_structure_1: list [(id, best_score, best_query, status, net decoy count, net active count), ...,] :param score_structu...
def maskrcnn_upXconv_head(feature, num_category, num_convs, norm=None): """ Args: feature (NxCx s x s): size is 7 in C4 models and 14 in FPN models. num_category(int): num_convs (int): number of convolution layers norm (str or None): either None or 'GN' Returns: mask...
Args: feature (NxCx s x s): size is 7 in C4 models and 14 in FPN models. num_category(int): num_convs (int): number of convolution layers norm (str or None): either None or 'GN' Returns: mask_logits (N x num_category x 2s x 2s):
def cosine_similarity(sentence1, sentence2, tf1, tf2, idf_metrics): """ We compute idf-modified-cosine(sentence1, sentence2) here. It's cosine similarity of these two sentences (vectors) A, B computed as cos(x, y) = A . B / (|A| . |B|) Sentences are represented as vector TF*IDF metrics. ...
We compute idf-modified-cosine(sentence1, sentence2) here. It's cosine similarity of these two sentences (vectors) A, B computed as cos(x, y) = A . B / (|A| . |B|) Sentences are represented as vector TF*IDF metrics. :param sentence1: Iterable object where every item represents word ...
def cache(self): """Cache the Zotero data.""" with open(self.cache_path, "wb") as f: cache = {self.CACHE_REFERENCE_LIST: self._references, self.CACHE_REFERENCE_TYPES: self.reference_types, self.CACHE_REFERENCE_TEMPLATES: self.reference_templates} ...
Cache the Zotero data.
def get_field_mapping(self, fields, index=None, doc_type=None, params=None): """ Retrieve mapping definition of a specific field. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-get-field-mapping.html>`_ :arg fields: A comma-separated list of fields :arg...
Retrieve mapping definition of a specific field. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-get-field-mapping.html>`_ :arg fields: A comma-separated list of fields :arg index: A comma-separated list of index names :arg doc_type: A comma-separated list of do...
def build_mmd(target_folder=DEFAULT_LIBRARY_DIR): """Build and install the MultiMarkdown shared library.""" mmd_dir = tempfile.mkdtemp() mmd_repo = pygit2.clone_repository('https://github.com/jasedit/MultiMarkdown-5', mmd_dir, checkout_branch='fix_windows') mmd_rep...
Build and install the MultiMarkdown shared library.
def resize_dimension(self, name, new_size): """Returns a copy where one dimension has a different size.""" if name not in self.dimension_names: raise ValueError("Shape %s does not have dimension named %s" % (self, name)) return Shape( [Dimension(name, new_size) if d.name...
Returns a copy where one dimension has a different size.
def absent(name, version=-1, recursive=False, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Make sure znode is absent name path to znode version Specify the version which should be deleted Default: -1 (always match) ...
Make sure znode is absent name path to znode version Specify the version which should be deleted Default: -1 (always match) recursive Boolean to indicate if children should be recursively deleted Default: False profile Configured Zookeeper profile to a...
def nps_surveys_1_update(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/nps-api/surveys#update-survey" api_path = "/api/v2/nps/surveys/1" return self.call(api_path, method="PUT", data=data, **kwargs)
https://developer.zendesk.com/rest_api/docs/nps-api/surveys#update-survey
def do_hello(self, sin, sout, name=None): """Using the /hello GET interface There is one optional argument, "name". This name argument must be provided with proper URL excape codes, like %20 for spaces. """ name = '' if name is None else '/' + name r = requests.get('htt...
Using the /hello GET interface There is one optional argument, "name". This name argument must be provided with proper URL excape codes, like %20 for spaces.
def BMI(self, params): """ BMI label Branch to the instruction at label if the N flag is set """ label = self.get_one_parameter(self.ONE_PARAMETER, params) self.check_arguments(label_exists=(label,)) # BMI label def BMI_func(): if self.is_N_...
BMI label Branch to the instruction at label if the N flag is set
def scenarios(self, generate_seed=False): """ Generator function. Spits out scenarios for this experiment """ seed = prime_numbers(1000) sweeps_all = self.experiment["sweeps"].keys() if "combinations" in self.experiment: if isinstance(self.experiment["combinat...
Generator function. Spits out scenarios for this experiment
def get_block(name, data, newline="\n"): """ First block in a list of one line strings containing reStructuredText data. The result is as a joined string with the given newline, or a line generator if it's None. The BLOCK_START and BLOCK_END delimiters are selected with the given name and aren't...
First block in a list of one line strings containing reStructuredText data. The result is as a joined string with the given newline, or a line generator if it's None. The BLOCK_START and BLOCK_END delimiters are selected with the given name and aren't included in the result.
def write(self, data, timeout_s=None): ''' Write to serial port. Waits for serial connection to be established before writing. Parameters ---------- data : str or bytes Data to write to serial port. timeout_s : float, optional Maximum num...
Write to serial port. Waits for serial connection to be established before writing. Parameters ---------- data : str or bytes Data to write to serial port. timeout_s : float, optional Maximum number of seconds to wait for serial connection to be ...
def updateSolutionTerminal(self): ''' Update the terminal period solution. This method should be run when a new AgentType is created or when CRRA changes. Parameters ---------- none Returns ------- none ''' self.solution_terminal...
Update the terminal period solution. This method should be run when a new AgentType is created or when CRRA changes. Parameters ---------- none Returns ------- none
def to_file(self, filepath, codec='utf-8', mode='normal'): """Write the object to a file. :param str filepath: Path of the fil. :param str codec: Text encoding. :param string mode: Flag to for write mode, possible modes: 'n'/'normal', 's'/'short' and 'b'/'binary' """...
Write the object to a file. :param str filepath: Path of the fil. :param str codec: Text encoding. :param string mode: Flag to for write mode, possible modes: 'n'/'normal', 's'/'short' and 'b'/'binary'
def rounding_full(number, is_population=False): """This function performs a rigorous rounding. :param number: The amount to round. :type number: int, float :param is_population: If we should use the population rounding rule, #4062. :type is_population: bool :returns: result and rounding brack...
This function performs a rigorous rounding. :param number: The amount to round. :type number: int, float :param is_population: If we should use the population rounding rule, #4062. :type is_population: bool :returns: result and rounding bracket. :rtype: (int, int)
def update_agent(self, agent_id, **kwargs): """Updates an agent""" url = 'agents/%s' % agent_id agent = self._api._put(url, data=json.dumps(kwargs)) return Agent(**agent)
Updates an agent
def QueryUserDefinedFunctions(self, collection_link, query, options=None): """Queries user defined functions in a collection. :param str collection_link: The link to the collection. :param (str or dict) query: :param dict options: The request options for the requ...
Queries user defined functions in a collection. :param str collection_link: The link to the collection. :param (str or dict) query: :param dict options: The request options for the request. :return: Query Iterable of UDFs. :rtype: ...
def match(self, name, chamber=None): """ If this matcher has uniquely seen a matching name, return its value. Otherwise, return None. If chamber is set then the search will be limited to legislators with matching chamber. If chamber is None then the search will be cross-...
If this matcher has uniquely seen a matching name, return its value. Otherwise, return None. If chamber is set then the search will be limited to legislators with matching chamber. If chamber is None then the search will be cross-chamber.
def fetch(self, method, uri, query=None, body=None, **kwargs): """ wrapper method that all the top level methods (get, post, etc.) use to actually make the request """ if not query: query = {} fetch_url = self.get_fetch_url(uri, query) args = [fetch_url] ...
wrapper method that all the top level methods (get, post, etc.) use to actually make the request
def list_loadbalancers_on_lbaas_agent(self, lbaas_agent, **_params): """Fetches a list of loadbalancers hosted by the loadbalancer agent.""" return self.get((self.agent_path + self.AGENT_LOADBALANCERS) % lbaas_agent, params=_params)
Fetches a list of loadbalancers hosted by the loadbalancer agent.
def _get_cubic_root(self): """Get the cubic root.""" # We have the equation x^2 D^2 + (1-x)^4 * C / h_min^2 # where x = sqrt(mu). # We substitute x, which is sqrt(mu), with x = y + 1. # It gives y^3 + py = q # where p = (D^2 h_min^2)/(2*C) and q = -p. # We use the Vieta's substitution to com...
Get the cubic root.
def is_equal(self, other): """Equality checker with message :param other: Other Impact Function to be compared. :type other: ImpactFunction :returns: True if both are the same IF, other wise False and the message. :rtype: bool, str """ properties = [...
Equality checker with message :param other: Other Impact Function to be compared. :type other: ImpactFunction :returns: True if both are the same IF, other wise False and the message. :rtype: bool, str
def find_meta(meta): """ Extract __*meta*__ from META_FILE. """ meta_match = re.search( r"^__{meta}__ = ['\"]([^'\"]*)['\"]".format(meta=meta), META_FILE, re.M ) if meta_match: return meta_match.group(1) raise RuntimeError("Unable to find __{meta}__ string.".format(me...
Extract __*meta*__ from META_FILE.
def add(self, target, args=None, kwargs=None, **options): """Add an Async job to this context. Takes an Async object or the arguments to construct an Async object as arguments. Returns the newly added Async object. """ from furious.async import Async from furious.batche...
Add an Async job to this context. Takes an Async object or the arguments to construct an Async object as arguments. Returns the newly added Async object.
def plot(self, left, right, labels=None, vertical=True): """ Plot left / right DataFrames in specified layout. Parameters ---------- left : list of DataFrames before operation is applied right : DataFrame of operation result labels : list of str to be drawn as ti...
Plot left / right DataFrames in specified layout. Parameters ---------- left : list of DataFrames before operation is applied right : DataFrame of operation result labels : list of str to be drawn as titles of left DataFrames vertical : bool If True, use vert...
def add(clss, func, deprecated_name): """Add the deprecated version of a member function to the given class. Gives a deprecation warning on usage. Args: clss: the class where the deprecated function is to be added func: the actual function that is called by the deprecate...
Add the deprecated version of a member function to the given class. Gives a deprecation warning on usage. Args: clss: the class where the deprecated function is to be added func: the actual function that is called by the deprecated version deprecated_name: the deprec...
def parameter_action(self, text, loc, par): """Code executed after recognising a parameter""" exshared.setpos(loc, text) if DEBUG > 0: print("PARAM:",par) if DEBUG == 2: self.symtab.display() if DEBUG > 2: return index = self.symtab.insert_param...
Code executed after recognising a parameter
def iter_halfs_double(graph): """Select two random non-consecutive bonds that divide the molecule in two""" edges = graph.edges for index1, (atom_a1, atom_b1) in enumerate(edges): for atom_a2, atom_b2 in edges[:index1]: try: affected_atoms1, affected_atoms2, hinge_atoms =...
Select two random non-consecutive bonds that divide the molecule in two
async def message_fields(self, msg, fields, obj=None): """ Load/dump individual message fields :param msg: :param fields: :param obj: :return: """ for field in fields: await self.message_field(msg, field, obj) return msg
Load/dump individual message fields :param msg: :param fields: :param obj: :return:
def proxy_set(self, value): """ A helper to easily call the proxy_setter of the field """ setter = getattr(self, self.proxy_setter) if isinstance(value, (list, tuple, set)): result = setter(*value) elif isinstance(value, dict): result = setter(**va...
A helper to easily call the proxy_setter of the field
def path(self, which=None): """Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: available_repositories /repository_sets/<id>/available_repositories enable /repository_sets/<id>/enable disabl...
Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: available_repositories /repository_sets/<id>/available_repositories enable /repository_sets/<id>/enable disable /repository_sets/<id>/dis...
def count(self, eventRegistry): """ return the number of events that match the criteria """ self.setRequestedResult(RequestEventsInfo()) res = eventRegistry.execQuery(self) if "error" in res: print(res["error"]) count = res.get("events", {}).get("total...
return the number of events that match the criteria
def _send_string_clipboard(self, string: str, paste_command: model.SendMode): """ Use the clipboard to send a string. """ backup = self.clipboard.text # Keep a backup of current content, to restore the original afterwards. if backup is None: logger.warning("Tried to ...
Use the clipboard to send a string.
def setup_console(output): """Console setup.""" global console # All console related operations is handled via the ConsoleOutput class console = ConsoleOutput(output, streamlink) console.json = args.json # Handle SIGTERM just like SIGINT signal.signal(signal.SIGTERM, signal.default_int_han...
Console setup.
def get_token(self): """ get current oauth token """ self.token = self._session.fetch_token( token_url=CLOUD_URLS["get_token"][1], client_id=self._client_id, client_secret=self._client_secret )
get current oauth token
def urlnext(parser, token): """ {% url %} copied from Django 1.7. """ bits = token.split_contents() if len(bits) < 2: raise template.TemplateSyntaxError( "'%s' takes at least one argument" " (path to a view)" % bits[0] ) viewname = parser.compile_filter(bi...
{% url %} copied from Django 1.7.
def set_value(request, name, value): """ For manual shortcut links to perform set value actions """ obj = service.system.namespace.get(name, None) if not obj or service.read_only: raise Http404 obj.status = value if service.redirect_from_setters: return HttpResponseRedirect(r...
For manual shortcut links to perform set value actions
def set_evict_number(self, new_evict_number, only_read=False): """ >>> cache = Cache(log_level=logging.WARNING) >>> cache.set_evict_number(10) >>> cache.evict_number 10 >>> cache.set_evict_number('haha') >>> cache.evict_number 10 """ if not...
>>> cache = Cache(log_level=logging.WARNING) >>> cache.set_evict_number(10) >>> cache.evict_number 10 >>> cache.set_evict_number('haha') >>> cache.evict_number 10
def start_asweep(self, start=None, stop=None, step=None): """Starts a amplitude sweep. :param start: Sets the start frequency. :param stop: Sets the target frequency. :param step: Sets the frequency step. """ if start: self.amplitude_start = start if...
Starts a amplitude sweep. :param start: Sets the start frequency. :param stop: Sets the target frequency. :param step: Sets the frequency step.
def int_element(element, name, default=0): """ Returns the int value of an element, or a default if it's not defined :param element: The XML Element object :type element: etree._Element :param name: The name of the element to evaluate :type name: str :param default: The default value to ...
Returns the int value of an element, or a default if it's not defined :param element: The XML Element object :type element: etree._Element :param name: The name of the element to evaluate :type name: str :param default: The default value to return if the element is not defined :type default...
def loads(content, ac_parser=None, ac_dict=None, ac_template=False, ac_context=None, **options): """ :param content: Configuration file's content (a string) :param ac_parser: Forced parser type or ID or parser object :param ac_dict: callable (function or class) to make mapping object w...
:param content: Configuration file's content (a string) :param ac_parser: Forced parser type or ID or parser object :param ac_dict: callable (function or class) to make mapping object will be returned as a result or None. If not given or ac_dict is None, default mapping object used to st...
def build(ctx, max_revisions, targets, operators, archiver): """Build the wily cache.""" config = ctx.obj["CONFIG"] from wily.commands.build import build if max_revisions: logger.debug(f"Fixing revisions to {max_revisions}") config.max_revisions = max_revisions if operators: ...
Build the wily cache.
def import_transcript_from_fs(edx_video_id, language_code, file_name, provider, resource_fs, static_dir): """ Imports transcript file from file system and creates transcript record in DS. Arguments: edx_video_id (str): Video id of the video. language_code (unicode): Language code of the req...
Imports transcript file from file system and creates transcript record in DS. Arguments: edx_video_id (str): Video id of the video. language_code (unicode): Language code of the requested transcript. file_name (unicode): File name of the transcript file. provider (unicode): Transcri...