code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def yesterday(date=None): """yesterday once more""" if not date: return _date - datetime.timedelta(days=1) else: current_date = parse(date) return current_date - datetime.timedelta(days=1)
yesterday once more
def safe_size_check(checked_path, error_detail, max_bytes=500000000): """Determines if a particular path is larger than expected. Useful before any recursive remove.""" actual_size = 0 for dirpath, dirnames, filenames in os.walk(checked_path): for f in filenames: fp = os.path.join(dirpat...
Determines if a particular path is larger than expected. Useful before any recursive remove.
def valuecounter(table, *field, **kwargs): """ Find distinct values for the given field and count the number of occurrences. Returns a :class:`dict` mapping values to counts. E.g.:: >>> import petl as etl >>> table = [['foo', 'bar'], ... ['a', True], ... ['...
Find distinct values for the given field and count the number of occurrences. Returns a :class:`dict` mapping values to counts. E.g.:: >>> import petl as etl >>> table = [['foo', 'bar'], ... ['a', True], ... ['b'], ... ['b', True], ... ...
def groups_roles(self, room_id=None, room_name=None, **kwargs): """Lists all user’s roles in the private group.""" if room_id: return self.__call_api_get('groups.roles', roomId=room_id, kwargs=kwargs) elif room_name: return self.__call_api_get('groups.roles', roomName=roo...
Lists all user’s roles in the private group.
def register(im1, im2, params, exact_params=False, verbose=1): """ register(im1, im2, params, exact_params=False, verbose=1) Perform the registration of `im1` to `im2`, using the given parameters. Returns `(im1_deformed, field)`, where `field` is a tuple with arrays describing the deformation for ...
register(im1, im2, params, exact_params=False, verbose=1) Perform the registration of `im1` to `im2`, using the given parameters. Returns `(im1_deformed, field)`, where `field` is a tuple with arrays describing the deformation for each dimension (x-y-z order, in world units). Parameters: ...
def reftrack_uptodate_data(rt, role): """Return the data for the uptodate status :param rt: the :class:`jukeboxcore.reftrack.Reftrack` holds the data :type rt: :class:`jukeboxcore.reftrack.Reftrack` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the uptodate s...
Return the data for the uptodate status :param rt: the :class:`jukeboxcore.reftrack.Reftrack` holds the data :type rt: :class:`jukeboxcore.reftrack.Reftrack` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the uptodate status :rtype: depending on role :rais...
def _process_file(input_file, output_file, apikey): """Shrinks input_file to output_file. This function should be used only inside process_directory. It takes input_file, tries to shrink it and if shrink was successful save compressed image to output_file. Otherwise raise exception. @return compre...
Shrinks input_file to output_file. This function should be used only inside process_directory. It takes input_file, tries to shrink it and if shrink was successful save compressed image to output_file. Otherwise raise exception. @return compressed: PNGResponse
def _build_migrated_variables(checkpoint_reader, name_value_fn): """Builds the TensorFlow variables of the migrated checkpoint. Args: checkpoint_reader: A `tf.train.NewCheckPointReader` of the checkpoint to be read from. name_value_fn: Function taking two arguments, `name` and `value`, which re...
Builds the TensorFlow variables of the migrated checkpoint. Args: checkpoint_reader: A `tf.train.NewCheckPointReader` of the checkpoint to be read from. name_value_fn: Function taking two arguments, `name` and `value`, which returns the pair of new name and value for that a variable of that name....
def fasper(x, y, ofac, hifac, n_threads, MACC=4): """ Given abscissas x (which need not be equally spaced) and ordinates y, and given a desired oversampling factor ofac (a typical value being 4 or larger). this routine creates an array wk1 with a sequence of nout increasing frequencies (not angular ...
Given abscissas x (which need not be equally spaced) and ordinates y, and given a desired oversampling factor ofac (a typical value being 4 or larger). this routine creates an array wk1 with a sequence of nout increasing frequencies (not angular frequencies) up to hifac times the "average" Nyquist frequ...
def clip_polygon(self, points): """Create a polygonal clip region. You must call endclip() after you completed drawing. See also the polygon method.""" self.gsave() self._path_polygon(points) self.__clip_stack.append(self.__clip_box) self.__clip_box = _intersect_box(self....
Create a polygonal clip region. You must call endclip() after you completed drawing. See also the polygon method.
def get_sections(self, gradebook_id='', simple=False): """Get the sections for a gradebook. Return a dictionary of types of sections containing a list of that type for a given gradebook. Specified by a gradebookid. If simple=True, a list of dictionaries is provided for each se...
Get the sections for a gradebook. Return a dictionary of types of sections containing a list of that type for a given gradebook. Specified by a gradebookid. If simple=True, a list of dictionaries is provided for each section regardless of type. The dictionary only contains one ...
def send_message(self, message): """Send a raw JSON-RPC message. The *message* argument must be a dictionary containing a valid JSON-RPC message according to the version passed into the constructor. """ if self._error: raise compat.saved_exc(self._error) elif...
Send a raw JSON-RPC message. The *message* argument must be a dictionary containing a valid JSON-RPC message according to the version passed into the constructor.
def write(self): """Write changes to our file, if there are changes at all :raise IOError: if this is a read-only writer instance or if we could not obtain a file lock""" self._assure_writable("write") if not self._dirty: return if isinstance(self._file_...
Write changes to our file, if there are changes at all :raise IOError: if this is a read-only writer instance or if we could not obtain a file lock
def asDigraph(self): """ Generate a L{graphviz.Digraph} that represents this machine's states and transitions. @return: L{graphviz.Digraph} object; for more information, please see the documentation for U{graphviz<https://graphviz.readthedocs.io/>} """ ...
Generate a L{graphviz.Digraph} that represents this machine's states and transitions. @return: L{graphviz.Digraph} object; for more information, please see the documentation for U{graphviz<https://graphviz.readthedocs.io/>}
def issue(self, issue_instance_id): """Select an issue. Parameters: issue_instance_id: int id of the issue instance to select Note: We are selecting issue instances, even though the command is called issue. """ with self.db.make_session() as session: ...
Select an issue. Parameters: issue_instance_id: int id of the issue instance to select Note: We are selecting issue instances, even though the command is called issue.
def get_permissions(self, user_id): """Fetches the permissions object from the graph.""" response = self.request( "{0}/{1}/permissions".format(self.version, user_id), {} )["data"] return {x["permission"] for x in response if x["status"] == "granted"}
Fetches the permissions object from the graph.
def addSourceId(self, value): '''Adds SourceId to External_Info ''' if isinstance(value, Source_Id): self.source_ids.append(value) else: raise (TypeError, 'source_id Type should be Source_Id, not %s' % type(source_id))
Adds SourceId to External_Info
def remove_user_from_acl(self, name, user): """Remove a user from the given acl (both allow and deny).""" if name not in self._acl: return False if user in self._acl[name]['allow']: self._acl[name]['allow'].remove(user) if user in self._acl[name]['deny']: ...
Remove a user from the given acl (both allow and deny).
def make_data(n,width): """make_data: compute matrix distance and time windows.""" x = dict([(i,100*random.random()) for i in range(1,n+1)]) y = dict([(i,100*random.random()) for i in range(1,n+1)]) c = {} for i in range(1,n+1): for j in range(1,n+1): if j != i: c...
make_data: compute matrix distance and time windows.
def _events(self): """Get the monitoring events from the daemon This is used by the arbiter to get the monitoring events from all its satellites :return: Events list serialized :rtype: list """ with self.app.events_lock: res = self.app.get_events() r...
Get the monitoring events from the daemon This is used by the arbiter to get the monitoring events from all its satellites :return: Events list serialized :rtype: list
def get_layers_output(self, dataset): """Get output from each layer of the network. :param dataset: input data :return: list of np array, element i is the output of layer i """ layers_out = [] with self.tf_graph.as_default(): with tf.Session() as self.tf_ses...
Get output from each layer of the network. :param dataset: input data :return: list of np array, element i is the output of layer i
def symbol(self, index): """Generates symbol name from index""" #if index is actually a string, just return it if isinstance(index, str): return index elif (index < 0) or (index >= self.symtab.table_len): self.error("symbol table index out of range") ...
Generates symbol name from index
def readSB(self, bits): """ Read a signed int using the specified number of bits """ shift = 32 - bits return int32(self.readbits(bits) << shift) >> shift
Read a signed int using the specified number of bits
def traverse_imports(names): """ Walks over all the names imported in a dotted_as_names node. """ pending = [names] while pending: node = pending.pop() if node.type == token.NAME: yield node.value elif node.type == syms.dotted_name: yield "".join([ch.v...
Walks over all the names imported in a dotted_as_names node.
def constraint_matrices(model, array_type='dense', include_vars=False, zero_tol=1e-6): """Create a matrix representation of the problem. This is used for alternative solution approaches that do not use optlang. The function will construct the equality matrix, inequality matrix and ...
Create a matrix representation of the problem. This is used for alternative solution approaches that do not use optlang. The function will construct the equality matrix, inequality matrix and bounds for the complete problem. Notes ----- To accomodate non-zero equalities the problem will add th...
def create_from_pytz(cls, tz_info): """Create an instance using the result of the timezone() call in "pytz". """ zone_name = tz_info.zone utc_transition_times_list_raw = getattr(tz_info, '_utc_transition_times', ...
Create an instance using the result of the timezone() call in "pytz".
def get_snapshots(self): """ Returns a list of all completed snapshots for this volume ID. """ ec2 = self.get_ec2_connection() rs = ec2.get_all_snapshots() all_vols = [self.volume_id] + self.past_volume_ids snaps = [] for snapshot in rs: if sna...
Returns a list of all completed snapshots for this volume ID.
def remote(*args, **kwargs): """Define a remote function or an actor class. This can be used with no arguments to define a remote function or actor as follows: .. code-block:: python @ray.remote def f(): return 1 @ray.remote class Foo(object): ...
Define a remote function or an actor class. This can be used with no arguments to define a remote function or actor as follows: .. code-block:: python @ray.remote def f(): return 1 @ray.remote class Foo(object): def method(self): re...
def initialize(): """ Initialize the configuration system by installing YAML handlers. Automatically done on first call to load() specified in this file. """ global is_initialized # Add the custom multi-constructor yaml.add_multi_constructor('!obj:', multi_constructor) yaml.add_multi_con...
Initialize the configuration system by installing YAML handlers. Automatically done on first call to load() specified in this file.
def all(self, data={}, **kwargs): """" Fetch all Virtual Account entities Returns: Dictionary of Virtual Account data """ return super(VirtualAccount, self).all(data, **kwargs)
Fetch all Virtual Account entities Returns: Dictionary of Virtual Account data
def receive_response(self, transaction): """ Handles the Blocks option in a incoming response. :type transaction: Transaction :param transaction: the transaction that owns the response :rtype : Transaction :return: the edited transaction """ host, port = ...
Handles the Blocks option in a incoming response. :type transaction: Transaction :param transaction: the transaction that owns the response :rtype : Transaction :return: the edited transaction
def _request(self, *args, **kwargs): # type (Any) -> Response """Make requests using configured :class:`requests.Session`. Any error details will be extracted to an :class:`HTTPError` which will contain relevant error details when printed.""" self._amend_request_kwargs(kwargs) ...
Make requests using configured :class:`requests.Session`. Any error details will be extracted to an :class:`HTTPError` which will contain relevant error details when printed.
def _fail_with_undefined_error(self, *args, **kwargs): """Regular callback function for undefined objects that raises an `UndefinedError` on call. """ if self._undefined_hint is None: if self._undefined_obj is missing: hint = '%r is undefined' % self._undefine...
Regular callback function for undefined objects that raises an `UndefinedError` on call.
def remove_group(self, group = None): """This method removes a group. The group needed to remove the group. group must be a v1Group. """ if group is None: raise KPError("Need group to remove a group") elif type(group) is not v1Group: ra...
This method removes a group. The group needed to remove the group. group must be a v1Group.
def _FormatExpression(self, frame, expression): """Evaluates a single watched expression and formats it into a string form. If expression evaluation fails, returns error message string. Args: frame: Python stack frame in which the expression is evaluated. expression: string expression to evalu...
Evaluates a single watched expression and formats it into a string form. If expression evaluation fails, returns error message string. Args: frame: Python stack frame in which the expression is evaluated. expression: string expression to evaluate. Returns: Formatted expression value tha...
def hash160(msg_bytes): ''' byte-like -> bytes ''' h = hashlib.new('ripemd160') if 'decred' in riemann.get_current_network_name(): h.update(blake256(msg_bytes)) return h.digest() h.update(sha256(msg_bytes)) return h.digest()
byte-like -> bytes
def GetOptionBool(self, section, option): """Get the value of an option in the config file. Args: section: string, the section of the config file to check. option: string, the option to retrieve the value of. Returns: bool, True if the option is enabled or not set. """ return (no...
Get the value of an option in the config file. Args: section: string, the section of the config file to check. option: string, the option to retrieve the value of. Returns: bool, True if the option is enabled or not set.
def get_files_by_path(path): '''Get a file or set of files from a file path Return list of files with path ''' if os.path.isfile(path): return [path] if os.path.isdir(path): return get_morph_files(path) raise IOError('Invalid data path %s' % path)
Get a file or set of files from a file path Return list of files with path
def _get_data_from_rawfile(path_to_data, raw_data_id): """Get a HandwrittenData object that has ``raw_data_id`` from a pickle file ``path_to_data``. :returns: The HandwrittenData object if ``raw_data_id`` is in path_to_data, otherwise ``None``.""" loaded = pickle.load(open(path_to...
Get a HandwrittenData object that has ``raw_data_id`` from a pickle file ``path_to_data``. :returns: The HandwrittenData object if ``raw_data_id`` is in path_to_data, otherwise ``None``.
def components(self, visible=True): """ Return the component notes of chord :param bool visible: returns the name of notes if True else list of int :rtype: list[(str or int)] :return: component notes of chord """ if self._on: self._quality.append_on_chord(sel...
Return the component notes of chord :param bool visible: returns the name of notes if True else list of int :rtype: list[(str or int)] :return: component notes of chord
def make_mask(filename, ext, trail_coords, sublen=75, subwidth=200, order=3, sigma=4, pad=10, plot=False, verbose=False): """Create DQ mask for an image for a given satellite trail. This mask can be added to existing DQ data using :func:`update_dq`. .. note:: Unlike :func:`detsat`, m...
Create DQ mask for an image for a given satellite trail. This mask can be added to existing DQ data using :func:`update_dq`. .. note:: Unlike :func:`detsat`, multiprocessing is not available for this function. Parameters ---------- filename : str FITS image filename. ...
def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to con...
Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is p...
def create_router(self, name, tenant_id, subnet_lst): """Create a openstack router and add the interfaces. """ try: body = {'router': {'name': name, 'tenant_id': tenant_id, 'admin_state_up': True}} router = self.neutronclient.create_router(body=body...
Create a openstack router and add the interfaces.
def _validate_response(url, response): """Validates that the response from Google was successful.""" if response['status'] not in [GooglePlaces.RESPONSE_STATUS_OK, GooglePlaces.RESPONSE_STATUS_ZERO_RESULTS]: error_detail = ('Request to URL %s failed with response code: ...
Validates that the response from Google was successful.
def complete_pool_name(arg): """ Returns list of matching pool names """ search_string = '^' if arg is not None: search_string += arg res = Pool.search({ 'operator': 'regex_match', 'val1': 'name', 'val2': search_string }) ret = [] for p in res['result']...
Returns list of matching pool names
def get(cls, user_id, db_session=None): """ Fetch row using primary key - will use existing object in session if already present :param user_id: :param db_session: :return: """ db_session = get_db_session(db_session) return db_session.query(cls.mo...
Fetch row using primary key - will use existing object in session if already present :param user_id: :param db_session: :return:
def main(): """Takes crash data via stdin and generates a Socorro signature""" parser = argparse.ArgumentParser(description=DESCRIPTION) parser.add_argument( '-v', '--verbose', help='increase output verbosity', action='store_true' ) args = parser.parse_args() generator = SignatureGenera...
Takes crash data via stdin and generates a Socorro signature
def font_size_splitter(font_map): """ Split fonts to 4 category (small,medium,large,xlarge) by maximum length of letter in each font. :param font_map: input fontmap :type font_map : dict :return: splitted fonts as dict """ small_font = [] medium_font = [] large_font = [] xlarge_...
Split fonts to 4 category (small,medium,large,xlarge) by maximum length of letter in each font. :param font_map: input fontmap :type font_map : dict :return: splitted fonts as dict
def is_promisc(ip, fake_bcast="ff:ff:00:00:00:00", **kargs): """Try to guess if target is in Promisc mode. The target is provided by its ip.""" # noqa: E501 responses = srp1(Ether(dst=fake_bcast) / ARP(op="who-has", pdst=ip), type=ETH_P_ARP, iface_hint=ip, timeout=1, verbose=0, **kargs) # noqa: E501 ret...
Try to guess if target is in Promisc mode. The target is provided by its ip.
def json_decode(data_type, serialized_obj, caller_permissions=None, alias_validators=None, strict=True, old_style=False): """Performs the reverse operation of json_encode. Args: data_type (Validator): Validator for serialized_obj. serialized_obj (str): The JSON string to deseria...
Performs the reverse operation of json_encode. Args: data_type (Validator): Validator for serialized_obj. serialized_obj (str): The JSON string to deserialize. caller_permissions (list): The list of raw-string caller permissions with which to serialize. alias_validators ...
def add_highlight(self, artist, *args, **kwargs): """ Create, add, and return a highlighting artist. This method is should be called with an "unpacked" `Selection`, possibly with some fields set to None. It is up to the caller to register the artist with the proper `Sel...
Create, add, and return a highlighting artist. This method is should be called with an "unpacked" `Selection`, possibly with some fields set to None. It is up to the caller to register the artist with the proper `Selection` (by calling ``sel.extras.append`` on the result of this ...
def dump(self): """ raw dump of all records in the b-tree """ print("pagesize=%08x, reccount=%08x, pagecount=%08x" % (self.pagesize, self.reccount, self.pagecount)) self.dumpfree() self.dumptree(self.firstindex)
raw dump of all records in the b-tree
def replace_volume_attachment(self, name, body, **kwargs): """ replace the specified VolumeAttachment This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_volume_attachment(name, body, a...
replace the specified VolumeAttachment This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_volume_attachment(name, body, async_req=True) >>> result = thread.get() :param async_req bool...
def get_subgraph(graph, seed_method: Optional[str] = None, seed_data: Optional[Any] = None, expand_nodes: Optional[List[BaseEntity]] = None, remove_nodes: Optional[List[BaseEntity]] = None, ): """Run a pipeline query on graph with ...
Run a pipeline query on graph with multiple sub-graph filters and expanders. Order of Operations: 1. Seeding by given function name and data 2. Add nodes 3. Remove nodes :param pybel.BELGraph graph: A BEL graph :param seed_method: The name of the get_subgraph_by_* function to use :param s...
def _edge_list_to_dataframe(ls, src_column_name, dst_column_name): """ Convert a list of edges into dataframe. """ assert HAS_PANDAS, 'Cannot use dataframe because Pandas is not available or version is too low.' cols = reduce(set.union, (set(e.attr.keys()) for e in ls)) df = pd.DataFrame({ ...
Convert a list of edges into dataframe.
def get_storage_hash(storage): """ Return a hex string hash for a storage object (or string containing 'full.path.ClassName' referring to a storage object). """ # If storage is wrapped in a lazy object we need to get the real thing. if isinstance(storage, LazyObject): if storage._wrapped...
Return a hex string hash for a storage object (or string containing 'full.path.ClassName' referring to a storage object).
def list(self, id, seq): # pylint: disable=invalid-name,redefined-builtin """Get a list of captures. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :return: :class:`captures.Capture <captures.Capture>` list """ schema = CaptureSchema(exclud...
Get a list of captures. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :return: :class:`captures.Capture <captures.Capture>` list
def getColorHSV(name): """Retrieve the hue, saturation, value triple of a color name. Returns: a triple (degree, percent, percent). If not found (-1, -1, -1) is returned. """ try: x = getColorInfoList()[getColorList().index(name.upper())] except: return (-1, -1, -1) ...
Retrieve the hue, saturation, value triple of a color name. Returns: a triple (degree, percent, percent). If not found (-1, -1, -1) is returned.
def package_locations(self, package_keyname): """List datacenter locations for a package keyname :param str package_keyname: The package for which to get the items. :returns: List of locations a package is orderable in """ mask = "mask[description, keyname, locations]" ...
List datacenter locations for a package keyname :param str package_keyname: The package for which to get the items. :returns: List of locations a package is orderable in
def get_permission_requests(parser, token): """ Retrieves all permissions requests associated with the given obj and user and assigns the result to a context variable. Syntax:: {% get_permission_requests obj %} {% for perm in permissions %} {{ perm }} {% endfor %} ...
Retrieves all permissions requests associated with the given obj and user and assigns the result to a context variable. Syntax:: {% get_permission_requests obj %} {% for perm in permissions %} {{ perm }} {% endfor %} {% get_permission_requests obj as "my_permission...
def error(self, error): """ set the error """ # TODO: check length with value? # TODO: type checks (similar to value) if self.direction not in ['x', 'y', 'z'] and error is not None: raise ValueError("error only accepted for x, y, z dimensions") if isi...
set the error
def _get_stats_columns(cls, table, relation_type): """Given a table, return an iterator of key/value pairs for stats column names/values. """ column_names = cls._get_stats_column_names() # agate does not handle the array of column names gracefully clustering_value = None...
Given a table, return an iterator of key/value pairs for stats column names/values.
def _match_type(self, i): """Looks at line 'i' to see if the line matches a module user type def.""" self.col_match = self.RE_TYPE.match(self._source[i]) if self.col_match is not None: self.section = "types" self.el_type = CustomType self.el_name = self.col_ma...
Looks at line 'i' to see if the line matches a module user type def.
def distinct_words(string_matrix: List[List[str]]) -> Set[str]: """ Diagnostic function :param string_matrix: :return: >>> dl = distinct_words([['the', 'quick', 'brown'], ['here', 'lies', 'the', 'fox']]) >>> sorted(dl) ['brown', 'fox', 'here', 'lies', 'quick', 'the'] """ return set([...
Diagnostic function :param string_matrix: :return: >>> dl = distinct_words([['the', 'quick', 'brown'], ['here', 'lies', 'the', 'fox']]) >>> sorted(dl) ['brown', 'fox', 'here', 'lies', 'quick', 'the']
def get_slopes(data, s_freq, level='all', smooth=0.05): """Get the slopes (average and/or maximum) for each quadrant of a slow wave, as well as the combination of quadrants 2 and 3. Parameters ---------- data : ndarray raw data as vector s_freq : int sampling frequency level...
Get the slopes (average and/or maximum) for each quadrant of a slow wave, as well as the combination of quadrants 2 and 3. Parameters ---------- data : ndarray raw data as vector s_freq : int sampling frequency level : str if 'average', returns average slopes (uV / s). i...
def health(self, index=None, params=None): """ Get a very simple status on the health of the cluster. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-health.html>`_ :arg index: Limit the information returned to a specific index :arg level: Specify the le...
Get a very simple status on the health of the cluster. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-health.html>`_ :arg index: Limit the information returned to a specific index :arg level: Specify the level of detail for returned information, default 'cl...
def should_include_file_in_search(file_name, extensions, exclude_dirs): """ Whether or not a filename matches a search criteria according to arguments. Args: file_name (str): A file path to check. extensions (list): A list of file extensions file should match. exclude_dirs (list): A lis...
Whether or not a filename matches a search criteria according to arguments. Args: file_name (str): A file path to check. extensions (list): A list of file extensions file should match. exclude_dirs (list): A list of directories to exclude from search. Returns: A boolean of whet...
def setdim(P, dim=None): """ Adjust the dimensions of a polynomial. Output the results into Poly object Args: P (Poly) : Input polynomial dim (int) : The dimensions of the output polynomial. If omitted, increase polynomial with one dimension. If the new dim is ...
Adjust the dimensions of a polynomial. Output the results into Poly object Args: P (Poly) : Input polynomial dim (int) : The dimensions of the output polynomial. If omitted, increase polynomial with one dimension. If the new dim is smaller then P's dimensions, v...
def slice_around_gaps (values, maxgap): """Given an ordered array of values, generate a set of slices that traverse all of the values. Within each slice, no gap between adjacent values is larger than `maxgap`. In other words, these slices break the array into chunks separated by gaps of size larger than...
Given an ordered array of values, generate a set of slices that traverse all of the values. Within each slice, no gap between adjacent values is larger than `maxgap`. In other words, these slices break the array into chunks separated by gaps of size larger than maxgap.
def _check_channel_state_for_update( self, channel_identifier: ChannelID, closer: Address, update_nonce: Nonce, block_identifier: BlockSpecification, ) -> Optional[str]: """Check the channel state on chain to see if it has been updated. Co...
Check the channel state on chain to see if it has been updated. Compare the nonce, we are about to update the contract with, with the updated nonce in the onchain state and, if it's the same, return a message with which the caller should raise a RaidenRecoverableError. If all is okay r...
def perform_remote_action(i): """ Input: { See 'perform_action' function } Output: { See 'perform_action' function } """ # Import modules compatible with Python 2.x and 3.x import urllib try: import urllib.request as urllib2 except: import urllib2 # pragma: no cover try: fr...
Input: { See 'perform_action' function } Output: { See 'perform_action' function }
def get_term_pillar(filter_name, term_name, pillar_key='acl', pillarenv=None, saltenv=None): ''' Helper that can be used inside a state SLS, in order to get the term configuration given its name, under a certain filter uniqu...
Helper that can be used inside a state SLS, in order to get the term configuration given its name, under a certain filter uniquely identified by its name. filter_name The name of the filter. term_name The name of the term. pillar_key: ``acl`` The root key of the whole poli...
def check(self): """ Checks the values of the windows. If any problems are found, it flags them by changing the background colour. Only active windows are checked. Returns status, flag for whether parameters are viable. """ status = True synced = True ...
Checks the values of the windows. If any problems are found, it flags them by changing the background colour. Only active windows are checked. Returns status, flag for whether parameters are viable.
def read_csv(filename, delimiter=",", skip=0, guess_type=True, has_header=True, use_types={}): """Read a CSV file Usage ----- >>> data = read_csv(filename, delimiter=delimiter, skip=skip, guess_type=guess_type, has_header=True, use_types={}) # Use specific types >>> types = {"...
Read a CSV file Usage ----- >>> data = read_csv(filename, delimiter=delimiter, skip=skip, guess_type=guess_type, has_header=True, use_types={}) # Use specific types >>> types = {"sepal.length": int, "petal.width": float} >>> data = read_csv(filename, guess_type=guess_type, use...
def osd_page_handler(config=None, identifier=None, prefix=None, **args): """Flask handler to produce HTML response for OpenSeadragon view of identifier. Arguments: config - Config object for this IIIF handler identifier - identifier of image/generator prefix - path prefix **args...
Flask handler to produce HTML response for OpenSeadragon view of identifier. Arguments: config - Config object for this IIIF handler identifier - identifier of image/generator prefix - path prefix **args - other aguments ignored
def ref2names2commdct(ref2names, commdct): """embed ref2names into commdct""" for comm in commdct: for cdct in comm: try: refs = cdct['object-list'][0] validobjects = ref2names[refs] cdct.update({'validobjects':validobjects}) except...
embed ref2names into commdct
def create(cls, name, division, api=None): """ Create team within a division :param name: Team name. :param division: Parent division. :param api: Api instance. :return: Team object. """ division = Transform.to_division(division) api = api if api...
Create team within a division :param name: Team name. :param division: Parent division. :param api: Api instance. :return: Team object.
def deref(self, ctx): """ Returns the value this reference is pointing to. This method uses 'ctx' to resolve the reference and return the value this reference references. If the call was already made, it returns a cached result. It also makes sure there's no cyclic reference, and...
Returns the value this reference is pointing to. This method uses 'ctx' to resolve the reference and return the value this reference references. If the call was already made, it returns a cached result. It also makes sure there's no cyclic reference, and if so raises CyclicReferenceError.
def visit_ellipsis(self, node, parent): """visit an Ellipsis node by returning a fresh instance of it""" return nodes.Ellipsis( getattr(node, "lineno", None), getattr(node, "col_offset", None), parent )
visit an Ellipsis node by returning a fresh instance of it
def program_files(self, executable): """ Determine the file paths to be adopted """ if self._get_version() == 6: paths = self.REQUIRED_PATHS_6 elif self._get_version() > 6: paths = self.REQUIRED_PATHS_7_1 return paths
Determine the file paths to be adopted
def _match_processes(self, pid, name, cur_process): """ Determine whether user-specified "pid/processes" contain this process :param pid: The user input of pid :param name: The user input of process name :param process: current process info :return: True or Not; (if both pid/process are given, t...
Determine whether user-specified "pid/processes" contain this process :param pid: The user input of pid :param name: The user input of process name :param process: current process info :return: True or Not; (if both pid/process are given, then both of them need to match)
def get(self, name, param=None): """Retreive a metadata attribute. :param string name: name of the attribute to retrieve. See `attribs` :param param: Required parameter for some attributes """ if name not in self.attribs: raise exceptions.SoftLayerError('Unknown met...
Retreive a metadata attribute. :param string name: name of the attribute to retrieve. See `attribs` :param param: Required parameter for some attributes
def getlocals(back=2): """Get the local variables some levels back (-1 is top).""" import inspect fr = inspect.currentframe() try: while fr and back != 0: fr1 = fr fr = fr.f_back back -= 1 except: pass return fr1.f_locals
Get the local variables some levels back (-1 is top).
def network(n): """Validate a |Network|. Checks the TPM and connectivity matrix. """ tpm(n.tpm) connectivity_matrix(n.cm) if n.cm.shape[0] != n.size: raise ValueError("Connectivity matrix must be NxN, where N is the " "number of nodes in the network.") retur...
Validate a |Network|. Checks the TPM and connectivity matrix.
def validate(self): """Validate that the OutputContextField is correctly representable.""" if not isinstance(self.location, Location): raise TypeError(u'Expected Location location, got: {} {}'.format( type(self.location).__name__, self.location)) if not self.location...
Validate that the OutputContextField is correctly representable.
def sign_execute_deposit(deposit_params, key_pair): """ Function to execute the deposit request by signing the transaction generated by the create deposit function. Execution of this function is as follows:: sign_execute_deposit(deposit_details=create_deposit, key_pair=key_pair) The expected r...
Function to execute the deposit request by signing the transaction generated by the create deposit function. Execution of this function is as follows:: sign_execute_deposit(deposit_details=create_deposit, key_pair=key_pair) The expected return result for this function is as follows:: { ...
def compile_file_into_spirv(filepath, stage, optimization='size', warnings_as_errors=False): """Compile shader file into Spir-V binary. This function uses shaderc to compile your glsl file code into Spir-V code. Args: filepath (strs): Absolute path to your shader fi...
Compile shader file into Spir-V binary. This function uses shaderc to compile your glsl file code into Spir-V code. Args: filepath (strs): Absolute path to your shader file stage (str): Pipeline stage in ['vert', 'tesc', 'tese', 'geom', 'frag', 'comp'] optimiza...
def _dstr(degrees, places=1, signed=False): r"""Convert floating point `degrees` into a sexagesimal string. >>> _dstr(181.875) '181deg 52\' 30.0"' >>> _dstr(181.875, places=3) '181deg 52\' 30.000"' >>> _dstr(181.875, signed=True) '+181deg 52\' 30.0"' >>> _dstr(float('nan')) 'nan' ...
r"""Convert floating point `degrees` into a sexagesimal string. >>> _dstr(181.875) '181deg 52\' 30.0"' >>> _dstr(181.875, places=3) '181deg 52\' 30.000"' >>> _dstr(181.875, signed=True) '+181deg 52\' 30.0"' >>> _dstr(float('nan')) 'nan'
def isSet(self, param): """ Checks whether a param is explicitly set by user. """ param = self._resolveParam(param) return param in self._paramMap
Checks whether a param is explicitly set by user.
def send_event_to_salt(self, result): ''' This function identifies whether the engine is running on the master or the minion and sends the data to the master event bus accordingly. :param result: It's a dictionary which has the final data and topic. ''' if result['send'...
This function identifies whether the engine is running on the master or the minion and sends the data to the master event bus accordingly. :param result: It's a dictionary which has the final data and topic.
def unhex(s): """Get the integer value of a hexadecimal number.""" bits = 0 for c in s: if '0' <= c <= '9': i = ord('0') elif 'a' <= c <= 'f': i = ord('a')-10 elif 'A' <= c <= 'F': i = ord('A')-10 else: break bits = bits...
Get the integer value of a hexadecimal number.
def save_config(self): """ Save config file Creates config.restore (back up file) Returns: -1: Error saving config 0: Config saved successfully 1: Config not saved (not modified""" if not self.opts['dirty_config'][1]: ...
Save config file Creates config.restore (back up file) Returns: -1: Error saving config 0: Config saved successfully 1: Config not saved (not modified
def check_cgroup_availability_in_thread(options): """ Run check_cgroup_availability() in a separate thread to detect the following problem: If "cgexec --sticky" is used to tell cgrulesengd to not interfere with our child processes, the sticky flag unfortunately works only for processes spawned by th...
Run check_cgroup_availability() in a separate thread to detect the following problem: If "cgexec --sticky" is used to tell cgrulesengd to not interfere with our child processes, the sticky flag unfortunately works only for processes spawned by the main thread, not those spawned by other threads (and thi...
def run(): """This client pulls PCAP files for building report. Returns: A list with `view_pcap` , `meta` and `filename` objects. """ global WORKBENCH # Grab grab_server_argsrver args args = client_helper.grab_server_args() # Start up workbench connection WORKBENCH = zero...
This client pulls PCAP files for building report. Returns: A list with `view_pcap` , `meta` and `filename` objects.
def __ensure_provisioning_writes( table_name, table_key, gsi_name, gsi_key, num_consec_write_checks): """ Ensure that provisioning of writes is correct :type table_name: str :param table_name: Name of the DynamoDB table :type table_key: str :param table_key: Table configuration option key n...
Ensure that provisioning of writes is correct :type table_name: str :param table_name: Name of the DynamoDB table :type table_key: str :param table_key: Table configuration option key name :type gsi_name: str :param gsi_name: Name of the GSI :type gsi_key: str :param gsi_key: Configurat...
def im2mat(I): """Converts and image to matrix (one pixel per line)""" return I.reshape((I.shape[0] * I.shape[1], I.shape[2]))
Converts and image to matrix (one pixel per line)
def _rds_cluster_tags(model, dbs, session_factory, generator, retry): """Augment rds clusters with their respective tags.""" client = local_session(session_factory).client('rds') def process_tags(db): try: db['Tags'] = retry( client.list_tags_for_resource, ...
Augment rds clusters with their respective tags.
def revoke(self, auth, codetype, code, defer=False): """ Given an activation code, the associated entity is revoked after which the activation code can no longer be used. Args: auth: Takes the owner's cik codetype: The type of code to revoke (client | share) ...
Given an activation code, the associated entity is revoked after which the activation code can no longer be used. Args: auth: Takes the owner's cik codetype: The type of code to revoke (client | share) code: Code specified by <codetype> (cik | share-activation-code)
def _get_model_parameters_estimations(self, error_model): """ Infer model estimation method from the 'error_model'. Return an object of type ModelParametersEstimation. """ if error_model.dependance == NIDM_INDEPEDENT_ERROR: if error_model.variance_homo: ...
Infer model estimation method from the 'error_model'. Return an object of type ModelParametersEstimation.
def order_assets(self, asset_ids, composition_id): """Reorders a set of assets in a composition. arg: asset_ids (osid.id.Id[]): ``Ids`` for a set of ``Assets`` arg: composition_id (osid.id.Id): ``Id`` of the ``Composition`` raise: NotFound - ``comp...
Reorders a set of assets in a composition. arg: asset_ids (osid.id.Id[]): ``Ids`` for a set of ``Assets`` arg: composition_id (osid.id.Id): ``Id`` of the ``Composition`` raise: NotFound - ``composition_id`` not found or, an ``asset_id`` not...