code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def apply_config(self, config): """ Applies config """ self.hash_name = config['hash_name'] self.dim = config['dim'] self.projection_count = config['projection_count'] self.normals = config['normals'] self.tree_root = config['tree_root'] self.minim...
Applies config
def scroll_up(self, n, pre_dl=None, post_dl=None): """Scroll up ``n`` times. **中文文档** 鼠标滚轮向上滚动n次。 """ self.delay(pre_dl) self.m.scroll(vertical=n) self.delay(post_dl)
Scroll up ``n`` times. **中文文档** 鼠标滚轮向上滚动n次。
def install_cub(mb_inc_path): """ Downloads and installs cub into mb_inc_path """ cub_url = 'https://github.com/NVlabs/cub/archive/1.6.4.zip' cub_sha_hash = '0d5659200132c2576be0b3959383fa756de6105d' cub_version_str = 'Current release: v1.6.4 (12/06/2016)' cub_zip_file = 'cub.zip' cub_zip_dir = ...
Downloads and installs cub into mb_inc_path
def confirm(message="", title="", default=False, ok=False, cancel=False, parent=None): "Ask for confirmation (yes/no or ok and cancel), returns True or False" style = wx.CENTRE if ok: style |= wx.OK else: style |= wx.YES | wx.NO if default: style...
Ask for confirmation (yes/no or ok and cancel), returns True or False
def transfer_data_from_mongo(self, index, doc_type, use_mongo_id=False, indexed_flag_field_name='', mongo_query_params={}, ...
Transfer data from MongoDB into the Elasticsearch, the hostname, port, database and collection name in MongoDB default from load in default.py :param index: The name of the index :param doc_type: The type of the document :param use_mongo_id: Use id of MongoDB in the Elasticsearch if is ...
def identify(self, access_token, leeway=10.0): """ Gather identifying information about a user via an authorized token. :Parameters: access_token : `AccessToken` A token representing an authorized user. Obtained from `complete()`. leeway ...
Gather identifying information about a user via an authorized token. :Parameters: access_token : `AccessToken` A token representing an authorized user. Obtained from `complete()`. leeway : `int` | `float` The number of seconds of leeway t...
def format_coord(self, x, y): """Format displayed coordinates during mouseover of axes.""" p, b = stereonet_math.geographic2plunge_bearing(x, y) s, d = stereonet_math.geographic2pole(x, y) pb = u'P/B={:0.0f}\u00b0/{:03.0f}\u00b0'.format(p[0], b[0]) sd = u'S/D={:03.0f}\u00b0/{:0.0...
Format displayed coordinates during mouseover of axes.
def goBack(self): """ Goes up one level if possible and returns the url at the current level. If it cannot go up, then a blank string will be returned. :return <str> """ if not self.canGoBack(): return '' self._blockStack = Tru...
Goes up one level if possible and returns the url at the current level. If it cannot go up, then a blank string will be returned. :return <str>
def ProduceExtractionWarning(self, message, path_spec=None): """Produces an extraction warning. Args: message (str): message of the warning. path_spec (Optional[dfvfs.PathSpec]): path specification, where None will use the path specification of current file entry set in the medi...
Produces an extraction warning. Args: message (str): message of the warning. path_spec (Optional[dfvfs.PathSpec]): path specification, where None will use the path specification of current file entry set in the mediator. Raises: RuntimeError: when storage writer is not se...
def with_item(self, context, as_opt): """(2.7, 3.1-) with_item: test ['as' expr]""" if as_opt: as_loc, optional_vars = as_opt return ast.withitem(context_expr=context, optional_vars=optional_vars, as_loc=as_loc, loc=context.loc.join(optional_vars.l...
(2.7, 3.1-) with_item: test ['as' expr]
def add(self, count, timestamp=None): """Add a value at the specified time to the series. :param count: The number of work items ready at the specified time. :param timestamp: The timestamp to add. Defaults to None, meaning current time. It should be strictly greater (ne...
Add a value at the specified time to the series. :param count: The number of work items ready at the specified time. :param timestamp: The timestamp to add. Defaults to None, meaning current time. It should be strictly greater (newer) than the last added timestamp.
def groups(self): """Return the names of groups in the file Note that there is not necessarily a TDMS object associated with each group name. :rtype: List of strings. """ # Split paths into components and take the first (group) component. object_paths = ( ...
Return the names of groups in the file Note that there is not necessarily a TDMS object associated with each group name. :rtype: List of strings.
def handle(self, request): """Handle an HTTP request for executing an API call. This method authenticates the request checking its signature, and then calls the C{execute} method, passing it a L{Call} object set with the principal for the authenticated user and the generic parameters ...
Handle an HTTP request for executing an API call. This method authenticates the request checking its signature, and then calls the C{execute} method, passing it a L{Call} object set with the principal for the authenticated user and the generic parameters extracted from the request. ...
def summary( self ): """ Creates a text string representing the current query and its children for this item. :return <str> """ child_text = [] for c in range(self.childCount()): child = self.child(c) text =...
Creates a text string representing the current query and its children for this item. :return <str>
def queryMore(self, queryLocator): ''' Retrieves the next batch of objects from a query. ''' self._setHeaders('queryMore') return self._sforce.service.queryMore(queryLocator)
Retrieves the next batch of objects from a query.
def axis_angle_to_rotation_matrix(v, theta): """Convert rotation from axis-angle to rotation matrix Parameters --------------- v : (3,) ndarray Rotation axis (normalized) theta : float Rotation angle (radians) Returns ---------------- R : (3,3) ndarray ...
Convert rotation from axis-angle to rotation matrix Parameters --------------- v : (3,) ndarray Rotation axis (normalized) theta : float Rotation angle (radians) Returns ---------------- R : (3,3) ndarray Rotation matrix
def substitute_any_type(type_: Type, basic_types: Set[BasicType]) -> List[Type]: """ Takes a type and a set of basic types, and substitutes all instances of ANY_TYPE with all possible basic types and returns a list with all possible combinations. Note that this substitution is unconstrained. That is, ...
Takes a type and a set of basic types, and substitutes all instances of ANY_TYPE with all possible basic types and returns a list with all possible combinations. Note that this substitution is unconstrained. That is, If you have a type with placeholders, <#1,#1> for example, this may substitute the placeh...
def get_chacra_repo(shaman_url): """ From a Shaman URL, get the chacra url for a repository, read the contents that point to the repo and return it as a string. """ shaman_response = get_request(shaman_url) chacra_url = shaman_response.geturl() chacra_response = get_request(chacra_url) ...
From a Shaman URL, get the chacra url for a repository, read the contents that point to the repo and return it as a string.
def _enable(name, started, result=True, skip_verify=False, **kwargs): ''' Enable the service ''' ret = {} if not skip_verify: # is service available? try: if not _available(name, ret): return ret except CommandExecutionError as exc: re...
Enable the service
def parse_version(version): """ Return a comparable tuple from a version string. We try to force tuple to semver with version like 1.2.0 Replace pkg_resources.parse_version which now display a warning when use for comparing version with tuple :returns: Version string as comparable tuple """ r...
Return a comparable tuple from a version string. We try to force tuple to semver with version like 1.2.0 Replace pkg_resources.parse_version which now display a warning when use for comparing version with tuple :returns: Version string as comparable tuple
def p_definition_list(p): """ definition_list : definition definition_list | definition """ if len(p) == 3: p[0] = p[1] + p[2] elif len(p) == 2: p[0] = p[1] else: raise RuntimeError("Invalid production rules 'p_action_list'")
definition_list : definition definition_list | definition
def main( req_files, verbose=False, outdated=False, latest=False, verbatim=False, repo=None, path='requirements.txt', token=None, branch='master', url=None, delay=None, ): """Given a list of requirements files reports which requirements are out of date. Everythin...
Given a list of requirements files reports which requirements are out of date. Everything is rather somewhat obvious: - verbose makes things a little louder - outdated forces piprot to only report out of date packages - latest outputs the requirements line with the latest version - verbatim out...
def calculate_within_class_scatter_matrix(X, y): """Calculates the Within-Class Scatter matrix Parameters: ----------- X : array-like, shape (m, n) - the samples y : array-like, shape (m, ) - the class labels Returns: -------- within_class_scatter_matrix : array-like, shape (n,...
Calculates the Within-Class Scatter matrix Parameters: ----------- X : array-like, shape (m, n) - the samples y : array-like, shape (m, ) - the class labels Returns: -------- within_class_scatter_matrix : array-like, shape (n, n)
def read(cls, data): """Reads data from URL or OrderedDict. Args: data: can be a URL pointing to a JSONstat file, a JSON string or an OrderedDict. Returns: An object of class Collection populated with data. """ if isinstance(data, Order...
Reads data from URL or OrderedDict. Args: data: can be a URL pointing to a JSONstat file, a JSON string or an OrderedDict. Returns: An object of class Collection populated with data.
def _filter_attributes(self, keyset): """ Return a copy of this object with a subset of its attributes set. """ filtered = self._filter_keys(self.to_dict(), keyset) return Language.make(**filtered)
Return a copy of this object with a subset of its attributes set.
def _time_show(self): """Show the time marker window""" if not self._time_visible: self._time_visible = True self._time_window = tk.Toplevel(self) self._time_window.attributes("-topmost", True) self._time_window.overrideredirect(True) self._tim...
Show the time marker window
def status(name, runas=None): ''' Status of a VM :param str name: Name/ID of VM whose status will be returned :param str runas: The user that the prlctl command will be run as Example: .. code-block:: bash salt '*' parallels.status macvm runas=macdev ''' retu...
Status of a VM :param str name: Name/ID of VM whose status will be returned :param str runas: The user that the prlctl command will be run as Example: .. code-block:: bash salt '*' parallels.status macvm runas=macdev
def match(self, *command_tokens, **command_env): """ :meth:`.WCommandProto.match` implementation """ mutated_command_tokens = self.mutate_command_tokens(*command_tokens) if mutated_command_tokens is None: return False return self.selector().select(*mutated_command_tokens, **command_env) is not None
:meth:`.WCommandProto.match` implementation
def scroll_to(self, selector, by=By.CSS_SELECTOR, timeout=settings.SMALL_TIMEOUT): ''' Fast scroll to destination ''' if self.demo_mode: self.slow_scroll_to(selector, by=by, timeout=timeout) return if self.timeout_multiplier and timeout == settings.SMALL...
Fast scroll to destination
def cli(context, host, username, password): """ FritzBox SmartHome Tool \b Provides the following functions: - A easy to use library for querying SmartHome actors - This CLI tool for testing - A carbon client for pipeing data into graphite """ context.obj = FritzBox(host, username, ...
FritzBox SmartHome Tool \b Provides the following functions: - A easy to use library for querying SmartHome actors - This CLI tool for testing - A carbon client for pipeing data into graphite
def disable_host_svc_notifications(self, host): """Disable services notifications for a host Format of the line that triggers function call:: DISABLE_HOST_SVC_NOTIFICATIONS;<host_name> :param host: host to edit :type host: alignak.objects.host.Host :return: None ...
Disable services notifications for a host Format of the line that triggers function call:: DISABLE_HOST_SVC_NOTIFICATIONS;<host_name> :param host: host to edit :type host: alignak.objects.host.Host :return: None
def update_pypsa_bus_timeseries(network, timesteps=None): """ Updates buses voltage time series in pypsa representation. This function overwrites v_mag_pu_set of buses_t attribute of pypsa network. Be aware that if you call this function with `timesteps` and thus overwrite current time steps it...
Updates buses voltage time series in pypsa representation. This function overwrites v_mag_pu_set of buses_t attribute of pypsa network. Be aware that if you call this function with `timesteps` and thus overwrite current time steps it may lead to inconsistencies in the pypsa network since only bus t...
def set_autocut_params(self, method, **params): """Set auto-cut parameters. Parameters ---------- method : str Auto-cut algorithm. A list of acceptable options can be obtained by :meth:`get_autocut_methods`. params : dict Algorithm-specific ...
Set auto-cut parameters. Parameters ---------- method : str Auto-cut algorithm. A list of acceptable options can be obtained by :meth:`get_autocut_methods`. params : dict Algorithm-specific keywords and values.
def connectSubsystem(connection, protocol, subsystem): """Connect a Protocol to a ssh subsystem channel """ deferred = connectSession(connection, protocol) @deferred.addCallback def requestSubsystem(session): return session.requestSubsystem(subsystem) return deferred
Connect a Protocol to a ssh subsystem channel
def Images(vent=True): """ Get images that are build, by default limit to vent images """ images = [] # TODO needs to also check images in the manifest that couldn't have the # label added try: d_client = docker.from_env() if vent: i = d_client.images.list(filters={'...
Get images that are build, by default limit to vent images
def reference(self): """Return the Reference object for this Key. This is a entity_pb.Reference instance -- a protocol buffer class used by the lower-level API to the datastore. NOTE: The caller should not mutate the return value. """ if self.__reference is None: self.__reference = _Cons...
Return the Reference object for this Key. This is a entity_pb.Reference instance -- a protocol buffer class used by the lower-level API to the datastore. NOTE: The caller should not mutate the return value.
def text_editor(file='', background=False, return_cmd=False): '''Starts the default graphical text editor. Start the user's preferred graphical text editor, optionally with a file. Args: file (str) : The file to be opened with the editor. Defaults to an empty string (i.e. no file). background (bool): Runs...
Starts the default graphical text editor. Start the user's preferred graphical text editor, optionally with a file. Args: file (str) : The file to be opened with the editor. Defaults to an empty string (i.e. no file). background (bool): Runs the editor in the background, instead of waiting for completion. ...
def create_scan(self, host_ips): """ Creates a scan with the given host ips Returns the scan id of the created object. """ now = datetime.datetime.now() data = { "uuid": self.get_template_uuid(), "settings": { "name": "jacka...
Creates a scan with the given host ips Returns the scan id of the created object.
def filter_rep_set(inF, otuSet): """ Parse the rep set file and remove all sequences not associated with unique OTUs. :@type inF: file :@param inF: The representative sequence set :@rtype: list :@return: The set of sequences associated with unique OTUs """ seqs = [] for record ...
Parse the rep set file and remove all sequences not associated with unique OTUs. :@type inF: file :@param inF: The representative sequence set :@rtype: list :@return: The set of sequences associated with unique OTUs
def netHours(self): ''' For regular event staff, this is the net hours worked for financial purposes. For Instructors, netHours is caclulated net of any substitutes. ''' if self.specifiedHours is not None: return self.specifiedHours elif self.category in [getC...
For regular event staff, this is the net hours worked for financial purposes. For Instructors, netHours is caclulated net of any substitutes.
def find_common_root(elements): """ Find root which is common for all `elements`. Args: elements (list): List of double-linked HTMLElement objects. Returns: list: Vector of HTMLElement containing path to common root. """ if not elements: raise UserWarning("Can't find co...
Find root which is common for all `elements`. Args: elements (list): List of double-linked HTMLElement objects. Returns: list: Vector of HTMLElement containing path to common root.
def appendNullPadding(str, blocksize=AES_blocksize): 'Pad with null bytes' pad_len = paddingLength(len(str), blocksize) padding = '\0'*pad_len return str + padding
Pad with null bytes
def _field_name_from_uri(self, uri): """helper, returns the name of an attribute (without namespace prefix) """ # TODO - should use graph API uri = str(uri) parts = uri.split('#') if len(parts) == 1: return uri.split('/')[-1] or uri return parts[-1]
helper, returns the name of an attribute (without namespace prefix)
def import_results(log, pathToYamlFile): """ *Import the results of the simulation (the filename is an argument of this models)* **Key Arguments:** - ``log`` -- logger - ``pathToYamlFile`` -- the path to the yaml file to be imported **Return:** - None """ ##############...
*Import the results of the simulation (the filename is an argument of this models)* **Key Arguments:** - ``log`` -- logger - ``pathToYamlFile`` -- the path to the yaml file to be imported **Return:** - None
def get_arguments(self): """ Extracts the specific arguments of this CLI """ PluginBase.get_arguments(self) if self.args.organizationName is not None: self.organizationName = self.args.organizationName if self.args.repositoryName is not None: self....
Extracts the specific arguments of this CLI
def sequence_equal(self, second_iterable, equality_comparer=operator.eq): ''' Determine whether two sequences are equal by elementwise comparison. Sequence equality is defined as the two sequences being equal length and corresponding elements being equal as determined by the equality ...
Determine whether two sequences are equal by elementwise comparison. Sequence equality is defined as the two sequences being equal length and corresponding elements being equal as determined by the equality comparer. Note: This method uses immediate execution. Args: ...
def weighted_choice(self, probabilities, key): """Makes a weighted choice between several options. Probabilities is a list of 2-tuples, (probability, option). The probabilties don't need to add up to anything, they are automatically scaled.""" try: choice = self.val...
Makes a weighted choice between several options. Probabilities is a list of 2-tuples, (probability, option). The probabilties don't need to add up to anything, they are automatically scaled.
def initial(self, request, *args, **kwargs): """ Custom initial method: * ensure node exists and store it in an instance attribute * change queryset to return only links of current node """ super(NodeLinkList, self).initial(request, *args, **kwargs) # ensu...
Custom initial method: * ensure node exists and store it in an instance attribute * change queryset to return only links of current node
def to_element(self, root_name=None): """Serialize this `Resource` instance to an XML element.""" if not root_name: root_name = self.nodename elem = ElementTreeBuilder.Element(root_name) for attrname in self.serializable_attributes(): # Only use values that have b...
Serialize this `Resource` instance to an XML element.
def get_all_assignable_users_for_project(self, project_key, start=0, limit=50): """ Provide assignable users for project :param project_key: :param start: OPTIONAL: The start point of the collection to return. Default: 0. :param limit: OPTIONAL: The limit of the number of users t...
Provide assignable users for project :param project_key: :param start: OPTIONAL: The start point of the collection to return. Default: 0. :param limit: OPTIONAL: The limit of the number of users to return, this may be restricted by fixed system limits. Default by built-in method:...
def _bash_completion(self): """Prints all of the commands and options for bash-completion.""" commands = set() options = set() for option, _action in self.parser._option_string_actions.items(): options.add(option) for _name, _command in self.command_manager: ...
Prints all of the commands and options for bash-completion.
def _factory(slice_, axis, weighted): """return subclass for PairwiseSignificance, based on slice dimension types.""" if slice_.dim_types[0] == DT.MR_SUBVAR: return _MrXCatPairwiseSignificance(slice_, axis, weighted) return _CatXCatPairwiseSignificance(slice_, axis, weighted)
return subclass for PairwiseSignificance, based on slice dimension types.
def sign_data(self, data, expires_in=None, url_safe=True): """ To safely sign a user data. It will be signed with the user key :param data: mixed :param expires_in: The time for it to expire :param url_safe: bool. If true it will allow it to be passed in URL :return: str ...
To safely sign a user data. It will be signed with the user key :param data: mixed :param expires_in: The time for it to expire :param url_safe: bool. If true it will allow it to be passed in URL :return: str - the token/signed data
def linestring_to_utm(linestring: LineString) -> LineString: """ Given a Shapely LineString in WGS84 coordinates, convert it to the appropriate UTM coordinates. If ``inverse``, then do the inverse. """ proj = lambda x, y: utm.from_latlon(y, x)[:2] return transform(proj, linestring)
Given a Shapely LineString in WGS84 coordinates, convert it to the appropriate UTM coordinates. If ``inverse``, then do the inverse.
def delete_resource(self, resource, resource_id, msg="resource", max_wait=120): """Delete one openstack resource, such as one instance, keypair, image, volume, stack, etc., and confirm deletion within max wait time. :param resource: pointer to os resource type, ex:glance...
Delete one openstack resource, such as one instance, keypair, image, volume, stack, etc., and confirm deletion within max wait time. :param resource: pointer to os resource type, ex:glance_client.images :param resource_id: unique name or id for the openstack resource :param msg: text to...
def shorten(text): """ Reduce text length for displaying / logging purposes. """ if len(text) >= MAX_DISPLAY_LEN: text = text[:MAX_DISPLAY_LEN//2]+"..."+text[-MAX_DISPLAY_LEN//2:] return text
Reduce text length for displaying / logging purposes.
def now(cls, Name = None): """ Instantiate a Time element initialized to the current UTC time in the default format (ISO-8601). The Name attribute will be set to the value of the Name parameter if given. """ self = cls() if Name is not None: self.Name = Name self.pcdata = datetime.datetime.utcnow() ...
Instantiate a Time element initialized to the current UTC time in the default format (ISO-8601). The Name attribute will be set to the value of the Name parameter if given.
def fcoe_get_login_output_fcoe_login_list_interface_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") fcoe_get_login = ET.Element("fcoe_get_login") config = fcoe_get_login output = ET.SubElement(fcoe_get_login, "output") fcoe_login_lis...
Auto Generated Code
def wsgi_app(self, environ, start_response): """A basic WSGI app""" @_LOCAL_MANAGER.middleware def _wrapped_app(environ, start_response): request = Request(environ) setattr(_local, _CURRENT_REQUEST_KEY, request) response = self._dispatch_request(request) ...
A basic WSGI app
def shell_call(self, shellcmd): """Shell call with necessary setup first.""" return(subprocess.call(self.shellsetup + shellcmd, shell=True))
Shell call with necessary setup first.
def edit(self, name, config, events=github.GithubObject.NotSet, add_events=github.GithubObject.NotSet, remove_events=github.GithubObject.NotSet, active=github.GithubObject.NotSet): """ :calls: `PATCH /repos/:owner/:repo/hooks/:id <http://developer.github.com/v3/repos/hooks>`_ :param name: string...
:calls: `PATCH /repos/:owner/:repo/hooks/:id <http://developer.github.com/v3/repos/hooks>`_ :param name: string :param config: dict :param events: list of string :param add_events: list of string :param remove_events: list of string :param active: bool :rtype: Non...
def get_authorization_url(self, client_id=None, instance_id=None, redirect_uri=None, region=None, scope=None, state=None): """Generate authorization URL. Args: client_id (str): OAuth2 client ID. Defaults to ``None``. in...
Generate authorization URL. Args: client_id (str): OAuth2 client ID. Defaults to ``None``. instance_id (str): App Instance ID. Defaults to ``None``. redirect_uri (str): Redirect URI. Defaults to ``None``. region (str): App Region. Defaults to ``None``. ...
def AddTableColumn(self, table, column): """Add column to table if it is not already there.""" if column not in self._table_columns[table]: self._table_columns[table].append(column)
Add column to table if it is not already there.
def update_metric(self, metric, labels, pre_sliced=False): """Update evaluation metric with label and current outputs.""" for current_exec, (texec, islice) in enumerate(zip(self.train_execs, self.slices)): if not pre_sliced: labels_slice = [label[islice] for label in labels] ...
Update evaluation metric with label and current outputs.
def _paths_from_env(variable: str, default: List[Path]) -> List[Path]: """Read an environment variable as a list of paths. The environment variable with the specified name is read, and its value split on colons and returned as a list of paths. If the environment variable is not set, or set to the empty...
Read an environment variable as a list of paths. The environment variable with the specified name is read, and its value split on colons and returned as a list of paths. If the environment variable is not set, or set to the empty string, the default value is returned. Parameters ---------- ...
def dist( self, src, tar, word_approx_min=0.3, char_approx_min=0.73, tests=2 ** 12 - 1, ): """Return the normalized Synoname distance between two words. Parameters ---------- src : str Source string for comparison t...
Return the normalized Synoname distance between two words. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison word_approx_min : float The minimum word approximation value to signal a 'word_appro...
def read_data(self, size): """Receive data from the device. If the read fails for any reason, an :obj:`IOError` exception is raised. :param size: the number of bytes to read. :type size: int :return: the data received. :rtype: list(int) """ r...
Receive data from the device. If the read fails for any reason, an :obj:`IOError` exception is raised. :param size: the number of bytes to read. :type size: int :return: the data received. :rtype: list(int)
def _trim_xpath(self, xpath, prop): """ Removes primitive type tags from an XPATH """ xroot = self._get_xroot_for(prop) if xroot is None and isinstance(xpath, string_types): xtags = xpath.split(XPATH_DELIM) if xtags[-1] in _iso_tag_primitives: xroot = X...
Removes primitive type tags from an XPATH
def close_other_windows(self): """ Closes all not current windows. Useful for tests - after each test you can automatically close all windows. """ main_window_handle = self.current_window_handle for window_handle in self.window_handles: if window_handle == mai...
Closes all not current windows. Useful for tests - after each test you can automatically close all windows.
def configure(self, config_file): """ Parse configuration, and setup objects to use it. """ cfg = configparser.RawConfigParser() try: cfg.readfp(open(config_file)) except IOError as err: logger.critical( 'Error while reading config...
Parse configuration, and setup objects to use it.
async def peers(self): """Returns the current Raft peer set Returns: Collection: addresses of peers This endpoint retrieves the Raft peers for the datacenter in which the agent is running. It returns a collection of addresses, such as:: [ "10.1.1...
Returns the current Raft peer set Returns: Collection: addresses of peers This endpoint retrieves the Raft peers for the datacenter in which the agent is running. It returns a collection of addresses, such as:: [ "10.1.10.12:8300", "10.1.1...
async def set_agent_neighbors(self): '''Set neighbors for each agent in each cardinal direction. This method assumes that the neighboring :class:`GridEnvironment` of this grid environment have already been set. ''' for i in range(len(self.grid)): for j in range(len(s...
Set neighbors for each agent in each cardinal direction. This method assumes that the neighboring :class:`GridEnvironment` of this grid environment have already been set.
def page(self, friendly_name=values.unset, evaluate_worker_attributes=values.unset, worker_sid=values.unset, page_token=values.unset, page_number=values.unset, page_size=values.unset): """ Retrieve a single page of TaskQueueInstance records from the API. Re...
Retrieve a single page of TaskQueueInstance records from the API. Request is executed immediately :param unicode friendly_name: Filter by a human readable description of a TaskQueue :param unicode evaluate_worker_attributes: Provide a Worker attributes expression, and this will return the list ...
def get_aligned_adjacent_coords(x, y): ''' returns the nine clockwise adjacent coordinates on a keypad, where each row is vertically aligned. ''' return [(x-1, y), (x-1, y-1), (x, y-1), (x+1, y-1), (x+1, y), (x+1, y+1), (x, y+1), (x-1, y+1)]
returns the nine clockwise adjacent coordinates on a keypad, where each row is vertically aligned.
def _get_host_only_mac_address(): """Returns the MAC address assigned to the host-only adapter, using output from VBoxManage. Returned MAC address has no colons and is lower-cased.""" # Get the number of the host-only adapter vm_config = _get_vm_config() for line in vm_config: if line.st...
Returns the MAC address assigned to the host-only adapter, using output from VBoxManage. Returned MAC address has no colons and is lower-cased.
def _get_attach_id(self, key, value, attributes): """ Get the attach record ID and extra attributes. """ if isinstance(value, dict): key = list(value.keys())[0] attributes.update(value[key]) return [key, attributes] return value, attributes
Get the attach record ID and extra attributes.
def color(colors, export_type, output_file=None): """Export a single template file.""" all_colors = flatten_colors(colors) template_name = get_export_type(export_type) template_file = os.path.join(MODULE_DIR, "templates", template_name) output_file = output_file or os.path.join(CACHE_DIR, template_...
Export a single template file.
def _determine_namespaces(self): """ Determine the names of all namespaces of the WBEM server, by communicating with it and enumerating the instances of a number of possible CIM classes that typically represent CIM namespaces. Their class names are defined in the :attr:`NAMESPACE...
Determine the names of all namespaces of the WBEM server, by communicating with it and enumerating the instances of a number of possible CIM classes that typically represent CIM namespaces. Their class names are defined in the :attr:`NAMESPACE_CLASSNAMES` class variable. If the ...
def wrap_json_response(func=None, *, encoder=json.JSONEncoder): """ A middleware that encodes in json the response body in case of that the "Content-Type" header is "application/json". This middlware accepts and optional `encoder` parameter, that allow to the user specify its own json encoder class...
A middleware that encodes in json the response body in case of that the "Content-Type" header is "application/json". This middlware accepts and optional `encoder` parameter, that allow to the user specify its own json encoder class.
def _call_in_reactor_thread(self, f, *args, **kwargs): """Call the given function with args in the reactor thread.""" self._reactor.callFromThread(f, *args, **kwargs)
Call the given function with args in the reactor thread.
def process_terminals(self, word): """ Deal with terminal Es and Ls and convert any uppercase Ys back to lowercase. """ length = len(word) if word[length - 1] == 'e': if self.r2 <= (length - 1): word = word[:-1] elif self.r1 <= (l...
Deal with terminal Es and Ls and convert any uppercase Ys back to lowercase.
def _optimize(self, maxIter=1000, c1=1.193, c2=1.193, lookback=0.25, standard_dev=None): """ :param maxIter: maximum number of swarm iterations :param c1: social weight :param c2: personal weight :param lookback: how many particles to assess when considering convergence ...
:param maxIter: maximum number of swarm iterations :param c1: social weight :param c2: personal weight :param lookback: how many particles to assess when considering convergence :param standard_dev: the standard deviation of the last lookback # of particles used to determine convergence ...
def createDataFrame(self, data, schema=None, samplingRatio=None, verifySchema=True): """ Creates a :class:`DataFrame` from an :class:`RDD`, a list or a :class:`pandas.DataFrame`. When ``schema`` is a list of column names, the type of each column will be inferred from ``data``. ...
Creates a :class:`DataFrame` from an :class:`RDD`, a list or a :class:`pandas.DataFrame`. When ``schema`` is a list of column names, the type of each column will be inferred from ``data``. When ``schema`` is ``None``, it will try to infer the schema (column names and types) from ``data...
def fit(self, blocks, y=None): """ Args: blocks (List[Block]): as output by :class:`Blockifier.blockify` y (None): This isn't used, it's only here for API consistency. Returns: :class:`StandardizedFeature`: an instance of this class with the `...
Args: blocks (List[Block]): as output by :class:`Blockifier.blockify` y (None): This isn't used, it's only here for API consistency. Returns: :class:`StandardizedFeature`: an instance of this class with the ``self.scaler`` attribute fit to the ``blocks`` data...
def generate_targets(self, local_go_targets=None): """Generate Go targets in memory to form a complete Go graph. :param local_go_targets: The local Go targets to fill in a complete target graph for. If `None`, then all local Go targets under the Go source root are used. :type ...
Generate Go targets in memory to form a complete Go graph. :param local_go_targets: The local Go targets to fill in a complete target graph for. If `None`, then all local Go targets under the Go source root are used. :type local_go_targets: :class:`collections.Iterable` of ...
def withColumnRenamed(self, existing, new): """Returns a new :class:`DataFrame` by renaming an existing column. This is a no-op if schema doesn't contain the given column name. :param existing: string, name of the existing column to rename. :param new: string, new name of the column. ...
Returns a new :class:`DataFrame` by renaming an existing column. This is a no-op if schema doesn't contain the given column name. :param existing: string, name of the existing column to rename. :param new: string, new name of the column. >>> df.withColumnRenamed('age', 'age2').collect(...
def create_settings(sender, **kwargs): """ create user notification settings on user creation """ created = kwargs['created'] user = kwargs['instance'] if created: UserWebNotificationSettings.objects.create(user=user) UserEmailNotificationSettings.objects.create(user=user)
create user notification settings on user creation
def save(self, prepend_vault_id=''): """ Adds or updates a users CC to the vault. @prepend_vault_id: any string to prepend all vault id's with in case the same braintree account is used by multiple projects/apps. """ assert self.is_valid() cc_det...
Adds or updates a users CC to the vault. @prepend_vault_id: any string to prepend all vault id's with in case the same braintree account is used by multiple projects/apps.
def message(self, category, subject, msg_file): """Send message to all users in `category`.""" users = getattr(self.sub, category) if not users: print('There are no {} users on {}.'.format(category, self.sub)) return if msg_file: try: ...
Send message to all users in `category`.
def setBottomLeft(self, loc): """ Move this region so its bottom left corner is on ``loc`` """ offset = self.getBottomLeft().getOffset(loc) # Calculate offset from current bottom left return self.setLocation(self.getTopLeft().offset(offset)) # Move top left corner by the same offset
Move this region so its bottom left corner is on ``loc``
def merge_env(self, env): """ :param env: :return: """ # convert to dict to allow update current_env = dict(item.split('=') for item in self._env) # do validation and set new values. self.env = env # convert to dict to allow update new_en...
:param env: :return:
def annotate_snapshot(self, snapshot): """ Store additional statistical data in snapshot. """ if hasattr(snapshot, 'classes'): return snapshot.classes = {} for classname in list(self.index.keys()): total = 0 active = 0 mer...
Store additional statistical data in snapshot.
def _check_link_completion(self, link, fail_pending=False, fail_running=False): """Internal function to check the completion of all the dispatched jobs Returns ------- status_vect : `JobStatusVector` Vector that summarize the number of jobs in various states. """ ...
Internal function to check the completion of all the dispatched jobs Returns ------- status_vect : `JobStatusVector` Vector that summarize the number of jobs in various states.
def validate_VALUERANGE(in_value, restriction): """ Test to ensure that a value sits between a lower and upper bound. Parameters: A Decimal value and a tuple, containing a lower and upper bound, both as Decimal values. """ if len(restriction) != 2: raise ValidationError("Temp...
Test to ensure that a value sits between a lower and upper bound. Parameters: A Decimal value and a tuple, containing a lower and upper bound, both as Decimal values.
def query(self, sql_query, return_as="dataframe"): """ Execute a raw SQL query against the the SQL DB. Args: sql_query (str): A raw SQL query to execute. Kwargs: return_as (str): Specify what type of object should be returned. The following are accep...
Execute a raw SQL query against the the SQL DB. Args: sql_query (str): A raw SQL query to execute. Kwargs: return_as (str): Specify what type of object should be returned. The following are acceptable types: - "dataframe": pandas.DataFrame or None if no ...
async def nodes(self, *, dc=None, near=None, watch=None, consistency=None): """Lists nodes in a given DC Parameters: dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. near (str): Sort the node list...
Lists nodes in a given DC Parameters: dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. near (str): Sort the node list in ascending order based on the estimated round trip time from that node. ...
def _get_importer(path_name): """Python version of PyImport_GetImporter C API function""" cache = sys.path_importer_cache try: importer = cache[path_name] except KeyError: # Not yet cached. Flag as using the # standard machinery until we finish # checking the hooks ...
Python version of PyImport_GetImporter C API function
def nworker(data, smpchunk, tests): """ The workhorse function. Not numba. """ ## tell engines to limit threads #numba.config.NUMBA_DEFAULT_NUM_THREADS = 1 ## open the seqarray view, the modified array is in bootsarr with h5py.File(data.database.input, 'r') as io5: seqview = io5["b...
The workhorse function. Not numba.
def numericalize(self, arr, device=None): """Turn a batch of examples that use this field into a Variable. If the field has include_lengths=True, a tensor of lengths will be included in the return value. Arguments: arr (List[List[str]], or tuple of (List[List[str]], List[in...
Turn a batch of examples that use this field into a Variable. If the field has include_lengths=True, a tensor of lengths will be included in the return value. Arguments: arr (List[List[str]], or tuple of (List[List[str]], List[int])): List of tokenized and padded ex...
def setRpms(self, package, build, build_ts, rpms): """Add/Update package rpm """ self._builds[package] = {"build": build, "build_ts": build_ts, "rpms": rpms}
Add/Update package rpm