code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def is_same_address(left: AnyAddress, right: AnyAddress) -> bool: """ Checks if both addresses are same or not. """ if not is_address(left) or not is_address(right): raise ValueError("Both values must be valid addresses") else: return to_normalized_address(left) == to_normalized_addr...
Checks if both addresses are same or not.
def customize_ruleset(self, custom_ruleset_file=None): """ Updates the ruleset to include a set of custom rules. These rules will be _added_ to the existing ruleset or replace the existing rule with the same ID. Args: custom_ruleset_file (optional): The filepath to ...
Updates the ruleset to include a set of custom rules. These rules will be _added_ to the existing ruleset or replace the existing rule with the same ID. Args: custom_ruleset_file (optional): The filepath to the custom rules. Defaults to `None`. If `custom_ruleset_fi...
def drag(duration: int, amp: complex, sigma: float, beta: float, name: str = None) -> SamplePulse: r"""Generates Y-only correction DRAG `SamplePulse` for standard nonlinear oscillator (SNO) [1]. Centered at `duration/2` and zeroed at `t=-1` to prevent large initial discontinuity. Applies `left` sampling s...
r"""Generates Y-only correction DRAG `SamplePulse` for standard nonlinear oscillator (SNO) [1]. Centered at `duration/2` and zeroed at `t=-1` to prevent large initial discontinuity. Applies `left` sampling strategy to generate discrete pulse from continuous function. [1] Gambetta, J. M., Motzoi, F., Merk...
def hash(self): """ Returns a hash of this render configuration from the variable, renderer, and time_index parameters. Used for caching the full-extent, native projection render so that subsequent requests can be served by a warp operation only. """ renderer_str = "{}|{...
Returns a hash of this render configuration from the variable, renderer, and time_index parameters. Used for caching the full-extent, native projection render so that subsequent requests can be served by a warp operation only.
def _sphinx_build(self, kind): """ Call sphinx to build documentation. Attribute `num_jobs` from the class is used. Parameters ---------- kind : {'html', 'latex'} Examples -------- >>> DocBuilder(num_jobs=4)._sphinx_build('html') """ ...
Call sphinx to build documentation. Attribute `num_jobs` from the class is used. Parameters ---------- kind : {'html', 'latex'} Examples -------- >>> DocBuilder(num_jobs=4)._sphinx_build('html')
def register_metric_descriptor(self, oc_md): """Register a metric descriptor with stackdriver.""" metric_type = self.get_metric_type(oc_md) with self._md_lock: if metric_type in self._md_cache: return self._md_cache[metric_type] descriptor = self.get_metric_d...
Register a metric descriptor with stackdriver.
def on_clipboard_mode_change(self, clipboard_mode): """Notification when the shared clipboard mode changes. in clipboard_mode of type :class:`ClipboardMode` The new shared clipboard mode. """ if not isinstance(clipboard_mode, ClipboardMode): raise TypeError("cli...
Notification when the shared clipboard mode changes. in clipboard_mode of type :class:`ClipboardMode` The new shared clipboard mode.
def migrate(src_path, src_passphrase, src_backend, dst_path, dst_passphrase, dst_backend): """Migrate all keys in a source stash to a destination stash The migration process will decrypt all keys using the source stash's passphrase and then encryp...
Migrate all keys in a source stash to a destination stash The migration process will decrypt all keys using the source stash's passphrase and then encrypt them based on the destination stash's passphrase. re-encryption will take place only if the passphrases are differing
def gcd(*numbers): """ Returns the greatest common divisor for a sequence of numbers. Args: \*numbers: Sequence of numbers. Returns: (int) Greatest common divisor of numbers. """ n = numbers[0] for i in numbers: n = pygcd(n, i) return n
Returns the greatest common divisor for a sequence of numbers. Args: \*numbers: Sequence of numbers. Returns: (int) Greatest common divisor of numbers.
def line_is_interesting(self, line): """Return True, False, or None. True means always output, False means never output, None means output only if there are interesting lines. """ if line.startswith('Name'): return None if line.startswith('--------'): ...
Return True, False, or None. True means always output, False means never output, None means output only if there are interesting lines.
def _BuildOobLink(self, param, mode): """Builds out-of-band URL. Gitkit API GetOobCode() is called and the returning code is combined with Gitkit widget URL to building the out-of-band url. Args: param: dict of request. mode: string, Gitkit widget mode to handle the oob action after user ...
Builds out-of-band URL. Gitkit API GetOobCode() is called and the returning code is combined with Gitkit widget URL to building the out-of-band url. Args: param: dict of request. mode: string, Gitkit widget mode to handle the oob action after user clicks the oob url in the email. ...
def SplitPatch(data): """Splits a patch into separate pieces for each file. Args: data: A string containing the output of svn diff. Returns: A list of 2-tuple (filename, text) where text is the svn diff output pertaining to filename. """ patches = [] filename = None diff = [] for line in data.splitline...
Splits a patch into separate pieces for each file. Args: data: A string containing the output of svn diff. Returns: A list of 2-tuple (filename, text) where text is the svn diff output pertaining to filename.
def cfht_megacam_tap_query(ra_deg=180.0, dec_deg=0.0, width=1, height=1, date=None): """Do a query of the CADC Megacam table. Get all observations inside the box (right now it turns width/height into a radius, should not do this). @rtype : Table @param ra_deg: center of search region, in degrees @...
Do a query of the CADC Megacam table. Get all observations inside the box (right now it turns width/height into a radius, should not do this). @rtype : Table @param ra_deg: center of search region, in degrees @param dec_deg: center of search region in degrees @param width: width of search region i...
def getmoduleinfo(path): """Get the module name, suffix, mode, and module type for a given file.""" filename = os.path.basename(path) suffixes = map(lambda (suffix, mode, mtype): (-len(suffix), suffix, mode, mtype), imp.get_suffixes()) suffixes.sort() # try longest suffixes first, in ...
Get the module name, suffix, mode, and module type for a given file.
def _compute(self): """Computes the state variable tendencies in time for implicit processes. To calculate the new state the :func:`_implicit_solver()` method is called for daughter classes. This however returns the new state of the variables, not just the tendencies. Therefore, the adj...
Computes the state variable tendencies in time for implicit processes. To calculate the new state the :func:`_implicit_solver()` method is called for daughter classes. This however returns the new state of the variables, not just the tendencies. Therefore, the adjustment is calculated w...
def from_argparse(cls, args): """Generate the Settings from parsed arguments.""" settings = vars(args) settings['repository_name'] = settings.pop('repository') settings['cacert'] = settings.pop('cert') return cls(**settings)
Generate the Settings from parsed arguments.
def initialize_simulation(components: List, input_config: Mapping=None, plugin_config: Mapping=None) -> InteractiveContext: """Construct a simulation from a list of components, component configuration, and a plugin configuration. The simulation context returned by this method stil...
Construct a simulation from a list of components, component configuration, and a plugin configuration. The simulation context returned by this method still needs to be setup by calling its setup method. It is mostly useful for testing and debugging. Parameters ---------- components A l...
def ref_frequency(self, context): """ Reference frequency data source """ num_chans = self._manager.spectral_window_table.getcol(MS.NUM_CHAN) ref_freqs = self._manager.spectral_window_table.getcol(MS.REF_FREQUENCY) data = np.hstack((np.repeat(rf, bs) for bs, rf in zip(num_chans, ref_fre...
Reference frequency data source
def get(self, block_alias, context): """Main method returning block contents (static or dynamic).""" contents = [] dynamic_block_contents = self.get_contents_dynamic(block_alias, context) if dynamic_block_contents: contents.append(dynamic_block_contents) static_bloc...
Main method returning block contents (static or dynamic).
def get_solution(self, parameters=None): """stub""" if not self.has_solution(): raise IllegalState() return DisplayText(self.my_osid_object._my_map['solution'])
stub
def select(self, ): """Store the selected taskfileinfo self.selected and accept the dialog :returns: None :rtype: None :raises: None """ s = self.browser.selected_indexes(self.browser.get_depth()-1) if not s: return i = s[0].internalPointer() ...
Store the selected taskfileinfo self.selected and accept the dialog :returns: None :rtype: None :raises: None
def circle(rad=0.5): """Draw a circle""" _ctx = _state["ctx"] _ctx.arc(0, 0, rad, 0, 2 * math.pi) _ctx.set_line_width(0) _ctx.stroke_preserve() # _ctx.set_source_rgb(0.3, 0.4, 0.6) _ctx.fill()
Draw a circle
def pivot(self, index, column, value): """ Pivot the frame designated by the three columns: index, column, and value. Index and column should be of type enum, int, or time. For cases of multiple indexes for a column label, the aggregation method is to pick the first occurrence in the dat...
Pivot the frame designated by the three columns: index, column, and value. Index and column should be of type enum, int, or time. For cases of multiple indexes for a column label, the aggregation method is to pick the first occurrence in the data frame :param index: Index is a column that will ...
def plot_fit(self, **kwargs): """ Plots the fit of the model Returns ---------- None (plots data and the fit) """ import matplotlib.pyplot as plt import seaborn as sns figsize = kwargs.get('figsize',(10,7)) if self.latent_variables.estimated is ...
Plots the fit of the model Returns ---------- None (plots data and the fit)
def _update_estimate_and_sampler(self, ell, ell_hat, weight, extra_info, **kwargs): """Update the BB models and the estimates""" stratum_idx = extra_info['stratum'] self._BB_TP.update(ell*ell_hat, stratum_idx) self._BB_PP.update(ell_hat, stratum_idx) ...
Update the BB models and the estimates
def _overlapping(files): """Quick method to see if a file list contains overlapping files """ segments = set() for path in files: seg = file_segment(path) for s in segments: if seg.intersects(s): return True segments.add(seg) return False
Quick method to see if a file list contains overlapping files
def env_set(context): """Set $ENVs to specified string. from the pypyr context. Args: context: is dictionary-like. context is mandatory. context['env']['set'] must exist. It's a dictionary. Values are strings to write to $ENV. Keys are the names of the...
Set $ENVs to specified string. from the pypyr context. Args: context: is dictionary-like. context is mandatory. context['env']['set'] must exist. It's a dictionary. Values are strings to write to $ENV. Keys are the names of the $ENV values to which to writ...
def render_honeypot_field(field_name=None): """ Renders honeypot field named field_name (defaults to HONEYPOT_FIELD_NAME). """ if not field_name: field_name = settings.HONEYPOT_FIELD_NAME value = getattr(settings, 'HONEYPOT_VALUE', '') if callable(value): value = value() ...
Renders honeypot field named field_name (defaults to HONEYPOT_FIELD_NAME).
def validate(self, value): """Validate string by regex :param value: str :return: """ if not self._compiled_regex.match(value): raise ValidationError( 'value {:s} not match r"{:s}"'.format(value, self._regex))
Validate string by regex :param value: str :return:
def meta_features_path(self, path): """Returns path for meta-features Args: path (str): Absolute/local path of xcessiv folder """ return os.path.join( path, app.config['XCESSIV_META_FEATURES_FOLDER'], str(self.id) )...
Returns path for meta-features Args: path (str): Absolute/local path of xcessiv folder
def _parse_CHANLIMIT(value): """ >>> res = FeatureSet._parse_CHANLIMIT('ibe:250,xyz:100') >>> len(res) 6 >>> res['x'] 100 >>> res['i'] == res['b'] == res['e'] == 250 True """ pairs = map(string_int_pair, value.split(',')) return dic...
>>> res = FeatureSet._parse_CHANLIMIT('ibe:250,xyz:100') >>> len(res) 6 >>> res['x'] 100 >>> res['i'] == res['b'] == res['e'] == 250 True
def WriteSignedBinary(binary_urn, binary_content, private_key, public_key, chunk_size = 1024, token = None): """Signs a binary and saves it to the datastore. If a signed binary with the given URN already e...
Signs a binary and saves it to the datastore. If a signed binary with the given URN already exists, its contents will get overwritten. Args: binary_urn: URN that should serve as a unique identifier for the binary. binary_content: Contents of the binary, as raw bytes. private_key: Key that should be ...
def from_str(cls, emotestr): """Create an emote from the emote tag key :param emotestr: the tag key, e.g. ``'123:0-4'`` :type emotestr: :class:`str` :returns: an emote :rtype: :class:`Emote` :raises: None """ emoteid, occstr = emotestr.split(':') ...
Create an emote from the emote tag key :param emotestr: the tag key, e.g. ``'123:0-4'`` :type emotestr: :class:`str` :returns: an emote :rtype: :class:`Emote` :raises: None
def maybe_center_plot(result): """Embeds a possible tikz image inside a center environment. Searches for matplotlib2tikz last commend line to detect tikz images. Args: result: The code execution result Returns: The input result if no tikzpicture was found, otherwise a centered ...
Embeds a possible tikz image inside a center environment. Searches for matplotlib2tikz last commend line to detect tikz images. Args: result: The code execution result Returns: The input result if no tikzpicture was found, otherwise a centered version.
def reverse( self, query, radius=None, exactly_one=True, maxresults=None, pageinformation=None, language=None, mode='retrieveAddresses', timeout=DEFAULT_SENTINEL ): """ Return an address by lo...
Return an address by location point. This implementation supports only a subset of all available parameters. A list of all parameters of the pure REST API is available here: https://developer.here.com/documentation/geocoder/topics/resource-reverse-geocode.html :param query: The coordin...
def load(self, text, fieldnames=None): """Item from TSV representation.""" lines = text.split('\n') fieldnames = load_line(lines[0]) values = load_line(lines[1]) self.__dict__ = dict(zip(fieldnames, values))
Item from TSV representation.
def _redirect_with_params(url_name, *args, **kwargs): """Helper method to create a redirect response with URL params. This builds a redirect string that converts kwargs into a query string. Args: url_name: The name of the url to redirect to. kwargs: the query string param and their val...
Helper method to create a redirect response with URL params. This builds a redirect string that converts kwargs into a query string. Args: url_name: The name of the url to redirect to. kwargs: the query string param and their values to build. Returns: A properly formatted redi...
def json_to_pages(json, user, preferred_lang=None): """ Attept to create/update pages from JSON string json. user is the user that will be used when creating a page if a page's original author can't be found. preferred_lang is the language code of the slugs to include in error messages (defaults t...
Attept to create/update pages from JSON string json. user is the user that will be used when creating a page if a page's original author can't be found. preferred_lang is the language code of the slugs to include in error messages (defaults to settings.PAGE_DEFAULT_LANGUAGE). Returns (errors, pag...
def parse_arg(f, kwd, offset=0): """ convert dictionary of keyword argument and value to positional argument equivalent to:: vnames = describe(f) return tuple([kwd[k] for k in vnames[offset:]]) """ vnames = describe(f) return tuple([kwd[k] for k in vnames[offset:]])
convert dictionary of keyword argument and value to positional argument equivalent to:: vnames = describe(f) return tuple([kwd[k] for k in vnames[offset:]])
def loadtxt2(fname, dtype=None, delimiter=' ', newline='\n', comment_character='#', skiplines=0): """ Known issues delimiter and newline is not respected. string quotation with space is broken. """ dtypert = [None, None, None] def preparedtype(dtype): dtypert[0] = dtype ...
Known issues delimiter and newline is not respected. string quotation with space is broken.
def setup_icons(self, ): """Set all icons on buttons :returns: None :rtype: None :raises: None """ plus_icon = get_icon('glyphicons_433_plus_bright.png', asicon=True) self.addnew_tb.setIcon(plus_icon)
Set all icons on buttons :returns: None :rtype: None :raises: None
def get_status(task, prefix, expnum, version, ccd, return_message=False): """ Report back status of the given program by looking up the associated VOSpace annotation. @param task: name of the process or task that will be checked. @param prefix: prefix of the file that was processed (often fk or None) ...
Report back status of the given program by looking up the associated VOSpace annotation. @param task: name of the process or task that will be checked. @param prefix: prefix of the file that was processed (often fk or None) @param expnum: which exposure number (or base filename) @param version: which ...
def is_callable_type(tp): """Test if the type is a generic callable type, including subclasses excluding non-generic types and callables. Examples:: is_callable_type(int) == False is_callable_type(type) == False is_callable_type(Callable) == True is_callable_type(Callable[.....
Test if the type is a generic callable type, including subclasses excluding non-generic types and callables. Examples:: is_callable_type(int) == False is_callable_type(type) == False is_callable_type(Callable) == True is_callable_type(Callable[..., int]) == True is_calla...
def transform_audio(self, y): '''Compute the tempogram Parameters ---------- y : np.ndarray Audio buffer Returns ------- data : dict data['tempogram'] : np.ndarray, shape=(n_frames, win_length) The tempogram ''' ...
Compute the tempogram Parameters ---------- y : np.ndarray Audio buffer Returns ------- data : dict data['tempogram'] : np.ndarray, shape=(n_frames, win_length) The tempogram
def body(self): """ Return body request parameter :return: Body parameter :rtype: Parameter or None """ body = self.get_parameters_by_location(['body']) return self.root.schemas.get(body[0].type) if body else None
Return body request parameter :return: Body parameter :rtype: Parameter or None
def _hook_unmapped(self, uc, access, address, size, value, data): """ We hit an unmapped region; map it into unicorn. """ try: self.sync_unicorn_to_manticore() logger.warning(f"Encountered an operation on unmapped memory at {hex(address)}") m = self._c...
We hit an unmapped region; map it into unicorn.
def at_time(self, time, asof=False, axis=None): """ Select values at particular time of day (e.g. 9:30AM). Parameters ---------- time : datetime.time or str axis : {0 or 'index', 1 or 'columns'}, default 0 .. versionadded:: 0.24.0 Returns --...
Select values at particular time of day (e.g. 9:30AM). Parameters ---------- time : datetime.time or str axis : {0 or 'index', 1 or 'columns'}, default 0 .. versionadded:: 0.24.0 Returns ------- Series or DataFrame Raises ------ ...
def _clean_flags(args, caller): ''' Sanitize flags passed into df ''' flags = '' if args is None: return flags allowed = ('a', 'B', 'h', 'H', 'i', 'k', 'l', 'P', 't', 'T', 'x', 'v') for flag in args: if flag in allowed: flags += flag else: rais...
Sanitize flags passed into df
def _gl_initialize(self): """ Deal with compatibility; desktop does not have sprites enabled by default. ES has. """ if '.es' in gl.current_backend.__name__: pass # ES2: no action required else: # Desktop, enable sprites GL_VERTEX_PROGRAM_POIN...
Deal with compatibility; desktop does not have sprites enabled by default. ES has.
def xd(self): """get xarray dataset file handle to LSM files""" if self._xd is None: path_to_lsm_files = path.join(self.lsm_input_folder_path, self.lsm_search_card) self._xd = pa.open_mfdataset(path_to_lsm_files, ...
get xarray dataset file handle to LSM files
def flip(self, reactions): """Flip the specified reactions.""" for reaction in reactions: if reaction in self._flipped: self._flipped.remove(reaction) else: self._flipped.add(reaction)
Flip the specified reactions.
def exec(self, container: Container, command: str, context: Optional[str] = None, stdout: bool = True, stderr: bool = False, time_limit: Optional[int] = None ) -> ExecResponse: """ Executes a given command inside ...
Executes a given command inside a provided container. Parameters: container: the container to which the command should be issued. command: the command that should be executed. context: the working directory that should be used to perform the execution. If no ...
def start(): """Start the CherryPy application server.""" setupdir = dirname(dirname(__file__)) curdir = os.getcwd() # First look on the command line for a desired config file, # if it's not on the command line, then look for 'setup.py' # in the current directory. If there, load configuration ...
Start the CherryPy application server.
def open(self): """ Open a connection to the AMQP compliant broker. """ self._connection = \ amqp.Connection(host='%s:%s' % (self.hostname, self.port), userid=self.username, password=self.password, virtual_host=self.virtual_ho...
Open a connection to the AMQP compliant broker.
def bin_b64_type(arg): """An argparse type representing binary data encoded in base64.""" try: arg = base64.standard_b64decode(arg) except (binascii.Error, TypeError): raise argparse.ArgumentTypeError("{0} is invalid base64 data".format(repr(arg))) return arg
An argparse type representing binary data encoded in base64.
def export(name: str, value: Any): """ Exports a named stack output. :param str name: The name to assign to this output. :param Any value: The value of this output. """ stack = get_root_resource() if stack is not None: stack.output(name, value)
Exports a named stack output. :param str name: The name to assign to this output. :param Any value: The value of this output.
def _raise_for_status(response): """Raises stored :class:`HTTPError`, if one occurred. This is the :meth:`requests.models.Response.raise_for_status` method, modified to add the response from Space-Track, if given. """ http_error_msg = '' if 400 <= response.status_code < 500: http_erro...
Raises stored :class:`HTTPError`, if one occurred. This is the :meth:`requests.models.Response.raise_for_status` method, modified to add the response from Space-Track, if given.
def load_terms(self, terms): """Create a builder from a sequence of terms, usually a TermInterpreter""" #if self.root and len(self.root.children) > 0: # raise MetatabError("Can't run after adding terms to document.") for t in terms: t.doc = self if t.term_i...
Create a builder from a sequence of terms, usually a TermInterpreter
def buildURL(self, action, **query): """Build a URL relative to the server base_url, with the given query parameters added.""" base = urlparse.urljoin(self.server.base_url, action) return appendArgs(base, query)
Build a URL relative to the server base_url, with the given query parameters added.
def print_tb(tb, limit=None, file=None): """Print up to 'limit' stack trace entries from the traceback 'tb'. If 'limit' is omitted or None, all entries are printed. If 'file' is omitted or None, the output goes to sys.stderr; otherwise 'file' should be an open file or file-like object with a write() ...
Print up to 'limit' stack trace entries from the traceback 'tb'. If 'limit' is omitted or None, all entries are printed. If 'file' is omitted or None, the output goes to sys.stderr; otherwise 'file' should be an open file or file-like object with a write() method.
def to_bluesky( traffic: Traffic, filename: Union[str, Path], minimum_time: Optional[timelike] = None, ) -> None: """Generates a Bluesky scenario file.""" if minimum_time is not None: minimum_time = to_datetime(minimum_time) traffic = traffic.query(f"timestamp >= '{minimum_time}'") ...
Generates a Bluesky scenario file.
def uniquelines(q): """ Given all the facets, convert it into a set of unique lines. Specifically used for converting convex hull facets into line pairs of coordinates. Args: q: A 2-dim sequence, where each row represents a facet. E.g., [[1,2,3],[3,6,7],...] Returns: s...
Given all the facets, convert it into a set of unique lines. Specifically used for converting convex hull facets into line pairs of coordinates. Args: q: A 2-dim sequence, where each row represents a facet. E.g., [[1,2,3],[3,6,7],...] Returns: setoflines: A set of ...
def gdal_rasterize(src, dst, options): """ a simple wrapper for gdal.Rasterize Parameters ---------- src: str or :osgeo:class:`ogr.DataSource` the input data set dst: str the output data set options: dict additional parameters passed to gdal.Rasterize; see :osgeo:fun...
a simple wrapper for gdal.Rasterize Parameters ---------- src: str or :osgeo:class:`ogr.DataSource` the input data set dst: str the output data set options: dict additional parameters passed to gdal.Rasterize; see :osgeo:func:`gdal.RasterizeOptions` Returns -------
def strerror(errno): """Translate an error code to a message string.""" from pypy.module._codecs.locale import str_decode_locale_surrogateescape return str_decode_locale_surrogateescape(os.strerror(errno))
Translate an error code to a message string.
def open_file(filename): """ Multi-platform way to make the OS open a file with its default application """ if sys.platform.startswith("darwin"): subprocess.call(("open", filename)) elif sys.platform == "cygwin": subprocess.call(("cygstart", filename)) elif os.name == "nt": ...
Multi-platform way to make the OS open a file with its default application
def add_user(self, attrs): """ Add a user to the backend :param attrs: attributes of the user :type attrs: dict ({<attr>: <value>}) .. warning:: raise UserAlreadyExists if user already exists """ username = attrs[self.key] if username in self.users: ...
Add a user to the backend :param attrs: attributes of the user :type attrs: dict ({<attr>: <value>}) .. warning:: raise UserAlreadyExists if user already exists
def __get_metrics(self): """ Each metric must have its own filters copy to modify it freely""" esfilters_closed = None esfilters_opened = None if self.esfilters: esfilters_closed = self.esfilters.copy() esfilters_opened = self.esfilters.copy() closed = se...
Each metric must have its own filters copy to modify it freely
def _expect_empty(self): """ Checks if the token stream is empty. * Raises a ``ParseError` exception if a token is found. """ item = self._lexer.get_token() if item: line_no, token = item raise ParseError(u"Unexpected token '{0}' on line {1}" ...
Checks if the token stream is empty. * Raises a ``ParseError` exception if a token is found.
def create_from_request_pdu(pdu): """ Create instance from request PDU. :param pdu: A request PDU. :return: Instance of this class. """ _, starting_address, quantity = struct.unpack('>BHH', pdu) instance = ReadHoldingRegisters() instance.starting_address = start...
Create instance from request PDU. :param pdu: A request PDU. :return: Instance of this class.
def _parse(self, line): """Parse the output line""" try: result = line.split(':', maxsplit=4) filename, line_num_txt, column_txt, message_type, text = result except ValueError: return try: self.line_num = int(line_num_txt.strip()) ...
Parse the output line
def configure(self, options, conf): """Configure which kinds of exceptions trigger plugin. """ self.conf = conf self.enabled = options.debugErrors or options.debugFailures self.enabled_for_errors = options.debugErrors self.enabled_for_failures = options.debugFailures
Configure which kinds of exceptions trigger plugin.
def get_host_from_service_info(service_info): """ Get hostname or IP from service_info. """ host = None port = None if (service_info and service_info.port and (service_info.server or service_info.address)): if service_info.address: host = socket.inet_ntoa(service_info.add...
Get hostname or IP from service_info.
def is_symlink(self): """ Whether this path is a symbolic link. """ try: return S_ISLNK(self.lstat().st_mode) except OSError as e: if e.errno != ENOENT: raise # Path doesn't exist return False
Whether this path is a symbolic link.
def combine(objs): """Combine the specified `~gala.dynamics.PhaseSpacePosition` or `~gala.dynamics.Orbit` objects. Parameters ---------- objs : iterable An iterable of either `~gala.dynamics.PhaseSpacePosition` or `~gala.dynamics.Orbit` objects. """ from .orbit import Orbit ...
Combine the specified `~gala.dynamics.PhaseSpacePosition` or `~gala.dynamics.Orbit` objects. Parameters ---------- objs : iterable An iterable of either `~gala.dynamics.PhaseSpacePosition` or `~gala.dynamics.Orbit` objects.
def pyhttp(self, value): """ converts a no namespaces uri to a python excessable name """ if value.startswith("pyuri_"): return value parts = self.parse_uri(value) return "pyuri_%s_%s" % (base64.b64encode(bytes(parts[0], ...
converts a no namespaces uri to a python excessable name
def role_definitions(self): """Instance depends on the API version: * 2015-07-01: :class:`RoleDefinitionsOperations<azure.mgmt.authorization.v2015_07_01.operations.RoleDefinitionsOperations>` * 2018-01-01-preview: :class:`RoleDefinitionsOperations<azure.mgmt.authorization.v2018_01_01_prev...
Instance depends on the API version: * 2015-07-01: :class:`RoleDefinitionsOperations<azure.mgmt.authorization.v2015_07_01.operations.RoleDefinitionsOperations>` * 2018-01-01-preview: :class:`RoleDefinitionsOperations<azure.mgmt.authorization.v2018_01_01_preview.operations.RoleDefinitionsOperation...
def stream_json_lines(file): """ Load a JSON stream and return a generator, yielding one object at a time. """ if isinstance(file, string_type): file = open(file, 'rb') for line in file: line = line.strip() if line: if isinstance(line, bytes): line...
Load a JSON stream and return a generator, yielding one object at a time.
def read(cls, proto): """ Intercepts TemporalMemory deserialization request in order to initialize `self.infActiveState` @param proto (DynamicStructBuilder) Proto object @return (TemporalMemory) TemporalMemory shim instance """ tm = super(TMShimMixin, cls).read(proto) tm.infActiveState...
Intercepts TemporalMemory deserialization request in order to initialize `self.infActiveState` @param proto (DynamicStructBuilder) Proto object @return (TemporalMemory) TemporalMemory shim instance
def format_private_ip_address(result): ''' Formats the PrivateIPAddress object removing arguments that are empty ''' from collections import OrderedDict # Only display parameters that have content order_dict = OrderedDict() if result.ip_address is not None: order_dict['ipAddress'] = ...
Formats the PrivateIPAddress object removing arguments that are empty
def embed(self, url, **kwargs): """ The heart of the matter """ try: # first figure out the provider provider = self.provider_for_url(url) except OEmbedMissingEndpoint: raise else: try: # check the database f...
The heart of the matter
def deploy( src, requirements=None, local_package=None, config_file='config.yaml', profile_name=None, preserve_vpc=False ): """Deploys a new function to AWS Lambda. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler...
Deploys a new function to AWS Lambda. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or...
def generate(env): """Add Builders and construction variables for dvips to an Environment.""" global PSAction if PSAction is None: PSAction = SCons.Action.Action('$PSCOM', '$PSCOMSTR') global DVIPSAction if DVIPSAction is None: DVIPSAction = SCons.Action.Action(DviPsFunction, strfun...
Add Builders and construction variables for dvips to an Environment.
def _submit_result(self): """ Adding current values as a Raw Result and Resetting everything. Notice that we are not calculating final result of assay. We just set NP and GP values and in Bika, AS will have a Calculation to generate final result based on NP and GP values. ...
Adding current values as a Raw Result and Resetting everything. Notice that we are not calculating final result of assay. We just set NP and GP values and in Bika, AS will have a Calculation to generate final result based on NP and GP values.
def get_tags(self, rev=None): """ Get the tags for the given revision specifier (or the current revision if not specified). """ rev_num = self._get_rev_num(rev) # rev_num might end with '+', indicating local modifications. return ( set(self._read_tags_for_rev(rev_num)) if not rev_num.endswith('+') ...
Get the tags for the given revision specifier (or the current revision if not specified).
def simplify(self): """ Return a simplified expr in canonical form. This means double negations are canceled out and all contained boolean objects are in their canonical form. """ if self.iscanonical: return self expr = self.cancel() if not i...
Return a simplified expr in canonical form. This means double negations are canceled out and all contained boolean objects are in their canonical form.
def scoreatpercentile(inlist, percent): """ Returns the score at a given percentile relative to the distribution given by inlist. Usage: lscoreatpercentile(inlist,percent) """ if percent > 1: print("\nDividing percent>1 by 100 in lscoreatpercentile().\n") percent = percent / 100.0 targetc...
Returns the score at a given percentile relative to the distribution given by inlist. Usage: lscoreatpercentile(inlist,percent)
def rollback_savepoint(self, savepoint): """Rolls back to the given savepoint. :param savepoint: the name of the savepoint to rollback to :raise: pydbal.exception.DBALConnectionError """ if not self._platform.is_savepoints_supported(): raise DBALConnectionError.savep...
Rolls back to the given savepoint. :param savepoint: the name of the savepoint to rollback to :raise: pydbal.exception.DBALConnectionError
def patch(self, endpoint, data): """ Method to update an item The headers must include an If-Match containing the object _etag. headers = {'If-Match': contact_etag} The data dictionary contain the fields that must be modified. If the patching fails because the _eta...
Method to update an item The headers must include an If-Match containing the object _etag. headers = {'If-Match': contact_etag} The data dictionary contain the fields that must be modified. If the patching fails because the _etag object do not match with the provided one, a ...
def read_all(filename): """ Reads the serialized objects from disk. Caller must wrap objects in appropriate Python wrapper classes. :param filename: the file with the serialized objects :type filename: str :return: the list of JB_OBjects :rtype: list """ array = javabridge.static_call( ...
Reads the serialized objects from disk. Caller must wrap objects in appropriate Python wrapper classes. :param filename: the file with the serialized objects :type filename: str :return: the list of JB_OBjects :rtype: list
def calc_synch_eta(b, ne, delta, sinth, nu, E0=1.): """Calculate the relativistic synchrotron emission coefficient η_ν. This is Dulk (1985) equation 40, which is an approximation assuming a power-law electron population. Arguments are: b Magnetic field strength in Gauss ne The density ...
Calculate the relativistic synchrotron emission coefficient η_ν. This is Dulk (1985) equation 40, which is an approximation assuming a power-law electron population. Arguments are: b Magnetic field strength in Gauss ne The density of electrons per cubic centimeter with energies greater tha...
def get_opt_repairs_add_remove_edges_greedy(instance,nm, edges): ''' only apply with elementary path consistency notion ''' sem = [sign_cons_prg, elem_path_prg, fwd_prop_prg, bwd_prop_prg] inst = instance.to_file() f_edges = TermSet(edges).to_file() prg = [ inst, f_edges, remove_edges_prg...
only apply with elementary path consistency notion
def list(self, resource, url_prefix, auth, session, send_opts): """List all resources of the same type as the given resource. Args: resource (intern.resource.boss.BossResource): List resources of the same type as this.. url_prefix (string): Protocol + host such as https://api.th...
List all resources of the same type as the given resource. Args: resource (intern.resource.boss.BossResource): List resources of the same type as this.. url_prefix (string): Protocol + host such as https://api.theboss.io auth (string): Token to send in the request header. ...
def _extract_alphabet(self, grammar): """ Extract an alphabet from the given grammar. """ alphabet = set([]) for terminal in grammar.Terminals: alphabet |= set([x for x in terminal]) self.alphabet = list(alphabet)
Extract an alphabet from the given grammar.
def findAllCfgTasksUnderDir(aDir): """ Finds all installed tasks by examining any .cfg files found on disk at and under the given directory, as an installation might be. This returns a dict of { file name : task name } """ retval = {} for f in irafutils.rglob(aDir, '*.cfg'): retv...
Finds all installed tasks by examining any .cfg files found on disk at and under the given directory, as an installation might be. This returns a dict of { file name : task name }
def add_node_collection(self, node, collection): """Add the collected test items from a node Collection is complete once all nodes have submitted their collection. In this case its pending list is set to an empty list. When the collection is already completed this submission i...
Add the collected test items from a node Collection is complete once all nodes have submitted their collection. In this case its pending list is set to an empty list. When the collection is already completed this submission is from a node which was restarted to replace a dead ...
def new(cls, gen: Generator, sign_key: SignKey) -> 'VerKey': """ Creates and returns BLS ver key that corresponds to the given generator and sign key. :param: gen - Generator :param: sign_key - Sign Key :return: BLS verification key """ logger = logging.getLogger(...
Creates and returns BLS ver key that corresponds to the given generator and sign key. :param: gen - Generator :param: sign_key - Sign Key :return: BLS verification key
def transform(self, data): """ Transforms the data. """ if not self._get("fitted"): raise RuntimeError("`transform` called before `fit` or `fit_transform`.") data = data.copy() output_column_prefix = self._get("output_column_prefix") if output_colum...
Transforms the data.
def encrypt(self, key): """This method encrypts and signs the state to make it unreadable by the server, since it contains information that would allow faking proof of storage. :param key: the key to encrypt and sign with """ if (self.encrypted): return ...
This method encrypts and signs the state to make it unreadable by the server, since it contains information that would allow faking proof of storage. :param key: the key to encrypt and sign with
def add_tokens_for_single(self, ignore=False): """Add the tokens for the single signature""" args = self.single.args name = self.single.python_name # Reset indentation to proper amount and add signature self.reset_indentation(self.indent_type * self.single.indent) self.r...
Add the tokens for the single signature
def bot_config(player_config_path: Path, team: Team) -> 'PlayerConfig': """ A function to cover the common case of creating a config for a bot. """ bot_config = PlayerConfig() bot_config.bot = True bot_config.rlbot_controlled = True bot_config.team = team.value ...
A function to cover the common case of creating a config for a bot.