code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def press_key(self, key, mode=0): ''' modes: 0 -> simple press 1 -> long press 2 -> release after long press ''' if isinstance(key, str): assert key in KEYS, 'No such key: {}'.format(key) key = KEYS[key] _LOGGER.info('Pr...
modes: 0 -> simple press 1 -> long press 2 -> release after long press
def start_vm(access_token, subscription_id, resource_group, vm_name): '''Start a virtual machine. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vm_name (str): Name of t...
Start a virtual machine. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vm_name (str): Name of the virtual machine. Returns: HTTP response.
def add_execution_data(self, context_id, data): """Within a context, append data to the execution result. Args: context_id (str): the context id returned by create_context data (bytes): data to append Returns: (bool): True if the operation is successful, Fal...
Within a context, append data to the execution result. Args: context_id (str): the context id returned by create_context data (bytes): data to append Returns: (bool): True if the operation is successful, False if the context_id doesn't reference a kn...
def get_max_instances_of_storage_bus(self, chipset, bus): """Returns the maximum number of storage bus instances which can be configured for each VM. This corresponds to the number of storage controllers one can have. Value may depend on chipset type used. in chipset of type :cl...
Returns the maximum number of storage bus instances which can be configured for each VM. This corresponds to the number of storage controllers one can have. Value may depend on chipset type used. in chipset of type :class:`ChipsetType` The chipset type to get the value for. ...
def p_expression_sra(self, p): 'expression : expression RSHIFTA expression' p[0] = Sra(p[1], p[3], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
expression : expression RSHIFTA expression
def get_cutout(self, token, channel, x_start, x_stop, y_start, y_stop, z_start, z_stop, t_start=0, t_stop=1, resolution=1, block_size=DEFAULT_BLOCK_SIZE, neariso=False): """ ...
Get volumetric cutout data from the neurodata server. Arguments: token (str): Token to identify data to download channel (str): Channel resolution (int): Resolution level Q_start (int): The lower bound of dimension 'Q' Q_stop (int): The upper bound of...
def _warning_handler(self, code: int): """处理300~399段状态码,抛出对应警告. Parameters: (code): - 响应的状态码 Return: (bool): - 已知的警告类型则返回True,否则返回False """ if code == 300: warnings.warn( "ExpireWarning", RuntimeWarning, ...
处理300~399段状态码,抛出对应警告. Parameters: (code): - 响应的状态码 Return: (bool): - 已知的警告类型则返回True,否则返回False
def WriteProtoFile(self, printer): """Write the messages file to out as proto.""" self.Validate() extended_descriptor.WriteMessagesFile( self.__file_descriptor, self.__package, self.__client_info.version, printer)
Write the messages file to out as proto.
def get_algorithm(alg: str) -> Callable: """ :param alg: The name of the requested `JSON Web Algorithm <https://tools.ietf.org/html/rfc7519#ref-JWA>`_. `RFC7518 <https://tools.ietf.org/html/rfc7518#section-3.2>`_ is related. :type alg: str :return: The requested algorithm. :rtype: Callable :rais...
:param alg: The name of the requested `JSON Web Algorithm <https://tools.ietf.org/html/rfc7519#ref-JWA>`_. `RFC7518 <https://tools.ietf.org/html/rfc7518#section-3.2>`_ is related. :type alg: str :return: The requested algorithm. :rtype: Callable :raises: ValueError
def get_nearest_nodes(G, X, Y, method=None): """ Return the graph nodes nearest to a list of points. Pass in points as separate vectors of X and Y coordinates. The 'kdtree' method is by far the fastest with large data sets, but only finds approximate nearest nodes if working in unprojected coordinat...
Return the graph nodes nearest to a list of points. Pass in points as separate vectors of X and Y coordinates. The 'kdtree' method is by far the fastest with large data sets, but only finds approximate nearest nodes if working in unprojected coordinates like lat-lng (it precisely finds the nearest node ...
def remove_timedim(self, var): """Remove time dimension from dataset""" if self.pps and var.dims[0] == 'time': data = var[0, :, :] data.attrs = var.attrs var = data return var
Remove time dimension from dataset
def _zp_decode(self, msg): """ZP: Zone partitions.""" zone_partitions = [ord(x)-0x31 for x in msg[4:4+Max.ZONES.value]] return {'zone_partitions': zone_partitions}
ZP: Zone partitions.
def create_win32tz_map(windows_zones_xml): """Creates a map between Windows and Olson timezone names. Args: windows_zones_xml: The CLDR XML mapping. Yields: (win32_name, olson_name, comment) """ coming_comment = None win32_name = None territory = None parser = genshi.input.XMLParser(StringIO(w...
Creates a map between Windows and Olson timezone names. Args: windows_zones_xml: The CLDR XML mapping. Yields: (win32_name, olson_name, comment)
def set_enumerated_subtypes(self, subtype_fields, is_catch_all): """ Sets the list of "enumerated subtypes" for this struct. This differs from regular subtyping in that each subtype is associated with a tag that is used in the serialized format to indicate the subtype. Also, this...
Sets the list of "enumerated subtypes" for this struct. This differs from regular subtyping in that each subtype is associated with a tag that is used in the serialized format to indicate the subtype. Also, this list of subtypes was explicitly defined in an "inner-union" in the specifica...
def mcc(y, z): """Matthews correlation coefficient """ tp, tn, fp, fn = contingency_table(y, z) return (tp * tn - fp * fn) / K.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn))
Matthews correlation coefficient
def intersection(l1, l2): '''Returns intersection of two lists. Assumes the lists are sorted by start positions''' if len(l1) == 0 or len(l2) == 0: return [] out = [] l2_pos = 0 for l in l1: while l2_pos < len(l2) and l2[l2_pos].end < l.start: l2_pos += 1 if l...
Returns intersection of two lists. Assumes the lists are sorted by start positions
def init_request(self): """ Init the native request using the okhttp3.Request.Builder """ #: Build the request builder = Request.Builder() builder.url(self.url) #: Set any headers for k, v in self.headers.items(): builder.addHeader(k, v) #: Get the ...
Init the native request using the okhttp3.Request.Builder
def _read_python_source(self, filename): """ Do our best to decode a Python source file correctly. """ try: f = open(filename, "rb") except IOError as err: self.log_error("Can't open %s: %s", filename, err) return None, None try: ...
Do our best to decode a Python source file correctly.
def named(self, name): '''Returns .get_by('name', name)''' name = self.serialize(name) return self.get_by('name', name)
Returns .get_by('name', name)
def getDarkCurrentAverages(exposuretimes, imgs): ''' return exposure times, image averages for each exposure time ''' x, imgs_p = sortForSameExpTime(exposuretimes, imgs) s0, s1 = imgs[0].shape imgs = np.empty(shape=(len(x), s0, s1), dtype=imgs[0].dtype) for i, i...
return exposure times, image averages for each exposure time
def projScatter(lon, lat, **kwargs): """ Create a scatter plot on HEALPix projected axes. Inputs: lon (deg), lat (deg) """ hp.projscatter(lon, lat, lonlat=True, **kwargs)
Create a scatter plot on HEALPix projected axes. Inputs: lon (deg), lat (deg)
def _string_from_ip_int(self, ip_int=None): """Turns a 128-bit integer into hexadecimal notation. Args: ip_int: An integer, the IP address. Returns: A string, the hexadecimal representation of the address. Raises: ValueError: The address is bigger t...
Turns a 128-bit integer into hexadecimal notation. Args: ip_int: An integer, the IP address. Returns: A string, the hexadecimal representation of the address. Raises: ValueError: The address is bigger than 128 bits of all ones.
def publish(self, rawtx): """Publish signed <rawtx> to bitcoin network.""" tx = deserialize.signedtx(rawtx) if not self.dryrun: self.service.send_tx(tx) return serialize.txid(tx.hash())
Publish signed <rawtx> to bitcoin network.
def pgettext(msgctxt, message): """'Particular gettext' function. It works with 'msgctxt' .po modifiers and allow duplicate keys with different translations. Python 2 don't have support for this GNU gettext function, so we reimplement it. It works by joining msgctx and msgid by '4' byte.""" key ...
Particular gettext' function. It works with 'msgctxt' .po modifiers and allow duplicate keys with different translations. Python 2 don't have support for this GNU gettext function, so we reimplement it. It works by joining msgctx and msgid by '4' byte.
def add_droplets(self, droplet): """ Add the Tag to a Droplet. Attributes accepted at creation time: droplet: array of string or array of int, or array of Droplets. """ droplets = droplet if not isinstance(droplets, list): droplets = [...
Add the Tag to a Droplet. Attributes accepted at creation time: droplet: array of string or array of int, or array of Droplets.
def set_webconfiguration_settings(name, settings, location=''): r''' Set the value of the setting for an IIS container. Args: name (str): The PSPath of the IIS webconfiguration settings. settings (list): A list of dictionaries containing setting name, filter and value. location (str...
r''' Set the value of the setting for an IIS container. Args: name (str): The PSPath of the IIS webconfiguration settings. settings (list): A list of dictionaries containing setting name, filter and value. location (str): The location of the settings (optional) Returns: boo...
def show(self): """Print innards of model, without regards to type.""" if self._future: self._job.poll_once() return if self._model_json is None: print("No model trained yet") return if self.model_id is None: print("This H2OEsti...
Print innards of model, without regards to type.
def _validate_class(self, cl): """return error if class `cl` is not found in the ontology""" if cl not in self.schema_def.attributes_by_class: search_string = self._build_search_string(cl) err = self.err( "{0} - invalid class", self._field_name_from_uri(cl), ...
return error if class `cl` is not found in the ontology
def git_path_valid(git_path=None): """ Check whether the git executable is found. """ if git_path is None and GIT_PATH is None: return False if git_path is None: git_path = GIT_PATH try: call([git_path, '--version']) return True except OSError: return False
Check whether the git executable is found.
def _handle_consent_response(self, context): """ Endpoint for handling consent service response :type context: satosa.context.Context :rtype: satosa.response.Response :param context: response context :return: response """ consent_state = context.state[STA...
Endpoint for handling consent service response :type context: satosa.context.Context :rtype: satosa.response.Response :param context: response context :return: response
def elements(self): '''Iterator over elements repeating each as many times as its count. >>> c = Counter('ABCABC') >>> sorted(c.elements()) ['A', 'A', 'B', 'B', 'C', 'C'] If an element's count has been set to zero or is a negative number, elements() will ignore it. ...
Iterator over elements repeating each as many times as its count. >>> c = Counter('ABCABC') >>> sorted(c.elements()) ['A', 'A', 'B', 'B', 'C', 'C'] If an element's count has been set to zero or is a negative number, elements() will ignore it.
def div(self, key, value=2): """Divides the specified key value by the specified value. :param str|unicode key: :param int value: :rtype: bool """ return uwsgi.cache_mul(key, value, self.timeout, self.name)
Divides the specified key value by the specified value. :param str|unicode key: :param int value: :rtype: bool
def walklevel(path, depth = -1, **kwargs): """It works just like os.walk, but you can pass it a level parameter that indicates how deep the recursion will go. If depth is -1 (or less than 0), the full depth is walked. """ # if depth is negative, just walk if depth < 0: ...
It works just like os.walk, but you can pass it a level parameter that indicates how deep the recursion will go. If depth is -1 (or less than 0), the full depth is walked.
def on_configurationdone_request(self, py_db, request): ''' :param ConfigurationDoneRequest request: ''' self.api.run(py_db) configuration_done_response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, configuration_done_response, is_json=True...
:param ConfigurationDoneRequest request:
def encode_for_locale(s): """ Encode text items for system locale. If encoding fails, fall back to ASCII. """ try: return s.encode(LOCALE_ENCODING, 'ignore') except (AttributeError, UnicodeDecodeError): return s.decode('ascii', 'ignore').encode(LOCALE_ENCODING)
Encode text items for system locale. If encoding fails, fall back to ASCII.
def new(self, *args, **kwargs): '''Create a new instance of :attr:`model` and commit it to the backend server. This a shortcut method for the more verbose:: instance = manager.session().add(MyModel(**kwargs)) ''' return self.session().add(self.model(*args, **kwargs))
Create a new instance of :attr:`model` and commit it to the backend server. This a shortcut method for the more verbose:: instance = manager.session().add(MyModel(**kwargs))
def wrap_exceptions(callable): """Call callable into a try/except clause and translate ENOENT, EACCES and EPERM in NoSuchProcess or AccessDenied exceptions. """ def wrapper(self, *args, **kwargs): try: return callable(self, *args, **kwargs) except EnvironmentError: ...
Call callable into a try/except clause and translate ENOENT, EACCES and EPERM in NoSuchProcess or AccessDenied exceptions.
def publish(self, load): ''' Publish "load" to minions ''' payload = {'enc': 'aes'} crypticle = salt.crypt.Crypticle(self.opts, salt.master.SMaster.secrets['aes']['secret'].value) payload['load'] = crypticle.dumps(load) if self.opts['sign_pub_messages']: ...
Publish "load" to minions
def return_action(self, text, loc, ret): """Code executed after recognising a return statement""" exshared.setpos(loc, text) if DEBUG > 0: print("RETURN:",ret) if DEBUG == 2: self.symtab.display() if DEBUG > 2: return if not self.symtab.same_typ...
Code executed after recognising a return statement
def greenlet_timeouts(self): """ This greenlet kills jobs in other greenlets if they timeout. """ while True: now = datetime.datetime.utcnow() for greenlet in list(self.gevent_pool): job = get_current_job(id(greenlet)) if job and job.timeo...
This greenlet kills jobs in other greenlets if they timeout.
def clean_existing(self, value): """Clean the data and return an existing document with its fields updated based on the cleaned values. """ existing_pk = value[self.pk_field] try: obj = self.fetch_existing(existing_pk) except ReferenceNotFoundError: ...
Clean the data and return an existing document with its fields updated based on the cleaned values.
def update_extent_from_rectangle(self): """Update extent value in GUI based from the QgsMapTool rectangle. .. note:: Delegates to update_extent() """ self.show() self.canvas.unsetMapTool(self.rectangle_map_tool) self.canvas.setMapTool(self.pan_tool) rectangle =...
Update extent value in GUI based from the QgsMapTool rectangle. .. note:: Delegates to update_extent()
def ensure_dir(path): """Ensure directory exists. Args: path(str): dir path """ dirpath = os.path.dirname(path) if dirpath and not os.path.exists(dirpath): os.makedirs(dirpath)
Ensure directory exists. Args: path(str): dir path
def _should_run(het_file): """Check for enough input data to proceed with analysis. """ has_hets = False with open(het_file) as in_handle: for i, line in enumerate(in_handle): if i > 1: has_hets = True break return has_hets
Check for enough input data to proceed with analysis.
def type_alias(self): """Return the type alias this target was constructed via. For a target read from a BUILD file, this will be target alias, like 'java_library'. For a target constructed in memory, this will be the simple class name, like 'JavaLibrary'. The end result is that the type alias should ...
Return the type alias this target was constructed via. For a target read from a BUILD file, this will be target alias, like 'java_library'. For a target constructed in memory, this will be the simple class name, like 'JavaLibrary'. The end result is that the type alias should be the most natural way to re...
def _pred(aclass): """ :param aclass :return: boolean """ isaclass = inspect.isclass(aclass) return isaclass and aclass.__module__ == _pred.__module__
:param aclass :return: boolean
def sample(self, cursor): """Extract records randomly from the database. Continue until the target proportion of the items have been extracted, or until `min_items` if this is larger. If `max_items` is non-negative, do not extract more than these. This function is a generator, y...
Extract records randomly from the database. Continue until the target proportion of the items have been extracted, or until `min_items` if this is larger. If `max_items` is non-negative, do not extract more than these. This function is a generator, yielding items incrementally. ...
def down(force): """ destroys an existing cluster """ try: cloud_config = CloudConfig() cloud_controller = CloudController(cloud_config) cloud_controller.down(force) except CloudComposeException as ex: print(ex)
destroys an existing cluster
def package_releases(self, package, url_fmt=lambda u: u): """List all versions of a package Along with the version, the caller also receives the file list with all the available formats. """ return [{ 'name': package, 'version': version, 'urls...
List all versions of a package Along with the version, the caller also receives the file list with all the available formats.
def focus_up(pymux): " Move focus up. " _move_focus(pymux, lambda wp: wp.xpos, lambda wp: wp.ypos - 2)
Move focus up.
def touch(self): """ Respond to ``nsqd`` that you need more time to process the message. """ assert not self._has_responded self.trigger(event.TOUCH, message=self)
Respond to ``nsqd`` that you need more time to process the message.
def close(self, reason=None): """Stop consuming messages and shutdown all helper threads. This method is idempotent. Additional calls will have no effect. Args: reason (Any): The reason to close this. If None, this is considered an "intentional" shutdown. This is pa...
Stop consuming messages and shutdown all helper threads. This method is idempotent. Additional calls will have no effect. Args: reason (Any): The reason to close this. If None, this is considered an "intentional" shutdown. This is passed to the callbacks spe...
def from_string(values, separator, remove_duplicates = False): """ Splits specified string into elements using a separator and assigns the elements to a newly created AnyValueArray. :param values: a string value to be split and assigned to AnyValueArray :param separator: a sepa...
Splits specified string into elements using a separator and assigns the elements to a newly created AnyValueArray. :param values: a string value to be split and assigned to AnyValueArray :param separator: a separator to split the string :param remove_duplicates: (optional) true to rem...
def _scan_block(self, cfg_job): """ Scan a basic block starting at a specific address :param CFGJob cfg_job: The CFGJob instance. :return: a list of successors :rtype: list """ addr = cfg_job.addr current_func_addr = cfg_job.func_addr if self._a...
Scan a basic block starting at a specific address :param CFGJob cfg_job: The CFGJob instance. :return: a list of successors :rtype: list
def constraint(self): """Constraint string""" constraint_arr = [] if self._not_null: constraint_arr.append("PRIMARY KEY" if self._pk else "NOT NULL") if self._unique: constraint_arr.append("UNIQUE") return " ".join(constraint_arr)
Constraint string
def get(self, list_id, segment_id): """ returns the specified list segment. """ return self._mc_client._get(url=self._build_path(list_id, 'segments', segment_id))
returns the specified list segment.
def _safe_sendBreak_v2_7(self): # pylint: disable=invalid-name """! pyserial 2.7 API implementation of sendBreak/setBreak @details Below API is deprecated for pyserial 3.x versions! http://pyserial.readthedocs.org/en/latest/pyserial_api.html#serial.Serial.sendBreak http://pyseri...
! pyserial 2.7 API implementation of sendBreak/setBreak @details Below API is deprecated for pyserial 3.x versions! http://pyserial.readthedocs.org/en/latest/pyserial_api.html#serial.Serial.sendBreak http://pyserial.readthedocs.org/en/latest/pyserial_api.html#serial.Serial.setBreak
def init_default(m:nn.Module, func:LayerFunc=nn.init.kaiming_normal_)->None: "Initialize `m` weights with `func` and set `bias` to 0." if func: if hasattr(m, 'weight'): func(m.weight) if hasattr(m, 'bias') and hasattr(m.bias, 'data'): m.bias.data.fill_(0.) return m
Initialize `m` weights with `func` and set `bias` to 0.
def ip4_address(self): """Returns the IPv4 address of the network interface. If multiple interfaces are provided, the address of the first found is returned. """ if self._ip4_address is None and self.network is not None: self._ip4_address = self._get_ip_address( ...
Returns the IPv4 address of the network interface. If multiple interfaces are provided, the address of the first found is returned.
def _exec_loop(self, a, bd_all, mask): """Solves the kriging system by looping over all specified points. Less memory-intensive, but involves a Python-level loop.""" npt = bd_all.shape[0] n = self.X_ADJUSTED.shape[0] kvalues = np.zeros(npt) sigmasq = np.zeros(npt) ...
Solves the kriging system by looping over all specified points. Less memory-intensive, but involves a Python-level loop.
def _flip_kron_order(mat4x4: np.ndarray) -> np.ndarray: """Given M = sum(kron(a_i, b_i)), returns M' = sum(kron(b_i, a_i)).""" result = np.array([[0] * 4] * 4, dtype=np.complex128) order = [0, 2, 1, 3] for i in range(4): for j in range(4): result[order[i], ord...
Given M = sum(kron(a_i, b_i)), returns M' = sum(kron(b_i, a_i)).
def _push_new_tag_to_git(self): """ tags a new release and pushes to origin/master """ print("Pushing new version to git") ## stage the releasefile and initfileb subprocess.call(["git", "add", self.release_file]) subprocess.call(["git", "add", self.in...
tags a new release and pushes to origin/master
def get(self, byte_sig: str, online_timeout: int = 2) -> List[str]: """Get a function text signature for a byte signature 1) try local cache 2) try online lookup (if enabled; if not flagged as unavailable) :param byte_sig: function signature hash as hexstr :param online_timeout: online ...
Get a function text signature for a byte signature 1) try local cache 2) try online lookup (if enabled; if not flagged as unavailable) :param byte_sig: function signature hash as hexstr :param online_timeout: online lookup timeout :return: list of matching function text signatures
def inject_code(self, payload, lpParameter = 0): """ Injects relocatable code into the process memory and executes it. @warning: Don't forget to free the memory when you're done with it! Otherwise you'll be leaking memory in the target process. @see: L{inject_dll} ...
Injects relocatable code into the process memory and executes it. @warning: Don't forget to free the memory when you're done with it! Otherwise you'll be leaking memory in the target process. @see: L{inject_dll} @type payload: str @param payload: Relocatable code to run i...
def calc_bhhh_hessian_approximation_mixed_logit(params, design_3d, alt_IDs, rows_to_obs, rows_to_alts, ...
Parameters ---------- params : 1D ndarray. All elements should by ints, floats, or longs. Should have 1 element for each utility coefficient being estimated (i.e. num_features + num_coefs_being_mixed). design_3d : 3D ndarray. All elements should be ints, floats, or longs. Sh...
def check_spelling(spelling_lang, txt): """ Check the spelling in the text, and compute a score. The score is the number of words correctly (or almost correctly) spelled, minus the number of mispelled words. Words "almost" correct remains neutral (-> are not included in the score) Returns: ...
Check the spelling in the text, and compute a score. The score is the number of words correctly (or almost correctly) spelled, minus the number of mispelled words. Words "almost" correct remains neutral (-> are not included in the score) Returns: A tuple : (fixed text, score)
def get_date_datetime_param(self, request, param): """Check the request for the provided query parameter and returns a rounded value. :param request: WSGI request object to retrieve query parameter data. :param param: the name of the query parameter. """ if param in request.GET:...
Check the request for the provided query parameter and returns a rounded value. :param request: WSGI request object to retrieve query parameter data. :param param: the name of the query parameter.
def get_traceback_data(self): """Return a dictionary containing traceback information.""" default_template_engine = None if default_template_engine is None: template_loaders = [] frames = self.get_traceback_frames() for i, frame in enumerate(frames): if ...
Return a dictionary containing traceback information.
def add_source_get_correlated(gta, name, src_dict, correl_thresh=0.25, non_null_src=False): """Add a source and get the set of correlated sources Parameters ---------- gta : `fermipy.gtaanalysis.GTAnalysis` The analysis object name : str Name of the source we are adding src_d...
Add a source and get the set of correlated sources Parameters ---------- gta : `fermipy.gtaanalysis.GTAnalysis` The analysis object name : str Name of the source we are adding src_dict : dict Dictionary of the source parameters correl_thresh : float Threshold...
def get_info(self, wiki=None, show=True, proxy=None, timeout=0): """ GET site info (general, statistics, siteviews, mostviewed) via https://www.mediawiki.org/wiki/API:Siteinfo, and https://www.mediawiki.org/wiki/Extension:PageViewInfo Optional arguments: - [wiki]: <str> ...
GET site info (general, statistics, siteviews, mostviewed) via https://www.mediawiki.org/wiki/API:Siteinfo, and https://www.mediawiki.org/wiki/Extension:PageViewInfo Optional arguments: - [wiki]: <str> alternate wiki site (default=en.wikipedia.org) - [show]: <bool> echo page dat...
def elliptical_arc_to(x1, y1, rx, ry, phi, large_arc_flag, sweep_flag, x2, y2): """ An elliptical arc approximated with Bezier curves or a line segment. Algorithm taken from the SVG 1.1 Implementation Notes: http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes """ # Basic normalizati...
An elliptical arc approximated with Bezier curves or a line segment. Algorithm taken from the SVG 1.1 Implementation Notes: http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes
def main(): """ NAME k15_s.py DESCRIPTION converts .k15 format data to .s format. assumes Jelinek Kappabridge measurement scheme SYNTAX k15_s.py [-h][-i][command line options][<filename] OPTIONS -h prints help message and quits -i allows inte...
NAME k15_s.py DESCRIPTION converts .k15 format data to .s format. assumes Jelinek Kappabridge measurement scheme SYNTAX k15_s.py [-h][-i][command line options][<filename] OPTIONS -h prints help message and quits -i allows interactive entry of options...
def contains_some_of(self, elements): """ Ensures :attr:`subject` contains at least one of *elements*, which must be an iterable. """ if all(e not in self._subject for e in elements): raise self._error_factory(_format("Expected {} to have some of {}", self._subject, elements)...
Ensures :attr:`subject` contains at least one of *elements*, which must be an iterable.
def random_state(state=None): """ Helper function for processing random_state arguments. Parameters ---------- state : int, np.random.RandomState, None. If receives an int, passes to np.random.RandomState() as seed. If receives an np.random.RandomState object, just returns object. ...
Helper function for processing random_state arguments. Parameters ---------- state : int, np.random.RandomState, None. If receives an int, passes to np.random.RandomState() as seed. If receives an np.random.RandomState object, just returns object. If receives `None`, returns np.rand...
def write_sampler_metadata(self, sampler): """Writes the sampler's metadata.""" self.attrs['sampler'] = sampler.name self[self.sampler_group].attrs['nwalkers'] = sampler.nwalkers # write the model's metadata sampler.model.write_metadata(self)
Writes the sampler's metadata.
def get_dist(dist): """Return a distribution object from scipy.stats. """ from scipy import stats dc = getattr(stats, dist, None) if dc is None: e = "Statistical distribution `{}` is not in scipy.stats.".format(dist) raise ValueError(e) return dc
Return a distribution object from scipy.stats.
def _get_prefixes(self, metric_type): """Get prefixes where applicable Add metric prefix counters, timers respectively if :attr:`prepend_metric_type` flag is True. :param str metric_type: The metric type :rtype: list """ prefixes = [] if self._prepend_m...
Get prefixes where applicable Add metric prefix counters, timers respectively if :attr:`prepend_metric_type` flag is True. :param str metric_type: The metric type :rtype: list
def cleanTempDirs(job): """Remove temporarly created directories.""" if job is CWLJob and job._succeeded: # Only CWLJobs have this attribute. for tempDir in job.openTempDirs: if os.path.exists(tempDir): shutil.rmtree(tempDir) job.openTempDirs = []
Remove temporarly created directories.
def drop_if_exists(self, table): """ Drop a table from the schema. :param table: The table :type table: str """ blueprint = self._create_blueprint(table) blueprint.drop_if_exists() self._build(blueprint)
Drop a table from the schema. :param table: The table :type table: str
def get_events(fd, timeout=None): """get_events(fd[, timeout]) Return a list of InotifyEvent instances representing events read from inotify. If timeout is None, this will block forever until at least one event can be read. Otherwise, timeout should be an integer or float specifying a timeout in ...
get_events(fd[, timeout]) Return a list of InotifyEvent instances representing events read from inotify. If timeout is None, this will block forever until at least one event can be read. Otherwise, timeout should be an integer or float specifying a timeout in seconds. If get_events times out waiting...
def encode_dict(dynamizer, value): """ Encode a dict for the DynamoDB format """ encoded_dict = {} for k, v in six.iteritems(value): encoded_type, encoded_value = dynamizer.raw_encode(v) encoded_dict[k] = { encoded_type: encoded_value, } return 'M', encoded_dict
Encode a dict for the DynamoDB format
def _count_spaces_startswith(line): ''' Count the number of spaces before the first character ''' if line.split('#')[0].strip() == "": return None spaces = 0 for i in line: if i.isspace(): spaces += 1 else: return spaces
Count the number of spaces before the first character
def _get_mro(cls): """Get an mro for a type or classic class""" if not isinstance(cls, type): class cls(cls, object): pass return cls.__mro__[1:] return cls.__mro__
Get an mro for a type or classic class
def plot(self, joints, ax, target=None, show=False): """Plots the Chain using Matplotlib Parameters ---------- joints: list The list of the positions of each joint ax: matplotlib.axes.Axes A matplotlib axes target: numpy.array An optio...
Plots the Chain using Matplotlib Parameters ---------- joints: list The list of the positions of each joint ax: matplotlib.axes.Axes A matplotlib axes target: numpy.array An optional target show: bool Display the axe. Defau...
def img_from_vgg(x): '''Decondition an image from the VGG16 model.''' x = x.transpose((1, 2, 0)) x[:, :, 0] += 103.939 x[:, :, 1] += 116.779 x[:, :, 2] += 123.68 x = x[:,:,::-1] # to RGB return x
Decondition an image from the VGG16 model.
def _parse_byte_data(self, byte_data): """Extract the values from byte string.""" chunks = unpack('<iiiii', byte_data[:self.size]) det_id, run, time_slice, time_stamp, ticks = chunks self.det_id = det_id self.run = run self.time_slice = time_slice self.time_stamp ...
Extract the values from byte string.
def is_contained_in(pe_pe, root): ''' Determine if a PE_PE is contained within a EP_PKG or a C_C. ''' if not pe_pe: return False if type(pe_pe).__name__ != 'PE_PE': pe_pe = one(pe_pe).PE_PE[8001]() ep_pkg = one(pe_pe).EP_PKG[8000]() c_c = one(pe_pe).C_C[8003]() ...
Determine if a PE_PE is contained within a EP_PKG or a C_C.
def _get_signed_predecessors(im, node, polarity): """Get upstream nodes in the influence map. Return the upstream nodes along with the overall polarity of the path to that node by account for the polarity of the path to the given node and the polarity of the edge between the given node and its immediat...
Get upstream nodes in the influence map. Return the upstream nodes along with the overall polarity of the path to that node by account for the polarity of the path to the given node and the polarity of the edge between the given node and its immediate predecessors. Parameters ---------- im...
def zoneToRegion(zone): """Get a region (e.g. us-west-2) from a zone (e.g. us-west-1c).""" from toil.lib.context import Context return Context.availability_zone_re.match(zone).group(1)
Get a region (e.g. us-west-2) from a zone (e.g. us-west-1c).
def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(use...
Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup
def maxsize(self, size): """Resize the cache, evicting the oldest items if necessary.""" if size < 0: raise ValueError('maxsize must be non-negative') with self._lock: self._enforce_size_limit(size) self._maxsize = size
Resize the cache, evicting the oldest items if necessary.
def time_report(self, include_overhead=False, header=None, include_server=True, digits=4): """ Returns a str table of the times for this api call :param include_overhead: bool if True include information from overhead, such as the time for...
Returns a str table of the times for this api call :param include_overhead: bool if True include information from overhead, such as the time for this class code :param header: bool if True includes the column header :param include_server: bool if True...
def get_byte(self, i): """Get byte.""" value = [] for x in range(2): c = next(i) if c.lower() in _HEX: value.append(c) else: # pragma: no cover raise SyntaxError('Invalid byte character at %d!' % (i.index - 1)) return ...
Get byte.
def pi_zoom_origin(self, viewer, event, msg=True): """Like pi_zoom(), but pans the image as well to keep the coordinate under the cursor in that same position relative to the window. """ origin = (event.data_x, event.data_y) return self._pinch_zoom_rotate(viewer, event.st...
Like pi_zoom(), but pans the image as well to keep the coordinate under the cursor in that same position relative to the window.
def get_netloc(self): """Determine scheme, host and port for this connection taking proxy data into account. @return: tuple (scheme, host, port) @rtype: tuple(string, string, int) """ if self.proxy: scheme = self.proxytype host = self.proxyhost ...
Determine scheme, host and port for this connection taking proxy data into account. @return: tuple (scheme, host, port) @rtype: tuple(string, string, int)
def deserialize(self, value, **kwargs): """Deserialization of value. :return: Deserialized value. :raises: :class:`halogen.exception.ValidationError` exception if value is not valid. """ for validator in self.validators: validator.validate(value, **kwargs) r...
Deserialization of value. :return: Deserialized value. :raises: :class:`halogen.exception.ValidationError` exception if value is not valid.
def _reciprocal_condition_number(lu_mat, one_norm): r"""Compute reciprocal condition number of a matrix. Args: lu_mat (numpy.ndarray): A 2D array of a matrix :math:`A` that has been LU-factored, with the non-diagonal part of :math:`L` stored in the strictly lower triangle and :m...
r"""Compute reciprocal condition number of a matrix. Args: lu_mat (numpy.ndarray): A 2D array of a matrix :math:`A` that has been LU-factored, with the non-diagonal part of :math:`L` stored in the strictly lower triangle and :math:`U` stored in the upper triangle. one_norm (...
def set_user_attribute(self, user_name, key, value): """Sets a user attribute :param user_name: name of user to modify :param key: key of the attribute to set :param value: value to set :returns: True if the operation succeeded, False otherwise :raises: HTTPResponseError...
Sets a user attribute :param user_name: name of user to modify :param key: key of the attribute to set :param value: value to set :returns: True if the operation succeeded, False otherwise :raises: HTTPResponseError in case an HTTP error status was returned
def get_content(self, obj): """ Obtain the QuerySet of content items. :param obj: Page object. :return: List of rendered content items. """ serializer = ContentSerializer( instance=obj.contentitem_set.all(), many=True, context=self.cont...
Obtain the QuerySet of content items. :param obj: Page object. :return: List of rendered content items.
def p_elseif_list(p): '''elseif_list : empty | elseif_list ELSEIF LPAREN expr RPAREN statement''' if len(p) == 2: p[0] = [] else: p[0] = p[1] + [ast.ElseIf(p[4], p[6], lineno=p.lineno(2))]
elseif_list : empty | elseif_list ELSEIF LPAREN expr RPAREN statement