code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def get_sequence_rules_for_assessment_part(self, assessment_part_id): """Gets a ``SequenceRuleList`` for the given source assessment part. arg: assessment_part_id (osid.id.Id): an assessment part ``Id`` return: (osid.assessment.authoring.SequenceRuleList) - the ...
Gets a ``SequenceRuleList`` for the given source assessment part. arg: assessment_part_id (osid.id.Id): an assessment part ``Id`` return: (osid.assessment.authoring.SequenceRuleList) - the returned ``SequenceRule`` list raise: NullArgument - ``assessment_part...
def with_name(cls, name, id_user=0, **extra_data): """Instantiate a WorkflowEngine given a name or UUID. :param name: name of workflow to run. :type name: str :param id_user: id of user to associate with workflow :type id_user: int :param module_name: label used to que...
Instantiate a WorkflowEngine given a name or UUID. :param name: name of workflow to run. :type name: str :param id_user: id of user to associate with workflow :type id_user: int :param module_name: label used to query groups of workflows. :type module_name: str
def _call(self, method, url, params): """Return response from Clef API call.""" request_params = {} if method == 'GET': request_params['params'] = params elif method == 'POST': request_params['data'] = params response = requests.request(method, url, **requ...
Return response from Clef API call.
def places_within_radius( self, place=None, latitude=None, longitude=None, radius=0, **kwargs ): """ Return descriptions of the places stored in the collection that are within the circle specified by the given location and radius. A list of dicts will be returned. Th...
Return descriptions of the places stored in the collection that are within the circle specified by the given location and radius. A list of dicts will be returned. The center of the circle can be specified by the identifier of another place in the collection with the *place* keyword arg...
def make_request(method, url, params): """Make an HTTP request, formatting params as required.""" empty = [] # TODO # del params[key] # without list for key, value in six.iteritems(params): if value is None: empty.append(key) for key in empty: del params[key] ...
Make an HTTP request, formatting params as required.
def get_excitation_spectrum(self, width=0.1, npoints=2000): """ Generate an excitation spectra from the singlet roots of TDDFT calculations. Args: width (float): Width for Gaussian smearing. npoints (int): Number of energy points. More points => smoother ...
Generate an excitation spectra from the singlet roots of TDDFT calculations. Args: width (float): Width for Gaussian smearing. npoints (int): Number of energy points. More points => smoother curve. Returns: (ExcitationSpectrum) which can be p...
def delete_empty_dir(directory): """ 删除空目录 :param directory: 目录路径 """ if os.path.exists(directory): if os.path.isdir(directory): for d in os.listdir(directory): path = os.path.join(directory, d) if os.path.isdir(path): delete_e...
删除空目录 :param directory: 目录路径
def encode(self, value): """The encoder for this schema. Tries each encoder in order of the types specified for this schema. """ if value is None and self._default is not None: value = self._default for encoder in self._encoders: try: retu...
The encoder for this schema. Tries each encoder in order of the types specified for this schema.
def make_xml_name(self, source_name, galkey, fullpath): """ Make the name of an xml file for a model definition for a set of merged rings Parameters ---------- source_name : str The galprop component, used to define path to gasmap files galkey : str A sh...
Make the name of an xml file for a model definition for a set of merged rings Parameters ---------- source_name : str The galprop component, used to define path to gasmap files galkey : str A short key identifying the galprop parameters fullpath : bool ...
def get_path_contents(self, project, provider_name, service_endpoint_id=None, repository=None, commit_or_branch=None, path=None): """GetPathContents. [Preview API] Gets the contents of a directory in the given source code repository. :param str project: Project ID or project name :param ...
GetPathContents. [Preview API] Gets the contents of a directory in the given source code repository. :param str project: Project ID or project name :param str provider_name: The name of the source provider. :param str service_endpoint_id: If specified, the ID of the service endpoint to q...
def get_request_id(self): """ This must be called while self.lock is held. """ try: return self.request_ids.popleft() except IndexError: new_request_id = self.highest_request_id + 1 # in_flight checks should guarantee this assert ne...
This must be called while self.lock is held.
def run(self, root_allowed=False): """Start daemon mode :param bool root_allowed: Only used for ExecuteCmd :return: loop """ self.root_allowed = root_allowed scan_devices(self.on_push, lambda d: d.src.lower() in self.devices, self.settings.get('interface'))
Start daemon mode :param bool root_allowed: Only used for ExecuteCmd :return: loop
def download_items(self, items, file_path, file_format='zip'): """ Retrieve a file from the server containing the metadata and documents for the speficied items :type items: List or ItemGroup :param items: List of the the URLs of the items to download, or an ItemGroup object...
Retrieve a file from the server containing the metadata and documents for the speficied items :type items: List or ItemGroup :param items: List of the the URLs of the items to download, or an ItemGroup object :type file_path: String :param file_path: the path to whic...
def short_relative_path_to(self, destination): """The shorter of either the absolute path of the destination, or the relative path to it >>> print(DotPath('/home/guido/bin').short_relative_path_to( ... '/home/guido/build/python.tar')) ../build/python.tar >>> prin...
The shorter of either the absolute path of the destination, or the relative path to it >>> print(DotPath('/home/guido/bin').short_relative_path_to( ... '/home/guido/build/python.tar')) ../build/python.tar >>> print(DotPath('/home/guido/bin').short_relative_path_to( ...
def name2marc(self, key, value): """Populates the ``100`` field. Also populates the ``400``, ``880``, and ``667`` fields through side effects. """ result = self.get('100', {}) result['a'] = value.get('value') result['b'] = value.get('numeration') result['c'] = value.get('title') re...
Populates the ``100`` field. Also populates the ``400``, ``880``, and ``667`` fields through side effects.
def _read_file_and_pos(self): """ Read last position from file, store as current position """ try: with open(self.pos_storage_filename, 'r+') as f: _pos = f.read() _logger.debug('Got position "%s" from file %s' % (_pos, se...
Read last position from file, store as current position
def binPack(self, jobShapes): """Pack a list of jobShapes into the fewest nodes reasonable. Can be run multiple times.""" # TODO: Check for redundancy with batchsystems.mesos.JobQueue() sorting logger.debug('Running bin packing for node shapes %s and %s job(s).', self.nodeSh...
Pack a list of jobShapes into the fewest nodes reasonable. Can be run multiple times.
def as_boxes(self, solid=False): """ A rough Trimesh representation of the voxels with a box for each filled voxel. Parameters ----------- solid: bool, if True return boxes for sparse_solid Returns --------- mesh: Trimesh object made up of one bo...
A rough Trimesh representation of the voxels with a box for each filled voxel. Parameters ----------- solid: bool, if True return boxes for sparse_solid Returns --------- mesh: Trimesh object made up of one box per filled cell.
def get(*dataset, **kwargs): ''' Displays properties for the given datasets. dataset : string name of snapshot(s), filesystem(s), or volume(s) properties : string comma-separated list of properties to list, defaults to all recursive : boolean recursively list children de...
Displays properties for the given datasets. dataset : string name of snapshot(s), filesystem(s), or volume(s) properties : string comma-separated list of properties to list, defaults to all recursive : boolean recursively list children depth : int recursively list childr...
def remove_file(self, name): """Remove cur_dir/name.""" self.check_write(name) path = os.path.join(self.cur_dir, name) os.remove(path)
Remove cur_dir/name.
def ask_for_board_id(self): """Factored out in case interface isn't keyboard""" board_id = raw_input("paste in board id or url: ").strip() m = re.search(r"(?:https?://)?(?:trello.com)?/?b?/?([a-zA-Z]{8})/(?:.*)", board_id) if m: board_id = m.group(1) return board_id
Factored out in case interface isn't keyboard
def update_grammar_to_be_variable_free(grammar_dictionary: Dict[str, List[str]]): """ SQL is a predominately variable free language in terms of simple usage, in the sense that most queries do not create references to variables which are not already static tables in a dataset. However, it is possible to ...
SQL is a predominately variable free language in terms of simple usage, in the sense that most queries do not create references to variables which are not already static tables in a dataset. However, it is possible to do this via derived tables. If we don't require this functionality, we can tighten the ...
def _list_vlans_by_name(self, name): """Returns a list of IDs of VLANs which match the given VLAN name. :param string name: a VLAN name :returns: List of matching IDs """ results = self.list_vlans(name=name, mask='id') return [result['id'] for result in results]
Returns a list of IDs of VLANs which match the given VLAN name. :param string name: a VLAN name :returns: List of matching IDs
def strip_docstrings(tokens): """Replace docstring tokens with NL tokens in a `tokenize` stream. Any STRING token not part of an expression is deemed a docstring. Indented docstrings are not yet recognised. """ stack = [] state = 'wait_string' for t in tokens: typ = t[0] if ...
Replace docstring tokens with NL tokens in a `tokenize` stream. Any STRING token not part of an expression is deemed a docstring. Indented docstrings are not yet recognised.
def run(self, image, command=None, create_kwargs=None, start_kwargs=None, volume_bindings=None, privileged=None): """ create container from provided image and start it for more info, see documentation of REST API calls: * containers/{}/start * container/create ...
create container from provided image and start it for more info, see documentation of REST API calls: * containers/{}/start * container/create :param image: ImageName or string, name or id of the image :param command: str :param create_kwargs: dict, kwargs for docker....
def _submit(self): '''submit the issue to github. When we get here we should have: {'user_prompt_issue': 'I want to do the thing.', 'user_prompt_repo': 'vsoch/hello-world', 'user_prompt_title': 'Error with this thing', 'record_asciinema': '/tmp/helpme...
submit the issue to github. When we get here we should have: {'user_prompt_issue': 'I want to do the thing.', 'user_prompt_repo': 'vsoch/hello-world', 'user_prompt_title': 'Error with this thing', 'record_asciinema': '/tmp/helpme.93o__nt5.json', '...
def reshape_text(buffer, from_row, to_row): """ Reformat text, taking the width into account. `to_row` is included. (Vi 'gq' operator.) """ lines = buffer.text.splitlines(True) lines_before = lines[:from_row] lines_after = lines[to_row + 1:] lines_to_reformat = lines[from_row:to_row ...
Reformat text, taking the width into account. `to_row` is included. (Vi 'gq' operator.)
def run(self): """ Creates a listener and loops while waiting for an event. Intended to run as a background thread. """ self.tap = Quartz.CGEventTapCreate( Quartz.kCGSessionEventTap, Quartz.kCGHeadInsertEventTap, Quartz.kCGEventTapOptionDefault, Qu...
Creates a listener and loops while waiting for an event. Intended to run as a background thread.
def xSectionChunk(lines): """ Parse XSEC Method """ # Constants KEYWORDS = ('MANNINGS_N', 'BOTTOM_WIDTH', 'BANKFULL_DEPTH', 'SIDE_SLOPE', 'NPAIRS', 'NUM_INTERP', 'X1', 'ERODE', ...
Parse XSEC Method
def _parse_complex_list(self, prop): """ Default parsing operation for lists of complex structs """ xpath_root = self._get_xroot_for(prop) xpath_map = self._data_structures[prop] return parse_complex_list(self._xml_tree, xpath_root, xpath_map, prop)
Default parsing operation for lists of complex structs
def CreateAllStaticECMWFFiles(in_catchment, catchment_river_id, rapid_output_folder, rapid_connect_file, file_geodatabase=None ): """ This creates all of the ECMW...
This creates all of the ECMWF grid weight tables using an area weighted method based on Esri's RAPID_Toolbox. Parameters ---------- in_catchment: str Path to the Catchment shapefile. catchment_river_id: str The name of the field with the river ID (Ex. 'DrainLnID' or 'LINKNO'). r...
def save(path, json_data): """ Saves json_data in path :param Path path: Path that json_data will be persisted :param json_data: Data that will be persisted """ try: loop = asyncio.get_event_loop() if loop.is_running(): asyncio.run...
Saves json_data in path :param Path path: Path that json_data will be persisted :param json_data: Data that will be persisted
def constructTx(self): """ Construct the actual transaction and store it in the class's dict store """ ops = list() for op in self.ops: if isinstance(op, ProposalBuilder): # This operation is a proposal an needs to be deal with # di...
Construct the actual transaction and store it in the class's dict store
def start_timer(self, name): """ This method is called by pywbem to start the timer for a particular operation execution. It returns the corresponding :class:`~pywbem.OperationStatistic` object, creating one if needed. The timer is subsequently stopped by pywbem by calling the ...
This method is called by pywbem to start the timer for a particular operation execution. It returns the corresponding :class:`~pywbem.OperationStatistic` object, creating one if needed. The timer is subsequently stopped by pywbem by calling the :meth:`~pywbem.OperationStatistic.stop_tim...
def C_Reader_Harris_Gallagher(D, Do, rho, mu, m, taps='corner'): r'''Calculates the coefficient of discharge of the orifice based on the geometry of the plate, measured pressures of the orifice, mass flow rate through the orifice, and the density and viscosity of the fluid. .. math:: C = 0...
r'''Calculates the coefficient of discharge of the orifice based on the geometry of the plate, measured pressures of the orifice, mass flow rate through the orifice, and the density and viscosity of the fluid. .. math:: C = 0.5961 + 0.0261\beta^2 - 0.216\beta^8 + 0.000521\left(\frac{ 1...
def array2qimage(array, normalize = False): """Convert a 2D or 3D numpy array into a 32-bit QImage_. The first dimension represents the vertical image axis; the optional third dimension is supposed to contain 1-4 channels: ========= =================== #channels interpretation ========= ======...
Convert a 2D or 3D numpy array into a 32-bit QImage_. The first dimension represents the vertical image axis; the optional third dimension is supposed to contain 1-4 channels: ========= =================== #channels interpretation ========= =================== 1 scalar/gray ...
def subtask(*args, **kwargs): '''Decorator which prints out the name of the decorated function on execution. ''' depth = kwargs.get('depth', 2) prefix = kwargs.get('prefix', '\n' + '#' * depth + ' ') tail = kwargs.get('tail', '\n') doc1 = kwargs.get('doc1', False) color = kwargs.get('col...
Decorator which prints out the name of the decorated function on execution.
def sfs_folded(ac, n=None): """Compute the folded site frequency spectrum given reference and alternate allele counts at a set of biallelic variants. Parameters ---------- ac : array_like, int, shape (n_variants, 2) Allele counts array. n : int, optional The total number of chro...
Compute the folded site frequency spectrum given reference and alternate allele counts at a set of biallelic variants. Parameters ---------- ac : array_like, int, shape (n_variants, 2) Allele counts array. n : int, optional The total number of chromosomes called. Returns --...
def pkcs_emsa_pss_verify(M, EM, emBits, h, mgf, sLen): """ Implements EMSA-PSS-VERIFY() function described in Sect. 9.1.2 of RFC 3447 Input: M : message to be encoded, an octet string EM : encoded message, an octet string of length emLen = ceil(emBits/8) emBits: maximal bit leng...
Implements EMSA-PSS-VERIFY() function described in Sect. 9.1.2 of RFC 3447 Input: M : message to be encoded, an octet string EM : encoded message, an octet string of length emLen = ceil(emBits/8) emBits: maximal bit length of the integer resulting of pkcs_os2ip(EM) h : hash f...
def execution_history_focus(self, model, prop_name, info): """ Arranges to put execution-history widget page to become top page in notebook when execution starts and stops and resets the boolean of modification_history_was_focused to False each time this notification are observed. """ if...
Arranges to put execution-history widget page to become top page in notebook when execution starts and stops and resets the boolean of modification_history_was_focused to False each time this notification are observed.
def __str_cleanup(line): """ Remove the unnecessary characters in the line that we don't want :param str line: :return str: """ if '#' in line: line = line.replace("#", "") line = line.strip() if '-----------' in line: line = ''...
Remove the unnecessary characters in the line that we don't want :param str line: :return str:
def read_sql(sql, con, index_col=None, coerce_float=True, params=None, parse_dates=None, columns=None, chunksize=None): """ Read SQL query or database table into a DataFrame. This function is a convenience wrapper around ``read_sql_table`` and ``read_sql_query`` (for backward compatibility...
Read SQL query or database table into a DataFrame. This function is a convenience wrapper around ``read_sql_table`` and ``read_sql_query`` (for backward compatibility). It will delegate to the specific function depending on the provided input. A SQL query will be routed to ``read_sql_query``, while a d...
def html_format(data, out='nested', opts=None, **kwargs): ''' Return the formatted string as HTML. data The JSON serializable object. out: ``nested`` The name of the output to use to transform the data. Default: ``nested``. opts Dictionary of configuration options. Default...
Return the formatted string as HTML. data The JSON serializable object. out: ``nested`` The name of the output to use to transform the data. Default: ``nested``. opts Dictionary of configuration options. Default: ``__opts__``. kwargs Arguments to sent to the outputter...
def _transform_should_cast(self, func_nm): """ Parameters: ----------- func_nm: str The name of the aggregation function being performed Returns: -------- bool Whether transform should attempt to cast the result of aggregation """ ...
Parameters: ----------- func_nm: str The name of the aggregation function being performed Returns: -------- bool Whether transform should attempt to cast the result of aggregation
def add_node(self, name_base, attrs=None): """Add a node with a given base name to the Nugget and return ID.""" if name_base not in self.counters: node_id = name_base else: node_id = '%s_%d' % (name_base, self.counters[name_base]) node = {'id': node_id} if...
Add a node with a given base name to the Nugget and return ID.
def image_to_url(image, colormap=None, origin='upper'): """ Infers the type of an image argument and transforms it into a URL. Parameters ---------- image: string, file or array-like object * If string, it will be written directly in the output file. * If file, it's content will be ...
Infers the type of an image argument and transforms it into a URL. Parameters ---------- image: string, file or array-like object * If string, it will be written directly in the output file. * If file, it's content will be converted as embedded in the output file. * If arr...
def get_sdb_secret_version_paths(self, sdb_id): """ Get SDB secret version paths. This function takes the sdb_id """ sdb_resp = get_with_retry(str.join('', [self.cerberus_url, '/v1/sdb-secret-version-paths/', sdb_id]), headers=self.HEADERS) throw_if_bad_response...
Get SDB secret version paths. This function takes the sdb_id
def _generate_injection_cmd(self, meta_data): """ example injector response: [ { "config_path":"/configs/cli_config.py", "path":"/opt/cia-cli/cia_sdk/config", "user":"injector", "status_code":201, "chmod":755, ...
example injector response: [ { "config_path":"/configs/cli_config.py", "path":"/opt/cia-cli/cia_sdk/config", "user":"injector", "status_code":201, "chmod":755, "checksum":"a4bcf3939dd3a6aa4e04ee9f92131df4", ...
def layers(self): '''Construct Keras input layers for all feature transformers in the pump. Returns ------- layers : {field: keras.layers.Input} A dictionary of keras input layers, keyed by the corresponding fields. ''' layermap = dict() ...
Construct Keras input layers for all feature transformers in the pump. Returns ------- layers : {field: keras.layers.Input} A dictionary of keras input layers, keyed by the corresponding fields.
def execute(self): """ Given the command-line arguments, this figures out which subcommand is being run, creates a parser appropriate to that command, and runs it. """ # Preprocess options to extract --settings and --pythonpath. # These options could affect the commands t...
Given the command-line arguments, this figures out which subcommand is being run, creates a parser appropriate to that command, and runs it.
def setInterimValue(self, keyword, value): """Sets a value to an interim of this analysis :param keyword: the keyword of the interim :param value: the value for the interim """ # Ensure result integrity regards to None, empty and 0 values val = str('' if not value and val...
Sets a value to an interim of this analysis :param keyword: the keyword of the interim :param value: the value for the interim
def remove_handler(self, handler): """Detach active handler from the session `handler` Handler to remove """ super(Session, self).remove_handler(handler) self.promote() self.stop_heartbeat()
Detach active handler from the session `handler` Handler to remove
def compute_from_counts(self,countmat,beta=0): """ m.compute_from_counts(,countmat,beta=0) -- Utility function to build a motif object from a matrix of letter counts. """ self.counts = countmat self.width = len(countmat) self.bgscale = 0 maxcount = 0 #...
m.compute_from_counts(,countmat,beta=0) -- Utility function to build a motif object from a matrix of letter counts.
def getattribute(value, arg): """Gets an attribute of an object dynamically from a string name""" if callable(getattr(value, arg)): return str(getattr(value, arg)()) elif hasattr(value, str(arg)): return getattr(value, arg) elif hasattr(value, 'has_key') and value.has_key(arg): ...
Gets an attribute of an object dynamically from a string name
def match_path_against(pathname, patterns, case_sensitive=True): """ Determines whether the pathname matches any of the given wildcard patterns, optionally ignoring the case of the pathname and patterns. :param pathname: A path name that will be matched against a wildcard pattern. :param pa...
Determines whether the pathname matches any of the given wildcard patterns, optionally ignoring the case of the pathname and patterns. :param pathname: A path name that will be matched against a wildcard pattern. :param patterns: A list of wildcard patterns to match_path the filename agains...
def add_conversation_tab(self, conv_id, switch=False): """Add conversation tab if not present, and optionally switch to it.""" conv_widget = self.get_conv_widget(conv_id) self._tabbed_window.set_tab(conv_widget, switch=switch, title=conv_widget.title)
Add conversation tab if not present, and optionally switch to it.
def read_sql(self, code: str) -> pandas.DataFrame: """Evaluate a Spark SQL satatement and retrieve the result. :param code: The Spark SQL statement to evaluate. """ if self.kind != SessionKind.SQL: raise ValueError("not a SQL session") output = self._execute(code) ...
Evaluate a Spark SQL satatement and retrieve the result. :param code: The Spark SQL statement to evaluate.
def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_i...
Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the ...
def fast_approximate_personalized_pagerank(s, r, w_i, a_i, out_degree, in_degree, ...
Calculates the approximate personalized PageRank starting from a seed node without self-loops.
def get_so_far(self): """ Returns the `str` bytes of this message that have been parsed and returned. The string passed into a message's constructor can be regenerated by concatenating ``get_so_far`` and `get_remainder`. """ position = self.packet.tell() self.rewi...
Returns the `str` bytes of this message that have been parsed and returned. The string passed into a message's constructor can be regenerated by concatenating ``get_so_far`` and `get_remainder`.
def match_pattern(self, path): """ Return if given path match the pattern(s). :param path: path to check. :return: True if match, False otherwise. """ for pattern in self.__pattern: if len(fnmatch.filter([path], pattern)) > 0: return True ...
Return if given path match the pattern(s). :param path: path to check. :return: True if match, False otherwise.
def list(self, path): """GET /<path>?list=true :param path: :type path: :return: :rtype: """ try: payload = { 'list': True } return self._adapter.get('/v1/{0}'.format(path), params=payload).json() except...
GET /<path>?list=true :param path: :type path: :return: :rtype:
def get_date_format_string(period): """ For a given period (e.g. 'month', 'day', or some numeric interval such as 3600 (in secs)), return the format string that can be used with strftime to format that time to specify the times across that interval, but no more detailed. For example, >>> get_date_format_string(...
For a given period (e.g. 'month', 'day', or some numeric interval such as 3600 (in secs)), return the format string that can be used with strftime to format that time to specify the times across that interval, but no more detailed. For example, >>> get_date_format_string('month') '%Y-%m' >>> get_date_format_str...
def attach(self, handle, filters=None, resolution=None): """Attach to an existing SignalFlow computation.""" params = self._get_params(filters=filters, resolution=resolution) c = computation.Computation( lambda since: self._transport.attach(handle, params)) self._computations...
Attach to an existing SignalFlow computation.
def send_confirmation(self, message, success=True): """Send success or error message to configured confirmation :param str message: Body message to send :param bool success: Device executed successfully to personalize message :return: None """ message = message.strip() ...
Send success or error message to configured confirmation :param str message: Body message to send :param bool success: Device executed successfully to personalize message :return: None
def get_all_resource_ids_in_datastore(configuration=None): # type: (Optional[Configuration]) -> List[str] """Get list of resources that have a datastore returning their ids. Args: configuration (Optional[Configuration]): HDX configuration. Defaults to global configuration. ...
Get list of resources that have a datastore returning their ids. Args: configuration (Optional[Configuration]): HDX configuration. Defaults to global configuration. Returns: List[str]: List of resource ids that are in the datastore
def unbind(self, exchange, source, routing_key='', nowait=True, arguments={}, ticket=None, cb=None): ''' Unbind an exchange from another. ''' nowait = nowait and self.allow_nowait() and not cb args = Writer() args.write_short(ticket or self.default_ticket)...
Unbind an exchange from another.
def _color_button_clicked(self, n,top): """ Opens the dialog. """ self._button_save.setEnabled(True) if top: self._color_dialogs_top[n].open() else: self._color_dialogs_bottom[n].open()
Opens the dialog.
def get_all_conditions(self): """ Returns a generator which yields groups of lists of conditions. >>> for set_id, label, field in gargoyle.get_all_conditions(): #doctest: +SKIP >>> print "%(label)s: %(field)s" % (label, field.label) #doctest: +SKIP """ for condition_...
Returns a generator which yields groups of lists of conditions. >>> for set_id, label, field in gargoyle.get_all_conditions(): #doctest: +SKIP >>> print "%(label)s: %(field)s" % (label, field.label) #doctest: +SKIP
def shorten_type(typ): """ Shorten a type. E.g. drops 'System.' """ offset = 0 for prefix in SHORTEN_TYPE_PREFIXES: if typ.startswith(prefix): if len(prefix) > offset: offset = len(prefix) return typ[offset:]
Shorten a type. E.g. drops 'System.'
def segment_into_chars(utterance: str) -> str: """ Segments an utterance into space delimited characters. """ if not isinstance(utterance, str): raise TypeError("Input type must be a string. Got {}.".format(type(utterance))) utterance.strip() utterance = utterance.replace(" ", "") return "...
Segments an utterance into space delimited characters.
def add_rds_instance(self, instance, region): ''' Adds an RDS instance to the inventory and index, as long as it is addressable ''' # Only want available instances unless all_rds_instances is True if not self.all_rds_instances and instance.status != 'available': return ...
Adds an RDS instance to the inventory and index, as long as it is addressable
def __write(self, containers, initialize=True): '''Write the given state information into a file''' path = self._state_file self._assure_dir() try: flags = os.O_WRONLY | os.O_CREAT if initialize: flags |= os.O_EXCL with os.fdopen(os.ope...
Write the given state information into a file
def make_view(robot): """ 为一个 BaseRoBot 生成 Django view。 :param robot: 一个 BaseRoBot 实例。 :return: 一个标准的 Django view """ assert isinstance(robot, BaseRoBot),\ "RoBot should be an BaseRoBot instance." @csrf_exempt def werobot_view(request): timestamp = request.GET.get("time...
为一个 BaseRoBot 生成 Django view。 :param robot: 一个 BaseRoBot 实例。 :return: 一个标准的 Django view
def option(*args, **kwargs): """Decorator to add an option to the optparser argument of a Cmdln subcommand. Example: class MyShell(cmdln.Cmdln): @cmdln.option("-f", "--force", help="force removal") def do_remove(self, subcmd, opts, *args): #... """ #...
Decorator to add an option to the optparser argument of a Cmdln subcommand. Example: class MyShell(cmdln.Cmdln): @cmdln.option("-f", "--force", help="force removal") def do_remove(self, subcmd, opts, *args): #...
def get_contents(self, path, ref=github.GithubObject.NotSet): """ :calls: `GET /repos/:owner/:repo/contents/:path <http://developer.github.com/v3/repos/contents>`_ :param path: string :param ref: string :rtype: :class:`github.ContentFile.ContentFile` """ return se...
:calls: `GET /repos/:owner/:repo/contents/:path <http://developer.github.com/v3/repos/contents>`_ :param path: string :param ref: string :rtype: :class:`github.ContentFile.ContentFile`
def _PrintExtractionStatusUpdateLinear(self, processing_status): """Prints an extraction status update in linear mode. Args: processing_status (ProcessingStatus): processing status. """ for worker_status in processing_status.workers_status: status_line = ( '{0:s} (PID: {1:d}) - ev...
Prints an extraction status update in linear mode. Args: processing_status (ProcessingStatus): processing status.
def future(self, request_iterator, timeout=None, metadata=None, credentials=None): """Asynchronously invokes the underlying RPC on the client. Args: request_iterator: An ASYNC iterator that yields request values for the RPC. timeout: A...
Asynchronously invokes the underlying RPC on the client. Args: request_iterator: An ASYNC iterator that yields request values for the RPC. timeout: An optional duration of time in seconds to allow for the RPC. If None, the timeout is considered infinite. metadata: Optional :term:`m...
def update_count(self): """ updates comment count """ node_rating_count = self.node.rating_count node_rating_count.comment_count = self.node.comment_set.count() node_rating_count.save()
updates comment count
def sorted(self, by, **kwargs): """Sort array by a column. Parameters ========== by: str Name of the columns to sort by(e.g. 'time'). """ sort_idc = np.argsort(self[by], **kwargs) return self.__class__( self[sort_idc], h5loc=se...
Sort array by a column. Parameters ========== by: str Name of the columns to sort by(e.g. 'time').
def delete(self, key, *keys): """Delete a key.""" fut = self.execute(b'DEL', key, *keys) return wait_convert(fut, int)
Delete a key.
def key_deploy(self, host, ret): ''' Deploy the SSH key if the minions don't auth ''' if not isinstance(ret[host], dict) or self.opts.get('ssh_key_deploy'): target = self.targets[host] if target.get('passwd', False) or self.opts['ssh_passwd']: self...
Deploy the SSH key if the minions don't auth
def import_object_with_scope(name): """ Imports a Python object by an absolute identifier. # Arguments name (str): The name of the Python object to import. # Returns (any, Module): The object and the module that contains it. Note that for plain modules loaded with this function, both elements of the ...
Imports a Python object by an absolute identifier. # Arguments name (str): The name of the Python object to import. # Returns (any, Module): The object and the module that contains it. Note that for plain modules loaded with this function, both elements of the tuple may be the same object.
def gitignore_template(self, language): """Returns the template for language. :returns: str """ url = self._build_url('gitignore', 'templates', language) json = self._json(self._get(url), 200) if not json: return '' return json.get('source', '')
Returns the template for language. :returns: str
def loadIcon(self, fileName, color=None): """ Reads SVG from a file name and creates an QIcon from it. Optionally replaces the color. Caches the created icons. :param fileName: absolute path to an icon file. If False/empty/None, None returned, which yields no icon. ...
Reads SVG from a file name and creates an QIcon from it. Optionally replaces the color. Caches the created icons. :param fileName: absolute path to an icon file. If False/empty/None, None returned, which yields no icon. :param color: '#RRGGBB' string (e.g. '#FF0000'...
def batchnorm_2d(nf:int, norm_type:NormType=NormType.Batch): "A batchnorm2d layer with `nf` features initialized depending on `norm_type`." bn = nn.BatchNorm2d(nf) with torch.no_grad(): bn.bias.fill_(1e-3) bn.weight.fill_(0. if norm_type==NormType.BatchZero else 1.) return bn
A batchnorm2d layer with `nf` features initialized depending on `norm_type`.
def load_hdf(cls, filename, path=''): """Loads StarPopulation from .h5 file Correct properties should be restored to object, and object will be original type that was saved. Complement to :func:`StarPopulation.save_hdf`. Example usage:: >>> from vespa.stars import...
Loads StarPopulation from .h5 file Correct properties should be restored to object, and object will be original type that was saved. Complement to :func:`StarPopulation.save_hdf`. Example usage:: >>> from vespa.stars import Raghavan_BinaryPopulation, StarPopulation ...
def _extractFeatureClasses(lookupIndex, subtableIndex, classDefs, coverage=None): """ Extract classes for a specific lookup in a specific subtable. This is relatively straightforward, except for class 0 interpretation. Some fonts don't have class 0. Some fonts have a list of class members that are c...
Extract classes for a specific lookup in a specific subtable. This is relatively straightforward, except for class 0 interpretation. Some fonts don't have class 0. Some fonts have a list of class members that are clearly not all to be used in kerning pairs. In the case of a missing class 0, the coverage...
def delete(self, uri, logon_required=True): """ Perform the HTTP DELETE method against the resource identified by a URI. A set of standard HTTP headers is automatically part of the request. If the HMC session token is expired, this method re-logs on and retries the oper...
Perform the HTTP DELETE method against the resource identified by a URI. A set of standard HTTP headers is automatically part of the request. If the HMC session token is expired, this method re-logs on and retries the operation. Parameters: uri (:term:`string`): ...
def pointColors(self, scalars, cmap="jet", alpha=1, bands=None, vmin=None, vmax=None): """ Set individual point colors by providing a list of scalar values and a color map. `scalars` can be a string name of the ``vtkArray``. :param cmap: color map scheme to transform a real number into ...
Set individual point colors by providing a list of scalar values and a color map. `scalars` can be a string name of the ``vtkArray``. :param cmap: color map scheme to transform a real number into a color. :type cmap: str, list, vtkLookupTable, matplotlib.colors.LinearSegmentedColormap :...
def describe(i): """ Input: { (dict) - dict with current repo description } Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 (dict) ...
Input: { (dict) - dict with current repo description } Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 (dict) - updated dict with current ...
def loaded_instruments(self) -> Dict[str, Optional['InstrumentContext']]: """ Get the instruments that have been loaded into the protocol. :returns: A dict mapping mount names in lowercase to the instrument in that mount, or `None` if no instrument is present. """ retu...
Get the instruments that have been loaded into the protocol. :returns: A dict mapping mount names in lowercase to the instrument in that mount, or `None` if no instrument is present.
def filter_input(self, forced=False, context=None): """ Passes each hunk (file or code) to the 'input' methods of the compressor filters. """ content = [] for hunk in self.hunks(forced, context=context): content.append(hunk) return content
Passes each hunk (file or code) to the 'input' methods of the compressor filters.
def process_input_data(filename, imager, grid_data, grid_norm, grid_weights): """Reads visibility data from a Measurement Set. The visibility grid or weights grid is updated accordingly. Visibility data are read from disk in blocks of size num_baselines. Args: filename (str): ...
Reads visibility data from a Measurement Set. The visibility grid or weights grid is updated accordingly. Visibility data are read from disk in blocks of size num_baselines. Args: filename (str): Name of Measurement Set to open. imager (oskar.Imager): Handle...
def search(obj, glob, yielded=False, separator="/", afilter=None, dirs = True): """ Given a path glob, return a dictionary containing all keys that matched the given glob. If 'yielded' is true, then a dictionary will not be returned. Instead tuples will be yielded in the form of (path, value) for ...
Given a path glob, return a dictionary containing all keys that matched the given glob. If 'yielded' is true, then a dictionary will not be returned. Instead tuples will be yielded in the form of (path, value) for every element in the document that matched the glob.
def process_npdu(self, npdu): """encode NPDUs from the service access point and send them downstream.""" if _debug: RouterToRouterService._debug("process_npdu %r", npdu) # encode the npdu as if it was about to be delivered to the network pdu = PDU() npdu.encode(pdu) if _...
encode NPDUs from the service access point and send them downstream.
def fill_categorical_na(df, nan_cat='NA'): """Fill categoricals with 'NA', possibly creating a new category, and fill other NaNa with blanks """ for col in df.columns[df.isna().any()].tolist(): if df[col].dtype.name != 'category': # If not categorical, fill with a blank, which creates a...
Fill categoricals with 'NA', possibly creating a new category, and fill other NaNa with blanks
def _output(self, s): """Host header should always be first""" if s.lower().startswith(b'host: '): self._buffer.insert(1, s) else: self._buffer.append(s)
Host header should always be first
def check_alert(self, text): """ Assert an alert is showing with the given text. """ try: alert = Alert(world.browser) if alert.text != text: raise AssertionError( "Alert text expected to be {!r}, got {!r}.".format( text, alert.text)) ...
Assert an alert is showing with the given text.
def delete_group_category(self, group_category_id): """ Delete a Group Category. Deletes a group category and all groups under it. Protected group categories can not be deleted, i.e. "communities" and "student_organized". """ path = {} data = {} ...
Delete a Group Category. Deletes a group category and all groups under it. Protected group categories can not be deleted, i.e. "communities" and "student_organized".