code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def pause(self): """ Pauses a running pipeline. This will stop retrieving results from the pipeline. Parallel parts of the pipeline will stop after the ``NuMap`` buffer is has been filled. A paused pipeline can be run or stopped. """ # 1. stop the plumbing thr...
Pauses a running pipeline. This will stop retrieving results from the pipeline. Parallel parts of the pipeline will stop after the ``NuMap`` buffer is has been filled. A paused pipeline can be run or stopped.
def _safe_copy(dat): ''' mongodb doesn't allow '.' in keys, but does allow unicode equivs. Apparently the docs suggest using escaped unicode full-width encodings. *sigh* \\ --> \\\\ $ --> \\\\u0024 . --> \\\\u002e Personally, I prefer URL encoding...
mongodb doesn't allow '.' in keys, but does allow unicode equivs. Apparently the docs suggest using escaped unicode full-width encodings. *sigh* \\ --> \\\\ $ --> \\\\u0024 . --> \\\\u002e Personally, I prefer URL encodings, \\ --> %5c ...
def add_dir(self, path, compress): """Add all files under directory `path` to the MAR file. Args: path (str): path to directory to add to this MAR file compress (str): One of 'xz', 'bz2', or None. Defaults to None. """ if not os.path.isdir(path): rais...
Add all files under directory `path` to the MAR file. Args: path (str): path to directory to add to this MAR file compress (str): One of 'xz', 'bz2', or None. Defaults to None.
def _create_field(self, uri , name, field_type, **kwargs): '''Creates a field with the provided attributes. Args: uri base uri for the field (pipeline or box uri) name required name string field_type required type string [TEXT_INPUT, DATE or PERSON] kwargs {} return (status code, field dict) ''' ...
Creates a field with the provided attributes. Args: uri base uri for the field (pipeline or box uri) name required name string field_type required type string [TEXT_INPUT, DATE or PERSON] kwargs {} return (status code, field dict)
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ C = self.COEFFS[imt] mag = rup.mag - 6 d = np.sqrt(di...
See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values.
def _get_collection_counts(self, core_data): """ Queries each core to get individual counts for each core for each shard. """ if core_data['base_url'] not in self.solr_clients: from SolrClient import SolrClient self.solr_clients['base_url'] = SolrClient(core_data[...
Queries each core to get individual counts for each core for each shard.
def _determine_next_study_id(self): """Return the numeric part of the newest study_id Checks out master branch as a side effect! """ if self._doc_counter_lock is None: self._doc_counter_lock = Lock() prefix = self._new_study_prefix lp = len(prefix) n ...
Return the numeric part of the newest study_id Checks out master branch as a side effect!
def multi_occurrence(self): """ Get whether the node has multiple occurrences, i.e. is a I{collection}. @return: True if it has, False if it has at most 1 occurrence. @rtype: boolean """ max = self.max if max is None: return False if max.isdi...
Get whether the node has multiple occurrences, i.e. is a I{collection}. @return: True if it has, False if it has at most 1 occurrence. @rtype: boolean
def write(self, req, ino, buf, off, fi): """Write data Valid replies: reply_write reply_err """ self.reply_err(req, errno.EROFS)
Write data Valid replies: reply_write reply_err
def wait_for_string(self, expected_string, timeout=60): """Wait for string FSM for XR 64 bit.""" ADMIN_USERNAME_PROMPT = re.compile("Admin Username:") ADMIN_PASSWORD_PROMPT = re.compile("Password:") # Big thanks to calvados developers for make this FSM such complex ;-) # ...
Wait for string FSM for XR 64 bit.
def eth_addr(f): """eth_addr :param f: eth frame """ data = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" % (f[0], f[1], f[2], f[3], ...
eth_addr :param f: eth frame
def n_weekends(self) -> int: """ Returns the number of weekends that this interval covers. Includes partial weekends. """ startdate = self.start.date() enddate = self.end.date() ndays = (enddate - startdate).days + 1 in_weekend = False n_weekends =...
Returns the number of weekends that this interval covers. Includes partial weekends.
def _set_section(self, section): """Set the renderer's current section. Sections must be rendered order: QUESTION, ANSWER, AUTHORITY, ADDITIONAL. Sections may be empty. @param section: the section @type section: int @raises dns.exception.FormError: an attempt was made ...
Set the renderer's current section. Sections must be rendered order: QUESTION, ANSWER, AUTHORITY, ADDITIONAL. Sections may be empty. @param section: the section @type section: int @raises dns.exception.FormError: an attempt was made to set a section value less than the...
def create_model(config: dict, output_dir: Optional[str], dataset: AbstractDataset, restore_from: Optional[str]=None) -> AbstractModel: """ Create a model object either from scratch of from the checkpoint in ``resume_dir``. Cxflow allows the following scenarios 1. Create model: leave ...
Create a model object either from scratch of from the checkpoint in ``resume_dir``. Cxflow allows the following scenarios 1. Create model: leave ``restore_from=None`` and specify ``class``; 2. Restore model: specify ``restore_from`` which is a backend-specific path to (a directory with) the saved model. ...
def get_value(self): """ Retrieves the value to inject in the component :return: The value to inject """ with self._lock: # The value field must be a deep copy of our dictionary if self._future_value is not None: return { ...
Retrieves the value to inject in the component :return: The value to inject
def make_twitter_blueprint( api_key=None, api_secret=None, redirect_url=None, redirect_to=None, login_url=None, authorized_url=None, session_class=None, storage=None, ): """ Make a blueprint for authenticating with Twitter using OAuth 1. This requires an API key and API secre...
Make a blueprint for authenticating with Twitter using OAuth 1. This requires an API key and API secret from Twitter. You should either pass them to this constructor, or make sure that your Flask application config defines them, using the variables :envvar:`TWITTER_OAUTH_CLIENT_KEY` and :envvar:`TWITTER...
def populate_hazard_classification(self): """Populate hazard classification on hazard class form.""" new_class = { 'value': self.radius_form.value(), 'name': self.class_form.text()} self.classification.append(new_class) self.classification = sorted( se...
Populate hazard classification on hazard class form.
def groups_of(n, iterable): """ >>> groups_of(2, range(5)) """ args = [iter(iterable)] * n for x in izip_longest(*args): yield [v for v in x if v is not None]
>>> groups_of(2, range(5))
def create_certificate_issuer(self, certificate_issuer_request, **kwargs): # noqa: E501 """Create certificate issuer. # noqa: E501 Create a certificate issuer. The maximum number of issuers is limited to 20 per account. Multiple certificate issuers of the same issuer type can be created, provided the...
Create certificate issuer. # noqa: E501 Create a certificate issuer. The maximum number of issuers is limited to 20 per account. Multiple certificate issuers of the same issuer type can be created, provided they have a different name. This allows verification of the certificate issuer configuration before act...
def prj_remove_user(self, *args, **kwargs): """Remove the, in the user table view selected, user. :returns: None :rtype: None :raises: None """ if not self.cur_prj: return i = self.prj_user_tablev.currentIndex() item = i.internalPointer() ...
Remove the, in the user table view selected, user. :returns: None :rtype: None :raises: None
def _build_verb_statement_mapping(): """Build the mapping between ISI verb strings and INDRA statement classes. Looks up the INDRA statement class name, if any, in a resource file, and resolves this class name to a class. Returns ------- verb_to_statement_type : dict Dictionary mapping...
Build the mapping between ISI verb strings and INDRA statement classes. Looks up the INDRA statement class name, if any, in a resource file, and resolves this class name to a class. Returns ------- verb_to_statement_type : dict Dictionary mapping verb name to an INDRA statment class
def execute_from_command_line(argv=None): """A simple method that runs a Command.""" if sys.stdout.encoding is None: print('please set python env PYTHONIOENCODING=UTF-8, example: ' 'export PYTHONIOENCODING=UTF-8, when writing to stdout', file=sys.stderr) exit(1) ...
A simple method that runs a Command.
def run_all(*modules): '''Start all services. ''' processes = [multiprocessing.Process(target=mod.run) for mod in modules] for p in processes: p.start() for p in processes: p.join()
Start all services.
def solve(expected: List[Tuple[float, float]], actual: List[Tuple[float, float]]) -> np.ndarray: """ Takes two lists of 3 x-y points each, and calculates the matrix representing the transformation from one space to the other. The 3x3 matrix returned by this method represents the 2-D transform...
Takes two lists of 3 x-y points each, and calculates the matrix representing the transformation from one space to the other. The 3x3 matrix returned by this method represents the 2-D transformation matrix from the actual point to the expected point. Example: If the expected points are: ...
def grid(lon_edges, lat_edges, values, cmap, alpha=255, vmin=None, vmax=None, levels=10, colormap_scale='lin', show_colorbar=True): """ Values on a uniform grid :param lon_edges: longitude edges :param lat_edges: latitude edges :param values: matrix representing values on th...
Values on a uniform grid :param lon_edges: longitude edges :param lat_edges: latitude edges :param values: matrix representing values on the grid :param cmap: colormap name :param alpha: color alpha :param vmin: minimum value for the colormap :param vmax...
def add_info_field(self, field): """Adds new info field (flag or key=value pair). Args: field: String flag (e.g. "SOMATIC") or key-value ("NEW_DP=42") Raises: KeyError: if info field already exists """ if field in self.info_dict: msg = "New i...
Adds new info field (flag or key=value pair). Args: field: String flag (e.g. "SOMATIC") or key-value ("NEW_DP=42") Raises: KeyError: if info field already exists
def incidental (self): """ Returns incidental properties. """ result = [p for p in self.lazy_properties if p.feature.incidental] result.extend(self.incidental_) return result
Returns incidental properties.
def add_record(self, msg_id, rec): """Add a new Task Record, by msg_id.""" d = self._defaults() d.update(rec) d['msg_id'] = msg_id line = self._dict_to_list(d) tups = '(%s)'%(','.join(['?']*len(line))) self._db.execute("INSERT INTO %s VALUES %s"%(self.table, tups)...
Add a new Task Record, by msg_id.
def discard_event(event: events.Event, bot_id: str = None) -> bool: """ Check if the incoming event needs to be discarded Args: event: Incoming :class:`slack.events.Event` bot_id: Id of connected bot Returns: boolean """ if event["type"] in SKIP_EVENTS: return T...
Check if the incoming event needs to be discarded Args: event: Incoming :class:`slack.events.Event` bot_id: Id of connected bot Returns: boolean
def role_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/chat/roles#create-role" api_path = "/api/v2/roles" return self.call(api_path, method="POST", data=data, **kwargs)
https://developer.zendesk.com/rest_api/docs/chat/roles#create-role
def store_file(self, path, data, fast_lane=True): """ Store the file in temp folder and stream it to server if online. This makes sure that we have all newest data of this file on the server directly. This method always overwrites the content of path. If you want to a...
Store the file in temp folder and stream it to server if online. This makes sure that we have all newest data of this file on the server directly. This method always overwrites the content of path. If you want to append always the content, use Git.stream_file() instead. ...
def probability_in(self, a, b): """ Returns the probability of a random variable falling between the given values. """ if self.mean is None: return p1 = normdist(x=a, mu=self.mean, sigma=self.standard_deviation) p2 = normdist(x=b, mu=self.mean, sigma=s...
Returns the probability of a random variable falling between the given values.
def get_mems_of_org(self): """ Retrieves the emails of the members of the organization. Note this Only gets public emails. Private emails would need authentication for each user. """ print 'Getting members\' emails.' for member in self.org_retrieved.iter_members()...
Retrieves the emails of the members of the organization. Note this Only gets public emails. Private emails would need authentication for each user.
def _get_has_relation_query(self, relation): """ Get the "has" relation base query :type relation: str :rtype: Builder """ from .relations import Relation return Relation.no_constraints( lambda: getattr(self.get_model(), relation)() )
Get the "has" relation base query :type relation: str :rtype: Builder
def velocity_embedding_grid(adata, basis=None, vkey='velocity', density=None, smooth=None, min_mass=None, arrow_size=None, arrow_length=None, arrow_color=None, scale=None, autoscale=True, n_neighbors=None, X=None, V=None, X_grid=None, V_grid=None, principal_curve=...
\ Scatter plot of velocities on a grid. Arguments --------- adata: :class:`~anndata.AnnData` Annotated data matrix. x: `str`, `np.ndarray` or `None` (default: `None`) x coordinate y: `str`, `np.ndarray` or `None` (default: `None`) y coordinate vkey: `str` or `None` (...
def time_ago(dt): """ Return the current time ago """ now = datetime.datetime.now() return humanize.naturaltime(now - dt)
Return the current time ago
def items(self, limit=10000): """ Return all of the Items and Collections for this search """ _limit = 500 if 'ids' in self.kwargs: col = self.kwargs.get('query', {}).get('collection', {}).get('eq', None) if col is None: raise SatSearchError('Collection re...
Return all of the Items and Collections for this search
def scansearch(auth, label, filt, project=None, aid=None): ''' Search for scans by supplying a set of SQL-based conditionals. Example: >>> import yaxil >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') >>> query = { ... 'eor1': "note LIKE %EOR1%", ...
Search for scans by supplying a set of SQL-based conditionals. Example: >>> import yaxil >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') >>> query = { ... 'eor1': "note LIKE %EOR1%", ... 'eor2': "note LIKE %EOR2%", ... 'mpr': "series_descr...
def hide(self, selections): '''Hide objects in this representation. BallAndStickRepresentation support selections of atoms and bonds. To hide the first atom and the first bond you can use the following code:: from chemlab.mviewer.state import Selection represent...
Hide objects in this representation. BallAndStickRepresentation support selections of atoms and bonds. To hide the first atom and the first bond you can use the following code:: from chemlab.mviewer.state import Selection representation.hide({'atoms': Selection([0], sys...
def get_object(self, view_name, view_args, view_kwargs): """ Return the object corresponding to a matched URL. Takes the matched URL conf arguments, and should return an object instance, or raise an `ObjectDoesNotExist` exception. """ lookup_value = view_kwargs[self.look...
Return the object corresponding to a matched URL. Takes the matched URL conf arguments, and should return an object instance, or raise an `ObjectDoesNotExist` exception.
def enabled_actions_for_env(env): """Returns actions to perform when processing the given environment.""" def enabled(config_value, required): if config_value is Config.TriBool.No: return False if config_value is Config.TriBool.Yes: return True assert confi...
Returns actions to perform when processing the given environment.
def set(self, value): """ Sets the value of the object :param value: An integer, or a unicode string if _map is set :raises: ValueError - when an invalid value is passed """ if isinstance(value, str_cls): if self._map is None: ...
Sets the value of the object :param value: An integer, or a unicode string if _map is set :raises: ValueError - when an invalid value is passed
def Get(self, path): ''' Get the (modified) object from path ''' self.getting = path try: obj = self.dir.Get(path) return self.apply_view(obj) except DoesNotExist as dne: #print dir(dne) raise DoesNotExist( str(dne) + "[{0}]...
Get the (modified) object from path
def calculate_crop_list(full_page_box_list, bounding_box_list, angle_list, page_nums_to_crop): """Given a list of full-page boxes (media boxes) and a list of tight bounding boxes for each page, calculate and return another list giving the list o...
Given a list of full-page boxes (media boxes) and a list of tight bounding boxes for each page, calculate and return another list giving the list of bounding boxes to crop down to. The parameter `angle_list` is a list of rotation angles which correspond to the pages. The pages selected to crop are in ...
def responsive(self): """ bool: Whether the server for this app is up and responsive. """ if self.server_thread and self.server_thread.join(0): return False try: # Try to fetch the endpoint added by the middleware. identify_url = "http://{0}:{1}/__identify__...
bool: Whether the server for this app is up and responsive.
def server_off(self): ''' Stop experiment server ''' if (self.server.is_server_running() == 'yes' or self.server.is_server_running() == 'maybe'): self.server.shutdown() print 'Please wait. This could take a few seconds.' time.sleep(0.5)
Stop experiment server
def precision(x): """ Return the precision of x Parameters ---------- x : array_like | numeric Value(s) whose for which to compute the precision. Returns ------- out : numeric The precision of ``x`` or that the values in ``x``. Notes ----- The precision is ...
Return the precision of x Parameters ---------- x : array_like | numeric Value(s) whose for which to compute the precision. Returns ------- out : numeric The precision of ``x`` or that the values in ``x``. Notes ----- The precision is computed in base 10. Exam...
def match_reg(self, reg): """match the given regular expression object to the current text position. if a match occurs, update the current text and line position. """ mp = self.match_position match = reg.match(self.text, self.match_position) if match: ...
match the given regular expression object to the current text position. if a match occurs, update the current text and line position.
async def consume(self): """Consume coroutines from the queue by executing them.""" while True: coro = await self._queue.get() assert asyncio.iscoroutine(coro) await coro
Consume coroutines from the queue by executing them.
def set_piece_at(self, square, piece, from_hand=False, into_hand=False): '''Sets a piece at the given square. An existing piece is replaced.''' if from_hand: self.remove_piece_from_hand(piece.piece_type, self.turn) self.remove_piece_at(square, into_hand) self.pieces[square]...
Sets a piece at the given square. An existing piece is replaced.
def wait(self, auth, resource, options, defer=False): """ This is a HTTP Long Polling API which allows a user to wait on specific resources to be updated. Args: auth: <cik> for authentication resource: <ResourceID> to specify what resource to wait on. options...
This is a HTTP Long Polling API which allows a user to wait on specific resources to be updated. Args: auth: <cik> for authentication resource: <ResourceID> to specify what resource to wait on. options: Options for the wait including a timeout (in ms), (max 5min) and...
def _parse_info(self, data): """Parse the first line of a GNTP message to get security and other info values :param string data: GNTP Message :return dict: Parsed GNTP Info line """ match = GNTP_INFO_LINE.match(data) if not match: raise errors.ParseError('ERROR_PARSING_INFO_LINE') info = match.grou...
Parse the first line of a GNTP message to get security and other info values :param string data: GNTP Message :return dict: Parsed GNTP Info line
def post_pipeline(self, pipeline): """Send Pipeline JSON to Spinnaker. Args: pipeline (json): json of the pipeline to be created in Spinnaker """ url = "{0}/pipelines".format(API_URL) if isinstance(pipeline, str): pipeline_json = pipeline else: ...
Send Pipeline JSON to Spinnaker. Args: pipeline (json): json of the pipeline to be created in Spinnaker
def get_marshaller_for_type_string(self, type_string): """ Gets the appropriate marshaller for a type string. Retrieves the marshaller, if any, that can be used to read/write a Python object with the given type string. The modules it requires, if available, will be loaded. Para...
Gets the appropriate marshaller for a type string. Retrieves the marshaller, if any, that can be used to read/write a Python object with the given type string. The modules it requires, if available, will be loaded. Parameters ---------- type_string : str Typ...
def update(self, model, prop_name, info): """ The method updates the history (a Gtk.TreeStore) which is the model of respective TreeView. It functionality is strongly depends on a consistent history-tree hold by a ChangeHistory-Class. """ # logger.debug("History changed %s\n%s\n%s" % (mo...
The method updates the history (a Gtk.TreeStore) which is the model of respective TreeView. It functionality is strongly depends on a consistent history-tree hold by a ChangeHistory-Class.
def remove_dirs(self, directory): """Delete a directory recursively. :param directory: $PATH to directory. :type directory: ``str`` """ LOG.info('Removing directory [ %s ]', directory) local_files = self._drectory_local_files(directory=directory) for file_name i...
Delete a directory recursively. :param directory: $PATH to directory. :type directory: ``str``
def get_neighborhood_overlap(self, node1, node2, connection_type=None): """Get the intersection of two nodes's neighborhoods. Neighborhood is defined by parameter connection_type. :param Vertex node1: First node. :param Vertex node2: Second node. :param Optional[str] connection_...
Get the intersection of two nodes's neighborhoods. Neighborhood is defined by parameter connection_type. :param Vertex node1: First node. :param Vertex node2: Second node. :param Optional[str] connection_type: One of direct or second-degree. Defaults to direct. :return: Overlap ...
def sam_conversions(self, sam_file, depth=True): """ Convert sam files to bam files, then sort and index them for later use. :param bool depth: also calculate coverage over each position """ cmd = self.tools.samtools + " view -bS " + sam_file + " > " + sam_file.replace(".sam", "...
Convert sam files to bam files, then sort and index them for later use. :param bool depth: also calculate coverage over each position
def any_positivesmallinteger_field(field, **kwargs): """ Return random value for PositiveSmallIntegerField >>> result = any_field(models.PositiveSmallIntegerField()) >>> type(result) <type 'int'> >>> result < 256, result > 0 (True, True) """ min_value = kwargs.get('min_value...
Return random value for PositiveSmallIntegerField >>> result = any_field(models.PositiveSmallIntegerField()) >>> type(result) <type 'int'> >>> result < 256, result > 0 (True, True)
def to_python(self, value): """Convert the constant to the real choice value.""" # ``is_required`` is already checked in ``validate``. if value is None: return None # Validate the type. if not isinstance(value, six.string_types): raise forms.ValidationEr...
Convert the constant to the real choice value.
def arc(self, cx, cy, r, start_radians, end_radians, fill=None): """ NOTE: This will leave gaps between adjacent segments. You can fix this by disabling anti-aliasing using shape-rendering="crispEdges" on the path tag If you want to add a stroke to this, it's advisable to cr...
NOTE: This will leave gaps between adjacent segments. You can fix this by disabling anti-aliasing using shape-rendering="crispEdges" on the path tag If you want to add a stroke to this, it's advisable to create a second path that just strokes the outside of the circle ...
def show_news_line(slug=None, limit=3, **kwargs): """ Отображает список последних новостей Пример использования:: {% show_news_line 'news_section_slug' 3 class='news-class' %} :param slug: символьный код категории новостей, если не задан фильтрация по категории не происходит :param limit:...
Отображает список последних новостей Пример использования:: {% show_news_line 'news_section_slug' 3 class='news-class' %} :param slug: символьный код категории новостей, если не задан фильтрация по категории не происходит :param limit: количество выводимых новостей :param kwargs: html атрибут...
def help(self): """Return help for this plugin. This will be output as the help section of the --with-$name option that enables the plugin. """ if self.__class__.__doc__: # doc sections are often indented; compress the spaces return textwrap.dedent(self.__class__....
Return help for this plugin. This will be output as the help section of the --with-$name option that enables the plugin.
def create_one(self, commit=True): ''' Create and return one model instance. If *commit* is ``False`` the instance will not be saved and many to many relations will not be processed. Subclasses that override ``create_one`` can specify arbitrary keyword arguments. They wi...
Create and return one model instance. If *commit* is ``False`` the instance will not be saved and many to many relations will not be processed. Subclasses that override ``create_one`` can specify arbitrary keyword arguments. They will be passed through by the :meth:`autofixture....
def sort_by_length(self): """ Sorts dataset by the sequence length. """ self.lengths, indices = self.lengths.sort(descending=True) self.src = [self.src[idx] for idx in indices] self.indices = indices.tolist() self.sorted = True
Sorts dataset by the sequence length.
def get_encoded_filename(self, filename_parm): """ Handle encoded filenames per RFC6266. See also: http://tools.ietf.org/html/rfc2231#section-4 """ encoded_filename = force_text(filename_parm['filename*']) try: charset, lang, filename = encoded_filename.split(...
Handle encoded filenames per RFC6266. See also: http://tools.ietf.org/html/rfc2231#section-4
def f_store_items(self, iterator, *args, **kwargs): """Stores individual items to disk. This function is useful if you calculated very large results (or large derived parameters) during runtime and you want to write these to disk immediately and empty them afterwards to free some memory...
Stores individual items to disk. This function is useful if you calculated very large results (or large derived parameters) during runtime and you want to write these to disk immediately and empty them afterwards to free some memory. Instead of storing individual parameters or results ...
def get_email_regex(self): """ Return a regex pattern matching valid email addresses. Uses the same logic as the django validator, with the folowing exceptions: - Internationalized domain names not supported - IP addresses not supported - Strips lookbehinds (not supporte...
Return a regex pattern matching valid email addresses. Uses the same logic as the django validator, with the folowing exceptions: - Internationalized domain names not supported - IP addresses not supported - Strips lookbehinds (not supported in javascript regular expressions)
def _download_py2(link, path, __hdr__): """Download a file from a link in Python 2.""" try: req = urllib2.Request(link, headers=__hdr__) u = urllib2.urlopen(req) except Exception as e: raise Exception(' Download failed with the error:\n{}'.format(e)) with open(path, 'wb') as out...
Download a file from a link in Python 2.
def _verify_support(identity): """Make sure the device supports given configuration.""" if identity.curve_name not in {formats.CURVE_NIST256}: raise NotImplementedError( 'Unsupported elliptic curve: {}'.format(identity.curve_name))
Make sure the device supports given configuration.
def _check_security_groups(self, names): """ Raise an exception if any of the named security groups does not exist. :param List[str] groups: List of security group names :raises: `SecurityGroupError` if group does not exist """ self._init_os_api() log.debug("Chec...
Raise an exception if any of the named security groups does not exist. :param List[str] groups: List of security group names :raises: `SecurityGroupError` if group does not exist
def predict(self, X): """ Perform classification on an array of test vectors X. Parameters ---------- X : array-like, shape = [n_samples, n_features] Returns ------- C : array, shape = [n_samples] Predicted target values for X """ ...
Perform classification on an array of test vectors X. Parameters ---------- X : array-like, shape = [n_samples, n_features] Returns ------- C : array, shape = [n_samples] Predicted target values for X
def translate_job_state(code): '''AUX Function to translate the (numeric) state of a Job. Args: nr (int): A valid number to translate. Returns: HTTP response. JSON body. ''' code_description = "" if code == "0": code_description = "Queued" if code == "1": co...
AUX Function to translate the (numeric) state of a Job. Args: nr (int): A valid number to translate. Returns: HTTP response. JSON body.
def elcm_profile_delete(irmc_info, profile_name): """send an eLCM request to delete a profile :param irmc_info: node info :param profile_name: name of profile :raises: ELCMProfileNotFound if the profile does not exist :raises: SCCIClientError if SCCI failed """ # Send DELETE request to the ...
send an eLCM request to delete a profile :param irmc_info: node info :param profile_name: name of profile :raises: ELCMProfileNotFound if the profile does not exist :raises: SCCIClientError if SCCI failed
def print_settings(settings, depth=0): """Print all available settings of the device.""" # handle the case where a single setting is passed if isinstance(settings, Setting): settings = [settings] for setting in settings: cur = setting.currentValue print( "%s* %s (%s, ...
Print all available settings of the device.
def value_derived_from_wavefunction(self, state: np.ndarray, qubit_map: Dict[raw_types.Qid, int] ) -> Any: """The value of the display, derived from the full wavefunction. Args: ...
The value of the display, derived from the full wavefunction. Args: state: The wavefunction. qubit_map: A dictionary from qubit to qubit index in the ordering used to define the wavefunction.
def snmp_server_v3host_udp_port(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") snmp_server = ET.SubElement(config, "snmp-server", xmlns="urn:brocade.com:mgmt:brocade-snmp") v3host = ET.SubElement(snmp_server, "v3host") hostip_key = ET.SubElement...
Auto Generated Code
def find_objects(self, obj): """ Find all objects in obj that match the type of the type node. :param obj: A dictionary or list of dictionaries to search, recursively :type obj: union[dict, list[dict]] :return: a list of dictionary objects that have a "_type" key value that mat...
Find all objects in obj that match the type of the type node. :param obj: A dictionary or list of dictionaries to search, recursively :type obj: union[dict, list[dict]] :return: a list of dictionary objects that have a "_type" key value that matches the type of this node. :rtype: list[...
def unfollow(user, obj, send_action=False, flag=''): """ Removes a "follow" relationship. Set ``send_action`` to ``True`` (``False is default) to also send a ``<user> stopped following <object>`` action signal. Pass a string value to ``flag`` to determine which type of "follow" relationship you wa...
Removes a "follow" relationship. Set ``send_action`` to ``True`` (``False is default) to also send a ``<user> stopped following <object>`` action signal. Pass a string value to ``flag`` to determine which type of "follow" relationship you want to remove. Example:: unfollow(request.user, othe...
def build_skos_concepts(self): """ 2015-08-19: first draft """ self.all_skos_concepts = [] # @todo: keep adding? qres = self.sparqlHelper.getSKOSInstances() # print("rdflib query done") for candidate in qres: test_existing_cl = self.get_skos(uri=ca...
2015-08-19: first draft
def FromReadings(cls, uuid, readings): """Generate an instance of the report format from a list of readings and a uuid """ if len(readings) != 1: raise ArgumentError("IndividualReading reports must be created with exactly one reading", num_readings=le...
Generate an instance of the report format from a list of readings and a uuid
def number_to_bytes(n, endian='big'): """ Convert an integer to a corresponding string of bytes.. :param n: Integer to convert. :param endian: Byte order to convert into ('big' or 'little' endian-ness, default 'big') Assumes bytes are 8 bits. This is a special-case ve...
Convert an integer to a corresponding string of bytes.. :param n: Integer to convert. :param endian: Byte order to convert into ('big' or 'little' endian-ness, default 'big') Assumes bytes are 8 bits. This is a special-case version of number_to_string with a full base-256 ...
def init(self): """Start the process """ import subprocess import fcntl width = str(self.image_dimensions[0]) height = str(self.image_dimensions[1]) comlist = self.executable.split() + [width, height, self.tmpfile] # e.g. "python3", "example_proc...
Start the process
def _configDevActive(self, namestr, titlestr, devlist): """Generate configuration for I/O Queue Length. @param namestr: Field name component indicating device type. @param titlestr: Title component indicating device type. @param devlist: List of devices. """ ...
Generate configuration for I/O Queue Length. @param namestr: Field name component indicating device type. @param titlestr: Title component indicating device type. @param devlist: List of devices.
def get_idle_pc_prop(self): """ Gets the idle PC proposals. Takes 1000 measurements and records up to 10 idle PC proposals. There is a 10ms wait between each measurement. :returns: list of idle PC proposal """ is_running = yield from self.is_running() wa...
Gets the idle PC proposals. Takes 1000 measurements and records up to 10 idle PC proposals. There is a 10ms wait between each measurement. :returns: list of idle PC proposal
def is_solved(self): """ Check if Cube is solved. """ for side in "LUFDRB": sample = self.cube[side].facings[side] for square in sum(self.cube.get_face(side), []): if square != sample: return False return True
Check if Cube is solved.
def _BuildToken(self, request, execution_time): """Build an ACLToken from the request.""" token = access_control.ACLToken( username=request.user, reason=request.args.get("reason", ""), process="GRRAdminUI", expiry=rdfvalue.RDFDatetime.Now() + execution_time) for field in ["R...
Build an ACLToken from the request.
def quic_graph_lasso_ebic_manual(X, gamma=0): """Run QuicGraphicalLasso with mode='path' and gamma; use EBIC criteria for model selection. The EBIC criteria is built into InverseCovarianceEstimator base class so we demonstrate those utilities here. """ print("QuicGraphicalLasso (manual EBIC) wi...
Run QuicGraphicalLasso with mode='path' and gamma; use EBIC criteria for model selection. The EBIC criteria is built into InverseCovarianceEstimator base class so we demonstrate those utilities here.
def get_files_in_tree(profile, sha): """Get the files (blobs) in a tree. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. s...
Get the files (blobs) in a tree. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. sha The SHA of a tree. Retur...
def weight_targeting(w, k): """Weight-level magnitude pruning.""" k = tf.to_int32(k) w_shape = shape_list(w) size = tf.to_int32(tf.reduce_prod(w_shape[:-1])) w = tf.reshape(w, [size, w_shape[-1]]) transpose_w = tf.transpose(w) thres = tf.contrib.framework.sort(tf.abs(transpose_w), axis=1)[:, k] mask = ...
Weight-level magnitude pruning.
def get_secondary_count(context, default=0): """Returns the number of secondary ARs of this AR """ if not is_ar(context): return default primary = context.getPrimaryAnalysisRequest() if not primary: return default return len(primary.getSecondaryAnalysisRequests())
Returns the number of secondary ARs of this AR
def foreground_run(self, command, test=False, logger=None, logall=False, message=None, outname=None, errname=None): """A convenient wrapper to log and perform system calls. Parameters ---------- command : str The system command to run. It will be split internally by shlex.s...
A convenient wrapper to log and perform system calls. Parameters ---------- command : str The system command to run. It will be split internally by shlex.split(). test : bool, optional Set this to true to not actually run the commands. logger : logging.l...
def debugDumpOneNode(self, output, depth): """Dumps debug information for the element node, it is not recursive """ libxml2mod.xmlDebugDumpOneNode(output, self._o, depth)
Dumps debug information for the element node, it is not recursive
def _unique_resource_identifier_from_kwargs(**kwargs): """Chooses an identifier given different choices The unique identifier in BIG-IP's REST API at the time of this writing is called 'name'. This is in contrast to the unique identifier that is used by iWorkflow and BIG-IQ which at some times is 'name...
Chooses an identifier given different choices The unique identifier in BIG-IP's REST API at the time of this writing is called 'name'. This is in contrast to the unique identifier that is used by iWorkflow and BIG-IQ which at some times is 'name' and other times is 'uuid'. For example, in iWorkflo...
def collect(self, device, ip, user, password): """ This function collects the metrics for one filer. """ sys.path.append(self.config['netappsdkpath']) try: import NaServer except ImportError: self.log.error("Unable to load NetApp SDK from %s" % ( ...
This function collects the metrics for one filer.
def summary(self): """Returns the docstring summary for the code element if it exists.""" if self._summary is None: self._summary = "No summary for element." for doc in self.docstring: if doc.doctype == "summary": self._summary = doc.contents ...
Returns the docstring summary for the code element if it exists.
def get_children(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get children in znode path path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Defaul...
Get children in znode path path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to a...
def query_by_user(self, user_id, end_time=None, start_time=None): """ Query by user. List authentication events for a given user. """ path = {} data = {} params = {} # REQUIRED - PATH - user_id """ID""" path["user_id"] = user_...
Query by user. List authentication events for a given user.
def _merge_doc(original, to_merge): # type: (str, str) -> str """Merge two usage strings together. Args: original: The source of headers and initial section lines. to_merge: The source for the additional section lines to append. Returns: A new usage string that contains informa...
Merge two usage strings together. Args: original: The source of headers and initial section lines. to_merge: The source for the additional section lines to append. Returns: A new usage string that contains information from both usage strings.
def getvalue(self, v): """ Return a list of quantities making up the measures' value. :param v: a measure """ if not is_measure(v): raise TypeError('Incorrect input type for getvalue()') import re rx = re.compile("m\d+") out = [] keys ...
Return a list of quantities making up the measures' value. :param v: a measure