code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def build_command_tree(pattern, cmd_params): """ Recursively fill in a command tree in cmd_params according to a docopt-parsed "pattern" object. """ from docopt import Either, Optional, OneOrMore, Required, Option, Command, Argument if type(pattern) in [Either, Optional, OneOrMore]: for chil...
Recursively fill in a command tree in cmd_params according to a docopt-parsed "pattern" object.
def append_columns(self, colnames, values, **kwargs): """Append new columns to the table. When appending a single column, ``values`` can be a scalar or an array of either length 1 or the same length as this array (the one it's appended to). In case of multiple columns, values must have ...
Append new columns to the table. When appending a single column, ``values`` can be a scalar or an array of either length 1 or the same length as this array (the one it's appended to). In case of multiple columns, values must have the shape ``list(arrays)``, and the dimension of each arr...
def getPeer(self, url): """ Finds a peer by URL and return the first peer record with that URL. """ peers = list(models.Peer.select().where(models.Peer.url == url)) if len(peers) == 0: raise exceptions.PeerNotFoundException(url) return peers[0]
Finds a peer by URL and return the first peer record with that URL.
def _parse_table( self, parent_name=None ): # type: (Optional[str]) -> Tuple[Key, Union[Table, AoT]] """ Parses a table element. """ if self._current != "[": raise self.parse_error( InternalParserError, "_parse_table() called on non-bracket charac...
Parses a table element.
def addresses_for_key(gpg, key): """ Takes a key and extracts the email addresses for it. """ fingerprint = key["fingerprint"] addresses = [] for key in gpg.list_keys(): if key["fingerprint"] == fingerprint: addresses.extend([address.split("<")[-1].strip(">") ...
Takes a key and extracts the email addresses for it.
def put(self, key, value, minutes): """ Store an item in the cache for a given number of minutes. :param key: The cache key :type key: str :param value: The cache value :type value: mixed :param minutes: The lifetime in minutes of the cached value :type...
Store an item in the cache for a given number of minutes. :param key: The cache key :type key: str :param value: The cache value :type value: mixed :param minutes: The lifetime in minutes of the cached value :type minutes: int or datetime
def execute(self, command): """ Executes command on remote hosts :type command: str :param command: command to be run on remote host """ try: if self.ssh.get_transport() is not None: logger.debug('{0}: executing "{1}"'.format(self.target_addre...
Executes command on remote hosts :type command: str :param command: command to be run on remote host
def load_tf_weights_in_transfo_xl(model, config, tf_path): """ Load tf checkpoints in a pytorch model """ try: import numpy as np import tensorflow as tf except ImportError: print("Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see " ...
Load tf checkpoints in a pytorch model
def strains(self): """ Create a dictionary of SEQID: OLNID from the supplied """ with open(os.path.join(self.path, 'strains.csv')) as strains: next(strains) for line in strains: oln, seqid = line.split(',') self.straindict[oln] = se...
Create a dictionary of SEQID: OLNID from the supplied
async def get_messages(self, name): """Get stored messages for a service. Args: name (string): The name of the service to get messages from. Returns: list(ServiceMessage): A list of the messages stored for this service """ resp = await self.send_command...
Get stored messages for a service. Args: name (string): The name of the service to get messages from. Returns: list(ServiceMessage): A list of the messages stored for this service
def encode_request(name, expected, updated): """ Encode request into client_message""" client_message = ClientMessage(payload_size=calculate_size(name, expected, updated)) client_message.set_message_type(REQUEST_TYPE) client_message.set_retryable(RETRYABLE) client_message.append_str(name) client...
Encode request into client_message
def defaulted_config(modules, params=None, yaml=None, filename=None, config=None, validate=True): """Context manager version of :func:`set_default_config()`. Use this with a Python 'with' statement, like >>> config_yaml = ''' ... toplevel: ... param: value ... ''' >>...
Context manager version of :func:`set_default_config()`. Use this with a Python 'with' statement, like >>> config_yaml = ''' ... toplevel: ... param: value ... ''' >>> with yakonfig.defaulted_config([toplevel], yaml=config_yaml) as config: ... assert 'param' in config['toplevel'] ...
def from_coeff(self, chebcoeff, domain=None, prune=True, vscale=1.): """ Initialise from provided coefficients prune: Whether to prune the negligible coefficients vscale: the scale to use when pruning """ coeffs = np.asarray(chebcoeff) if prune: N = se...
Initialise from provided coefficients prune: Whether to prune the negligible coefficients vscale: the scale to use when pruning
def get_random(min_pt, max_pt): """Returns a random vector in the given range.""" result = Point(random.random(), random.random()) return result.get_component_product(max_pt - min_pt) + min_pt
Returns a random vector in the given range.
def list_subcommand(vcard_list, parsable): """Print a user friendly contacts table. :param vcard_list: the vcards to print :type vcard_list: list of carddav_object.CarddavObject :param parsable: machine readable output: columns devided by tabulator (\t) :type parsable: bool :returns: None :...
Print a user friendly contacts table. :param vcard_list: the vcards to print :type vcard_list: list of carddav_object.CarddavObject :param parsable: machine readable output: columns devided by tabulator (\t) :type parsable: bool :returns: None :rtype: None
def _init(self, run_conf, run_number=None): '''Initialization before a new run. ''' self.stop_run.clear() self.abort_run.clear() self._run_status = run_status.running self._write_run_number(run_number) self._init_run_conf(run_conf)
Initialization before a new run.
def interpolate(self, factor, minKerning, maxKerning, round=True, suppressError=True): """ Interpolates all pairs between two :class:`BaseKerning` objects: **minKerning** and **maxKerning**. The interpolation occurs on a 0 to 1.0 range where **minKerning** is located at 0 and **...
Interpolates all pairs between two :class:`BaseKerning` objects: **minKerning** and **maxKerning**. The interpolation occurs on a 0 to 1.0 range where **minKerning** is located at 0 and **maxKerning** is located at 1.0. The kerning data is replaced by the interpolated kerning. ...
def construct(self, request, service=None, http_args=None, **kwargs): """ Constructs a client assertion and signs it with a key. The request is modified as a side effect. :param request: The request :param service: A :py:class:`oidcservice.service.Service` instance :para...
Constructs a client assertion and signs it with a key. The request is modified as a side effect. :param request: The request :param service: A :py:class:`oidcservice.service.Service` instance :param http_args: HTTP arguments :param kwargs: Extra arguments :return: Constr...
def getAccountInfo(self, fields=None): """Use this method to get information about a Telegraph account. :param fields: List of account fields to return. Available fields: short_name, author_name, author_url, auth_url, page_count. :type fields: list :returns: Account obje...
Use this method to get information about a Telegraph account. :param fields: List of account fields to return. Available fields: short_name, author_name, author_url, auth_url, page_count. :type fields: list :returns: Account object on success.
def path(self, path): """ Path of the IOU executable. :param path: path to the IOU image executable """ self._path = self.manager.get_abs_image_path(path) log.info('IOU "{name}" [{id}]: IOU image updated to "{path}"'.format(name=self._name, id=self._id, path=self._path)...
Path of the IOU executable. :param path: path to the IOU image executable
def run(self): """ Statistics logger job callback. """ try: proxy = config_ini.engine.open() self.LOG.info("Stats for %s - up %s, %s" % ( config_ini.engine.engine_id, fmt.human_duration(proxy.system.time() - config_ini.engine.startup, 0, 2,...
Statistics logger job callback.
async def chat_send(self, message: str, team_only: bool): """ Writes a message to the chat """ ch = ChatChannel.Team if team_only else ChatChannel.Broadcast await self._execute( action=sc_pb.RequestAction( actions=[sc_pb.Action(action_chat=sc_pb.ActionChat(channel=ch....
Writes a message to the chat
def _msg(self, label, *msg): """ Prints a message with a label """ if self.quiet is False: txt = self._unpack_msg(*msg) print("[" + label + "] " + txt)
Prints a message with a label
def random_filtered_sources(sources, srcfilter, seed): """ :param sources: a list of sources :param srcfilte: a SourceFilter instance :param seed: a random seed :returns: an empty list or a list with a single filtered source """ random.seed(seed) while sources: src = random.choic...
:param sources: a list of sources :param srcfilte: a SourceFilter instance :param seed: a random seed :returns: an empty list or a list with a single filtered source
def _schema(self, path, obj, app): """ fulfill 'name' field for objects under '#/definitions' and with 'properties' """ if path.startswith('#/definitions'): last_token = jp_split(path)[-1] if app.version == '1.2': obj.update_field('name', scope_spl...
fulfill 'name' field for objects under '#/definitions' and with 'properties'
def _get_api_content(self): """Updates class api content by calling Github api and storing result""" if GITHUB_TOKEN is not None: self.add_params_to_url({ "access_token": GITHUB_TOKEN }) api_content_response = requests.get(self.api_url) self.api_...
Updates class api content by calling Github api and storing result
def category(self, value): """ Setter for **self.__category** attribute. :param value: Attribute value. :type value: unicode """ if value is not None: assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format( "cat...
Setter for **self.__category** attribute. :param value: Attribute value. :type value: unicode
def character_to_vk(self, character): """ Returns a tuple of (scan_code, modifiers) where ``scan_code`` is a numeric scan code and ``modifiers`` is an array of string modifier names (like 'shift') """ for vk in self.non_layout_keys: if self.non_layout_keys[vk] == character.lower(): ...
Returns a tuple of (scan_code, modifiers) where ``scan_code`` is a numeric scan code and ``modifiers`` is an array of string modifier names (like 'shift')
def sky_bbox_ll(self): """ The sky coordinates of the lower-left vertex of the minimal bounding box of the source segment, returned as a `~astropy.coordinates.SkyCoord` object. The bounding box encloses all of the source segment pixels in their entirety, thus the vertice...
The sky coordinates of the lower-left vertex of the minimal bounding box of the source segment, returned as a `~astropy.coordinates.SkyCoord` object. The bounding box encloses all of the source segment pixels in their entirety, thus the vertices are at the pixel *corners*.
def _refresh_channel(self): ''' Reset the channel, in the event of an interruption ''' self.channel = salt.transport.client.ReqChannel.factory(self.opts) return self.channel
Reset the channel, in the event of an interruption
def column_types(self): """Return a dict mapping column name to type for all columns in table """ column_types = {} for c in self.sqla_columns: column_types[c.name] = c.type return column_types
Return a dict mapping column name to type for all columns in table
def delete(method, hmc, uri, uri_parms, logon_required): """Operation: Delete Hipersocket (requires DPM mode).""" try: adapter = hmc.lookup_by_uri(uri) except KeyError: raise InvalidResourceError(method, uri) cpc = adapter.manager.parent assert cpc.dpm_ena...
Operation: Delete Hipersocket (requires DPM mode).
def convert_descriptor_and_rows(self, descriptor, rows): """Convert descriptor and rows to Pandas """ # Prepare primary_key = None schema = tableschema.Schema(descriptor) if len(schema.primary_key) == 1: primary_key = schema.primary_key[0] elif len(sc...
Convert descriptor and rows to Pandas
def _set_neighbor_route_map_name_direction_out(self, v, load=False): """ Setter method for neighbor_route_map_name_direction_out, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/ipv6/ipv6_unicast/af_ipv6_vrf/neighbor/af_ipv6_vrf_neighbor_address_holder/af_ipv6_neighbor_addr/neighbor_route...
Setter method for neighbor_route_map_name_direction_out, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/ipv6/ipv6_unicast/af_ipv6_vrf/neighbor/af_ipv6_vrf_neighbor_address_holder/af_ipv6_neighbor_addr/neighbor_route_map/neighbor_route_map_direction_out/neighbor_route_map_name_direction_out (comm...
def event(self, event_data, priority="normal", event_method="EVENT"): """This function will send event packets to the server. This is the main method you would use to send data from your application to the server. Whenever an event is sent to the server, a universally unique event id ...
This function will send event packets to the server. This is the main method you would use to send data from your application to the server. Whenever an event is sent to the server, a universally unique event id (euuid) is created for each event and stored in the "event_uuids" d...
def filter_kepler_lcdict(lcdict, filterflags=True, nanfilter='sap,pdc', timestoignore=None): '''This filters the Kepler `lcdict`, removing nans and bad observations. By default, this function removes points in the Kepler LC that hav...
This filters the Kepler `lcdict`, removing nans and bad observations. By default, this function removes points in the Kepler LC that have ANY quality flags set. Parameters ---------- lcdict : lcdict An `lcdict` produced by `consolidate_kepler_fitslc` or `read_kepler_fitslc`. ...
def get_selections(pattern=None, state=None): ''' View package state from the dpkg database. Returns a dict of dicts containing the state, and package names: .. code-block:: python {'<host>': {'<state>': ['pkg1', ... ] }...
View package state from the dpkg database. Returns a dict of dicts containing the state, and package names: .. code-block:: python {'<host>': {'<state>': ['pkg1', ... ] }, ... } CLI Example: .. code...
def hard_equals(a, b): """Implements the '===' operator.""" if type(a) != type(b): return False return a == b
Implements the '===' operator.
def set_parameter(self, name, value): """Sets a parameter for the BaseForecastingMethod. :param string name: Name of the parameter. :param numeric value: Value of the parameter. """ # set the furecast until variable to None if necessary if name == "valuesToForecast...
Sets a parameter for the BaseForecastingMethod. :param string name: Name of the parameter. :param numeric value: Value of the parameter.
def from_bma_history(cls: Type[TransactionType], currency: str, tx_data: Dict) -> TransactionType: """ Get the transaction instance from json :param currency: the currency of the tx :param tx_data: json data of the transaction :return: """ tx_data = tx_data.copy...
Get the transaction instance from json :param currency: the currency of the tx :param tx_data: json data of the transaction :return:
def authorized_tenants(self): """Returns a memoized list of tenants this user may access.""" if self.is_authenticated and self._authorized_tenants is None: endpoint = self.endpoint try: self._authorized_tenants = utils.get_project_list( user_id...
Returns a memoized list of tenants this user may access.
def img(self): '''return a cv image for the icon''' SlipThumbnail.img(self) if self.rotation: # rotate the image mat = cv.CreateMat(2, 3, cv.CV_32FC1) cv.GetRotationMatrix2D((self.width/2,self.height/2), -self.rotation, 1.0,...
return a cv image for the icon
def point_in_circle(pt, center, radius): ''' Returns true if a given point is located inside (or on the border) of a circle. >>> point_in_circle((0, 0), (0, 0), 1) True >>> point_in_circle((1, 0), (0, 0), 1) True >>> point_in_circle((1, 1), (0, 0), 1) False ''' d = np.linalg...
Returns true if a given point is located inside (or on the border) of a circle. >>> point_in_circle((0, 0), (0, 0), 1) True >>> point_in_circle((1, 0), (0, 0), 1) True >>> point_in_circle((1, 1), (0, 0), 1) False
def GetBaseFiles(self, diff): """Helper that calls GetBase file for each file in the patch. Returns: A dictionary that maps from filename to GetBaseFile's tuple. Filenames are retrieved based on lines that start with "Index:" or "Property changes on:". """ files = {} for line in diff.splitlines(Tru...
Helper that calls GetBase file for each file in the patch. Returns: A dictionary that maps from filename to GetBaseFile's tuple. Filenames are retrieved based on lines that start with "Index:" or "Property changes on:".
def argdistincts(self, nested=False): """ Return all unique combinations (up to permutation) of two elements, taken without replacement from the indices of the jagged dimension. Combinations are ordered lexicographically. nested: Return a doubly-jagged array where the first jagge...
Return all unique combinations (up to permutation) of two elements, taken without replacement from the indices of the jagged dimension. Combinations are ordered lexicographically. nested: Return a doubly-jagged array where the first jagged dimension matches the shape of this array
def write_defaults(self): """Create default config file and reload. """ self.defaults.write() self.reset_defaults(self.defaults.filename)
Create default config file and reload.
def term_symbols(self): """ All possible Russell-Saunders term symbol of the Element eg. L = 1, n_e = 2 (s2) returns [['1D2'], ['3P0', '3P1', '3P2'], ['1S0']] """ L_symbols = 'SPDFGHIKLMNOQRTUVWXYZ' L, v_e = self.valence # for one electron i...
All possible Russell-Saunders term symbol of the Element eg. L = 1, n_e = 2 (s2) returns [['1D2'], ['3P0', '3P1', '3P2'], ['1S0']]
def parse_results(fields, data): """ Traverses ordered dictionary, calls _traverse_results() to recursively read into the dictionary depth of data """ master = [] for record in data['records']: # for each 'record' in response row = [None] * len(fields) # create null list the length of num...
Traverses ordered dictionary, calls _traverse_results() to recursively read into the dictionary depth of data
def deprecated(message=None): """Decorator to mark functions as deprecated. A warning will be emitted when the function is used.""" def deco(func): @functools.wraps(func) def wrapped(*args, **kwargs): warnings.warn( message or 'Call to deprecated function {}'.format(f...
Decorator to mark functions as deprecated. A warning will be emitted when the function is used.
def np2model_tensor(a): "Tranform numpy array `a` to a tensor of the same type." dtype = model_type(a.dtype) res = as_tensor(a) if not dtype: return res return res.type(dtype)
Tranform numpy array `a` to a tensor of the same type.
def main(): """main.""" parser = create_parser() args = parser.parse_args() if hasattr(args, 'handler'): args.handler(args) else: parser.print_help()
main.
def _system_config_file(): """ Returns the path to the settings.cfg file. On Windows the file is located in the AppData/Local/envipyengine directory. On Unix, the file will be located in the ~/.envipyengine directory. :return: String specifying the full path to the settings.cfg file """ if ...
Returns the path to the settings.cfg file. On Windows the file is located in the AppData/Local/envipyengine directory. On Unix, the file will be located in the ~/.envipyengine directory. :return: String specifying the full path to the settings.cfg file
def circuit_to_tensorflow_runnable( circuit: circuits.Circuit, initial_state: Union[int, np.ndarray] = 0, ) -> ComputeFuncAndFeedDict: """Returns a compute function and feed_dict for a `cirq.Circuit`'s output. `result.compute()` will return a `tensorflow.Tensor` with `tensorflow.pla...
Returns a compute function and feed_dict for a `cirq.Circuit`'s output. `result.compute()` will return a `tensorflow.Tensor` with `tensorflow.placeholder` objects to be filled in by `result.feed_dict`, at which point it will evaluate to the output state vector of the circuit. You can apply further ope...
def midnight(arg=None): """ convert date to datetime as midnight or get current day's midnight :param arg: string or date/datetime :return: datetime at 00:00:00 """ if arg: _arg = parse(arg) if isinstance(_arg, datetime.date): return datetime.datetime.combine(_arg, da...
convert date to datetime as midnight or get current day's midnight :param arg: string or date/datetime :return: datetime at 00:00:00
def compose(layers, bbox=None, layer_filter=None, color=None, **kwargs): """ Compose layers to a single :py:class:`PIL.Image`. If the layers do not have visible pixels, the function returns `None`. Example:: image = compose([layer1, layer2]) In order to skip some layers, pass `layer_filte...
Compose layers to a single :py:class:`PIL.Image`. If the layers do not have visible pixels, the function returns `None`. Example:: image = compose([layer1, layer2]) In order to skip some layers, pass `layer_filter` function which should take `layer` as an argument and return `True` to keep th...
def trimult(U, x, uplo='U', transa='N', alpha=1., inplace=False): """ b = trimult(U,x, uplo='U') Multiplies U x, where U is upper triangular if uplo='U' or lower triangular if uplo = 'L'. """ if inplace: b = x else: b = x.copy('F') dtrmm_wrap(a=U, b=b, uplo=uplo, transa...
b = trimult(U,x, uplo='U') Multiplies U x, where U is upper triangular if uplo='U' or lower triangular if uplo = 'L'.
def create_item(self, name): """ create a new todo list item """ elem = self.controlled_list.create_item(name) if elem: return TodoElementUX(parent=self, controlled_element=elem)
create a new todo list item
def batches(dataset): '''Returns a callable that chooses sequences from netcdf data.''' seq_lengths = dataset.variables['seqLengths'].data seq_begins = np.concatenate(([0], np.cumsum(seq_lengths)[:-1])) def sample(): chosen = np.random.choice( list(range(len(seq_lengths))), BATCH_SI...
Returns a callable that chooses sequences from netcdf data.
def _find_types(pkgs): '''Form a package names list, find prefixes of packages types.''' return sorted({pkg.split(':', 1)[0] for pkg in pkgs if len(pkg.split(':', 1)) == 2})
Form a package names list, find prefixes of packages types.
def get_annotation(self, key, result_format='list'): """ Is a convenience method for accessing annotations on models that have them """ value = self.get('_annotations_by_key', {}).get(key) if not value: return value if result_format == 'one': retu...
Is a convenience method for accessing annotations on models that have them
def _reconstruct(self, path_to_root): ''' a helper method for finding the schema endpoint from a path to root :param path_to_root: string with dot path to root from :return: list, dict, string, number, or boolean at path to root ''' # split path to root into segments ...
a helper method for finding the schema endpoint from a path to root :param path_to_root: string with dot path to root from :return: list, dict, string, number, or boolean at path to root
def GroupBy(self: dict, f=None): """ [ { 'self': [1, 2, 3], 'f': lambda x: x%2, 'assert': lambda ret: ret[0] == [2] and ret[1] == [1, 3] } ] """ if f and is_to_destruct(f): f = destruct_func(f) return _group_by(self.items(), f)
[ { 'self': [1, 2, 3], 'f': lambda x: x%2, 'assert': lambda ret: ret[0] == [2] and ret[1] == [1, 3] } ]
def _parse_raw_members( self, leaderboard_name, members, members_only=False, **options): ''' Parse the raw leaders data as returned from a given leader board query. Do associative lookups with the member to rank, score and potentially sort the results. @param leaderboard_nam...
Parse the raw leaders data as returned from a given leader board query. Do associative lookups with the member to rank, score and potentially sort the results. @param leaderboard_name [String] Name of the leaderboard. @param members [List] A list of members as returned from a sorted set range q...
def offset(self): """ Property to be used for setting and getting the offset of the layer. Note that setting this property causes an immediate redraw. """ if callable(self._offset): return util.WatchingList(self._offset(*(self.widget.pos+self.widget.size)),se...
Property to be used for setting and getting the offset of the layer. Note that setting this property causes an immediate redraw.
def __disambiguate_proper_names_1(self, docs, lexicon): """ Teeme esmase yleliigsete analyyside kustutamise: kui sõnal on mitu erineva sagedusega pärisnimeanalüüsi, siis jätame alles vaid suurima sagedusega analyysi(d) ... """ for doc in docs: for word in doc...
Teeme esmase yleliigsete analyyside kustutamise: kui sõnal on mitu erineva sagedusega pärisnimeanalüüsi, siis jätame alles vaid suurima sagedusega analyysi(d) ...
def scramble(name, **kwargs): """ scramble text blocks and keep original file structure Parameters ---------- name : str | pathlib.Path file name Returns ------- name : str scrambled file name """ name = Path(name) ...
scramble text blocks and keep original file structure Parameters ---------- name : str | pathlib.Path file name Returns ------- name : str scrambled file name
def remove_vectored_io_slice_suffix_from_name(name, slice): # type: (str, int) -> str """Remove vectored io (stripe) slice suffix from a given name :param str name: entity name :param int slice: slice num :rtype: str :return: name without suffix """ suffix = '.bxslice-{}'.format(slice) ...
Remove vectored io (stripe) slice suffix from a given name :param str name: entity name :param int slice: slice num :rtype: str :return: name without suffix
def get(self, param=None, must=[APIKEY]): '''查账户信息 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 Args: param: (Optional) Results: Result ''' param = {} if param is None else param r = s...
查账户信息 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 Args: param: (Optional) Results: Result
def plot(self, feature): """ Spawns a new figure showing data for `feature`. :param feature: A `pybedtools.Interval` object Using the pybedtools.Interval `feature`, creates figure specified in :meth:`BaseMiniBrowser.make_fig` and plots data on panels according to `self....
Spawns a new figure showing data for `feature`. :param feature: A `pybedtools.Interval` object Using the pybedtools.Interval `feature`, creates figure specified in :meth:`BaseMiniBrowser.make_fig` and plots data on panels according to `self.panels()`.
def parse(self, buffer, inlineparent = None): ''' Compatible to Parser.parse() ''' size = 0 v = [] for i in range(0, self.size): # @UnusedVariable r = self.innerparser.parse(buffer[size:], None) if r is None: return None ...
Compatible to Parser.parse()
def get_distances(rupture, mesh, param): """ :param rupture: a rupture :param mesh: a mesh of points or a site collection :param param: the kind of distance to compute (default rjb) :returns: an array of distances from the given mesh """ if param == 'rrup': dist = rupture.surface.get...
:param rupture: a rupture :param mesh: a mesh of points or a site collection :param param: the kind of distance to compute (default rjb) :returns: an array of distances from the given mesh
def get_learning_objectives_metadata(self): """Gets the metadata for learning objectives. return: (osid.Metadata) - metadata for the learning objectives *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.ActivityForm.ge...
Gets the metadata for learning objectives. return: (osid.Metadata) - metadata for the learning objectives *compliance: mandatory -- This method must be implemented.*
def _virtualenv_sys(venv_path): "obtain version and path info from a virtualenv." executable = os.path.join(venv_path, env_bin_dir, 'python') # Must use "executable" as the first argument rather than as the # keyword argument "executable" to get correct value from sys.path p = subprocess.Popen([exec...
obtain version and path info from a virtualenv.
def cleanup(self): """ Release resources used during shell execution """ for future in self.futures: future.cancel() self.executor.shutdown(wait=10) if self.ssh.get_transport() != None: self.ssh.close()
Release resources used during shell execution
def get_results(self, title_prefix="", title_override="", rnd_dig=2): """ Constructs a summary of the results as an array, which might be useful for writing the results of multiple algorithms to a table. NOTE- This method must be called AFTER "roll_mc". :param title_prefix...
Constructs a summary of the results as an array, which might be useful for writing the results of multiple algorithms to a table. NOTE- This method must be called AFTER "roll_mc". :param title_prefix: If desired, prefix the title (such as "Alg 1 ") :param title_override: Override t...
def status(self): """ The status of the container. For example, ``running``, or ``exited``. """ if isinstance(self.attrs['State'], dict): return self.attrs['State']['Status'] return self.attrs['State']
The status of the container. For example, ``running``, or ``exited``.
def main(): """ The main loop for the commandline parser. """ DATABASE.load_contents() continue_flag = False while not continue_flag: DATABASE.print_contents() try: command = raw_input(">>> ") for stmnt_unformated in sqlparse.parse(command): ...
The main loop for the commandline parser.
def _read_openjp2_common(self): """ Read a JPEG 2000 image using libopenjp2. Returns ------- ndarray or lst Either the image as an ndarray or a list of ndarrays, each item corresponding to one band. """ with ExitStack() as stack: ...
Read a JPEG 2000 image using libopenjp2. Returns ------- ndarray or lst Either the image as an ndarray or a list of ndarrays, each item corresponding to one band.
def get_fd(file_or_fd, default=None): """Helper function for getting a file descriptor.""" fd = file_or_fd if fd is None: fd = default if hasattr(fd, "fileno"): fd = fd.fileno() return fd
Helper function for getting a file descriptor.
def deleteNetworkVisualProp(self, networkId, viewId, visualProperty, verbose=None): """ Deletes the bypass Visual Property specificed by the `visualProperty`, `viewId`, and `networkId` parameters. When this is done, the Visual Property will be defined by the Visual Style Additional deta...
Deletes the bypass Visual Property specificed by the `visualProperty`, `viewId`, and `networkId` parameters. When this is done, the Visual Property will be defined by the Visual Style Additional details on common Visual Properties can be found in the [Basic Visual Lexicon JavaDoc API](http://chianti.uc...
def to_struct(self, value): """Cast `date` object to string.""" if self.str_format: return value.strftime(self.str_format) return value.strftime(self.default_format)
Cast `date` object to string.
def make_naive(value, timezone): """ Makes an aware datetime.datetime naive in a given time zone. """ value = value.astimezone(timezone) if hasattr(timezone, 'normalize'): # available for pytz time zones value = timezone.normalize(value) return value.replace(tzinfo=None)
Makes an aware datetime.datetime naive in a given time zone.
def get_metric_values(self, group_name): """ Get the faked metric values for a metric group, by its metric group name. The result includes all metric object values added earlier for that metric group name, using :meth:`~zhmcclient.FakedMetricsContextManager.add_metric_ob...
Get the faked metric values for a metric group, by its metric group name. The result includes all metric object values added earlier for that metric group name, using :meth:`~zhmcclient.FakedMetricsContextManager.add_metric_object_values` i.e. the metric values for all resources...
def _SendTerminationMessage(self, status=None): """This notifies the parent flow of our termination.""" if not self.runner_args.request_state.session_id: # No parent flow, nothing to do here. return if status is None: status = rdf_flows.GrrStatus() client_resources = self.context.cli...
This notifies the parent flow of our termination.
def get_per_identity_records(self, events: Iterable, data_processor: DataProcessor ) -> Generator[Tuple[str, TimeAndRecord], None, None]: """ Uses the given iteratable events and the data processor convert the event into a list of Records along with its identity ...
Uses the given iteratable events and the data processor convert the event into a list of Records along with its identity and time. :param events: iteratable events. :param data_processor: DataProcessor to process each event in events. :return: yields Tuple[Identity, TimeAndRecord] for al...
def profile_different_methods(search_file, screen_file, method_list, dir_path, file_name): """对指定的图片进行性能测试.""" profiler = ProfileRecorder(0.05) # 加载图片 profiler.load_images(search_file, screen_file) # 传入待测试的方法列表 profiler.profile_methods(method_list) # 将性能数据写入文件 profiler.wite_to_json(dir_p...
对指定的图片进行性能测试.
def serialize(self, queryset, **options): """ Serialize a queryset. THE OUTPUT OF THIS SERIALIZER IS NOT MEANT TO BE SERIALIZED BACK INTO THE DB. """ self.options = options self.stream = options.get("stream", StringIO()) self.selected_fields = opt...
Serialize a queryset. THE OUTPUT OF THIS SERIALIZER IS NOT MEANT TO BE SERIALIZED BACK INTO THE DB.
def _compute_distance(self, rup, dists, C): """ Compute the distance function, equation (9): """ mref = 3.6 rref = 1.0 rval = np.sqrt(dists.rhypo ** 2 + C['h'] ** 2) return (C['c1'] + C['c2'] * (rup.mag - mref)) *\ np.log10(rval / rref) + C['c3'] * (rv...
Compute the distance function, equation (9):
def _are_safety_checks_disabled(self, caller=u"unknown_function"): """ Return ``True`` if safety checks are disabled. :param string caller: the name of the caller function :rtype: bool """ if self.rconf.safety_checks: return False self.log_warn([u"Saf...
Return ``True`` if safety checks are disabled. :param string caller: the name of the caller function :rtype: bool
def build_package(team, username, package, subpath, yaml_path, checks_path=None, dry_run=False, env='default'): """ Builds a package from a given Yaml file and installs it locally. Returns the name of the package. """ def find(key, value): """ find matching nodes r...
Builds a package from a given Yaml file and installs it locally. Returns the name of the package.
def get_value(self, section, option, default=None): """ :param default: If not None, the given default value will be returned in case the option did not exist :return: a properly typed value, either int, float or string :raise TypeError: in case the value could n...
:param default: If not None, the given default value will be returned in case the option did not exist :return: a properly typed value, either int, float or string :raise TypeError: in case the value could not be understood Otherwise the exceptions known to the Confi...
def configure(self, viewport=None, fbo_size=None, fbo_rect=None, canvas=None): """Automatically configure the TransformSystem: * canvas_transform maps from the Canvas logical pixel coordinate system to the framebuffer coordinate system, taking into account the log...
Automatically configure the TransformSystem: * canvas_transform maps from the Canvas logical pixel coordinate system to the framebuffer coordinate system, taking into account the logical/physical pixel scale factor, current FBO position, and y-axis inversion. * framebuff...
def weather_history_at_id(self, id, start=None, end=None): """ Queries the OWM Weather API for weather history for the specified city ID. A list of *Weather* objects is returned. It is possible to query for weather history in a closed time period, whose boundaries can be passed a...
Queries the OWM Weather API for weather history for the specified city ID. A list of *Weather* objects is returned. It is possible to query for weather history in a closed time period, whose boundaries can be passed as optional parameters. :param id: the city ID :type id: int ...
def _prepare_data_dir(self, data): """Prepare destination directory where the data will live. :param data: The :class:`~resolwe.flow.models.Data` object for which to prepare the private execution directory. :return: The prepared data directory path. :rtype: str """ ...
Prepare destination directory where the data will live. :param data: The :class:`~resolwe.flow.models.Data` object for which to prepare the private execution directory. :return: The prepared data directory path. :rtype: str
def omitted_parcov(self): """get the omitted prior parameter covariance matrix Returns ------- omitted_parcov : pyemu.Cov Note ---- returns a reference If ErrorVariance.__omitted_parcov is None, attribute is dynamically loaded ...
get the omitted prior parameter covariance matrix Returns ------- omitted_parcov : pyemu.Cov Note ---- returns a reference If ErrorVariance.__omitted_parcov is None, attribute is dynamically loaded
def stylesheet_declarations(string, is_merc=False, scale=1): """ Parse a string representing a stylesheet into a list of declarations. Required boolean is_merc indicates whether the projection should be interpreted as spherical mercator, so we know what to do with zoom/scale-denominator...
Parse a string representing a stylesheet into a list of declarations. Required boolean is_merc indicates whether the projection should be interpreted as spherical mercator, so we know what to do with zoom/scale-denominator in parse_rule().
def add_infos(self, *keyvals, **kwargs): """Adds the given info and returns a dict composed of just this added info.""" kv_pairs = [] for key, val in keyvals: key = key.strip() val = str(val).strip() if ':' in key: raise ValueError('info key "{}" must not contain a colon.'.format(k...
Adds the given info and returns a dict composed of just this added info.
def write(models, out=None, base=None, propertybase=None, shorteners=None, logger=logging): ''' models - input Versa models from which output is generated. Must be a sequence object, not an iterator ''' assert out is not None #Output stream required if not isinstance(models, list): m...
models - input Versa models from which output is generated. Must be a sequence object, not an iterator
def mandel(x, y, max_iters): """ Given the real and imaginary parts of a complex number, determine if it is a candidate for membership in the Mandelbrot set given a fixed number of iterations. """ i = 0 c = complex(x,y) z = 0.0j for i in range(max_iters): z = z*z + c ...
Given the real and imaginary parts of a complex number, determine if it is a candidate for membership in the Mandelbrot set given a fixed number of iterations.
def nvmlUnitGetCount(): r""" /** * Retrieves the number of units in the system. * * For S-class products. * * @param unitCount Reference in which to return the number of units * * @return * - \ref NVML_SUCCESS if \a unitC...
r""" /** * Retrieves the number of units in the system. * * For S-class products. * * @param unitCount Reference in which to return the number of units * * @return * - \ref NVML_SUCCESS if \a unitCount has been set * ...