code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def value(self) -> float: """ Get a centre-compensated, scaled, value for the axis, taking any dead-zone into account. The value will scale from 0.0 at the edge of the dead-zone to 1.0 (positive) at the extreme position of the trigger or the edge of the hot zone, if defined as other than...
Get a centre-compensated, scaled, value for the axis, taking any dead-zone into account. The value will scale from 0.0 at the edge of the dead-zone to 1.0 (positive) at the extreme position of the trigger or the edge of the hot zone, if defined as other than 1.0. :return: a float va...
def random_line(file_path: str, encoding: str = FORCED_ENCODING) -> str: """Get random line from a file.""" # Fancy alg from http://stackoverflow.com/a/35579149 to avoid loading full file. line_num = 0 selected_line = "" with open(file_path, encoding=encoding) as stream: while True: ...
Get random line from a file.
def call_path(self, basepath): """return that path to be able to call this script from the passed in basename example -- basepath = /foo/bar self.path = /foo/bar/che/baz.py self.call_path(basepath) # che/baz.py basepath -- string -- the directory yo...
return that path to be able to call this script from the passed in basename example -- basepath = /foo/bar self.path = /foo/bar/che/baz.py self.call_path(basepath) # che/baz.py basepath -- string -- the directory you would be calling this script in ...
def __get_cfg_pkgs_rpm(self): ''' Get packages with configuration files on RPM systems. ''' out, err = self._syscall('rpm', None, None, '-qa', '--configfiles', '--queryformat', '%{name}-%{version}-%{release}\\n') data = dict() pkg_name = N...
Get packages with configuration files on RPM systems.
async def _process_polling_updates(self, updates, fast: typing.Optional[bool] = True): """ Process updates received from long-polling. :param updates: list of updates. :param fast: """ need_to_call = [] for responses in itertools.chain.from_iterable(await self.pr...
Process updates received from long-polling. :param updates: list of updates. :param fast:
def _resolve(value, model_instance=None, context=None): """ Resolves any template references in the given value. """ if isinstance(value, basestring) and "{" in value: if context is None: context = Context() if model_instance is not None: context[model_instance._met...
Resolves any template references in the given value.
def next_task(self): """ Returns the next task to be executed. This simply asks for the next Node to be evaluated, and then wraps it in the specific Task subclass with which we were initialized. """ node = self._find_next_ready_node() if node is None: ...
Returns the next task to be executed. This simply asks for the next Node to be evaluated, and then wraps it in the specific Task subclass with which we were initialized.
def help_center_article_delete(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/help_center/articles#archive-article" api_path = "/api/v2/help_center/articles/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, method="DELETE", **kwargs)
https://developer.zendesk.com/rest_api/docs/help_center/articles#archive-article
def get( self, job_id, job_get_options=None, custom_headers=None, raw=False, **operation_config): """Gets information about the specified job. :param job_id: The ID of the job. :type job_id: str :param job_get_options: Additional parameters for the operation :type jo...
Gets information about the specified job. :param job_id: The ID of the job. :type job_id: str :param job_get_options: Additional parameters for the operation :type job_get_options: ~azure.batch.models.JobGetOptions :param dict custom_headers: headers that will be added to the re...
def add_item(self,jid,node=None,name=None,action=None): """Add a new item to the `DiscoItems` object. :Parameters: - `jid`: item JID. - `node`: item node name. - `name`: item name. - `action`: action for a "disco push". :Types: - `jid`...
Add a new item to the `DiscoItems` object. :Parameters: - `jid`: item JID. - `node`: item node name. - `name`: item name. - `action`: action for a "disco push". :Types: - `jid`: `pyxmpp.JID` - `node`: `unicode` - `name`...
def get_tokens(self): """Returns a generator of the tokens.""" try: while True: token = self.lexer.token() if not token: break yield token except QasmError as e: print('Exception tokenizing qasm file:',...
Returns a generator of the tokens.
def classify(self, dataset, verbose=True, batch_size=64): """ Return the classification for each examples in the ``dataset``. The output SFrame contains predicted class labels and its probability. Parameters ---------- dataset : SFrame | SArray | dict The aud...
Return the classification for each examples in the ``dataset``. The output SFrame contains predicted class labels and its probability. Parameters ---------- dataset : SFrame | SArray | dict The audio data to be classified. If dataset is an SFrame, it must have a ...
def _cast(self, value): """ Try to cast value to int or float if possible :param value: value to cast :return: casted value """ if value.isdigit(): value = int(value) elif re.compile("^\d+\.\d+").match(value): value = float(value) r...
Try to cast value to int or float if possible :param value: value to cast :return: casted value
def _init_metadata(self): """stub""" super(TextAnswerFormRecord, self)._init_metadata() self._min_string_length_metadata = { 'element_id': Id(self.my_osid_object_form._authority, self.my_osid_object_form._namespace, 'min-strin...
stub
def create(self, recording_status_callback_event=values.unset, recording_status_callback=values.unset, recording_status_callback_method=values.unset, trim=values.unset, recording_channels=values.unset): """ Create a new RecordingInstance :param unico...
Create a new RecordingInstance :param unicode recording_status_callback_event: The recording status changes that should generate a callback :param unicode recording_status_callback: The callback URL on each selected recording event :param unicode recording_status_callback_method: The HTTP metho...
def onLeftUp(self, event=None): """ left button up""" if event is None: return self.cursor_mode_action('leftup', event=event) self.canvas.draw_idle() self.canvas.draw() self.ForwardEvent(event=event.guiEvent)
left button up
def cli(): """Run the command line interface.""" args = docopt.docopt(__doc__, version=__VERSION__) secure = args['--secure'] numberofwords = int(args['<numberofwords>']) dictpath = args['--dict'] if dictpath is not None: dictfile = open(dictpath) else: dictfile = load_strea...
Run the command line interface.
def process_script(self, filename): """Running the Bash code.""" try: with managed_process(subprocess.Popen(shlex.split("bash %s" % filename), stdout=self.stdout, stderr=self.stderr, shell=sel...
Running the Bash code.
def get_active_entry(user, select_for_update=False): """Returns the user's currently-active entry, or None.""" entries = apps.get_model('entries', 'Entry').no_join if select_for_update: entries = entries.select_for_update() entries = entries.filter(user=user, end_time__isnull=True) if not e...
Returns the user's currently-active entry, or None.
def copy_non_reserved(props, target): # type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any] """ Copies all properties with non-reserved names from ``props`` to ``target`` :param props: A dictionary of properties :param target: Another dictionary :return: The target dictionary """ t...
Copies all properties with non-reserved names from ``props`` to ``target`` :param props: A dictionary of properties :param target: Another dictionary :return: The target dictionary
def getShocks(self): ''' Gets permanent and transitory income shocks for this period. Samples from IncomeDstn for each period in the cycle. This is a copy-paste from IndShockConsumerType, with the addition of the Markov macroeconomic state. Unfortunately, the getShocks method for ...
Gets permanent and transitory income shocks for this period. Samples from IncomeDstn for each period in the cycle. This is a copy-paste from IndShockConsumerType, with the addition of the Markov macroeconomic state. Unfortunately, the getShocks method for MarkovConsumerType cannot be used, as...
def setup_logging(default_path=None, default_level=logging.INFO, env_key=None): """ Setup logging configuration Parameters ---------- default_path: str Default path of the yaml logging configuration file. If None, it defaults to the 'logging.yaml' file in the confi...
Setup logging configuration Parameters ---------- default_path: str Default path of the yaml logging configuration file. If None, it defaults to the 'logging.yaml' file in the config directory default_level: int Default: :data:`logging.INFO`. Default level if default_path does n...
def evaluate_call_args(self, calculator): """Interpreting this literal as a function call, return a 2-tuple of ``(args, kwargs)``. """ args = [] kwargs = OrderedDict() # Sass kwargs preserve order for var_node, value_node in self.argpairs: value = value_node....
Interpreting this literal as a function call, return a 2-tuple of ``(args, kwargs)``.
def _open_response(self, objects, namespace, pull_type, **params): """ Build an open... response once the objects have been extracted from the repository. """ max_obj_cnt = params['MaxObjectCount'] if max_obj_cnt is None: max_obj_cnt = _DEFAULT_MAX_OBJECT_COUN...
Build an open... response once the objects have been extracted from the repository.
def p_types(self, p): '''types : type | type COMMA types''' if len(p) == 2: p[0] = tuple((t,) for t in p[1]) else: p[0] = tuple((t,) + ts for t in p[1] for ts in p[3])
types : type | type COMMA types
def humanize_dates(p_due=None, p_start=None, p_creation=None): """ Returns string with humanized versions of p_due, p_start and p_creation. Examples: - all dates: "16 days ago, due in a month, started 2 days ago" - p_due and p_start: "due in a month, started 2 days ago" - p_creation and p_due: "...
Returns string with humanized versions of p_due, p_start and p_creation. Examples: - all dates: "16 days ago, due in a month, started 2 days ago" - p_due and p_start: "due in a month, started 2 days ago" - p_creation and p_due: "16 days ago, due in a month"
def save(self, fp, mode='wb'): """ Save the PSD file. :param fp: filename or file-like object. :param mode: file open mode, default 'wb'. """ if hasattr(fp, 'write'): self._record.write(fp) else: with open(fp, mode) as f: s...
Save the PSD file. :param fp: filename or file-like object. :param mode: file open mode, default 'wb'.
def depclean(name=None, slot=None, fromrepo=None, pkgs=None): ''' Portage has a function to remove unused dependencies. If a package is provided, it will only removed the package if no other package depends on it. name The name of the package to be cleaned. slot Restrict the re...
Portage has a function to remove unused dependencies. If a package is provided, it will only removed the package if no other package depends on it. name The name of the package to be cleaned. slot Restrict the remove to a specific slot. Ignored if ``name`` is None. fromrepo ...
def tokenize(self): """Tokenizes all multiword names in the list of Units. Modifies: - (indirectly) self.unit_list, by combining words into compound words. This is done because many names may be composed of multiple words, e.g., 'grizzly bear'. In order to count the number ...
Tokenizes all multiword names in the list of Units. Modifies: - (indirectly) self.unit_list, by combining words into compound words. This is done because many names may be composed of multiple words, e.g., 'grizzly bear'. In order to count the number of permissible words ge...
def labelHealpix(pixels, values, nside, threshold=0, xsize=1000): """ Label contiguous regions of a (sparse) HEALPix map. Works by mapping HEALPix array to a Mollweide projection and applying scipy.ndimage.label Assumes non-nested HEALPix map. Parameters: ...
Label contiguous regions of a (sparse) HEALPix map. Works by mapping HEALPix array to a Mollweide projection and applying scipy.ndimage.label Assumes non-nested HEALPix map. Parameters: pixels : Pixel values associated to (sparse) HEALPix array values : (Spa...
def generate(self, chars, format='png'): """Generate an Image Captcha of the given characters. :param chars: text to be generated. :param format: image file format """ im = self.generate_image(chars) out = BytesIO() im.save(out, format=format) out.seek(0)...
Generate an Image Captcha of the given characters. :param chars: text to be generated. :param format: image file format
def ftp_download(ftp, ftp_path, local_path): """ Download the master database :param ftp: ftp connection :param ftp_path: path to file on the ftp server :param local_path: local path to download file :return: """ with open(local_path, 'wb') as _f: ftp.retrbinary('RETR %s' % ftp_p...
Download the master database :param ftp: ftp connection :param ftp_path: path to file on the ftp server :param local_path: local path to download file :return:
def get_repos(self, type=github.GithubObject.NotSet): """ :calls: `GET /orgs/:org/repos <http://developer.github.com/v3/repos>`_ :param type: string ('all', 'public', 'private', 'forks', 'sources', 'member') :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Repository...
:calls: `GET /orgs/:org/repos <http://developer.github.com/v3/repos>`_ :param type: string ('all', 'public', 'private', 'forks', 'sources', 'member') :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Repository.Repository`
def resize_imgs(fnames, targ, path, new_path, resume=True, fn=None): """ Enlarge or shrink a set of images in the same directory to scale, such that the smaller of the height or width dimension is equal to targ. Note: -- This function is multithreaded for efficiency. -- When destination file or fo...
Enlarge or shrink a set of images in the same directory to scale, such that the smaller of the height or width dimension is equal to targ. Note: -- This function is multithreaded for efficiency. -- When destination file or folder already exist, function exists without raising an error.
def run(self): """ Run the poll loop. This method never returns. """ try: from _winapi import WAIT_OBJECT_0, INFINITE except ImportError: from _subprocess import WAIT_OBJECT_0, INFINITE # Build the list of handle to listen on. handles = [] ...
Run the poll loop. This method never returns.
def compute_ema(smoothing_factor, points): """ Compute exponential moving average of a list of points. :param float smoothing_factor: the smoothing factor. :param list points: the data points. :return list: all ema in a list. """ ema = [] # The initial point has a ema equal to itself. ...
Compute exponential moving average of a list of points. :param float smoothing_factor: the smoothing factor. :param list points: the data points. :return list: all ema in a list.
def regional_atlas(graph, label_image, xxx_todo_changeme1): # label image is required to hold continuous ids starting from 1 r""" Regional term based on a probability atlas. An implementation of a regional term, suitable to be used with the `~medpy.graphcut.generate.graph_from_labels` function. ...
r""" Regional term based on a probability atlas. An implementation of a regional term, suitable to be used with the `~medpy.graphcut.generate.graph_from_labels` function. This regional term introduces statistical probability of a voxel to belong to the object to segment. It computes the su...
def factorise_strings (string_list, boundary_char=None): """Given a list of strings, finds the longest string that is common to the *beginning* of all strings in the list and returns a new list whose elements lack this common beginning. boundary_char defines a boundary that must be preserved, so th...
Given a list of strings, finds the longest string that is common to the *beginning* of all strings in the list and returns a new list whose elements lack this common beginning. boundary_char defines a boundary that must be preserved, so that the common string removed must end with this char. ...
def endpoint_from_flag(flag): """The object used for interacting with relations tied to a flag, or None. """ relation_name = None value = _get_flag_value(flag) if isinstance(value, dict) and 'relation' in value: # old-style RelationBase relation_name = value['relation'] elif flag...
The object used for interacting with relations tied to a flag, or None.
def main(): """Command line interface for the ``rotate-backups`` program.""" coloredlogs.install(syslog=True) # Command line option defaults. rotation_scheme = {} kw = dict(include_list=[], exclude_list=[]) parallel = False use_sudo = False # Internal state. selected_locations = [] ...
Command line interface for the ``rotate-backups`` program.
def idle(self, stop_signals: tuple = (SIGINT, SIGTERM, SIGABRT)): """Blocks the program execution until one of the signals are received, then gently stop the Client by closing the underlying connection. Args: stop_signals (``tuple``, *optional*): Iterable containing ...
Blocks the program execution until one of the signals are received, then gently stop the Client by closing the underlying connection. Args: stop_signals (``tuple``, *optional*): Iterable containing signals the signal handler will listen to. Defaults to (SIGIN...
def add_default(self, ext, content_type): """ Add a child ``<Default>`` element with attributes set to parameter values. """ return self._add_default(extension=ext, contentType=content_type)
Add a child ``<Default>`` element with attributes set to parameter values.
def scale(self, scale, center=None): """ Scale the matrix about a given origin. The scaling is applied *after* the transformations already present in the matrix. Parameters ---------- scale : array-like Scale factors along x, y and z axes. ce...
Scale the matrix about a given origin. The scaling is applied *after* the transformations already present in the matrix. Parameters ---------- scale : array-like Scale factors along x, y and z axes. center : array-like or None The x, y and z coor...
def msg(self, msg): '''Emit a message. Override to customize log spam.''' hookenv.log('coordinator.{} {}'.format(self._name(), msg), level=hookenv.INFO)
Emit a message. Override to customize log spam.
def listify(x, none_value=[]): """Make a list of the argument if it is not a list.""" if isinstance(x, list): return x elif isinstance(x, tuple): return list(x) elif x is None: return none_value else: return [x]
Make a list of the argument if it is not a list.
def wrap_queries_in_bool_clauses_if_more_than_one(queries, use_must_clause, preserve_bool_semantics_if_one_clause=False): """Helper for wrapping a list of queries into a bool.{must, should} clause. Args: ...
Helper for wrapping a list of queries into a bool.{must, should} clause. Args: queries (list): List of queries to be wrapped in a bool.{must, should} clause. use_must_clause (bool): Flag that signifies whether to use 'must' or 'should' clause. preserve_bool_semantics_if_one_clause (bool): F...
def filter_correlation(self, x_analyte, y_analyte, window=None, r_threshold=0.9, p_threshold=0.05, filt=True, samples=None, subset=None): """ Applies a correlation filter to the data. Calculates a rolling correlation between every `window` p...
Applies a correlation filter to the data. Calculates a rolling correlation between every `window` points of two analytes, and excludes data where their Pearson's R value is above `r_threshold` and statistically significant. Data will be excluded where their absolute R value is greater ...
def _download_tlds_list(self): """ Function downloads list of TLDs from IANA. LINK: https://data.iana.org/TLD/tlds-alpha-by-domain.txt :return: True if list was downloaded, False in case of an error :rtype: bool """ url_list = 'https://data.iana.org/TLD/tlds-alph...
Function downloads list of TLDs from IANA. LINK: https://data.iana.org/TLD/tlds-alpha-by-domain.txt :return: True if list was downloaded, False in case of an error :rtype: bool
def set_rich_text_font(self, font): """Set rich text mode font""" self.rich_text.set_font(font, fixed_font=self.get_plugin_font())
Set rich text mode font
def colorize_invoke_command(self, string): """ Apply various heuristics to return a colorized version the invoke command string. If these fail, simply return the string in plaintext. Inspired by colorize_log_entry(). """ final_string = string try: ...
Apply various heuristics to return a colorized version the invoke command string. If these fail, simply return the string in plaintext. Inspired by colorize_log_entry().
def add_position_pattern(self, m): """This method draws the position adjustment patterns onto the QR Code. All QR code versions larger than one require these special boxes called position adjustment patterns. """ #Version 1 does not have a position adjustment pattern if s...
This method draws the position adjustment patterns onto the QR Code. All QR code versions larger than one require these special boxes called position adjustment patterns.
def update(self, file_path, new_data={}, **kwargs): """Update an object on the server. Args: id: ID of the object to update (can be None if not required) new_data: the update data for the object **kwargs: Extra options to send to the server (e.g. sudo) Retur...
Update an object on the server. Args: id: ID of the object to update (can be None if not required) new_data: the update data for the object **kwargs: Extra options to send to the server (e.g. sudo) Returns: dict: The new object data (*not* a RESTObject) ...
def type(self) -> DataType: """ type : primitive | decimal | array | set | map | struct primitive : "any" | "null" | "bool" | "boolean" | "int8" ...
type : primitive | decimal | array | set | map | struct primitive : "any" | "null" | "bool" | "boolean" | "int8" | "int16" | "int32" ...
def coords(self): """ Returns a tuple representing the location of the address in a GIS coords format, i.e. (longitude, latitude). """ x, y = ("lat", "lng") if self.order == "lat" else ("lng", "lat") try: return (self["location"][x], self["location"][y]) ...
Returns a tuple representing the location of the address in a GIS coords format, i.e. (longitude, latitude).
def get_volumes(self): """Gets a list of all volumes in this disk, including volumes that are contained in other volumes.""" volumes = [] for v in self.volumes: volumes.extend(v.get_volumes()) return volumes
Gets a list of all volumes in this disk, including volumes that are contained in other volumes.
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'collections') and self.collections is not None: _dict['collections'] = [x._to_dict() for x in self.collections] return _dict
Return a json dictionary representing this model.
def is_prefix(cls, result): """Return ``True`` if result is a prefix object. .. note:: Boto uses the S3 Prefix object for GS prefixes. """ from boto.s3.prefix import Prefix return isinstance(result, Prefix) or cls._is_gs_folder(result)
Return ``True`` if result is a prefix object. .. note:: Boto uses the S3 Prefix object for GS prefixes.
def send_request(self, url): """ Send a request to given url. """ while True: try: return urllib.request.urlopen(url) except urllib.error.HTTPError as e: raise serror( "Request `%s` failed (%s:%s)." % (url, e...
Send a request to given url.
def filter(self, **kwargs): """ Filter data according to the given arguments. """ keys = self.filter_keys(**kwargs) return self.keys_to_values(keys)
Filter data according to the given arguments.
def el_to_path_vector(el): """ Convert `el` to vector of foregoing elements. Attr: el (obj): Double-linked HTMLElement instance. Returns: list: HTMLElements which considered as path from root to `el`. """ path = [] while el.parent: path.append(el) el = el.pa...
Convert `el` to vector of foregoing elements. Attr: el (obj): Double-linked HTMLElement instance. Returns: list: HTMLElements which considered as path from root to `el`.
def repl_proc(self, inputstring, log=True, **kwargs): """Process using replprocs.""" return self.apply_procs(self.replprocs, kwargs, inputstring, log=log)
Process using replprocs.
def toxml(self): """ Exports this object into a LEMS XML object """ argstr = '' if self.component: argstr += 'component="{0}" '.format(self.component) if self.component_type: argstr += 'componentType="{0}" '.format(self.component_type) if s...
Exports this object into a LEMS XML object
def main(): # pylint: disable-msg=R0912,R0915 """Main.""" parser = optparse.OptionParser() parser.usage = textwrap.dedent("""\ %prog {--run|--install_key|--dump_config} [options] SSH command authenticator. Used to restrict which commands can be run via trusted SSH keys. """) group = ...
Main.
def send_config_set( self, config_commands=None, exit_config_mode=False, delay_factor=1, max_loops=150, strip_prompt=False, strip_command=False, config_mode_command=None, ): """Remain in configuration mode.""" return super(VyOSSSH, self...
Remain in configuration mode.
def load_or_create_workflow(self): """ Tries to load the previously serialized (and saved) workflow Creates a new one if it can't """ self.workflow_spec = self.get_worfklow_spec() return self._load_workflow() or self.create_workflow()
Tries to load the previously serialized (and saved) workflow Creates a new one if it can't
def yml_fnc(fname, *args, **options): """An wrapper of yaml.safe_load, yaml.load, yaml.safe_dump and yaml.dump. :param fname: "load" or "dump", not checked but it should be OK. see also :func:`yml_load` and :func:`yml_dump` :param args: [stream] for load or [cnf, stream] for dump :param...
An wrapper of yaml.safe_load, yaml.load, yaml.safe_dump and yaml.dump. :param fname: "load" or "dump", not checked but it should be OK. see also :func:`yml_load` and :func:`yml_dump` :param args: [stream] for load or [cnf, stream] for dump :param options: keyword args may contain "ac_safe" ...
def list_attached_storage_groups(self, full_properties=False): """ Return the storage groups that are attached to this partition. The CPC must have the "dpm-storage-management" feature enabled. Authorization requirements: * Object-access permission to this partition. *...
Return the storage groups that are attached to this partition. The CPC must have the "dpm-storage-management" feature enabled. Authorization requirements: * Object-access permission to this partition. * Task permission to the "Partition Details" task. Parameters: f...
def generate(self, x, **kwargs): """ Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param kwargs: Keyword arguments. See `parse_params` for documentation. """ # Parse and save attack-specific parameters assert self.parse_params(**kwargs)...
Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param kwargs: Keyword arguments. See `parse_params` for documentation.
def load_template(filename): # type: (str) -> str """ Load template from file. The templates are part of the package and must be included as ``package_data`` in project ``setup.py``. Args: filename (str): The template path. Relative to `peltak` package directory. Returns: ...
Load template from file. The templates are part of the package and must be included as ``package_data`` in project ``setup.py``. Args: filename (str): The template path. Relative to `peltak` package directory. Returns: str: The content of the chosen template.
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'frequency') and self.frequency is not None: _dict['frequency'] = self.frequency ...
Return a json dictionary representing this model.
def set_params(self,**kwargs): """ Set the parameter values """ for key,value in list(kwargs.items()): setattr(self,key,value)
Set the parameter values
def get_bank_lookup_session(self): """Gets the OsidSession associated with the bank lookup service. return: (osid.assessment.BankLookupSession) - a ``BankLookupSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_bank_lookup()...
Gets the OsidSession associated with the bank lookup service. return: (osid.assessment.BankLookupSession) - a ``BankLookupSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_bank_lookup() is false`` *compliance: optional -- T...
def build_polygon_dict(self, path, stroke_color='#FF0000', stroke_opacity=.8, stroke_weight=2, fill_color='#FF0000', fill_opacity=0.3): """ Set a dict...
Set a dictionary with the javascript class Polygon parameters This function sets a default drawing configuration if the user just pass the polygon path, but also allows to set each parameter individually if the user wish so. Args: path (list): A list of latitude and longitu...
def kwinsert(clas,pool_or_cursor,**kwargs): "kwargs version of insert" returning = kwargs.pop('returning',None) fields,vals = zip(*kwargs.items()) # note: don't do SpecialField resolution here; clas.insert takes care of it return clas.insert(pool_or_cursor,fields,vals,returning=returning)
kwargs version of insert
def prune_hashes(self, hashes, list_type): """Prune any hashes not in source resource or change list.""" discarded = [] for hash in hashes: if (hash in self.hashes): self.hashes.discard(hash) discarded.append(hash) self.logger.info("Not calcula...
Prune any hashes not in source resource or change list.
def ensure_clean(self): """ Make sure the working tree is clean (contains no changes to tracked files). :raises: :exc:`~vcs_repo_mgr.exceptions.WorkingTreeNotCleanError` when the working tree contains changes to tracked files. """ if not self.is_clean: ...
Make sure the working tree is clean (contains no changes to tracked files). :raises: :exc:`~vcs_repo_mgr.exceptions.WorkingTreeNotCleanError` when the working tree contains changes to tracked files.
def save_json(object, handle, indent=2): """Save object as json on CNS.""" obj_json = json.dumps(object, indent=indent, cls=NumpyJSONEncoder) handle.write(obj_json)
Save object as json on CNS.
def calculate_size(name, timeout): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += LONG_SIZE_IN_BYTES return data_size
Calculates the request payload size
def _extract_resources(elem): """Extract the children of an element as a key/value mapping. """ resources = collections.defaultdict(list) for child in itertools.islice(elem.iter(), 1, None): try: basename = child.tag.split('}', 1)[-1] if child....
Extract the children of an element as a key/value mapping.
def coefficient_of_variation(data, data_mean=None, data_stdev=None): """Return the coefficient of variation (CV) of a sequence of numbers. :param data_mean: Precomputed mean of the sequence. :param data_stdevp: Precomputed stdevp of the sequence. """ data_mean = data_mean or mean(data) d...
Return the coefficient of variation (CV) of a sequence of numbers. :param data_mean: Precomputed mean of the sequence. :param data_stdevp: Precomputed stdevp of the sequence.
def get(self, deviceId, measurementId): """ details the specific measurement. """ record = self.measurements.get(deviceId) if record is not None: return record.get(measurementId) return None
details the specific measurement.
def group_keys(shape, *inputs_keys): """ Usecase: Two sets of chunks, one spans the whole of a dimension, the other chunked it up. We need to know that we need to collect together the chunked form, so that we can work with both sets at the same time. Conceptually we have multiple source inputs, ea...
Usecase: Two sets of chunks, one spans the whole of a dimension, the other chunked it up. We need to know that we need to collect together the chunked form, so that we can work with both sets at the same time. Conceptually we have multiple source inputs, each with multiple key sets for indexing. ...
def louvain_clustering(self, X=None, res=1, method='modularity'): """Runs Louvain clustering using the vtraag implementation. Assumes that 'louvain' optional dependency is installed. Parameters ---------- res - float, optional, default 1 The resolution parameter whic...
Runs Louvain clustering using the vtraag implementation. Assumes that 'louvain' optional dependency is installed. Parameters ---------- res - float, optional, default 1 The resolution parameter which tunes the number of clusters Louvain finds. method - s...
def _send_command(self, command, raw_text=False): """ Wrapper for NX-API show method. Allows more code sharing between NX-API and SSH. """ return self.device.show(command, raw_text=raw_text)
Wrapper for NX-API show method. Allows more code sharing between NX-API and SSH.
def to_html(self, index=False, escape=False, header=True, collapse_table=True, class_outer="table_outer", **kargs): """Return HTML version of the table This is a wrapper of the to_html method of the pandas dataframe. :param bool index: do not include the index :param bool e...
Return HTML version of the table This is a wrapper of the to_html method of the pandas dataframe. :param bool index: do not include the index :param bool escape: do not escape special characters :param bool header: include header :param bool collapse_table: long tables are shor...
def validate_users(self, **kwargs): # noqa: E501 """Returns valid users and invalid identifiers from the given list # 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 ...
Returns valid users and invalid identifiers from the given list # 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.validate_users(async_req=True) >>> result = thr...
def combine(self, a, b): """A generator that combines two iterables.""" for l in (a, b): for x in l: yield x
A generator that combines two iterables.
def update_project(project): """Update a project instance. :param project: PYBOSSA project :type project: PYBOSSA Project :returns: True -- the response status code """ try: project_id = project.id project = _forbidden_attributes(project) res = _pybossa_req('put', 'proj...
Update a project instance. :param project: PYBOSSA project :type project: PYBOSSA Project :returns: True -- the response status code
def setup_connection(): """ Set up the global pynipap connection object """ # get connection parameters, first from environment variables if they are # defined, otherwise from .nipaprc try: con_params = { 'username': os.getenv('NIPAP_USERNAME') or cfg.get('global', 'username'), ...
Set up the global pynipap connection object
def get_delete_security_group_commands(self, sg_id): """Commands for deleting ACL""" cmds = [] cmds.append("no ip access-list %s" % self._acl_name(sg_id, n_const.INGRESS_DIRECTION)) cmds.append("no ip access-list %s" % self._acl_name(sg_id, n_const...
Commands for deleting ACL
def peer(opt_peer, opt_username, opt_password, scope="module"): '''peer bigip fixture''' p = BigIP(opt_peer, opt_username, opt_password) return p
peer bigip fixture
def build_authorization_request(username, method, uri, nonce_count, digest_challenge=None, realm=None, nonce=None, opaque=None, password=None, request_digest=None, client_nonce=None): ''' Builds an authorization request that may be sent as the valu...
Builds an authorization request that may be sent as the value of the 'Authorization' header in an HTTP request. Either a digest_challenge object (as returned from parse_digest_challenge) or its required component parameters (nonce, realm, opaque) must be provided. The nonce_count should be the last us...
def add_register(self, register): """ .. _add_register: Adds the Register_ ``register`` to the interface. Will raise a SetupError_ if the interface is locked (because it is running) or if there is already a Register with the name of the new Register or if the number of Registers would exceed the size of t...
.. _add_register: Adds the Register_ ``register`` to the interface. Will raise a SetupError_ if the interface is locked (because it is running) or if there is already a Register with the name of the new Register or if the number of Registers would exceed the size of the interface. Returns the index of the ...
def get_variation_from_id(self, experiment_key, variation_id): """ Get variation given experiment and variation ID. Args: experiment: Key representing parent experiment of variation. variation_id: ID representing the variation. Returns Object representing the variation. """ vari...
Get variation given experiment and variation ID. Args: experiment: Key representing parent experiment of variation. variation_id: ID representing the variation. Returns Object representing the variation.
def invert(series): ''' Swap index with values of series. Parameters ---------- series : ~pandas.Series Series to swap on, must have a name. Returns ------- ~pandas.Series Series after swap. See also -------- pandas.Series.map Joins series ``a -> b`...
Swap index with values of series. Parameters ---------- series : ~pandas.Series Series to swap on, must have a name. Returns ------- ~pandas.Series Series after swap. See also -------- pandas.Series.map Joins series ``a -> b`` and ``b -> c`` into ``a -> c``...
def make_clean_html(raw, stream_item=None, encoding=None): '''Get a clean text representation of presumed HTML. Treat `raw` as though it is HTML, even if we have no idea what it really is, and attempt to get a properly formatted HTML document with all HTML-escaped characters converted to their unicode....
Get a clean text representation of presumed HTML. Treat `raw` as though it is HTML, even if we have no idea what it really is, and attempt to get a properly formatted HTML document with all HTML-escaped characters converted to their unicode. This is called below by the `clean_html` transform stage, wh...
def _build_web_client(cls, session: AppSession): '''Build Web Client.''' cookie_jar = cls._build_cookie_jar(session) http_client = cls._build_http_client(session) redirect_factory = functools.partial( session.factory.class_map['RedirectTracker'], max_redirects=se...
Build Web Client.
def CalculateBestPosition(self,widget): "When dealing with a Top-Level window position it absolute lower-right" if isinstance(widget, wx.Frame): screen = wx.ClientDisplayRect()[2:] left,top = widget.ClientToScreenXY(0,0) right,bottom = widget.ClientToScreenXY(*widget....
When dealing with a Top-Level window position it absolute lower-right
def longest_non_repeat_v1(string): """ Find the length of the longest substring without repeating characters. """ if string is None: return 0 dict = {} max_length = 0 j = 0 for i in range(len(string)): if string[i] in dict: j = max(dict[string[i]], j) ...
Find the length of the longest substring without repeating characters.
def run(self): """Runs the build extension.""" compiler = new_compiler(compiler=self.compiler) if compiler.compiler_type == "msvc": self.define = [ ("UNICODE", ""), ] else: command = "sh configure --disable-shared-libs" output = self._RunCommand(command) print_l...
Runs the build extension.