positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def get_player_bans(self, steamIDS, format=None): """Request the communities a steam id is banned in. steamIDS: Comma-delimited list of SteamIDs format: Return format. None defaults to json. (json, xml, vdf) """ parameters = {'steamids' : steamIDS} if format is not None...
Request the communities a steam id is banned in. steamIDS: Comma-delimited list of SteamIDs format: Return format. None defaults to json. (json, xml, vdf)
def values(self): """ Return a copy of the dictionary's list of values. See the note for dict.items(). """ r = [] for key in self._safe_keys(): try: r.append(self[key]) except KeyError: pass return r
Return a copy of the dictionary's list of values. See the note for dict.items().
def exception(self): '''Return an instance of the corresponding exception''' code, _, message = self.data.partition(' ') return self.find(code)(message)
Return an instance of the corresponding exception
def pseudolocalize(self, s): """ Performs pseudo-localization on a string. The specific transforms to be applied to the string is defined in the transforms field of the object. :param s: String to pseudo-localize. :returns: Copy of the string s with the transforms applied. If ...
Performs pseudo-localization on a string. The specific transforms to be applied to the string is defined in the transforms field of the object. :param s: String to pseudo-localize. :returns: Copy of the string s with the transforms applied. If the input string is an empty st...
def createReferenceWCS(self,refname,overwrite=yes): """ Write out the values of the WCS keywords to the NEW specified image 'fitsname'. """ hdu = self.createWcsHDU() # If refname already exists, delete it to make way for new file if os.path.exists(refname): ...
Write out the values of the WCS keywords to the NEW specified image 'fitsname'.
def get_node_at_path(query_path, context): """Return the SqlNode associated with the query path.""" if query_path not in context.query_path_to_node: raise AssertionError( u'Unable to find SqlNode for query path {} with context {}.'.format( query_path, context)) node = con...
Return the SqlNode associated with the query path.
def _group_centroid(mol, ilabels, group_atoms): """ Calculate the centroids of a group atoms indexed by the labels of inchi Args: mol: The molecule. OpenBabel OBMol object ilabel: inchi label map Returns: Centroid. Tuple (x, y, z) """ ...
Calculate the centroids of a group atoms indexed by the labels of inchi Args: mol: The molecule. OpenBabel OBMol object ilabel: inchi label map Returns: Centroid. Tuple (x, y, z)
def create_mysql(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.mysql), **kwargs )
:rtype: Engine
def json_options_to_metadata(options, add_brackets=True): """Read metadata from its json representation""" try: options = loads('{' + options + '}' if add_brackets else options) return options except ValueError: return {}
Read metadata from its json representation
def add_announcement_view(request): """Add an announcement.""" if request.method == "POST": form = AnnouncementForm(request.POST) logger.debug(form) if form.is_valid(): obj = form.save() obj.user = request.user # SAFE HTML obj.content = saf...
Add an announcement.
def next(self): """ Next CapitainsCtsPassage (Interactive CapitainsCtsPassage) """ if self.nextId is not None: return super(CapitainsCtsPassage, self).getTextualNode(subreference=self.nextId)
Next CapitainsCtsPassage (Interactive CapitainsCtsPassage)
def tsave( text, font=DEFAULT_FONT, filename="art", chr_ignore=True, print_status=True): r""" Save ascii art (support \n). :param text: input text :param font: input font :type font:str :type text:str :param filename: output file name :type filena...
r""" Save ascii art (support \n). :param text: input text :param font: input font :type font:str :type text:str :param filename: output file name :type filename:str :param chr_ignore: ignore not supported character :type chr_ignore:bool :param print_status : save message print f...
def get_instance(self, payload): """ Build an instance of FactorInstance :param dict payload: Payload response from the API :returns: twilio.rest.authy.v1.service.entity.factor.FactorInstance :rtype: twilio.rest.authy.v1.service.entity.factor.FactorInstance """ ...
Build an instance of FactorInstance :param dict payload: Payload response from the API :returns: twilio.rest.authy.v1.service.entity.factor.FactorInstance :rtype: twilio.rest.authy.v1.service.entity.factor.FactorInstance
def fingerprints(data): """ This function return the fingerprints of data. Args: data (string): raw data Returns: namedtuple: fingerprints md5, sha1, sha256, sha512 """ Hashes = namedtuple('Hashes', "md5 sha1 sha256 sha512") if six.PY2: if not isinstance(data, str...
This function return the fingerprints of data. Args: data (string): raw data Returns: namedtuple: fingerprints md5, sha1, sha256, sha512
def get_prep_value(self, value): """ Converts a list to its json representation to store in database as text. """ if value and not isinstance(value, list): raise ValidationError(u'ListField value {} is not a list.'.format(value)) return json.dumps(self.validate_list(v...
Converts a list to its json representation to store in database as text.
def p_generate_named_block(self, p): 'generate_block : BEGIN COLON ID generate_items END' p[0] = Block(p[4], p[3], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
generate_block : BEGIN COLON ID generate_items END
def exports(self): """ Return the information exported by this distribution. :return: A dictionary of exports, mapping an export category to a dict of :class:`ExportEntry` instances describing the individual export entries, and keyed by name. """ ...
Return the information exported by this distribution. :return: A dictionary of exports, mapping an export category to a dict of :class:`ExportEntry` instances describing the individual export entries, and keyed by name.
def disassemble(self, *, transforms=None) -> Iterator[Instruction]: """ Disassembles this method, yielding an iterable of :class:`~jawa.util.bytecode.Instruction` objects. """ if transforms is None: if self.cf.classloader: transforms = self.cf.classloa...
Disassembles this method, yielding an iterable of :class:`~jawa.util.bytecode.Instruction` objects.
def mode_key_up(self, viewer, keyname): """This method is called when a key is pressed in a mode and was not handled by some other handler with precedence, such as a subcanvas. """ # Is this a mode key? if keyname not in self.mode_map: # <== no ret...
This method is called when a key is pressed in a mode and was not handled by some other handler with precedence, such as a subcanvas.
def _main(): """\ Usage: tabulate [options] [FILE ...] Pretty-print tabular data. See also https://bitbucket.org/astanin/python-tabulate FILE a filename of the file with tabular data; if "-" or missing, read data from stdin. Options: -h,...
\ Usage: tabulate [options] [FILE ...] Pretty-print tabular data. See also https://bitbucket.org/astanin/python-tabulate FILE a filename of the file with tabular data; if "-" or missing, read data from stdin. Options: -h, --help ...
def get_index_range(blockchain_name, blockchain_client, impl, working_dir): """ Get the range of block numbers that we need to fetch from the blockchain. Requires virtualchain to have been configured with setup_virtualchain() if impl=None Return None, None if we fail to connect to the blockchain ...
Get the range of block numbers that we need to fetch from the blockchain. Requires virtualchain to have been configured with setup_virtualchain() if impl=None Return None, None if we fail to connect to the blockchain
def run(self, fetch_list, feed_dict=None, sess=None): """Runs the graph with the provided feeds and fetches. This function wraps sess.Run(), but takes care of state saving and restoring by feeding in states and storing the new state values. Args: fetch_list: A list of requested output tensors. ...
Runs the graph with the provided feeds and fetches. This function wraps sess.Run(), but takes care of state saving and restoring by feeding in states and storing the new state values. Args: fetch_list: A list of requested output tensors. feed_dict: A dictionary of feeds - see Session.Run(). Opt...
def revnet_cifar_base(): """Tiny hparams suitable for CIFAR/etc.""" hparams = revnet_base() hparams.num_channels_init_block = 32 hparams.first_batch_norm = [False, True, True] hparams.init_stride = 1 hparams.init_kernel_size = 3 hparams.init_maxpool = False hparams.strides = [1, 2, 2] hparams.batch_si...
Tiny hparams suitable for CIFAR/etc.
def importElementTree(module_names=None): """Find a working ElementTree implementation, trying the standard places that such a thing might show up. >>> ElementTree = importElementTree() @param module_names: The names of modules to try to use as ElementTree. Defaults to C{L{elementtree_modules}...
Find a working ElementTree implementation, trying the standard places that such a thing might show up. >>> ElementTree = importElementTree() @param module_names: The names of modules to try to use as ElementTree. Defaults to C{L{elementtree_modules}} @returns: An ElementTree module
def _parseXml(self,cc): """ INPUT: XML file with captions OUTPUT: parsed object like: [{'texlines': [u"So, I'm going to rewrite this", 'in a more concise form as'], 'time': {'hours':'1', 'min':'2','sec':44,'msec':232} }] """ htmlpar = HTMLParser.HTMLPa...
INPUT: XML file with captions OUTPUT: parsed object like: [{'texlines': [u"So, I'm going to rewrite this", 'in a more concise form as'], 'time': {'hours':'1', 'min':'2','sec':44,'msec':232} }]
def keras_tuples(stream, inputs=None, outputs=None): """Reformat data objects as keras-compatible tuples. For more detail: https://keras.io/models/model/#fit Parameters ---------- stream : iterable Stream of data objects. inputs : string or iterable of strings, None Keys to us...
Reformat data objects as keras-compatible tuples. For more detail: https://keras.io/models/model/#fit Parameters ---------- stream : iterable Stream of data objects. inputs : string or iterable of strings, None Keys to use for ordered input data. If not specified, returns ...
def calibrate(self, max_tracks=MAX_OPTIMIZATION_TRACKS, max_eval=MAX_OPTIMIZATION_FEV, norm_c=DEFAULT_NORM_C): """Perform calibration Parameters ---------------------- max_eval : int Maximum number of function evaluations Returns --------------------- ...
Perform calibration Parameters ---------------------- max_eval : int Maximum number of function evaluations Returns --------------------- dict Optimization result Raises ----------------------- CalibrationError ...
def start(name): ''' Start the specified service CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' cmd = '/usr/sbin/svcadm enable -s -t {0}'.format(name) retcode = __salt__['cmd.retcode'](cmd, python_shell=False) if not retcode: return True ...
Start the specified service CLI Example: .. code-block:: bash salt '*' service.start <service name>
def drawdown_end(self, return_date=False): """The date of the drawdown trough. Date at which the drawdown was most negative. Parameters ---------- return_date : bool, default False If True, return a `datetime.date` object. If False, return a Pandas Times...
The date of the drawdown trough. Date at which the drawdown was most negative. Parameters ---------- return_date : bool, default False If True, return a `datetime.date` object. If False, return a Pandas Timestamp object. Returns ------- ...
def onclick(self, event): """ Draw contours on the data for a click in the thematic map :param event: mouse click on thematic map preview """ if event.inaxes == self.previewax: y, x = int(event.xdata), int(event.ydata) label = self.selection_array[x, y] ...
Draw contours on the data for a click in the thematic map :param event: mouse click on thematic map preview
def parse_from_iterable(grm, data, **kwargs): """ Parse each sentence in *data* with ACE using grammar *grm*. Args: grm (str): path to a compiled grammar image data (iterable): the sentences to parse **kwargs: additional keyword arguments to pass to the AceParser Yields: ...
Parse each sentence in *data* with ACE using grammar *grm*. Args: grm (str): path to a compiled grammar image data (iterable): the sentences to parse **kwargs: additional keyword arguments to pass to the AceParser Yields: :class:`~delphin.interfaces.ParseResponse` Example: ...
def p_feature_contains(self, t): """feature_contains : VAR CONTAINS LPAREN features RPAREN""" t[0] = Feature(t[1], t[2], Features(t[4]), line=t.lineno(1))
feature_contains : VAR CONTAINS LPAREN features RPAREN
def transitingPlanets(self): """ Returns a list of transiting planet objects """ transitingPlanets = [] for planet in self.planets: try: if planet.isTransiting: transitingPlanets.append(planet) except KeyError: # No 'discover...
Returns a list of transiting planet objects
def draw(self): """ Draw the embedded centers with their sizes on the visualization. """ # Compute the sizes of the markers from their score sizes = self._get_cluster_sizes() # Draw the scatter plots with associated sizes on the graph self.ax.scatter( ...
Draw the embedded centers with their sizes on the visualization.
def serialize(cls, share_detail): """ :type share_detail: object_.ShareDetail :rtype: dict """ return { cls._FIELD_PAYMENT: converter.serialize( share_detail._payment_field_for_request), cls._FIELD_READ_ONLY: converter.serialize( ...
:type share_detail: object_.ShareDetail :rtype: dict
def port(self): """Port part of URL, with scheme-based fallback. None for relative URLs or URLs without explicit port and scheme without default port substitution. """ return self._val.port or DEFAULT_PORTS.get(self._val.scheme)
Port part of URL, with scheme-based fallback. None for relative URLs or URLs without explicit port and scheme without default port substitution.
def _build_paths(self, name, spec_path_lists, exists): """ Given an environment variable name and specified paths, return a pathsep-separated string of paths containing unique, extant, directories from those paths and from the environment variable. Raise an error if no paths ...
Given an environment variable name and specified paths, return a pathsep-separated string of paths containing unique, extant, directories from those paths and from the environment variable. Raise an error if no paths are resolved.
def print_KruskalWallisH(div_calc): """ Compute the Kruskal-Wallis H-test for independent samples. A typical rule is that each group must have at least 5 measurements. """ calc = defaultdict(list) try: for k1, v1 in div_calc.iteritems(): for k2, v2 in v1.iteritems(): ...
Compute the Kruskal-Wallis H-test for independent samples. A typical rule is that each group must have at least 5 measurements.
def raw_channel_mentions(self): """A property that returns an array of channel IDs matched with the syntax of <#channel_id> in the message content. """ return [int(x) for x in re.findall(r'<#([0-9]+)>', self.content)]
A property that returns an array of channel IDs matched with the syntax of <#channel_id> in the message content.
def _to_str(uri: URIRef) -> str: """ Convert a FHIR style URI into a tag name to be used to retrieve data from a JSON representation Example: http://hl7.org/fhir/Provenance.agent.whoReference --> whoReference :param uri: URI to convert :return: tag name """ local_...
Convert a FHIR style URI into a tag name to be used to retrieve data from a JSON representation Example: http://hl7.org/fhir/Provenance.agent.whoReference --> whoReference :param uri: URI to convert :return: tag name
def read(self, size=None): """Reads a byte string from the file-like object at the current offset. The function will read a byte string of the specified size or all of the remaining data if no size was specified. Args: size (Optional[int]): number of bytes to read, where None is all re...
Reads a byte string from the file-like object at the current offset. The function will read a byte string of the specified size or all of the remaining data if no size was specified. Args: size (Optional[int]): number of bytes to read, where None is all remaining data. Returns: ...
def parse_requirements( requirements_path: str = 'requirements.txt') -> t.List[str]: """Read contents of requirements.txt file and return data from its relevant lines. Only non-empty and non-comment lines are relevant. """ requirements = [] with HERE.joinpath(requirements_path).open() as re...
Read contents of requirements.txt file and return data from its relevant lines. Only non-empty and non-comment lines are relevant.
def img2img_transformer2d_n31(): """Set of hyperparameters.""" hparams = img2img_transformer2d_base() hparams.batch_size = 1 hparams.num_encoder_layers = 6 hparams.num_decoder_layers = 12 hparams.num_heads = 8 hparams.query_shape = (16, 32) hparams.memory_flange = (16, 32) return hparams
Set of hyperparameters.
def to_string( self, indentLevel=1, title=True, tags=None, projects=None, tasks=None, notes=None): """*convert this taskpaper object to a string* **Key Arguments:** - ``indentLevel`` -- the level of the inde...
*convert this taskpaper object to a string* **Key Arguments:** - ``indentLevel`` -- the level of the indent for this object. Default *1*. - ``title`` -- print the title of the taskpaper object alongside the contents. Default *True* - ``tags`` -- replace tags with these tags....
def _validate_data(dataset, target, features=None, validation_set='auto'): """ Validate and canonicalize training and validation data. Parameters ---------- dataset : SFrame Dataset for training the model. target : string Name of the column containing the target variable. ...
Validate and canonicalize training and validation data. Parameters ---------- dataset : SFrame Dataset for training the model. target : string Name of the column containing the target variable. features : list[string], optional List of feature names used. validation_s...
def get_insights_for_project(self, project_owner, project_id, **kwargs): """ Get insights for project. Get insights for a project. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invo...
Get insights for project. Get insights for a project. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> ...
def DecodePacket(self, packet): """Initialize the object from raw packet data. Decode a packet as received from the network and decode it. :param packet: raw packet :type packet: string""" try: (self.code, self.id, length, self.authenticator) = \ ...
Initialize the object from raw packet data. Decode a packet as received from the network and decode it. :param packet: raw packet :type packet: string
def revoker(self, revoker, **prefs): """ Generate a signature that specifies another key as being valid for revoking this key. :param revoker: The :py:obj:`PGPKey` to specify as a valid revocation key. :type revoker: :py:obj:`PGPKey` :raises: :py:exc:`~pgpy.errors.PGPError` if t...
Generate a signature that specifies another key as being valid for revoking this key. :param revoker: The :py:obj:`PGPKey` to specify as a valid revocation key. :type revoker: :py:obj:`PGPKey` :raises: :py:exc:`~pgpy.errors.PGPError` if the key is passphrase-protected and has not been unlocked ...
def get_stp_mst_detail_output_msti_port_oper_bpdu_guard(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_stp_mst_detail = ET.Element("get_stp_mst_detail") config = get_stp_mst_detail output = ET.SubElement(get_stp_mst_detail, "output") ...
Auto Generated Code
def evaluate_rmse(self, dataset, target): """ Evaluate the prediction error for each user-item pair in the given data set. Parameters ---------- dataset : SFrame An SFrame in the same format as the one used during training. target : str T...
Evaluate the prediction error for each user-item pair in the given data set. Parameters ---------- dataset : SFrame An SFrame in the same format as the one used during training. target : str The name of the target rating column in `dataset`. Ret...
def identify_core(core): """Identify the polynomial argument.""" for datatype, identifier in { int: _identify_scaler, numpy.int8: _identify_scaler, numpy.int16: _identify_scaler, numpy.int32: _identify_scaler, numpy.int64: _identify_scaler, ...
Identify the polynomial argument.
def _create_list_of_array_controllers(self): """Creates the list of Array Controller URIs. :raises: IloCommandNotSupportedError if the ArrayControllers doesnt have member "Member". :returns list of ArrayControllers. """ headers, array_uri, array_settings = ( ...
Creates the list of Array Controller URIs. :raises: IloCommandNotSupportedError if the ArrayControllers doesnt have member "Member". :returns list of ArrayControllers.
def queue_declare(self, queue, durable, exclusive, auto_delete, warn_if_exists=False, arguments=None): """Declare a named queue.""" return self.channel.queue_declare(queue=queue, durable=durable, exclusive=e...
Declare a named queue.
def parse_number_list(x, dtype=None): """Parse NRRD number list from string into (N,) :class:`numpy.ndarray`. See :ref:`user-guide:int list` and :ref:`user-guide:double list` for more information on the format. Parameters ---------- x : :class:`str` String containing NRRD number list d...
Parse NRRD number list from string into (N,) :class:`numpy.ndarray`. See :ref:`user-guide:int list` and :ref:`user-guide:double list` for more information on the format. Parameters ---------- x : :class:`str` String containing NRRD number list dtype : data-type, optional Datatype t...
def _exec_command(self, cmd): """Run a command on the remote SSH server. Returns: bytes: the output of the command, if it didn't fail None: if the error pipe of the command was not empty """ _, out, err = self._client.exec_command(cmd, timeout=self._timeout) ...
Run a command on the remote SSH server. Returns: bytes: the output of the command, if it didn't fail None: if the error pipe of the command was not empty
def compute_md5_for_file_asbase64( filename, pagealign=False, start=None, end=None, blocksize=65536): # type: (str, bool, int, int, int) -> str """Compute MD5 hash for file and encode as Base64 :param str filename: file to compute MD5 for :param bool pagealign: page align data :param int sta...
Compute MD5 hash for file and encode as Base64 :param str filename: file to compute MD5 for :param bool pagealign: page align data :param int start: file start offset :param int end: file end offset :param int blocksize: block size :rtype: str :return: MD5 for file encoded as Base64
def find_all(self, header, list_type=None): """Find all direct children with header and optional list type.""" found = [] for chunk in self: if chunk.header == header and (not list_type or (header in list_headers and chunk.type == list_type)): found.ap...
Find all direct children with header and optional list type.
def run(self): """Run self.rules_list. Return True if one rule channel has been passed. Otherwise return False and the deny() method of the last failed rule. """ failed_result = None for rule in self.rules_list: for check, deny in rule: if not...
Run self.rules_list. Return True if one rule channel has been passed. Otherwise return False and the deny() method of the last failed rule.
def run(self): """Listener method that keeps pulling new messages.""" t_last_click = -1 while True: d = self.device.read(13) if d is not None and self._enabled: if d[0] == 1: ## readings from 6-DoF sensor self.y = convert(d[1], d[2]...
Listener method that keeps pulling new messages.
def _parse_resources(resource_values: dict, resource_name: str) -> dict: """Parse resources key. Args: resource_values (dict): resource configurations values resource_name (string): Resource name Returns: dict, resources specification """ # ...
Parse resources key. Args: resource_values (dict): resource configurations values resource_name (string): Resource name Returns: dict, resources specification
def get_axes(x, y): """ computes the axis x and y of a given 2d grid :param x: :param y: :return: """ n=int(np.sqrt(len(x))) if n**2 != len(x): raise ValueError("lenght of input array given as %s is not square of integer number!" % (len(x))) x_image = x.reshape(n,n) y_ima...
computes the axis x and y of a given 2d grid :param x: :param y: :return:
def disconnect(remote): """Disconnect callback handler for GitHub.""" # User must be authenticated if not current_user.is_authenticated: return current_app.login_manager.unauthorized() external_method = 'github' external_ids = [i.id for i in current_user.external_identifiers ...
Disconnect callback handler for GitHub.
def stick_perm(presenter, egg, dist_dict, strategy): """Computes weights for one reordering using stick-breaking method""" # seed RNG np.random.seed() # unpack egg egg_pres, egg_rec, egg_features, egg_dist_funcs = parse_egg(egg) # reorder regg = order_stick(presenter, egg, dist_dict, stra...
Computes weights for one reordering using stick-breaking method
def get_person_by_prox_rfid(self, prox_rfid): """ Returns a restclients.Person object for the given rfid. If the rfid isn't found, or if there is an error communicating with the IdCard WS, a DataFailureException will be thrown. """ if not self.valid_prox_rfid(prox_rfid):...
Returns a restclients.Person object for the given rfid. If the rfid isn't found, or if there is an error communicating with the IdCard WS, a DataFailureException will be thrown.
def equipped(self): """ Returns a dict of classes that have the item equipped and in what slot """ equipped = self._item.get("equipped", []) # WORKAROUND: 0 is probably an off-by-one error # WORKAROUND: 65535 actually serves a purpose (according to Valve) return dict([(eq["class...
Returns a dict of classes that have the item equipped and in what slot
def mouseDoubleClickEvent(self, event): """ Overloads when a mouse press occurs. If in editable mode, and the click occurs on a selected index, then the editor will be created and no selection change will occur. :param event | <QMousePressEvent> """ ...
Overloads when a mouse press occurs. If in editable mode, and the click occurs on a selected index, then the editor will be created and no selection change will occur. :param event | <QMousePressEvent>
def close(self): ''' Terminates the session. It schedules the ``close()`` coroutine of the underlying aiohttp session and then enqueues a sentinel object to indicate termination. Then it waits until the worker thread to self-terminate by joining. ''' if self._cl...
Terminates the session. It schedules the ``close()`` coroutine of the underlying aiohttp session and then enqueues a sentinel object to indicate termination. Then it waits until the worker thread to self-terminate by joining.
def fmin(objective_function, x0, sigma0, options=None, args=(), gradf=None, restarts=0, restart_from_best='False', incpopsize=2, eval_initial_x=False, noise_handler=None, noise_change_sigma_exponent=1, noise_kappa_exponent=0, # T...
functional interface to the stochastic optimizer CMA-ES for non-convex function minimization. Calling Sequences ================= ``fmin(objective_function, x0, sigma0)`` minimizes `objective_function` starting at `x0` and with standard deviation `sigma0` (step-size) ...
def updateUser(self, username, password, fullname, description, email): """ Updates a user account in the user store Input: username - the name of the user. The name must be unique in the user store. password - the password for this user. ...
Updates a user account in the user store Input: username - the name of the user. The name must be unique in the user store. password - the password for this user. fullname - an optional full name for the user. description - an o...
def code128(self, data, **kwargs): """Renders given ``data`` as **Code 128** barcode symbology. :param str codeset: Optional. Keyword argument for the subtype (code set) to render. Defaults to :attr:`escpos.barcode.CODE128_A`. .. warning:: You should draw up your data ...
Renders given ``data`` as **Code 128** barcode symbology. :param str codeset: Optional. Keyword argument for the subtype (code set) to render. Defaults to :attr:`escpos.barcode.CODE128_A`. .. warning:: You should draw up your data according to the subtype (code set). ...
def _get(self, key, identity='image'): """ Deserializing, prefix wrapper for _get_raw """ value = self._get_raw(add_prefix(key, identity)) if not value: return None if identity == 'image': return deserialize_image_file(value) return dese...
Deserializing, prefix wrapper for _get_raw
def on_draw(): global yrot win.clear() glLoadIdentity() glTranslatef(0, 0, -100) glRotatef(yrot, 0.0, 1.0, 0.0) default_system.draw() ''' glBindTexture(GL_TEXTURE_2D, 1) glEnable(GL_TEXTURE_2D) glEnable(GL_POINT_SPRITE) glPointSize(100); glBegin(GL_POINTS) glVertex2f(0,0) glEnd() glBindTexture(GL_TEXTURE...
glBindTexture(GL_TEXTURE_2D, 1) glEnable(GL_TEXTURE_2D) glEnable(GL_POINT_SPRITE) glPointSize(100); glBegin(GL_POINTS) glVertex2f(0,0) glEnd() glBindTexture(GL_TEXTURE_2D, 2) glEnable(GL_TEXTURE_2D) glEnable(GL_POINT_SPRITE) glPointSize(100); glBegin(GL_POINTS) glVertex2f(50,0) glEnd() glBindTexture(GL_TE...
def write_waypoint(self, latitude=None, longitude=None, description=None): """ Adds a waypoint to the current task declaration. The first and the last waypoint added will be treated as takeoff and landing location, respectively. :: writer.write_waypoint( ...
Adds a waypoint to the current task declaration. The first and the last waypoint added will be treated as takeoff and landing location, respectively. :: writer.write_waypoint( latitude=(51 + 7.345 / 60.), longitude=(6 + 24.765 / 60.), ...
def revoke_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ REVOKES/INVALIDATES a filtered list of vouchers. :type vid_encoded: ...
REVOKES/INVALIDATES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` ...
def directional_irradiance(self, altitude=90, azimuth=180, ground_reflectance=0.2, isotrophic=True): """Returns the irradiance components facing a given altitude and azimuth. This method computes unobstructed solar flux facing a given altitude and azimuth. The def...
Returns the irradiance components facing a given altitude and azimuth. This method computes unobstructed solar flux facing a given altitude and azimuth. The default is set to return the golbal horizontal irradiance, assuming an altitude facing straight up (90 degrees). Args: ...
def copy(self, key=None): """ Return a new collection with the same items as this one. If *key* is specified, create the new collection with the given Redis key. """ other = self.__class__(redis=self.redis, key=key) other.update(self) return other
Return a new collection with the same items as this one. If *key* is specified, create the new collection with the given Redis key.
def search(self, text): """ Find text in log file from current position returns a tuple containing: absolute position, position in result buffer, result buffer (the actual file contents) """ key = hash(text) searcher = self._searchers....
Find text in log file from current position returns a tuple containing: absolute position, position in result buffer, result buffer (the actual file contents)
def run(self, path, pretend=False): """ Run the outstanding migrations for a given path. :param path: The path :type path: str :param pretend: Whether we execute the migrations as dry-run :type pretend: bool """ self._notes = [] files = self._get...
Run the outstanding migrations for a given path. :param path: The path :type path: str :param pretend: Whether we execute the migrations as dry-run :type pretend: bool
def iter_elements(element_function, parent_to_parse, **kwargs): """ Applies element_function to each of the sub-elements in parent_to_parse. The passed in function must take at least one element, and an optional list of kwargs which are relevant to each of the elements in the list: def elem_func...
Applies element_function to each of the sub-elements in parent_to_parse. The passed in function must take at least one element, and an optional list of kwargs which are relevant to each of the elements in the list: def elem_func(each_elem, **kwargs)
def get_item_ids_by_banks(self, bank_ids): """Gets the list of ``Item Ids`` corresponding to a list of ``Banks``. arg: bank_ids (osid.id.IdList): list of bank ``Ids`` return: (osid.id.IdList) - list of bank ``Ids`` raise: NullArgument - ``bank_ids`` is ``null`` raise: Opera...
Gets the list of ``Item Ids`` corresponding to a list of ``Banks``. arg: bank_ids (osid.id.IdList): list of bank ``Ids`` return: (osid.id.IdList) - list of bank ``Ids`` raise: NullArgument - ``bank_ids`` is ``null`` raise: OperationFailed - unable to complete request raise:...
def close(self): """Unsubscribe the group and all jobs being listened too""" for channel in self._listening_to: self.toredis.unsubscribe(channel) self.toredis.unsubscribe(self.group_pubsub)
Unsubscribe the group and all jobs being listened too
def check_unknown_fields(self, data, original_data): """Check for unknown keys.""" if isinstance(original_data, list): for elem in original_data: self.check_unknown_fields(data, elem) else: for key in original_data: if key not in [ ...
Check for unknown keys.
def save_dir(key, dir_path, *refs): """Convert the given parameters to a special JSON object. JSON object is of the form: { key: {"dir": dir_path}}, or { key: {"dir": dir_path, "refs": [refs[0], refs[1], ... ]}} """ if not os.path.isdir(dir_path): return error( "Output '{}'...
Convert the given parameters to a special JSON object. JSON object is of the form: { key: {"dir": dir_path}}, or { key: {"dir": dir_path, "refs": [refs[0], refs[1], ... ]}}
def K_tilting_disk_check_valve_Crane(D, angle, fd=None): r'''Returns the loss coefficient for a tilting disk check valve as shown in [1]_. Results are specified in [1]_ to be for the disk's resting position to be at 5 or 25 degrees to the flow direction. The model is implemented here so as to switch to...
r'''Returns the loss coefficient for a tilting disk check valve as shown in [1]_. Results are specified in [1]_ to be for the disk's resting position to be at 5 or 25 degrees to the flow direction. The model is implemented here so as to switch to the higher loss 15 degree coefficients at 10 degrees, a...
def exists(self, workflow_id): """ Checks whether a document with the specified workflow id already exists. Args: workflow_id (str): The workflow id that should be checked. Raises: DataStoreNotConnected: If the data store is not connected to the server. Returns...
Checks whether a document with the specified workflow id already exists. Args: workflow_id (str): The workflow id that should be checked. Raises: DataStoreNotConnected: If the data store is not connected to the server. Returns: bool: ``True`` if a document ...
def __iter_read_spectrum_meta(self): """ This method should only be called by __init__. Reads the data formats, coordinates and offsets from the .imzML file and initializes the respective attributes. While traversing the XML tree, the per-spectrum metadata is pruned, i.e. the <spectrumLi...
This method should only be called by __init__. Reads the data formats, coordinates and offsets from the .imzML file and initializes the respective attributes. While traversing the XML tree, the per-spectrum metadata is pruned, i.e. the <spectrumList> element(s) are left behind empty. Supported ...
def plot_power_factor_mu(self, temp=600, output='eig', relaxation_time=1e-14, xlim=None): """ Plot the power factor in function of Fermi level. Semi-log plot Args: temp: the temperature xlim: a list of min and max fermi energy by default (0, ...
Plot the power factor in function of Fermi level. Semi-log plot Args: temp: the temperature xlim: a list of min and max fermi energy by default (0, and band gap) tau: A relaxation time in s. By default none and the plot is by units of relaxatio...
def _handle_rfx(self, data): """ Handle RF messages. :param data: RF message to parse :type data: string :returns: :py:class:`~alarmdecoder.messages.RFMessage` """ msg = RFMessage(data) self.on_rfx_message(message=msg) return msg
Handle RF messages. :param data: RF message to parse :type data: string :returns: :py:class:`~alarmdecoder.messages.RFMessage`
def until_protocol(self, timeout=None): """Return future that resolves after receipt of katcp protocol info. If the returned future resolves, the server's protocol information is available in the ProtocolFlags instance self.protocol_flags. """ t0 = self.ioloop.time() yi...
Return future that resolves after receipt of katcp protocol info. If the returned future resolves, the server's protocol information is available in the ProtocolFlags instance self.protocol_flags.
def fetch_mid(self): """ Gets the next valid MID. :return: the mid to use """ current_mid = self._current_mid self._current_mid += 1 self._current_mid %= 65535 return current_mid
Gets the next valid MID. :return: the mid to use
def _find_executable(prog, pathext=("",)): """protected""" pathlist = _decode_if_not_text(os.environ.get('PATH', '')).split(os.pathsep) for dir in pathlist: for ext in pathext: filename = os.path.join(dir, prog + ext) try: st = os.stat(filename) e...
protected
def set_avatar(self, avatar, subject_descriptor): """SetAvatar. [Preview API] :param :class:`<Avatar> <azure.devops.v5_1.graph.models.Avatar>` avatar: :param str subject_descriptor: """ route_values = {} if subject_descriptor is not None: route_values[...
SetAvatar. [Preview API] :param :class:`<Avatar> <azure.devops.v5_1.graph.models.Avatar>` avatar: :param str subject_descriptor:
def register_prop(name, handler_get, handler_set): """ register a property handler """ global props_get, props_set if handler_get: props_get[name] = handler_get if handler_set: props_set[name] = handler_set
register a property handler
def image_linear_solve(self, kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_ps, inv_bool=False): """ computes the image (lens and source surface brightness with a given lens model). The linear parameters are computed with a weighted linear least square optimization (i.e. flux normalizatio...
computes the image (lens and source surface brightness with a given lens model). The linear parameters are computed with a weighted linear least square optimization (i.e. flux normalization of the brightness profiles) :param kwargs_lens: list of keyword arguments corresponding to the superposition of di...
def add_variables_from(self, linear, vartype=None): """Add variables and/or linear biases to a binary quadratic model. Args: linear (dict[variable, bias]/iterable[(variable, bias)]): A collection of variables and their linear biases to add to the model. If a ...
Add variables and/or linear biases to a binary quadratic model. Args: linear (dict[variable, bias]/iterable[(variable, bias)]): A collection of variables and their linear biases to add to the model. If a dict, keys are variables in the binary quadratic model and ...
def get_placeholder_data(self, request, obj=None): """ Return the data of the placeholder fields. """ # Return all placeholder fields in the model. if not hasattr(self.model, '_meta_placeholder_fields'): return [] data = [] for name, field in self.mod...
Return the data of the placeholder fields.
def load(self): """ Extract tabular data as |TableData| instances from a CSV text object. |load_source_desc_text| :return: Loaded table data. |load_table_name_desc| =================== ======================================== Format spec...
Extract tabular data as |TableData| instances from a CSV text object. |load_source_desc_text| :return: Loaded table data. |load_table_name_desc| =================== ======================================== Format specifier Value after the replacemen...
def of_type(self, classinfo): '''Filters elements according to whether they are of a certain type. Note: This method uses deferred execution. Args: classinfo: If classinfo is neither a class object nor a type object it may be a tuple of class or type objects, or may...
Filters elements according to whether they are of a certain type. Note: This method uses deferred execution. Args: classinfo: If classinfo is neither a class object nor a type object it may be a tuple of class or type objects, or may recursively contain othe...
def pre_run_cell(self, cellno, code): """Executes before the user-entered code in `ipython` is run. This intercepts loops and other problematic code that would produce lots of database entries and streamlines it to produce only a single entry. Args: cellno (int): the cell nu...
Executes before the user-entered code in `ipython` is run. This intercepts loops and other problematic code that would produce lots of database entries and streamlines it to produce only a single entry. Args: cellno (int): the cell number that is about to be executed. co...
def measurements_methods(meas_data, noave): """ get list of unique specs """ # version_num = get_version() sids = get_specs(meas_data) # list of measurement records for this specimen # # step through spec by spec # SpecTmps, SpecOuts = [], [] for spec in sids: TRM, IRM3D, ATRM, CR =...
get list of unique specs