code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def quadkey_to_tile(quadkey): """Transform quadkey to tile coordinates""" tile_x, tile_y = (0, 0) level = len(quadkey) for i in xrange(level): bit = level - i mask = 1 << (bit - 1) if quadkey[level - bit] == '1': tile_x |= mask ...
Transform quadkey to tile coordinates
def model_select( self, score_function, alleles=None, min_models=1, max_models=10000): """ Perform model selection using a user-specified scoring function. Model selection is done using a "step up" variable selection procedure, ...
Perform model selection using a user-specified scoring function. Model selection is done using a "step up" variable selection procedure, in which models are repeatedly added to an ensemble until the score stops improving. Parameters ---------- score_function : Class1Aff...
def activate_membercard(self, membership_number, code, **kwargs): """ 激活会员卡 - 接口激活方式 详情请参见 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1451025283 参数示例: { "init_bonus": 100, "init_bonus_record":"旧积分同步", "init_balance": 200, ...
激活会员卡 - 接口激活方式 详情请参见 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1451025283 参数示例: { "init_bonus": 100, "init_bonus_record":"旧积分同步", "init_balance": 200, "membership_number": "AAA00000001", "code": "12312313", ...
def get_external_references(self): """ Iterator that returns all the external reference objects of the external references object @rtype: L{CexternalReference} @return: the external reference objects """ for ext_ref_node in self.node.findall('externalRef'): ex...
Iterator that returns all the external reference objects of the external references object @rtype: L{CexternalReference} @return: the external reference objects
def lookup(self, path, must_be_leaf = False): '''Looks up a part of the color scheme. If used for looking up colors, must_be_leaf should be True.''' assert(type(path) == type(self.name)) d = self.color_scheme tokens = path.split('.') for t in tokens[:-1]: d = d.get(t...
Looks up a part of the color scheme. If used for looking up colors, must_be_leaf should be True.
def _add_services(self, this_service, other_services, use_source=None, no_origin=None): """Add services to the deployment and optionally set openstack-origin/source. :param this_service dict: Service dictionary describing the service whose...
Add services to the deployment and optionally set openstack-origin/source. :param this_service dict: Service dictionary describing the service whose amulet tests are being run :param other_services dict: List of service dictionaries describing ...
def from_response(response): """Returns the correct error type from a ::class::`Response` object.""" if response.code: return ERRORS[response.code](response) else: return Error(response)
Returns the correct error type from a ::class::`Response` object.
def send(self, msg): """Send `data` to `handle`, and tell the broker we have output. May be called from any thread.""" self._router.broker.defer(self._send, msg)
Send `data` to `handle`, and tell the broker we have output. May be called from any thread.
def register_on_state_changed(self, callback): """Set the callback function to consume on state changed events which are generated when the state of the machine changes. Callback receives a IStateChangeEvent object. Returns the callback_id """ event_type = library.VBoxE...
Set the callback function to consume on state changed events which are generated when the state of the machine changes. Callback receives a IStateChangeEvent object. Returns the callback_id
def _parse_boolean(value, default=False): """ Attempt to cast *value* into a bool, returning *default* if it fails. """ if value is None: return default try: return bool(value) except ValueError: return default
Attempt to cast *value* into a bool, returning *default* if it fails.
def _rewrite_paths_in_file(config_file, paths_to_replace): """ Rewrite paths in config files to match convention job_xxxx/symlink Requires path to run_xxxx/input/config_file and a list of paths_to_replace """ lines = [] # make a copy of config import shutil ...
Rewrite paths in config files to match convention job_xxxx/symlink Requires path to run_xxxx/input/config_file and a list of paths_to_replace
def research_organism(soup): "Find the research-organism from the set of kwd-group tags" if not raw_parser.research_organism_keywords(soup): return [] return list(map(node_text, raw_parser.research_organism_keywords(soup)))
Find the research-organism from the set of kwd-group tags
def make_osa_report(repo_dir, old_commit, new_commit, args): """Create initial RST report header for OpenStack-Ansible.""" update_repo(repo_dir, args.osa_repo_url, args.update) # Are these commits valid? validate_commits(repo_dir, [old_commit, new_commit]) # Do we have a valid ...
Create initial RST report header for OpenStack-Ansible.
def random_pure_actions(nums_actions, random_state=None): """ Return a tuple of random pure actions (integers). Parameters ---------- nums_actions : tuple(int) Tuple of the numbers of actions, one for each player. random_state : int or np.random.RandomState, optional Random see...
Return a tuple of random pure actions (integers). Parameters ---------- nums_actions : tuple(int) Tuple of the numbers of actions, one for each player. random_state : int or np.random.RandomState, optional Random seed (integer) or np.random.RandomState instance to set the initi...
async def verify(self, message: bytes, signature: bytes, verkey: str = None) -> bool: """ Verify signature against input signer verification key (default anchor's own). Raise AbsentMessage for missing message or signature, or WalletState if wallet is closed. :param message: Content to s...
Verify signature against input signer verification key (default anchor's own). Raise AbsentMessage for missing message or signature, or WalletState if wallet is closed. :param message: Content to sign, as bytes :param signature: signature, as bytes :param verkey: signer verification key...
def brent(seqs, f=None, start=None, key=lambda x: x): """Brent's Cycle Detector. See help(cycle_detector) for more context. Args: *args: Two iterators issueing the exact same sequence: -or- f, start: Function and starting state for finite state machine Yields: Values yielde...
Brent's Cycle Detector. See help(cycle_detector) for more context. Args: *args: Two iterators issueing the exact same sequence: -or- f, start: Function and starting state for finite state machine Yields: Values yielded by sequence_a if it terminates, undefined if a cycle ...
def requestAccountUpdates(self, subscribe=True): """ Register to account updates https://www.interactivebrokers.com/en/software/api/apiguide/java/reqaccountupdates.htm """ if self.subscribeAccount != subscribe: self.subscribeAccount = subscribe self.ibConn...
Register to account updates https://www.interactivebrokers.com/en/software/api/apiguide/java/reqaccountupdates.htm
def create_securitygroup(self, name=None, description=None): """Creates a security group. :param string name: The name of the security group :param string description: The description of the security group """ create_dict = {'name': name, 'description': description} ret...
Creates a security group. :param string name: The name of the security group :param string description: The description of the security group
def set_register(self, register, value): """ Sets the value of a specific register. @type register: str @param register: Register name. @rtype: int @return: Register value. """ context = self.get_context() context[register] = value self...
Sets the value of a specific register. @type register: str @param register: Register name. @rtype: int @return: Register value.
def package(package_string, arch_included=True): """Parse an RPM version string Parses most (all tested) RPM version strings to get their name, epoch, version, release, and architecture information. Epoch (also called serial) is an optional component for RPM versions, and it is also optional when p...
Parse an RPM version string Parses most (all tested) RPM version strings to get their name, epoch, version, release, and architecture information. Epoch (also called serial) is an optional component for RPM versions, and it is also optional when providing a version string to this function. RPM assu...
def ParseFileObject(self, parser_mediator, file_object): """Parses a Java WebStart Cache IDX file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dvfvs.FileIO): a file-like object to p...
Parses a Java WebStart Cache IDX file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dvfvs.FileIO): a file-like object to parse. Raises: UnableToParseFile: when the file cannot...
def value(self, name): """get value of a track at the current time""" return self.tracks.get(name).row_value(self.controller.row)
get value of a track at the current time
def main(command_line=True, **kwargs): """ NAME cit_magic.py DESCRIPTION converts CIT and .sam format files to magic_measurements format files SYNTAX cit_magic.py [command line options] OPTIONS -h: prints the help message and quits. -usr USER: identify u...
NAME cit_magic.py DESCRIPTION converts CIT and .sam format files to magic_measurements format files SYNTAX cit_magic.py [command line options] OPTIONS -h: prints the help message and quits. -usr USER: identify user, default is "" -f FILE: specify .sam fo...
def findbeam_radialpeak(data, orig_initial, mask, rmin, rmax, maxiter=100, drive_by='amplitude', extent=10, callback=None): """Find the beam by minimizing the width of a peak in the radial average. Inputs: data: scattering matrix orig_initial: first guess for the origin ...
Find the beam by minimizing the width of a peak in the radial average. Inputs: data: scattering matrix orig_initial: first guess for the origin mask: mask matrix. Nonzero is non-masked. rmin,rmax: distance from the origin (in pixels) of the peak range. drive_by: 'hwhm' to mi...
def trim(self, name): """When the name is too long, use the LHS or a random string instead.""" if len(name) > self.MAX_LENGTH and self.target: name = self.TEMP_VAR.format(self._name(self.target)) if len(name) > self.MAX_LENGTH: while True: name = '_{:04x}'.format(random.randint(0, 16 ** ...
When the name is too long, use the LHS or a random string instead.
def utcnow(): """Overridable version of utils.utcnow.""" if utcnow.override_time: try: return utcnow.override_time.pop(0) except AttributeError: return utcnow.override_time return datetime.datetime.utcnow()
Overridable version of utils.utcnow.
def weld_cast_scalar(scalar, to_weld_type): """Returns the scalar casted to the request Weld type. Parameters ---------- scalar : {int, float, WeldObject} Input array. to_weld_type : WeldType Type of each element in the input array. Returns ------- WeldObject Re...
Returns the scalar casted to the request Weld type. Parameters ---------- scalar : {int, float, WeldObject} Input array. to_weld_type : WeldType Type of each element in the input array. Returns ------- WeldObject Representation of this computation.
def _parse_tcpreplay_result(stdout, stderr, argv): """ Parse the output of tcpreplay and modify the results_dict to populate output information. # noqa: E501 Tested with tcpreplay v3.4.4 Tested with tcpreplay v4.1.2 :param stdout: stdout of tcpreplay subprocess call :param stderr: stderr of tcp...
Parse the output of tcpreplay and modify the results_dict to populate output information. # noqa: E501 Tested with tcpreplay v3.4.4 Tested with tcpreplay v4.1.2 :param stdout: stdout of tcpreplay subprocess call :param stderr: stderr of tcpreplay subprocess call :param argv: the command used in the...
def cells(self): '''Returns an interator of all cells in the table. ''' for line in self.text.splitlines(): for cell in self.getcells(line): yield cell
Returns an interator of all cells in the table.
def apply_dependencies(self): """Loop on hosts and register dependency between parent and son call Host.fill_parents_dependency() :return: None """ for host in self: for parent_id in getattr(host, 'parents', []): if parent_id is None: ...
Loop on hosts and register dependency between parent and son call Host.fill_parents_dependency() :return: None
def std(self): """ The standard deviation of the best results of each trial. Returns: float: standard deviation of measured seconds Note: As mentioned in the timeit source code, the standard deviation is not often useful. Typically the minimum value ...
The standard deviation of the best results of each trial. Returns: float: standard deviation of measured seconds Note: As mentioned in the timeit source code, the standard deviation is not often useful. Typically the minimum value is most informative. Examp...
def _iter_keys_as_str(key): """! Iterate over subkeys of a key returning subkey as string """ for i in range(winreg.QueryInfoKey(key)[0]): yield winreg.EnumKey(key, i)
! Iterate over subkeys of a key returning subkey as string
def completion_pre_event_input_accelerators(editor, event): """ Implements completion pre event input accelerators. :param editor: Document editor. :type editor: QWidget :param event: Event being handled. :type event: QEvent :return: Process event. :rtype: bool """ process_even...
Implements completion pre event input accelerators. :param editor: Document editor. :type editor: QWidget :param event: Event being handled. :type event: QEvent :return: Process event. :rtype: bool
def to_date(timeobject): """ Returns the ``datetime.datetime`` object corresponding to the time value conveyed by the specified object, which can be either a UNIXtime, a ``datetime.datetime`` object or an ISO8601-formatted string in the format `YYYY-MM-DD HH:MM:SS+00``. :param timeobject: the o...
Returns the ``datetime.datetime`` object corresponding to the time value conveyed by the specified object, which can be either a UNIXtime, a ``datetime.datetime`` object or an ISO8601-formatted string in the format `YYYY-MM-DD HH:MM:SS+00``. :param timeobject: the object conveying the time value :t...
def readchunk(self): """Reads a chunk at a time. If the current position is within a chunk the remainder of the chunk is returned. """ received = len(self.__buffer) chunk_data = EMPTY chunk_size = int(self.chunk_size) if received > 0: chunk_data = sel...
Reads a chunk at a time. If the current position is within a chunk the remainder of the chunk is returned.
def _height_and_width(self): """ Query console for dimensions Returns named tuple (columns, lines) """ # In Python 3.3+ we can let the standard library handle this if GTS_SUPPORTED: return os.get_terminal_size(self.stream_fd) window = get_csbi(self.s...
Query console for dimensions Returns named tuple (columns, lines)
def layout_padding(plots, renderer): """ Pads Nones in a list of lists of plots with empty plots. """ widths, heights = defaultdict(int), defaultdict(int) for r, row in enumerate(plots): for c, p in enumerate(row): if p is not None: width, height = renderer.get_si...
Pads Nones in a list of lists of plots with empty plots.
def connect(host, port=None, **kwargs): ''' Test connectivity to a host using a particular port from the minion. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' network.connect archlinux.org 80 salt '*' network.connect archlinux.org 80 timeout=3 ...
Test connectivity to a host using a particular port from the minion. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' network.connect archlinux.org 80 salt '*' network.connect archlinux.org 80 timeout=3 salt '*' network.connect archlinux.org 80 timeout=...
def _request(self, method, resource, **kwargs): """Given an HTTP method, a resource name and kwargs, construct a request and return the response. """ url = self._resolve_resource_name(resource) if hasattr(self, 'access_token'): kwargs.update(dict(oauth_token=self.acc...
Given an HTTP method, a resource name and kwargs, construct a request and return the response.
def _RegisterFlagByModule(self, module_name, flag): """Records the module that defines a specific flag. We keep track of which flag is defined by which module so that we can later sort the flags by module. Args: module_name: A string, the name of a Python module. flag: A Flag object, a fla...
Records the module that defines a specific flag. We keep track of which flag is defined by which module so that we can later sort the flags by module. Args: module_name: A string, the name of a Python module. flag: A Flag object, a flag that is key to the module.
def conference_list_members(self, call_params): """REST Conference List Members Helper """ path = '/' + self.api_version + '/ConferenceListMembers/' method = 'POST' return self.request(path, method, call_params)
REST Conference List Members Helper
def authenticated_session(username, password): """ Given username and password, return an authenticated Yahoo `requests` session that can be used for further scraping requests. Throw an AuthencationError if authentication fails. """ session = requests.Session() session.headers.update(header...
Given username and password, return an authenticated Yahoo `requests` session that can be used for further scraping requests. Throw an AuthencationError if authentication fails.
def add_security_group(self, name, isc_id, comment=None): """ Create a new security group. :param str name: NSX security group name :param str isc_id: NSX Security Group objectId i.e. (securitygroup-14) :raises CreateElementFailed: failed to create :rtype: Se...
Create a new security group. :param str name: NSX security group name :param str isc_id: NSX Security Group objectId i.e. (securitygroup-14) :raises CreateElementFailed: failed to create :rtype: SecurityGroup
def new( self, min, max ): """Create an empty index for intervals in the range min, max""" # Ensure the range will fit given the shifting strategy assert MIN <= min <= max <= MAX self.min = min self.max = max # Determine offsets to use self.offsets = offsets_for_m...
Create an empty index for intervals in the range min, max
def dimensions(self): """Get width and height of a PDF""" size = self.pdf.getPage(0).mediaBox return {'w': float(size[2]), 'h': float(size[3])}
Get width and height of a PDF
def add(self, data): """ Add a single entry to field. Entries can be added to a rule using the href of the element or by loading the element directly. Element should be of type :py:mod:`smc.elements.network`. After modifying rule, call :py:meth:`~.save`. Example...
Add a single entry to field. Entries can be added to a rule using the href of the element or by loading the element directly. Element should be of type :py:mod:`smc.elements.network`. After modifying rule, call :py:meth:`~.save`. Example of adding entry by element:: ...
def isValid( self ): """ Returns whether or not the filepath exists on the system. \ In the case of a SaveFile, only the base folder \ needs to exist on the system, in other modes the actual filepath must \ exist. :return <bool> """ check = na...
Returns whether or not the filepath exists on the system. \ In the case of a SaveFile, only the base folder \ needs to exist on the system, in other modes the actual filepath must \ exist. :return <bool>
def sender(self): """ Returns the sender, respecting the Resent-* headers. In any case, prefer Sender over From, meaning that if Sender is present then From is ignored, as per the RFC. """ to_fetch = ( ['Resent-Sender', 'Resent-From'] if self.resent el...
Returns the sender, respecting the Resent-* headers. In any case, prefer Sender over From, meaning that if Sender is present then From is ignored, as per the RFC.
def getBuyerInfo(self, auction_id, buyer_id): """Return buyer info.""" # TODO: add price from getBids rc = self.__ask__('doGetPostBuyData', itemsArray=self.ArrayOfLong([auction_id]), buyerFilterArray=self.ArrayOfLong([buyer_id])) rc = rc[0]['usersPostBuyData']['item'][0]['userData'] ...
Return buyer info.
def setup_managers(self): """ Allows to access manager by model name - it is convenient, because HasOffers returns model names in responses. """ self._managers = {} for manager_class in MODEL_MANAGERS: instance = manager_class(self) if not instance.forbid_...
Allows to access manager by model name - it is convenient, because HasOffers returns model names in responses.
def _next_ontology(self): """Dynamically retrieves the next ontology in the list""" currentfile = self.current['file'] try: idx = self.all_ontologies.index(currentfile) return self.all_ontologies[idx+1] except: return self.all_ontologies[0]
Dynamically retrieves the next ontology in the list
def __read(self): """ Read the next frame(s) from the socket. :return: list of frames read :rtype: list(bytes) """ fastbuf = BytesIO() while self.running: try: try: c = self.receive() except exceptio...
Read the next frame(s) from the socket. :return: list of frames read :rtype: list(bytes)
def generate_navigator(os=None, navigator=None, platform=None, device_type=None): """ Generates web navigator's config :param os: limit list of oses for generation :type os: string or list/tuple or None :param navigator: limit list of browser engines for generation :type ...
Generates web navigator's config :param os: limit list of oses for generation :type os: string or list/tuple or None :param navigator: limit list of browser engines for generation :type navigator: string or list/tuple or None :param device_type: limit possible oses by device type :type device_t...
def parse(self, input_text, syncmap): """ Parse the given ``input_text`` and append the extracted fragments to ``syncmap``. :param input_text: the input text as a Unicode string (read from file) :type input_text: string :param syncmap: the syncmap to append to :t...
Parse the given ``input_text`` and append the extracted fragments to ``syncmap``. :param input_text: the input text as a Unicode string (read from file) :type input_text: string :param syncmap: the syncmap to append to :type syncmap: :class:`~aeneas.syncmap.SyncMap`
def cli(env, identifier, allocation, port, routing_type, routing_method): """Adds a new load_balancer service.""" mgr = SoftLayer.LoadBalancerManager(env.client) _, loadbal_id = loadbal.parse_id(identifier) mgr.add_service_group(loadbal_id, allocation=allocation, ...
Adds a new load_balancer service.
def get_logs_between_commits(self, a, b): """ Retrieves all commit messages for all commits between the given commit numbers on the current branch. """ print('REAL') ret = self.local('git --no-pager log --pretty=oneline %s...%s' % (a, b), capture=True) if self.ver...
Retrieves all commit messages for all commits between the given commit numbers on the current branch.
def align_images(self, n_particles=10, n_iterations=10, lowerLimit=-0.2, upperLimit=0.2, threadCount=1, compute_bands=None): """ aligns the coordinate systems of different exposures within a fixed model parameterisation by executing a PSO with relative coordinate shifts as f...
aligns the coordinate systems of different exposures within a fixed model parameterisation by executing a PSO with relative coordinate shifts as free parameters :param n_particles: number of particles in the Particle Swarm Optimization :param n_iterations: number of iterations in the optimizati...
def getproducts(self, force_refresh=False, **kwargs): """ Query all products and return the raw dict info. Takes all the same arguments as product_get. On first invocation this will contact bugzilla and internally cache the results. Subsequent getproducts calls or accesses to ...
Query all products and return the raw dict info. Takes all the same arguments as product_get. On first invocation this will contact bugzilla and internally cache the results. Subsequent getproducts calls or accesses to self.products will return this cached data only. :param for...
def shutdown(self, msg): """Shutdown the scheduler.""" try: self.cleanup() self.history.append("Completed on: %s" % time.asctime()) self.history.append("Elapsed time: %s" % self.get_delta_etime()) if self.debug: print(">>>>> shutdown: Num...
Shutdown the scheduler.
def cmd_save(args): '''save a graph''' child = multiproc.Process(target=save_process, args=[mestate.last_graph, mestate.child_pipe_send_console, mestate.child_pipe_send_graph, mestate.status.msgs]) child.start()
save a graph
def _create_group_tree(self, levels): """This method creates a group tree""" if levels[0] != 0: raise KPError("Invalid group tree") for i in range(len(self.groups)): if(levels[i] == 0): self.groups[i].parent = self.root_group self...
This method creates a group tree
def join_host_port(host, port): """Joins a hostname and port together. This is a minimal implementation intended to cope with IPv6 literals. For example, _join_host_port('::1', 80) == '[::1]:80'. :Args: - host - A hostname. - port - An integer port. """ if ':' in host and not ...
Joins a hostname and port together. This is a minimal implementation intended to cope with IPv6 literals. For example, _join_host_port('::1', 80) == '[::1]:80'. :Args: - host - A hostname. - port - An integer port.
def get_logs(self, name): """ Obtain cluster status and logs from all pods and print them using logger. This method is useful for debugging. :param name: str, name of app generated by oc new-app :return: str, cluster status and logs from all pods """ logs = self.g...
Obtain cluster status and logs from all pods and print them using logger. This method is useful for debugging. :param name: str, name of app generated by oc new-app :return: str, cluster status and logs from all pods
def asyncSlot(*args): """Make a Qt async slot run on asyncio loop.""" def outer_decorator(fn): @Slot(*args) @functools.wraps(fn) def wrapper(*args, **kwargs): asyncio.ensure_future(fn(*args, **kwargs)) return wrapper return outer_decorator
Make a Qt async slot run on asyncio loop.
def list_to_cells(lst): '''convert list of cells to notebook form list should be of the form: [[list of strings representing python code for cell]] ''' cells = '"cells": [' for cell in lst: to_add = '{"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ...
convert list of cells to notebook form list should be of the form: [[list of strings representing python code for cell]]
def block_until_expired(timeout): """ 阻塞当前程序运行, 直到超时 .. note: 会阻塞当前程序运行 - 如果 ``timeout大于0``, 则当作 ``计时阻塞器`` 来使用 .. code:: python @run_until(0.1) def s2(): m = 5 while m: print('s2: ', m, now()) time.sleep(...
阻塞当前程序运行, 直到超时 .. note: 会阻塞当前程序运行 - 如果 ``timeout大于0``, 则当作 ``计时阻塞器`` 来使用 .. code:: python @run_until(0.1) def s2(): m = 5 while m: print('s2: ', m, now()) time.sleep(1) m -= 1 ...
def get_screen_density(self) -> str: '''Show device screen density (PPI).''' output, _ = self._execute( '-s', self.device_sn, 'shell', 'wm', 'density') return output.split()[2]
Show device screen density (PPI).
def create_url(base, path=None, *query): """ Create a url. Creates a url by combining base, path, and the query's list of key/value pairs. Escaping is handled automatically. Any key/value pair with a value that is None is ignored. Keyword arguments: base -- The left most part of the url (ex. h...
Create a url. Creates a url by combining base, path, and the query's list of key/value pairs. Escaping is handled automatically. Any key/value pair with a value that is None is ignored. Keyword arguments: base -- The left most part of the url (ex. http://localhost:5000). path -- The path after...
def append_pair(self, tag, value, header=False): """Append a tag=value pair to this message. :param tag: Integer or string FIX tag number. :param value: FIX tag value. :param header: Append to header if True; default to body. Both parameters are explicitly converted to strings ...
Append a tag=value pair to this message. :param tag: Integer or string FIX tag number. :param value: FIX tag value. :param header: Append to header if True; default to body. Both parameters are explicitly converted to strings before storage, so it's ok to pass integers if that'...
def striptags(self): r"""Unescape markup into an unicode string and strip all tags. This also resolves known HTML4 and XHTML entities. Whitespace is normalized to one: >>> Markup("Main &raquo; <em>About</em>").striptags() u'Main \xbb About' """ stripped = u' '...
r"""Unescape markup into an unicode string and strip all tags. This also resolves known HTML4 and XHTML entities. Whitespace is normalized to one: >>> Markup("Main &raquo; <em>About</em>").striptags() u'Main \xbb About'
def _z2deriv(self,R,z,phi=0.,t=0.): """ NAME: _z2deriv PURPOSE: evaluate the second vertical derivative for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUT...
NAME: _z2deriv PURPOSE: evaluate the second vertical derivative for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: the second vertical derivative H...
def fetch_from_archive(backend_class, backend_args, manager, category, archived_after): """Fetch items from an archive manager. Generator to get the items of a category (previously fetched by the given backend class) from an archive manager. Only those items archived after the gi...
Fetch items from an archive manager. Generator to get the items of a category (previously fetched by the given backend class) from an archive manager. Only those items archived after the given date will be returned. The parameters needed to initialize `backend` and get the items are given using `b...
def draw(board, term, cells): """Draw a board to the terminal.""" for (x, y), state in board.iteritems(): with term.location(x, y): print cells[state],
Draw a board to the terminal.
def dns_log_graph(self, stream): ''' Build up a graph (nodes and edges from a Bro dns.log) ''' dns_log = list(stream) print 'Entering dns_log_graph...(%d rows)' % len(dns_log) for row in dns_log: # Skip '-' hosts if (row['id.orig_h'] == '-'): ...
Build up a graph (nodes and edges from a Bro dns.log)
def show_qos_queue(self, queue, **_params): """Fetches information of a certain queue.""" return self.get(self.qos_queue_path % (queue), params=_params)
Fetches information of a certain queue.
def make_multisig_segwit_info( m, pks ): """ Make either a p2sh-p2wpkh or p2sh-p2wsh redeem script and p2sh address. Return {'address': p2sh address, 'redeem_script': **the witness script**, 'private_keys': privkeys, 'segwit': True} * privkeys and redeem_script will be hex-encoded """ pubs ...
Make either a p2sh-p2wpkh or p2sh-p2wsh redeem script and p2sh address. Return {'address': p2sh address, 'redeem_script': **the witness script**, 'private_keys': privkeys, 'segwit': True} * privkeys and redeem_script will be hex-encoded
def _to_DOM(self): """ Dumps object data to a fully traversable DOM representation of the object. :returns: a ``xml.etree.Element`` object """ root_node = ET.Element("uvindex") reference_time_node = ET.SubElement(root_node, "reference_time") reference_ti...
Dumps object data to a fully traversable DOM representation of the object. :returns: a ``xml.etree.Element`` object
def search_continuous( self, continuous_set_id=None, reference_name="", start=0, end=0): """ Returns the result of running a search_continuous method on a request with the passed-in parameters. :param str continuous_set_id: ID of the ContinuousSet being searched :par...
Returns the result of running a search_continuous method on a request with the passed-in parameters. :param str continuous_set_id: ID of the ContinuousSet being searched :param str reference_name: name of the reference to search (ex: "chr1") :param int start: search start po...
def mounts(): """Get a list of all mounted volumes as [[mountpoint,device],[...]]""" with open('/proc/mounts') as f: # [['/mount/point','/dev/path'],[...]] system_mounts = [m[1::-1] for m in [l.strip().split() for l in f.readlines()]] return system...
Get a list of all mounted volumes as [[mountpoint,device],[...]]
def get_cif(code, mmol_number, outfile=None): """ Parameters ---------- code : str PDB code. mmol_number : int mmol number (biological assembly number) of file to download. Numbers from PDBe. If None, defaults to the preferred biological assembly listed for code on the PDBe. ...
Parameters ---------- code : str PDB code. mmol_number : int mmol number (biological assembly number) of file to download. Numbers from PDBe. If None, defaults to the preferred biological assembly listed for code on the PDBe. outfile : str Filepath. Writes returned value ...
def extract_sort(self, params): '''Extract and build sort query from parameters''' sorts = params.pop('sort', []) sorts = [sorts] if isinstance(sorts, basestring) else sorts sorts = [(s[1:], 'desc') if s.startswith('-') else (s, 'asc') for s in sorts] ...
Extract and build sort query from parameters
def gen_rst(results): """ creates restructured text documents to display tests """ # make sure the destination directory exists try: os.mkdir(DOCPATH) except OSError as e: if e.args[0] != errno.EEXIST and e.args[0] != errno.EISDIR: raise toctree = [] class_ = [] ...
creates restructured text documents to display tests
def find_chan_in_region(channels, anat, region_name): """Find which channels are in a specific region. Parameters ---------- channels : instance of wonambi.attr.chan.Channels channels, that have locations anat : instance of wonambi.attr.anat.Freesurfer anatomical information taken f...
Find which channels are in a specific region. Parameters ---------- channels : instance of wonambi.attr.chan.Channels channels, that have locations anat : instance of wonambi.attr.anat.Freesurfer anatomical information taken from freesurfer. region_name : str the name of the...
def dest_path(self): """ :return: The destination path. :rtype: str """ if os.path.isabs(self.config.local_path): return self.config.local_path else: return os.path.normpath(os.path.join( os.getcwd(), self.config.loc...
:return: The destination path. :rtype: str
def show_profiles(self): """ Print the profile stats to stdout """ for i, (id, profiler, showed) in enumerate(self.profilers): if not showed and profiler: profiler.show(id) # mark it as showed self.profilers[i][2] = True
Print the profile stats to stdout
def is_pdf(document): """Check if a document is a PDF file and return True if is is.""" if not executable_exists('pdftotext'): current_app.logger.warning( "GNU file was not found on the system. " "Switching to a weak file extension test." ) if document.lower().end...
Check if a document is a PDF file and return True if is is.
def channels_replies(self, *, channel: str, thread_ts: str, **kwargs) -> SlackResponse: """Retrieve a thread of messages posted to a channel Args: channel (str): The channel id. e.g. 'C1234567890' thread_ts (str): The timestamp of an existing message with 0 or more replies. ...
Retrieve a thread of messages posted to a channel Args: channel (str): The channel id. e.g. 'C1234567890' thread_ts (str): The timestamp of an existing message with 0 or more replies. e.g. '1234567890.123456'
def retrieve_all(self, subset=None): """Return a list of all JSSListData elements as full JSSObjects. This can take a long time given a large number of objects, and depending on the size of each object. Subsetting to only include the data you need can improve performance. Args:...
Return a list of all JSSListData elements as full JSSObjects. This can take a long time given a large number of objects, and depending on the size of each object. Subsetting to only include the data you need can improve performance. Args: subset: For objects which support i...
def connection_lost(self, exc): """Log when connection is closed, if needed call callback.""" if exc: self.logger.error('disconnected due to error') else: self.logger.info('disconnected because of close/abort.') if self.disconnect_callback: asyncio.ens...
Log when connection is closed, if needed call callback.
def update_header(self): """ Updates header to edffile struct """ set_technician(self.handle, du(self.technician)) set_recording_additional(self.handle, du(self.recording_additional)) set_patientname(self.handle, du(self.patient_name)) set_patientcode(self.handle,...
Updates header to edffile struct
def _get_services(self, version='v1'): '''get version 1 of the google compute and storage service Parameters ========== version: version to use (default is v1) ''' self._bucket_service = storage.Client() creds = GoogleCredentials.get_application_default() ...
get version 1 of the google compute and storage service Parameters ========== version: version to use (default is v1)
def symbolic_rotation_matrix(phi, theta, symbolic_psi): """Retourne une matrice de rotation où psi est symbolique""" return sympy.Matrix(Rz_matrix(phi)) * sympy.Matrix(Rx_matrix(theta)) * symbolic_Rz_matrix(symbolic_psi)
Retourne une matrice de rotation où psi est symbolique
def upload(self, content, content_type, filename=None): """ Upload content to the home server and recieve a MXC url. Args: content (bytes): The data of the content. content_type (str): The mimetype of the content. filename (str): Optional. Filename of the content. ...
Upload content to the home server and recieve a MXC url. Args: content (bytes): The data of the content. content_type (str): The mimetype of the content. filename (str): Optional. Filename of the content. Raises: MatrixUnexpectedResponse: If the homeserv...
def is_email_enabled(email): """ Emails are activated by default. Returns false if an email has been disabled in settings.py """ s = get_settings(string="OVP_EMAILS") email_settings = s.get(email, {}) enabled = True if email_settings.get("disabled", False): enabled = False return enabled
Emails are activated by default. Returns false if an email has been disabled in settings.py
def _get_block_plain_text(self, block): """ Given a QTextBlock, return its unformatted text. """ cursor = QtGui.QTextCursor(block) cursor.movePosition(QtGui.QTextCursor.StartOfBlock) cursor.movePosition(QtGui.QTextCursor.EndOfBlock, QtGui.QTextCursor.K...
Given a QTextBlock, return its unformatted text.
def quality(self): """ Can't really trust presence of a schema here, but there is an ID sometimes """ try: qid = int((self.tool_metadata or {}).get("quality", 0)) except: qid = 0 # We might be able to get the quality strings from the item's tags internal_...
Can't really trust presence of a schema here, but there is an ID sometimes
def pout(*args, **kwargs): """print to stdout, maintaining indent level""" if should_msg(kwargs.get("groups", ["normal"])): args = indent_text(*args, **kwargs) # write to stdout sys.stderr.write("".join(args)) sys.stderr.write("\n")
print to stdout, maintaining indent level
def boundaries_lonlat(healpix_index, step, nside, order='ring'): """ Return the longitude and latitude of the edges of HEALPix pixels This returns the longitude and latitude of points along the edge of each HEALPIX pixel. The number of points returned for each pixel is ``4 * step``, so setting ``st...
Return the longitude and latitude of the edges of HEALPix pixels This returns the longitude and latitude of points along the edge of each HEALPIX pixel. The number of points returned for each pixel is ``4 * step``, so setting ``step`` to 1 returns just the corners. Parameters ---------- healpi...
def unzip_unicode(output, version): """Unzip the Unicode files.""" unzipper = zipfile.ZipFile(os.path.join(output, 'unicodedata', '%s.zip' % version)) target = os.path.join(output, 'unicodedata', version) print('Unzipping %s.zip...' % version) os.makedirs(target) for f in unzipper.namelist()...
Unzip the Unicode files.
def send(self, command, tab_key, params=None): ''' Send command `command` with optional parameters `params` to the remote chrome instance. The command `id` is automatically added to the outgoing message. return value is the command id, which can be used to match a command to it's associated response. ''...
Send command `command` with optional parameters `params` to the remote chrome instance. The command `id` is automatically added to the outgoing message. return value is the command id, which can be used to match a command to it's associated response.