code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def upgrade(self, flag): """Upgrade Slackware binary packages with new """ for pkg in self.binary: try: subprocess.call("upgradepkg {0} {1}".format(flag, pkg), shell=True) check = pkg[:-4].split("/")[-1] ...
Upgrade Slackware binary packages with new
def get_question_ids_for_assessment_part(self, assessment_part_id): """convenience method returns unique question ids associated with an assessment_part_id""" question_ids = [] for question_map in self._my_map['questions']: if question_map['assessmentPartId'] == str(assessment_part_i...
convenience method returns unique question ids associated with an assessment_part_id
def add_edge(self, from_index, to_index, weight=None, warn_duplicates=True, edge_properties=None): """ Add edge to graph. Since physically a 'bond' (or other connection between sites) doesn't have a direction, from_index, from_jimage can be swap...
Add edge to graph. Since physically a 'bond' (or other connection between sites) doesn't have a direction, from_index, from_jimage can be swapped with to_index, to_jimage. However, images will always always be shifted so that from_index < to_index and from_jimage becomes (0, 0,...
def generate_random_upload_path(instance, filename): """ Pass this function to upload_to argument of FileField to store the file on an unguessable path. The format of the path is class_name/hash/original_filename. """ return os.path.join(instance.__class__.__name__.lower(), uuid().hex, filename)
Pass this function to upload_to argument of FileField to store the file on an unguessable path. The format of the path is class_name/hash/original_filename.
def ensure_compatible(left, right): """Raise an informative ``ValueError`` if the two definitions disagree.""" conflicts = list(conflicting_pairs(left, right)) if conflicts: raise ValueError('conflicting values for object/property pairs: %r' % conflicts)
Raise an informative ``ValueError`` if the two definitions disagree.
def getUI(prog_name, args): """Build and return user interface object for this script.""" longDescription = "Given a set of BED intervals, compute a profile of " +\ "conservation by averaging over all intervals using a " +\ "whole genome alignment to a set of relevent species...
Build and return user interface object for this script.
def print_annotation(self): """Print annotation "key: value" pairs to standard output.""" for path, ann in self.annotation.items(): print("{}: {}".format(path, ann['value']))
Print annotation "key: value" pairs to standard output.
async def sonar_data_retrieve(self, trigger_pin): """ Retrieve Ping (HC-SR04 type) data. The data is presented as a dictionary. The 'key' is the trigger pin specified in sonar_config() and the 'data' is the current measured distance (in centimeters) for that pin. If there...
Retrieve Ping (HC-SR04 type) data. The data is presented as a dictionary. The 'key' is the trigger pin specified in sonar_config() and the 'data' is the current measured distance (in centimeters) for that pin. If there is no data, the value is set to None. :param trigger_pin: ke...
def parse(self, debug=False): """Returns parsed text""" if self._parsed is None: try: if self._mode == "html": self._parsed = self.html(self._content, self._show_everything, self._translation) else: self._parsed = self.r...
Returns parsed text
def gen_gradient(args, resource, inflow, radius, loc, common=True): """ Returns a line of text to add to an environment file, initializing a gradient resource with the specified name (string), inflow(int), radius(int), and location (tuple of ints) """ return "".join(["GRADIENT_RESOURCE ", str(re...
Returns a line of text to add to an environment file, initializing a gradient resource with the specified name (string), inflow(int), radius(int), and location (tuple of ints)
def set_titles(self, template="{coord} = {value}", maxchar=30, **kwargs): """ Draw titles either above each facet or on the grid margins. Parameters ---------- template : string Template for plot titles containing {coord} and {value} maxcha...
Draw titles either above each facet or on the grid margins. Parameters ---------- template : string Template for plot titles containing {coord} and {value} maxchar : int Truncate titles at maxchar kwargs : keyword args additional arguments to ...
def setup_logging(handler, exclude=EXCLUDE_LOGGER_DEFAULTS): """ Configures logging to pipe to Sentry. - ``exclude`` is a list of loggers that shouldn't go to Sentry. For a typical Python install: >>> from raven.handlers.logging import SentryHandler >>> client = Sentry(...) >>> setup_logg...
Configures logging to pipe to Sentry. - ``exclude`` is a list of loggers that shouldn't go to Sentry. For a typical Python install: >>> from raven.handlers.logging import SentryHandler >>> client = Sentry(...) >>> setup_logging(SentryHandler(client)) Within Django: >>> from raven.contri...
def _CreateWindowsPathResolver( self, file_system, mount_point, environment_variables): """Create a Windows path resolver and sets the environment variables. Args: file_system (dfvfs.FileSystem): file system. mount_point (dfvfs.PathSpec): mount point path specification. environment_vari...
Create a Windows path resolver and sets the environment variables. Args: file_system (dfvfs.FileSystem): file system. mount_point (dfvfs.PathSpec): mount point path specification. environment_variables (list[EnvironmentVariableArtifact]): environment variables. Returns: dfvfs...
def SGg(self): r'''Specific gravity of the gas phase of the chemical, [dimensionless]. The reference condition is air at 15.6 °C (60 °F) and 1 atm (rho=1.223 kg/m^3). The definition for gases uses the compressibility factor of the reference gas and the chemical both at the reference ...
r'''Specific gravity of the gas phase of the chemical, [dimensionless]. The reference condition is air at 15.6 °C (60 °F) and 1 atm (rho=1.223 kg/m^3). The definition for gases uses the compressibility factor of the reference gas and the chemical both at the reference conditions, not th...
def paula_etree_to_string(tree, dtd_filename): """convert a PAULA etree into an XML string.""" return etree.tostring( tree, pretty_print=True, xml_declaration=True, encoding="UTF-8", standalone='no', doctype='<!DOCTYPE paula SYSTEM "{0}">'.format(dtd_filename))
convert a PAULA etree into an XML string.
def dd2dm(dd): """Convert decimal to degrees, decimal minutes """ d,m,s = dd2dms(dd) m = m + float(s)/3600 return d,m,s
Convert decimal to degrees, decimal minutes
def _htpasswd(username, password, **kwargs): ''' Provide authentication via Apache-style htpasswd files ''' from passlib.apache import HtpasswdFile pwfile = HtpasswdFile(kwargs['filename']) # passlib below version 1.6 uses 'verify' function instead of 'check_password' if salt.utils.versio...
Provide authentication via Apache-style htpasswd files
def get_slo_url(self): """ Gets the SLO URL. :returns: An URL, the SLO endpoint of the IdP :rtype: string """ url = None idp_data = self.__settings.get_idp_data() if 'singleLogoutService' in idp_data.keys() and 'url' in idp_data['singleLogoutService']: ...
Gets the SLO URL. :returns: An URL, the SLO endpoint of the IdP :rtype: string
def _store_oauth_access_token(self, oauth_access_token): ''' Called when login is complete to store the oauth access token This implementation stores the oauth_access_token in a seperate cookie for domain steamwebbrowser.tld ''' c = Cookie(version=0, name='oauth_access_token', value=...
Called when login is complete to store the oauth access token This implementation stores the oauth_access_token in a seperate cookie for domain steamwebbrowser.tld
def retries(timeout=30, intervals=1, time=time): """Helper for retrying something, sleeping between attempts. Returns a generator that yields ``(elapsed, remaining, wait)`` tuples, giving times in seconds. The last item, `wait`, is the suggested amount of time to sleep before trying again. :param ...
Helper for retrying something, sleeping between attempts. Returns a generator that yields ``(elapsed, remaining, wait)`` tuples, giving times in seconds. The last item, `wait`, is the suggested amount of time to sleep before trying again. :param timeout: From now, how long to keep iterating, in second...
def additive_self_attention(units, n_hidden=None, n_output_features=None, activation=None): """ Computes additive self attention for time series of vectors (with batch dimension) the formula: score(h_i, h_j) = <v, tanh(W_1 h_i + W_2 h_j)> v is a learnable vector of n_hidden dimensionality, W...
Computes additive self attention for time series of vectors (with batch dimension) the formula: score(h_i, h_j) = <v, tanh(W_1 h_i + W_2 h_j)> v is a learnable vector of n_hidden dimensionality, W_1 and W_2 are learnable [n_hidden, n_input_features] matrices Args: units: tf tensor w...
def str_to_etree(xml_str, encoding='utf-8'): """Deserialize API XML doc to an ElementTree. Args: xml_str: bytes DataONE API XML doc encoding: str Decoder to use when converting the XML doc ``bytes`` to a Unicode str. Returns: ElementTree: Matching the API version of the ...
Deserialize API XML doc to an ElementTree. Args: xml_str: bytes DataONE API XML doc encoding: str Decoder to use when converting the XML doc ``bytes`` to a Unicode str. Returns: ElementTree: Matching the API version of the XML doc.
def will_tag(self): """ Check whether the feed should be tagged """ wanttags = self.retrieve_config('Tag', 'no') if wanttags == 'yes': if aux.staggerexists: willtag = True else: willtag = False print(("You wa...
Check whether the feed should be tagged
def list_market_catalogue(self, filter=market_filter(), market_projection=None, sort=None, max_results=1, locale=None, session=None, lightweight=None): """ Returns a list of information about published (ACTIVE/SUSPENDED) markets that does not change (or changes very...
Returns a list of information about published (ACTIVE/SUSPENDED) markets that does not change (or changes very rarely). :param dict filter: The filter to select desired markets :param list market_projection: The type and amount of data returned about the market :param str sort: The orde...
def _get_network(self, network_info): """Send network get request to DCNM. :param network_info: contains network info to query. """ org_name = network_info.get('organizationName', '') part_name = network_info.get('partitionName', '') segment_id = network_info['segmentId'...
Send network get request to DCNM. :param network_info: contains network info to query.
def _generate_reversed_sql(self, keys, changed_keys): """ Generate reversed operations for changes, that require full rollback and creation. """ for key in keys: if key not in changed_keys: continue app_label, sql_name = key old_item = ...
Generate reversed operations for changes, that require full rollback and creation.
def cleanup_kernels(self): """shutdown all kernels The kernels will shutdown themselves when this process no longer exists, but explicit shutdown allows the KernelManagers to cleanup the connection files. """ self.log.info('Shutting down kernels') km = self.kerne...
shutdown all kernels The kernels will shutdown themselves when this process no longer exists, but explicit shutdown allows the KernelManagers to cleanup the connection files.
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: ShortCodeContext for this ShortCodeInstance :rtype: twilio.rest.api.v2010.account.short_code.Shor...
Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: ShortCodeContext for this ShortCodeInstance :rtype: twilio.rest.api.v2010.account.short_code.ShortCodeContext
def dump(self, itemkey, filename=None, path=None): """ Dump a file attachment to disk, with optional filename and path """ if not filename: filename = self.item(itemkey)["data"]["filename"] if path: pth = os.path.join(path, filename) else: ...
Dump a file attachment to disk, with optional filename and path
def build(template='/', host=None, scheme=None, port=None, **template_vars): """Builds a url with a string template and template variables; relative path if host is None, abs otherwise: template format: "/staticendpoint/{dynamic_endpoint}?{params}" """ # TODO: refactor to build_absol...
Builds a url with a string template and template variables; relative path if host is None, abs otherwise: template format: "/staticendpoint/{dynamic_endpoint}?{params}"
def help_center_articles_attachment_delete(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/help_center/article_attachments#delete-article-attachment" api_path = "/api/v2/help_center/articles/attachments/{id}.json" api_path = api_path.format(id=id) return self.call(api_p...
https://developer.zendesk.com/rest_api/docs/help_center/article_attachments#delete-article-attachment
def stop_times(self): """Return all stop_times for this agency.""" stop_times = set() for trip in self.trips(): stop_times |= trip.stop_times() return stop_times
Return all stop_times for this agency.
def fetch_next_page(self, data): ''' Fetches next page based on previously fetched data. Will get the next page url from data['paging']['next']. :param data: previously fetched API response. :type data: dict :return: API response. :rtype: dict '''...
Fetches next page based on previously fetched data. Will get the next page url from data['paging']['next']. :param data: previously fetched API response. :type data: dict :return: API response. :rtype: dict
def parse_from_parent( self, parent, # type: ET.Element state # type: _ProcessorState ): # type: (...) -> Any """Parse the element from the given parent element.""" xml_value = self._processor.parse_from_parent(parent, state) return _hooks_apply_...
Parse the element from the given parent element.
def get_source_name(self, name): """Return the name of a source as it is defined in the pyLikelihood model object.""" if name not in self.like.sourceNames(): name = self.roi.get_source_by_name(name).name return name
Return the name of a source as it is defined in the pyLikelihood model object.
def register_list(self): """Returns a list of the indices for the CPU registers. The returned indices can be used to read the register content or grab the register name. Args: self (JLink): the ``JLink`` instance Returns: List of registers. """ ...
Returns a list of the indices for the CPU registers. The returned indices can be used to read the register content or grab the register name. Args: self (JLink): the ``JLink`` instance Returns: List of registers.
def read_hip(self, length, extension): """Read Host Identity Protocol. Structure of HIP header [RFC 5201][RFC 7401]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-...
Read Host Identity Protocol. Structure of HIP header [RFC 5201][RFC 7401]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ...
async def send_document(self, path, entity): """Sends the file located at path to the desired entity as a document""" await self.send_file( entity, path, force_document=True, progress_callback=self.upload_progress_callback ) print('Document sent!')
Sends the file located at path to the desired entity as a document
def to_html(self, wrap_slash=False): """Render a Text MessageElement as html. :param wrap_slash: Whether to replace slashes with the slash plus the html <wbr> tag which will help to e.g. wrap html in small cells if it contains a long filename. Disabled by default as it may cause...
Render a Text MessageElement as html. :param wrap_slash: Whether to replace slashes with the slash plus the html <wbr> tag which will help to e.g. wrap html in small cells if it contains a long filename. Disabled by default as it may cause side effects if the text contains h...
def assignees(self): """List of assignees to the activity.""" if 'assignees' in self._json_data and self._json_data.get('assignees_ids') == list(): return [] elif 'assignees' in self._json_data and self._json_data.get('assignees_ids'): assignees_ids_str = ','.join([str(id...
List of assignees to the activity.
def load(self, data): """ Load a single row of data and convert it into entities and relations. """ objs = {} for mapper in self.entities: objs[mapper.name] = mapper.load(self.loader, data) for mapper in self.relations: objs[mapper.name] = mapper.load(sel...
Load a single row of data and convert it into entities and relations.
def dip_pval_tabinterpol(dip, N): ''' dip - dip value computed from dip_from_cdf N - number of observations ''' # if qDiptab_df is None: # raise DataError("Tabulated p-values not available. See installation instructions.") if np.isnan(N) or N < 10: return ...
dip - dip value computed from dip_from_cdf N - number of observations
def conditional_http_tween_factory(handler, registry): """ Tween that adds ETag headers and tells Pyramid to enable conditional responses where appropriate. """ settings = registry.settings if hasattr(registry, 'settings') else {} if 'generate_etag_for.list' in settings: route_names = s...
Tween that adds ETag headers and tells Pyramid to enable conditional responses where appropriate.
def main(url, lamson_host, lamson_port, lamson_debug): """ Create, connect, and block on the Lamson worker. """ try: worker = LamsonWorker(url=url, lamson_host=lamson_host, lamson_port=lamson_port, lamson_d...
Create, connect, and block on the Lamson worker.
def deleteRows(self, login, tableName, startRow, endRow): """ Parameters: - login - tableName - startRow - endRow """ self.send_deleteRows(login, tableName, startRow, endRow) self.recv_deleteRows()
Parameters: - login - tableName - startRow - endRow
def list_to_str(lst): """ Turn a list into a comma- and/or and-separated string. Parameters ---------- lst : :obj:`list` A list of strings to join into a single string. Returns ------- str_ : :obj:`str` A string with commas and/or ands separating th elements from ``lst`...
Turn a list into a comma- and/or and-separated string. Parameters ---------- lst : :obj:`list` A list of strings to join into a single string. Returns ------- str_ : :obj:`str` A string with commas and/or ands separating th elements from ``lst``.
def as_dict(self, voigt=False): """ Serializes the tensor object Args: voigt (bool): flag for whether to store entries in voigt-notation. Defaults to false, as information may be lost in conversion. Returns (Dict): serialized for...
Serializes the tensor object Args: voigt (bool): flag for whether to store entries in voigt-notation. Defaults to false, as information may be lost in conversion. Returns (Dict): serialized format tensor object
def regulartype(prompt_template="default"): """Echo each character typed. Unlike magictype, this echos the characters the user is pressing. Returns: command_string | The command to be passed to the shell to run. This is | typed by the user. """ echo_prompt(prompt_templ...
Echo each character typed. Unlike magictype, this echos the characters the user is pressing. Returns: command_string | The command to be passed to the shell to run. This is | typed by the user.
def convert_ligatures(text_string): ''' Coverts Latin character references within text_string to their corresponding unicode characters and returns converted string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a string or No...
Coverts Latin character references within text_string to their corresponding unicode characters and returns converted string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a string or NoneType not be passed as an argument
def follow_directories_loaded(self, fname): """Follow directories loaded during startup""" if self._to_be_loaded is None: return path = osp.normpath(to_text_string(fname)) if path in self._to_be_loaded: self._to_be_loaded.remove(path) if self._to_be...
Follow directories loaded during startup
def create_document( self, parent, collection_id, document_id, document, mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new document. ...
Creates a new document. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]') >>> ...
def screen_to_client(self, x, y): """ Translates window screen coordinates to client coordinates. @note: This is a simplified interface to some of the functionality of the L{win32.Point} class. @see: {win32.Point.screen_to_client} @type x: int @param x: Ho...
Translates window screen coordinates to client coordinates. @note: This is a simplified interface to some of the functionality of the L{win32.Point} class. @see: {win32.Point.screen_to_client} @type x: int @param x: Horizontal coordinate. @type y: int @pa...
def get_build_properties(self, project, build_id, filter=None): """GetBuildProperties. [Preview API] Gets properties for a build. :param str project: Project ID or project name :param int build_id: The ID of the build. :param [str] filter: A comma-delimited list of properties. If...
GetBuildProperties. [Preview API] Gets properties for a build. :param str project: Project ID or project name :param int build_id: The ID of the build. :param [str] filter: A comma-delimited list of properties. If specified, filters to these specific properties. :rtype: :class:`<...
def id_fix(value): """ fix @prefix values for ttl """ if value.startswith('KSC_M'): pass else: value = value.replace(':','_') if value.startswith('ERO') or value.startswith('OBI') or value.startswith('GO') or value.startswith('UBERON') or value.startswith('IAO'): value = ...
fix @prefix values for ttl
def first(self): """ Return the first element. """ if self.mode == 'local': return self.values[0] if self.mode == 'spark': return self.values.first().toarray()
Return the first element.
def __process_requests_stack(self): """ Process the requests stack. """ while self.__requests_stack: try: exec self.__requests_stack.popleft() in self.__locals except Exception as error: umbra.exceptions.notify_exception_handler(er...
Process the requests stack.
def Random(self): """Chooses a random element from this PMF. Returns: float value from the Pmf """ if len(self.d) == 0: raise ValueError('Pmf contains no values.') target = random.random() total = 0.0 for x, p in self.d.iteritems(): ...
Chooses a random element from this PMF. Returns: float value from the Pmf
def send_msg(self, msg, wait_nak=True, wait_timeout=WAIT_TIMEOUT): """Place a message on the send queue for sending. Message are sent in the order they are placed in the queue. """ msg_info = MessageInfo(msg=msg, wait_nak=wait_nak, wait_timeout=wait_timeou...
Place a message on the send queue for sending. Message are sent in the order they are placed in the queue.
def get_wsgi_app(self, name=None, defaults=None): """ Reads the configuration source and finds and loads a WSGI application defined by the entry with name ``name`` per the PasteDeploy configuration format and loading mechanism. :param name: The named WSGI app to find, load and r...
Reads the configuration source and finds and loads a WSGI application defined by the entry with name ``name`` per the PasteDeploy configuration format and loading mechanism. :param name: The named WSGI app to find, load and return. Defaults to ``None`` which becomes ``main`` inside ...
def echo_percent(self,transferred=1, status=None): '''Sample usage: f=lambda x,y:x+y ldata = range(10) toBeTransferred = reduce(f,range(10)) import time progress = ProgressBarUtils("viewbar", toBeTransferred=toBeTransferred, run_sta...
Sample usage: f=lambda x,y:x+y ldata = range(10) toBeTransferred = reduce(f,range(10)) import time progress = ProgressBarUtils("viewbar", toBeTransferred=toBeTransferred, run_status="正在下载", fin_status="下载完成") for i in ldata:...
def is_subset(self, other): """Check that every element in self has a count <= in other. Args: other (Set) """ if isinstance(other, _basebag): for elem, count in self.counts(): if not count <= other.count(elem): return False else: for elem in self: if self.count(elem) > 1 or elem not in...
Check that every element in self has a count <= in other. Args: other (Set)
def pxe_netboot(self, filename): """Specify which file ipxe should load during the netboot.""" new_port = { 'extra_dhcp_opts': [ {'opt_name': 'bootfile-name', 'opt_value': 'http://192.0.2.240:8088/' + filename, 'ip_version': 4, }, {'opt_name': 'tftp-server', '...
Specify which file ipxe should load during the netboot.
def sqrt(scalar): """Square root of a :class:`Scalar` or scalar value This always returns a :class:`Scalar`, and uses a symbolic square root if possible (i.e., for non-floats):: >>> sqrt(2) sqrt(2) >>> sqrt(2.0) 1.414213... For a :class:`ScalarExpression` argument, it...
Square root of a :class:`Scalar` or scalar value This always returns a :class:`Scalar`, and uses a symbolic square root if possible (i.e., for non-floats):: >>> sqrt(2) sqrt(2) >>> sqrt(2.0) 1.414213... For a :class:`ScalarExpression` argument, it returns a :class:`Sc...
def _log(self, content): """ Write a string to the log """ self._buffer += content if self._auto_flush: self.flush()
Write a string to the log
def ProcessHuntClientCrash(flow_obj, client_crash_info): """Processes client crash triggerted by a given hunt-induced flow.""" if not hunt.IsLegacyHunt(flow_obj.parent_hunt_id): hunt.StopHuntIfCrashLimitExceeded(flow_obj.parent_hunt_id) return hunt_urn = rdfvalue.RDFURN("hunts").Add(flow_obj.parent_hunt...
Processes client crash triggerted by a given hunt-induced flow.
def deserialize(cls, did_doc: dict) -> 'DIDDoc': """ Construct DIDDoc object from dict representation. Raise BadIdentifier for bad DID. :param did_doc: DIDDoc dict reprentation. :return: DIDDoc from input json. """ rv = None if 'id' in did_doc: ...
Construct DIDDoc object from dict representation. Raise BadIdentifier for bad DID. :param did_doc: DIDDoc dict reprentation. :return: DIDDoc from input json.
def readdir(self, path, fh): """Called by FUSE when a directory is opened. Returns a list of file and directory names for the directory. """ log.debug('readdir(): {}'.format(path)) try: dir = self._directory_cache[path] except KeyError: dir = sel...
Called by FUSE when a directory is opened. Returns a list of file and directory names for the directory.
def com_google_fonts_check_contour_count(ttFont): """Check if each glyph has the recommended amount of contours. This check is useful to assure glyphs aren't incorrectly constructed. The desired_glyph_data module contains the 'recommended' countour count for encoded glyphs. The contour counts are derived from...
Check if each glyph has the recommended amount of contours. This check is useful to assure glyphs aren't incorrectly constructed. The desired_glyph_data module contains the 'recommended' countour count for encoded glyphs. The contour counts are derived from fonts which were chosen for their quality and unique...
def _filter_link_tag_data(self, source, soup, data, url): """This method filters the web page content for link tags that match patterns given in the ``FILTER_MAPS`` :param source: The key of the meta dictionary in ``FILTER_MAPS['link']`` :type source: string :param soup: BeautifulSoup i...
This method filters the web page content for link tags that match patterns given in the ``FILTER_MAPS`` :param source: The key of the meta dictionary in ``FILTER_MAPS['link']`` :type source: string :param soup: BeautifulSoup instance to find meta tags :type soup: instance :param...
def get_segment_count_data(self, start, end, use_shapes=True): """ Get segment data including PTN vehicle counts per segment that are fully _contained_ within the interval (start, end) Parameters ---------- start : int start time of the simulation in unix tim...
Get segment data including PTN vehicle counts per segment that are fully _contained_ within the interval (start, end) Parameters ---------- start : int start time of the simulation in unix time end : int end time of the simulation in unix time use...
def upload_part(self, data, index=None, display_progress=False, report_progress_fn=None, **kwargs): """ :param data: Data to be uploaded in this part :type data: str or mmap object, bytes on python3 :param index: Index of part to be uploaded; must be in [1, 10000] :type index: in...
:param data: Data to be uploaded in this part :type data: str or mmap object, bytes on python3 :param index: Index of part to be uploaded; must be in [1, 10000] :type index: integer :param display_progress: Whether to print "." to stderr when done :type display_progress: boolean ...
def configfilepopulator(self): """Populates an unpopulated config.xml file with run-specific values and creates the file in the appropriate location""" # Set the number of cycles for each read and index using the number of reads specified in the sample sheet self.forwardlength = self.met...
Populates an unpopulated config.xml file with run-specific values and creates the file in the appropriate location
def circumcenter(pt0, pt1, pt2): r"""Calculate and return the circumcenter of a circumcircle generated by a given triangle. All three points must be unique or a division by zero error will be raised. Parameters ---------- pt0: (x, y) Starting vertex of triangle pt1: (x, y) Seco...
r"""Calculate and return the circumcenter of a circumcircle generated by a given triangle. All three points must be unique or a division by zero error will be raised. Parameters ---------- pt0: (x, y) Starting vertex of triangle pt1: (x, y) Second vertex of triangle pt2: (x, y)...
def fitNull(self, verbose=False, cache=False, out_dir='./cache', fname=None, rewrite=False, seed=None, n_times=10, factr=1e3, init_method=None): """ Fit null model """ if seed is not None: sp.random.seed(seed) read_from_file = False if cache: assert fname ...
Fit null model
def add_perm(self, subj_str, perm_str): """Add a permission for a subject. Args: subj_str : str Subject for which to add permission(s) perm_str : str Permission to add. Implicitly adds all lower permissions. E.g., ``write`` will also add ``read``...
Add a permission for a subject. Args: subj_str : str Subject for which to add permission(s) perm_str : str Permission to add. Implicitly adds all lower permissions. E.g., ``write`` will also add ``read``.
def resizeEvent(self, event): """ Overloads the resize event to control if we are still editing. If we are resizing, then we are no longer editing. """ curr_item = self.currentItem() self.closePersistentEditor(curr_item) super(XMultiTagE...
Overloads the resize event to control if we are still editing. If we are resizing, then we are no longer editing.
def shebang(self): """Get the file shebang if is has one.""" with open(self.path, 'rb') as file_handle: hashtag = file_handle.read(2) if hashtag == b'#!': file_handle.seek(0) return file_handle.readline().decode('utf8') return None
Get the file shebang if is has one.
def in6_getnsma(a): """ Return link-local solicited-node multicast address for given address. Passed address must be provided in network format. Returned value is also in network format. """ r = in6_and(a, inet_pton(socket.AF_INET6, '::ff:ffff')) r = in6_or(inet_pton(socket.AF_INET6, 'ff02:...
Return link-local solicited-node multicast address for given address. Passed address must be provided in network format. Returned value is also in network format.
def is_excluded_for_sdesc(self, sdesc, is_tpl=False): """ Check whether this host should have the passed service *description* be "excluded" or "not included". :param sdesc: service description :type sdesc: :param is_tpl: True if service is template, otherwise False ...
Check whether this host should have the passed service *description* be "excluded" or "not included". :param sdesc: service description :type sdesc: :param is_tpl: True if service is template, otherwise False :type is_tpl: bool :return: True if service description ex...
def do_replace(eval_ctx, s, old, new, count=None): """Return a copy of the value with all occurrences of a substring replaced with a new one. The first argument is the substring that should be replaced, the second is the replacement string. If the optional third argument ``count`` is given, only the fir...
Return a copy of the value with all occurrences of a substring replaced with a new one. The first argument is the substring that should be replaced, the second is the replacement string. If the optional third argument ``count`` is given, only the first ``count`` occurrences are replaced: .. sourcec...
def forge_fdf(pdf_form_url=None, fdf_data_strings=[], fdf_data_names=[], fields_hidden=[], fields_readonly=[], checkbox_checked_name=b"Yes"): """Generates fdf string from fields specified * pdf_form_url (default: None): just the url for the form. * fdf_data_strings (default: [])...
Generates fdf string from fields specified * pdf_form_url (default: None): just the url for the form. * fdf_data_strings (default: []): array of (string, value) tuples for the form fields (or dicts). Value is passed as a UTF-16 encoded string, unless True/False, in which case it is assumed to be a ...
def triples_to_graph(self, triples, top=None): """ Create a Graph from *triples* considering codec configuration. The Graph class does not know about information in the codec, so if Graph instantiation depends on special `TYPE_REL` or `TOP_VAR` values, use this function instead ...
Create a Graph from *triples* considering codec configuration. The Graph class does not know about information in the codec, so if Graph instantiation depends on special `TYPE_REL` or `TOP_VAR` values, use this function instead of instantiating a Graph object directly. This is also wher...
def _check_dir(self): """Makes sure that the working directory for the wrapper modules exists. """ from os import path, mkdir if not path.isdir(self.dirpath): mkdir(self.dirpath) #Copy the ftypes.py module shipped with fortpy to the local directory. ft...
Makes sure that the working directory for the wrapper modules exists.
def new_file(self, basedir): """New file""" title = _("New file") filters = _("All files")+" (*)" def create_func(fname): """File creation callback""" if osp.splitext(fname)[1] in ('.py', '.pyw', '.ipy'): create_script(fname) el...
New file
def update_resolver_nameservers(resolver, nameservers, nameserver_filename): """ Update a resolver's nameservers. The following priority is taken: 1. Nameservers list provided as an argument 2. A filename containing a list of nameservers 3. The original nameservers associated with the re...
Update a resolver's nameservers. The following priority is taken: 1. Nameservers list provided as an argument 2. A filename containing a list of nameservers 3. The original nameservers associated with the resolver
def gen_reference_primitive(polypeptide, start, end): """ Generates a reference Primitive for a Polypeptide given start and end coordinates. Notes ----- Uses the rise_per_residue of the Polypeptide primitive to define the separation of points on the line joining start and end. Parameters -...
Generates a reference Primitive for a Polypeptide given start and end coordinates. Notes ----- Uses the rise_per_residue of the Polypeptide primitive to define the separation of points on the line joining start and end. Parameters ---------- polypeptide : Polypeptide start : numpy.arra...
def execute(self, args): """Execute show subcommand.""" if args.name is not None: self.show_workspace(slashes2dash(args.name)) elif args.all is not None: self.show_all()
Execute show subcommand.
def get_network_name(network_id): """ Return the keeper network name based on the current ethereum network id. Return `development` for every network id that is not mapped. :param network_id: Network id, int :return: Network name, str """ if os.environ.get('KEEPE...
Return the keeper network name based on the current ethereum network id. Return `development` for every network id that is not mapped. :param network_id: Network id, int :return: Network name, str
def p_catch(self, p): """catch : CATCH LPAREN identifier RPAREN block""" p[0] = self.asttypes.Catch(identifier=p[3], elements=p[5]) p[0].setpos(p)
catch : CATCH LPAREN identifier RPAREN block
def list_commands(self, ctx): """Return a list of commands present in the commands and resources folders, but not subcommands. """ commands = set(self.list_resource_commands()) commands.union(set(self.list_misc_commands())) return sorted(commands)
Return a list of commands present in the commands and resources folders, but not subcommands.
def coactivation(dataset, seed, threshold=0.0, output_dir='.', prefix='', r=6): """ Compute and save coactivation map given input image as seed. This is essentially just a wrapper for a meta-analysis defined by the contrast between those studies that activate within the seed and those that don't. ...
Compute and save coactivation map given input image as seed. This is essentially just a wrapper for a meta-analysis defined by the contrast between those studies that activate within the seed and those that don't. Args: dataset: a Dataset instance containing study and activation data. seed...
def cylrec(r, lon, z): """ Convert from cylindrical to rectangular coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cylrec_c.html :param r: Distance of a point from z axis. :type r: float :param lon: Angle (radians) of a point from xZ plane. :type lon: float :param ...
Convert from cylindrical to rectangular coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cylrec_c.html :param r: Distance of a point from z axis. :type r: float :param lon: Angle (radians) of a point from xZ plane. :type lon: float :param z: Height of a point above xY plane...
def read(path, attribute, **kwargs): ''' Read the given attributes on the given file/directory :param str path: The file to get attributes from :param str attribute: The attribute to read :param bool hex: Return the values with forced hexadecimal values :return: A string containing the value...
Read the given attributes on the given file/directory :param str path: The file to get attributes from :param str attribute: The attribute to read :param bool hex: Return the values with forced hexadecimal values :return: A string containing the value of the named attribute :rtype: str :rai...
def ldap_server_host_port(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ldap_server = ET.SubElement(config, "ldap-server", xmlns="urn:brocade.com:mgmt:brocade-aaa") host = ET.SubElement(ldap_server, "host") hostname_key = ET.SubElement(host, "h...
Auto Generated Code
def bounding_polygon(self): """ Returns the bounding box polygon for this tile :return: `pywom.utils.geo.Polygon` instance """ lon_left, lat_bottom, lon_right, lat_top = Tile.tile_coords_to_bbox(self.x, self.y, self.zoom) print(lon_left, lat_bottom, lon_right, lat_top) ...
Returns the bounding box polygon for this tile :return: `pywom.utils.geo.Polygon` instance
def _build_host_livestate(self, host_name, livestate): # pylint: disable=no-self-use, too-many-locals """Build and notify the external command for an host livestate PROCESS_HOST_CHECK_RESULT;<host_name>;<status_code>;<plugin_output> :param host_name: the concerned host name :pa...
Build and notify the external command for an host livestate PROCESS_HOST_CHECK_RESULT;<host_name>;<status_code>;<plugin_output> :param host_name: the concerned host name :param livestate: livestate dictionary :return: external command line
def _on_response(self, response): """Process all received Pub/Sub messages. For each message, send a modified acknowledgment request to the server. This prevents expiration of the message due to buffering by gRPC or proxy/firewall. This makes the server and client expiration tim...
Process all received Pub/Sub messages. For each message, send a modified acknowledgment request to the server. This prevents expiration of the message due to buffering by gRPC or proxy/firewall. This makes the server and client expiration timer closer to each other thus preventing the m...
def min(self, key=None): """ Find the minimum item in this RDD. :param key: A function used to generate key for comparing >>> rdd = sc.parallelize([2.0, 5.0, 43.0, 10.0]) >>> rdd.min() 2.0 >>> rdd.min(key=str) 10.0 """ if key is None: ...
Find the minimum item in this RDD. :param key: A function used to generate key for comparing >>> rdd = sc.parallelize([2.0, 5.0, 43.0, 10.0]) >>> rdd.min() 2.0 >>> rdd.min(key=str) 10.0
def queryMulti(self, queries): """ Execute a series of Deletes,Inserts, & Updates in the Queires List @author: Nick Verbeck @since: 9/7/2008 """ self.lastError = None self.affectedRows = 0 self.rowcount = None self.record = None cursor = None try: try: self._GetConnection() #Execu...
Execute a series of Deletes,Inserts, & Updates in the Queires List @author: Nick Verbeck @since: 9/7/2008
def next(self): """Trigger next agent to :py:meth:`~creamas.core.CreativeAgent.act` in the current step. """ # all agents acted, init next step t = time.time() if len(self._agents_to_act) == 0: self._init_step() addr = self._agents_to_act.pop(0) ...
Trigger next agent to :py:meth:`~creamas.core.CreativeAgent.act` in the current step.