code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def is30(msg): """Check if a message is likely to be BDS code 2,0 Args: msg (String): 28 bytes hexadecimal message string Returns: bool: True or False """ if allzeros(msg): return False d = hex2bin(data(msg)) if d[0:8] != '00110000': return False # t...
Check if a message is likely to be BDS code 2,0 Args: msg (String): 28 bytes hexadecimal message string Returns: bool: True or False
def atlas_get_peer( peer_hostport, peer_table=None ): """ Get the given peer's info """ ret = None with AtlasPeerTableLocked(peer_table) as ptbl: ret = ptbl.get(peer_hostport, None) return ret
Get the given peer's info
def set_cli_options(config, arguments=None): """Set any configuration options which have a CLI value set. Args: config (confpy.core.config.Configuration): A configuration object which has been initialized with options. arguments (iter of str): An iterable of strings which contains t...
Set any configuration options which have a CLI value set. Args: config (confpy.core.config.Configuration): A configuration object which has been initialized with options. arguments (iter of str): An iterable of strings which contains the CLI arguments passed. If nothing is g...
def export_legacy_ldcoeffs(self, models, filename=None, photon_weighted=True): """ @models: the path (including the filename) of legacy's models.list @filename: output filename for storing the table Exports CK2004 limb darkening coefficients to a PHOEBE legacy compatible format....
@models: the path (including the filename) of legacy's models.list @filename: output filename for storing the table Exports CK2004 limb darkening coefficients to a PHOEBE legacy compatible format.
def set_index_edited(self, index, edited): """Set whether the conf was edited or not. Edited files will be displayed with a \'*\' :param index: the index that was edited :type index: QModelIndex :param edited: if the file was edited, set edited to True, else False :type...
Set whether the conf was edited or not. Edited files will be displayed with a \'*\' :param index: the index that was edited :type index: QModelIndex :param edited: if the file was edited, set edited to True, else False :type edited: bool :returns: None :rtype: N...
def query(self, startTime=None, endTime=None, sinceServerStart=False, level="WARNING", services="*", machines="*", server="*", codes=[], processIds=[], export=False, ...
The query operation on the logs resource provides a way to aggregate, filter, and page through logs across the entire site. Inputs:
def commit(self): """ Store metadata on this Job to the backend. """ logger.debug('Committing job {0}'.format(self.name)) self.backend.commit_job(self._serialize()) self.parent.commit()
Store metadata on this Job to the backend.
def mdr_mutual_information(X, Y, labels, base=2): """Calculates the MDR mutual information, I(XY;labels), in the given base MDR mutual information is calculated by combining variables X and Y into a single MDR model then calculating the mutual information between the resulting model's predictions and the l...
Calculates the MDR mutual information, I(XY;labels), in the given base MDR mutual information is calculated by combining variables X and Y into a single MDR model then calculating the mutual information between the resulting model's predictions and the labels. Parameters ---------- X: array-like (...
def _update_metadata(self, kwargs=None): '''Extract any additional attributes to hold with the instance from kwargs ''' # If not given metadata, use instance.list to get it for container if kwargs == None and hasattr(self, 'name'): kwargs = self._list(self.name, q...
Extract any additional attributes to hold with the instance from kwargs
def sel_list_pres(ds_sfc_x): ''' select proper levels for model level data download ''' p_min, p_max = ds_sfc_x.sp.min().values, ds_sfc_x.sp.max().values list_pres_level = [ '1', '2', '3', '5', '7', '10', '20', '30', '50', '70', '100', '125', '150', '175', '20...
select proper levels for model level data download
def add_user(self, attrs): """add a user""" ldap_client = self._bind() # encoding crap attrs_srt = self.attrs_pretreatment(attrs) attrs_srt[self._byte_p2('objectClass')] = self.objectclasses # construct is DN dn = \ self._byte_p2(self.dn_user_attr) + ...
add a user
def approx_aic(self, ts): """ Calculates an approximation to the Akaike Information Criterion (AIC). This is an approximation as we use the conditional likelihood, rather than the exact likelihood. Please see [[https://en.wikipedia.org/wiki/Akaike_information_criterion]] for more informa...
Calculates an approximation to the Akaike Information Criterion (AIC). This is an approximation as we use the conditional likelihood, rather than the exact likelihood. Please see [[https://en.wikipedia.org/wiki/Akaike_information_criterion]] for more information on this measure. ...
def _interpret_regexp(self, string, flags): '''Perform sctring escape - for regexp literals''' self.index = 0 self.length = len(string) self.source = string self.lineNumber = 0 self.lineStart = 0 octal = False st = '' inside_square = 0 whil...
Perform sctring escape - for regexp literals
def returnDepositsWithdrawals(self, start=0, end=2**32-1): """Returns your deposit and withdrawal history within a range, specified by the "start" and "end" POST parameters, both of which should be given as UNIX timestamps.""" return self._private('returnDepositsWithdrawals', start=start...
Returns your deposit and withdrawal history within a range, specified by the "start" and "end" POST parameters, both of which should be given as UNIX timestamps.
def get_destinations(self, ascii_listing): """ returns all line numbers that are used in a jump. """ self.destinations = set() def collect_destinations(matchobj): numbers = matchobj.group("no") if numbers: self.destinations.update(set( ...
returns all line numbers that are used in a jump.
def update_metadata_filters(metadata, jupyter_md, cell_metadata): """Update or set the notebook and cell metadata filters""" cell_metadata = [m for m in cell_metadata if m not in ['language', 'magic_args']] if 'cell_metadata_filter' in metadata.get('jupytext', {}): metadata_filter = metadata_filte...
Update or set the notebook and cell metadata filters
def quick_summary(nml2_doc): ''' Or better just use nml2_doc.summary(show_includes=False) ''' info = 'Contents of NeuroML 2 document: %s\n'%nml2_doc.id membs = inspect.getmembers(nml2_doc) for memb in membs: if isinstance(memb[1], list) and len(memb[1])>0 \ and not...
Or better just use nml2_doc.summary(show_includes=False)
def set_extended_elements(self): """Parses and sets non required elements""" self.set_creative_commons() self.set_owner() self.set_subtitle() self.set_summary()
Parses and sets non required elements
def protect_libraries_from_patching(): """ In this function we delete some modules from `sys.modules` dictionary and import them again inside `_pydev_saved_modules` in order to save their original copies there. After that we can use these saved modules within the debugger to protect them from patchi...
In this function we delete some modules from `sys.modules` dictionary and import them again inside `_pydev_saved_modules` in order to save their original copies there. After that we can use these saved modules within the debugger to protect them from patching by external libraries (e.g. gevent).
def dispatch(self, req): """ Called by the Routes middleware to dispatch the request to the appropriate controller. If a webob exception is raised, it is returned; if some other exception is raised, the webob `HTTPInternalServerError` exception is raised. Otherwise, the ...
Called by the Routes middleware to dispatch the request to the appropriate controller. If a webob exception is raised, it is returned; if some other exception is raised, the webob `HTTPInternalServerError` exception is raised. Otherwise, the return value of the controller is returned.
def netconf_session_start_session_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") netconf_session_start = ET.SubElement(config, "netconf-session-start", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-notifications") session_id = ET.SubElement(netconf...
Auto Generated Code
def _CreateAllTypes(self, enumTypes, dataTypes, managedTypes): """ Create pyVmomi types from pyVmomi type definitions """ # Create versions for typeInfo in managedTypes: name = typeInfo[0] version = typeInfo[3] VmomiSupport.AddVersion(version, '', '1.0', 0, name) V...
Create pyVmomi types from pyVmomi type definitions
def search_globs(path, patterns): # type: (str, List[str]) -> bool """ Test whether the given *path* contains any patterns in *patterns* Args: path (str): A file path to test for matches. patterns (list[str]): A list of glob string patterns to test against. If *path*...
Test whether the given *path* contains any patterns in *patterns* Args: path (str): A file path to test for matches. patterns (list[str]): A list of glob string patterns to test against. If *path* matches any of those patters, it will return True. Returns: ...
def remove_listener(registry, listener): """ Removes a listener from the registry :param registry: A registry (a list) :param listener: The listener to remove :return: True if the listener was in the list """ if listener is not None and listener in registry: registry.remove(listener...
Removes a listener from the registry :param registry: A registry (a list) :param listener: The listener to remove :return: True if the listener was in the list
def parse_query(query): """ Given a simplified XPath query string, returns an array of normalized query parts. """ parts = query.split('/') norm = [] for p in parts: p = p.strip() if p: norm.append(p) elif '' not in norm: norm.append('') return...
Given a simplified XPath query string, returns an array of normalized query parts.
def setHoverIcon( self, column, icon ): """ Returns the icon to use when coloring when the user hovers over the item for the given column. :param column | <int> icon | <QtGui.QIcon) """ self._hoverIcon[column] = QtGui.QIcon(icon...
Returns the icon to use when coloring when the user hovers over the item for the given column. :param column | <int> icon | <QtGui.QIcon)
def integrateFullOrbit_c(pot,yo,t,int_method,rtol=None,atol=None,dt=None): """ NAME: integrateFullOrbit_c PURPOSE: C integrate an ode for a FullOrbit INPUT: pot - Potential or list of such instances yo - initial condition [q,p] t - set of times at which one wants the r...
NAME: integrateFullOrbit_c PURPOSE: C integrate an ode for a FullOrbit INPUT: pot - Potential or list of such instances yo - initial condition [q,p] t - set of times at which one wants the result int_method= 'leapfrog_c', 'rk4_c', 'rk6_c', 'symplec4_c' rtol, atol...
def get_meta(meta, name): """Retrieves the metadata variable 'name' from the 'meta' dict.""" assert name in meta data = meta[name] if data['t'] in ['MetaString', 'MetaBool']: return data['c'] elif data['t'] == 'MetaInlines': # Handle bug in pandoc 2.2.3 and 2.2.3.1: Return boolean v...
Retrieves the metadata variable 'name' from the 'meta' dict.
def fileinfo(self, fid): """Ask lain about what he knows about given file. If the given file exists in the file dict, it will get updated.""" if not isinstance(fid, str): raise TypeError("Your file ID must be a string") try: info = self.conn.make_call_with_cb("ge...
Ask lain about what he knows about given file. If the given file exists in the file dict, it will get updated.
def make_url(self, container=None, resource=None, query_items=None): """Create a URL from the specified parts.""" pth = [self._base_url] if container: pth.append(container.strip('/')) if resource: pth.append(resource) else: pth.append('') ...
Create a URL from the specified parts.
def list_files(self, offset=None, limit=None, api=None): """List files in a folder :param api: Api instance :param offset: Pagination offset :param limit: Pagination limit :return: List of files """ api = api or self._API if not self.is_folder(): ...
List files in a folder :param api: Api instance :param offset: Pagination offset :param limit: Pagination limit :return: List of files
def process_tick(self, tup): """Called every window_duration """ curtime = int(time.time()) window_info = WindowContext(curtime - self.window_duration, curtime) self.processWindow(window_info, list(self.current_tuples)) for tup in self.current_tuples: self.ack(tup) self.current_tuples....
Called every window_duration
def _dict_to_pio(d, class_=None): """ Convert a single dictionary object to a Physical Information Object. :param d: Dictionary to convert. :param class_: Subclass of :class:`.Pio` to produce, if not unambiguous :return: Single object derived from :class:`.Pio`. """ d = keys_to_snake_case(d...
Convert a single dictionary object to a Physical Information Object. :param d: Dictionary to convert. :param class_: Subclass of :class:`.Pio` to produce, if not unambiguous :return: Single object derived from :class:`.Pio`.
def authorize_url(self, state=''): """ return user authorize url """ url = 'https://openapi.youku.com/v2/oauth2/authorize?' params = { 'client_id': self.client_id, 'response_type': 'code', 'state': state, 'redirect_uri': self.redirect_uri ...
return user authorize url
def jcrop_css(css_url=None): """Load jcrop css file. :param css_url: The custom CSS URL. """ if css_url is None: if current_app.config['AVATARS_SERVE_LOCAL']: css_url = url_for('avatars.static', filename='jcrop/css/jquery.Jcrop.min.css') else: ...
Load jcrop css file. :param css_url: The custom CSS URL.
def last_job_statuses(self) -> List[str]: """The last constants of the job in this experiment.""" statuses = [] for status in self.jobs.values_list('status__status', flat=True): if status is not None: statuses.append(status) return statuses
The last constants of the job in this experiment.
def set_logger(self, logger): """subscribe to fortran log messages""" # we don't expect anything back try: self.library.set_logger.restype = None except AttributeError: logger.warn("Tried to set logger but method is not implemented in %s", self.engine) ...
subscribe to fortran log messages
def get_all_tasks(self, course): """ :return: a table containing taskid=>Task pairs """ tasks = self.get_readable_tasks(course) output = {} for task in tasks: try: output[task] = self.get_task(course, task) except: p...
:return: a table containing taskid=>Task pairs
def set_ylim(self, xlims, dx, xscale, reverse=False): """Set y limits for plot. This will set the limits for the y axis for the specific plot. Args: ylims (len-2 list of floats): The limits for the axis. dy (float): Amount to increment by between the limits. ...
Set y limits for plot. This will set the limits for the y axis for the specific plot. Args: ylims (len-2 list of floats): The limits for the axis. dy (float): Amount to increment by between the limits. yscale (str): Scale of the axis. Either `log` or `lin`. ...
def does_sqlatype_require_index_len( coltype: Union[TypeEngine, VisitableType]) -> bool: """ Is the SQLAlchemy column type one that requires its indexes to have a length specified? (MySQL, at least, requires index length to be specified for ``BLOB`` and ``TEXT`` columns: http://dev.mysq...
Is the SQLAlchemy column type one that requires its indexes to have a length specified? (MySQL, at least, requires index length to be specified for ``BLOB`` and ``TEXT`` columns: http://dev.mysql.com/doc/refman/5.7/en/create-index.html.)
def is_iterable(obj): """ Are we being asked to look up a list of things, instead of a single thing? We check for the `__iter__` attribute so that this can cover types that don't have to be known by this module, such as NumPy arrays. Strings, however, should be considered as atomic values to look u...
Are we being asked to look up a list of things, instead of a single thing? We check for the `__iter__` attribute so that this can cover types that don't have to be known by this module, such as NumPy arrays. Strings, however, should be considered as atomic values to look up, not iterables. We don'...
def recipients(messenger, addresses): """Structures recipients data. :param str|unicode, MessageBase messenger: MessengerBase heir :param list[str|unicode]|str|unicode addresses: recipients addresses or Django User model heir instances (NOTE: if supported by a messenger) :return: list of Recip...
Structures recipients data. :param str|unicode, MessageBase messenger: MessengerBase heir :param list[str|unicode]|str|unicode addresses: recipients addresses or Django User model heir instances (NOTE: if supported by a messenger) :return: list of Recipient :rtype: list[Recipient]
def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=No...
Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to creat...
def friendfeed_request(self, path, callback, access_token=None, post_args=None, **args): """Fetches the given relative API path, e.g., "/bret/friends" If the request is a POST, post_args should be provided. Query string arguments should be given as keyword arguments. ...
Fetches the given relative API path, e.g., "/bret/friends" If the request is a POST, post_args should be provided. Query string arguments should be given as keyword arguments. All the FriendFeed methods are documented at http://friendfeed.com/api/documentation. Many methods re...
def generate_csr(self, basename='djangoafip'): """ Creates a CSR for this TaxPayer's key Creates a file-like object that contains the CSR which can be used to request a new certificate from AFIP. """ csr = BytesIO() crypto.create_csr( self.key.file, ...
Creates a CSR for this TaxPayer's key Creates a file-like object that contains the CSR which can be used to request a new certificate from AFIP.
def solve_let(expr, vars): """Solves a let-form by calling RHS with nested scope.""" lhs_value = solve(expr.lhs, vars).value if not isinstance(lhs_value, structured.IStructured): raise errors.EfilterTypeError( root=expr.lhs, query=expr.original, message="The LHS of 'let' must...
Solves a let-form by calling RHS with nested scope.
def solve_tsp(V,c): """solve_tsp -- solve the traveling salesman problem - start with assignment model - check flow from a source to every other node; - if no flow, a sub-cycle has been found --> add cut - otherwise, the solution is optimal Parameters: - V: set/list of ...
solve_tsp -- solve the traveling salesman problem - start with assignment model - check flow from a source to every other node; - if no flow, a sub-cycle has been found --> add cut - otherwise, the solution is optimal Parameters: - V: set/list of nodes in the graph ...
def get_email_link(email, value=None): """ Returns a well-formed link to an email address. If email is None/empty, returns an empty string :param email: email address :param link_text: text to be displayed. If None, the email itself is used :return: a well-formatted html anchor """ if no...
Returns a well-formed link to an email address. If email is None/empty, returns an empty string :param email: email address :param link_text: text to be displayed. If None, the email itself is used :return: a well-formatted html anchor
def _validate_entity_cls(self, entity_cls): """Validate that Entity is a valid class""" # Import here to avoid cyclic dependency from protean.core.entity import Entity if not issubclass(entity_cls, Entity): raise AssertionError( f'Entity {entity_cls.__name__}...
Validate that Entity is a valid class
def to_array(self): """ Serializes this InlineQueryResultMpeg4Gif to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultMpeg4Gif, self).to_array() array['type'] = u(self.type) # py2: type unicode, py3...
Serializes this InlineQueryResultMpeg4Gif to a dictionary. :return: dictionary representation of this object. :rtype: dict
def is_bootstrapped(metadata): """Return True if cihai is correctly bootstrapped.""" fields = UNIHAN_FIELDS + DEFAULT_COLUMNS if TABLE_NAME in metadata.tables.keys(): table = metadata.tables[TABLE_NAME] if set(fields) == set(c.name for c in table.columns): return True el...
Return True if cihai is correctly bootstrapped.
def removeBiosample(self, biosample): """ Removes the specified biosample from this repository. """ q = models.Biosample.delete().where( models.Biosample.id == biosample.getId()) q.execute()
Removes the specified biosample from this repository.
def main(): """ Simple command-line program for powering on virtual machines on a system. """ args = GetArgs() if args.password: password = args.password else: password = getpass.getpass(prompt='Enter password for host %s and user %s: ' % (args.host,args.user)) try: vmnames = ar...
Simple command-line program for powering on virtual machines on a system.
def t_op(self, s): r'\+=|-=|\*=|/=|%=|&=|\|=|^=|<<=|>>=|\*\*=|//=|//|==|<=|>=|<<|>>|[<>%^&+/=~-]' # Operators need to be further classified since the grammar requires this if s in ('<', '>', '==', '>=', '<=', '<>', '!='): self.add_token('COMP_OP', s) elif s in ('+=', '-=', '...
r'\+=|-=|\*=|/=|%=|&=|\|=|^=|<<=|>>=|\*\*=|//=|//|==|<=|>=|<<|>>|[<>%^&+/=~-]
def whole_subnet_maker(ip_addr, cidr): """ Function to return a whole subnet value from a IP address and CIDR pair Args: ip_addr: Unicast or Multicast IP address or subnet in the following format 192.168.1.1, 239.1.1.1 cidr: CIDR value of 0 to 32 Returns: returns the corrected whole sub...
Function to return a whole subnet value from a IP address and CIDR pair Args: ip_addr: Unicast or Multicast IP address or subnet in the following format 192.168.1.1, 239.1.1.1 cidr: CIDR value of 0 to 32 Returns: returns the corrected whole subnet
def spdhg_generic(x, f, g, A, tau, sigma, niter, **kwargs): r"""Computes a saddle point with a stochastic PDHG. This means, a solution (x*, y*), y* = (y*_1, ..., y*_n) such that (x*, y*) in arg min_x max_y sum_i=1^n <y_i, A_i> - f*[i](y_i) + g(x) where g : X -> IR_infty and f[i] : Y[i] -> IR_infty ar...
r"""Computes a saddle point with a stochastic PDHG. This means, a solution (x*, y*), y* = (y*_1, ..., y*_n) such that (x*, y*) in arg min_x max_y sum_i=1^n <y_i, A_i> - f*[i](y_i) + g(x) where g : X -> IR_infty and f[i] : Y[i] -> IR_infty are convex, l.s.c. and proper functionals. For this algorithm,...
def overlap_bbox_and_point(bbox, xp, yp): """Given a bbox that contains a given point, return the (x, y) displacement necessary to make the bbox not overlap the point.""" cx, cy = get_midpoint(bbox) dir_x = np.sign(cx-xp) dir_y = np.sign(cy-yp) if dir_x == -1: dx = xp - bbox.xmax e...
Given a bbox that contains a given point, return the (x, y) displacement necessary to make the bbox not overlap the point.
def envs(backend=None, sources=False): ''' Return the available fileserver environments. If no backend is provided, then the environments for all configured backends will be returned. backend Narrow fileserver backends to a subset of the enabled ones. .. versionchanged:: 2015.5.0 ...
Return the available fileserver environments. If no backend is provided, then the environments for all configured backends will be returned. backend Narrow fileserver backends to a subset of the enabled ones. .. versionchanged:: 2015.5.0 If all passed backends start with a minus si...
def count(self): """ Count the number of domain for each status. """ if self.status: # The status is parsed. # We increase the number of tested. PyFunceble.INTERN["counter"]["number"]["tested"] += 1 if ( self.status.lower...
Count the number of domain for each status.
def _ctorCmprRange(self, vals): ''' Override default *range= handler to account for relative computation. ''' if not isinstance(vals, (list, tuple)): raise s_exc.BadCmprValu(valu=vals, cmpr='*range=') if len(vals) != 2: raise s_exc.BadCmprValu(valu=vals,...
Override default *range= handler to account for relative computation.
def create_superuser(self, email, password, **extra_fields): """Save new User with is_staff and is_superuser set to True""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('S...
Save new User with is_staff and is_superuser set to True
def apply(self, spectrum, plot=False): """ Apply the filter to the given [W, F], or [W, F, E] spectrum Parameters ---------- spectrum: array-like The wavelength [um] and flux of the spectrum to apply the filter to plot: bool Plot the o...
Apply the filter to the given [W, F], or [W, F, E] spectrum Parameters ---------- spectrum: array-like The wavelength [um] and flux of the spectrum to apply the filter to plot: bool Plot the original and filtered spectrum Returns ----...
async def movehere(self, channel): """ Moves the embed message to a new channel; can also be used to move the musicplayer to the front Args: channel (discord.Channel): The channel to move to """ self.logger.debug("movehere command") # Delete the old message...
Moves the embed message to a new channel; can also be used to move the musicplayer to the front Args: channel (discord.Channel): The channel to move to
def norm_slash(name): """Normalize path slashes.""" if isinstance(name, str): return name.replace('/', "\\") if not is_case_sensitive() else name else: return name.replace(b'/', b"\\") if not is_case_sensitive() else name
Normalize path slashes.
def transliterate(table, text): """ Transliterate text according to one of the tables above. `table` chooses the table. It looks like a language code but comes from a very restricted set: - 'sr-Latn' means to convert Serbian, which may be in Cyrillic, into the Latin alphabet. - 'az-Latn'...
Transliterate text according to one of the tables above. `table` chooses the table. It looks like a language code but comes from a very restricted set: - 'sr-Latn' means to convert Serbian, which may be in Cyrillic, into the Latin alphabet. - 'az-Latn' means the same for Azerbaijani Cyrillic to ...
def URIUnescapeString(str, len, target): """Unescaping routine, but does not check that the string is an URI. The output is a direct unsigned char translation of %XX values (no encoding) Note that the length of the result can only be smaller or same size as the input string. """ ret = libxml2...
Unescaping routine, but does not check that the string is an URI. The output is a direct unsigned char translation of %XX values (no encoding) Note that the length of the result can only be smaller or same size as the input string.
def normalize_name(decl): """ Cached variant of normalize Args: decl (declaration.declaration_t): the declaration Returns: str: normalized name """ if decl.cache.normalized_name is None: decl.cache.normalized_name = normalize(decl.name) return decl.cache.normalized_...
Cached variant of normalize Args: decl (declaration.declaration_t): the declaration Returns: str: normalized name
def legal_graph(graph): '''judge if a graph is legal or not. ''' descriptor = graph.extract_descriptor() skips = descriptor.skip_connections if len(skips) != len(set(skips)): return False return True
judge if a graph is legal or not.
def GetNBits(value, nbits): """ Get the first `nbits` from `value`. :param value: Source value from which to extract :type value: int or long or BitVec :param int nbits: How many bits to extract :return: Low `nbits` bits of `value`. :rtype int or long or BitVec """ # NOP if sizes ar...
Get the first `nbits` from `value`. :param value: Source value from which to extract :type value: int or long or BitVec :param int nbits: How many bits to extract :return: Low `nbits` bits of `value`. :rtype int or long or BitVec
def state(self, context): """ Get instance state. :param resort.engine.execution.Context context: Current execution context. :rtype: str :return: Instance state name. """ state = None for line in self.read(context, [ "status", context.resolve(self.__name) ]): if line[2]...
Get instance state. :param resort.engine.execution.Context context: Current execution context. :rtype: str :return: Instance state name.
def _validate_compression_params(self, img_array, cparams, colorspace): """Check that the compression parameters are valid. Parameters ---------- img_array : ndarray Image data to be written to file. cparams : CompressionParametersType(ctypes.Structure) C...
Check that the compression parameters are valid. Parameters ---------- img_array : ndarray Image data to be written to file. cparams : CompressionParametersType(ctypes.Structure) Corresponds to cparameters_t type in openjp2 headers.
def iterate(self, params, repetition, iteration): """ Called once for each training iteration (== epoch here). """ try: print("\nStarting iteration",iteration) t1 = time.time() ret = {} # Update learning rate using learning rate scheduler if configured if self.lr_scheduler...
Called once for each training iteration (== epoch here).
def crud_mutation_name(action, model): """ This function returns the name of a mutation that performs the specified crud action on the given model service """ model_string = get_model_string(model) # make sure the mutation name is correctly camelcases model_string = model_string[0].u...
This function returns the name of a mutation that performs the specified crud action on the given model service
def current(instance=True): """Returns the current thread's `IOLoop`. If an `IOLoop` is currently running or has been marked as current by `make_current`, returns that instance. If there is no current `IOLoop` and ``instance`` is true, creates one. .. versionchanged:: 4.1 ...
Returns the current thread's `IOLoop`. If an `IOLoop` is currently running or has been marked as current by `make_current`, returns that instance. If there is no current `IOLoop` and ``instance`` is true, creates one. .. versionchanged:: 4.1 Added ``instance`` argument to c...
def time_zone_by_name(self, hostname): """ Returns time zone in tzdata format (e.g. America/New_York or Europe/Paris) :arg hostname: Hostname (e.g. example.com) """ addr = self._gethostbyname(hostname) return self.time_zone_by_addr(addr)
Returns time zone in tzdata format (e.g. America/New_York or Europe/Paris) :arg hostname: Hostname (e.g. example.com)
def get_classification_node(self, project, structure_group, path=None, depth=None): """GetClassificationNode. Gets the classification node for a given node path. :param str project: Project ID or project name :param TreeStructureGroup structure_group: Structure group of the classificatio...
GetClassificationNode. Gets the classification node for a given node path. :param str project: Project ID or project name :param TreeStructureGroup structure_group: Structure group of the classification node, area or iteration. :param str path: Path of the classification node. :p...
def calc_geo_dist_vincenty(node_source, node_target): """ Calculates the geodesic distance between `node_source` and `node_target` incorporating the detour factor specified in :file:`ding0/ding0/config/config_calc.cfg`. Parameters ---------- node_source: LVStationDing0, GeneratorDing0, or CableDist...
Calculates the geodesic distance between `node_source` and `node_target` incorporating the detour factor specified in :file:`ding0/ding0/config/config_calc.cfg`. Parameters ---------- node_source: LVStationDing0, GeneratorDing0, or CableDistributorDing0 source node, member of GridDing0._graph ...
def extract_key_value(line, environ): """Return key, value from given line if present, else return None. """ segments = line.split("=", 1) if len(segments) < 2: return None key, value = segments # foo passes through as-is (with spaces stripped) # '{foo}' passes through literally ...
Return key, value from given line if present, else return None.
def _adjust_legend(self, overlay, axis): """ Accumulate the legend handles and labels for all subplots and set up the legend """ legend_data = [] dimensions = overlay.kdims title = ', '.join([d.name for d in dimensions]) for key, subplot in self.subplots.i...
Accumulate the legend handles and labels for all subplots and set up the legend
def intervaljoin(left, right, lstart='start', lstop='stop', rstart='start', rstop='stop', lkey=None, rkey=None, include_stop=False, lprefix=None, rprefix=None): """ Join two tables by overlapping intervals. E.g.:: >>> import petl as etl >>> left = [['begin', 'e...
Join two tables by overlapping intervals. E.g.:: >>> import petl as etl >>> left = [['begin', 'end', 'quux'], ... [1, 2, 'a'], ... [2, 4, 'b'], ... [2, 5, 'c'], ... [9, 14, 'd'], ... [1, 1, 'e'], ... [10, 10...
def parse(self, rrstr): # type: (bytes) -> None ''' Parse a Rock Ridge Parent Link record out of a string. Parameters: rrstr - The string to parse the record out of. Returns: Nothing. ''' if self._initialized: raise pycdlibexception....
Parse a Rock Ridge Parent Link record out of a string. Parameters: rrstr - The string to parse the record out of. Returns: Nothing.
def promote(self, cart_name): """ `name` - name of cart Promote a cart from its current environment to the next in the chain. """ cart = juicer.common.Cart.Cart(cart_name=cart_name, autoload=True, autosync=True) old_env = cart.current_env cart.current_env = juice...
`name` - name of cart Promote a cart from its current environment to the next in the chain.
def size_of_varint(value): """ Number of bytes needed to encode an integer in variable-length format. """ value = (value << 1) ^ (value >> 63) if value <= 0x7f: return 1 if value <= 0x3fff: return 2 if value <= 0x1fffff: return 3 if value <= 0xfffffff: return ...
Number of bytes needed to encode an integer in variable-length format.
def _get_linewise_report(self): """ Returns a report each line of which comprises a pair of an input line and an error. Unlike in the standard report, errors will appear as many times as they occur. Helper for the get_report method. """ d = defaultdict(list) # line: [] of errors for error, lines in s...
Returns a report each line of which comprises a pair of an input line and an error. Unlike in the standard report, errors will appear as many times as they occur. Helper for the get_report method.
def frame_parser(version=None, kind=0, extensions=None, protocols=None): '''Create a new :class:`FrameParser` instance. :param version: protocol version, the default is 13 :param kind: the kind of parser, and integer between 0 and 3 (check the :class:`FrameParser` documentation for details) :pa...
Create a new :class:`FrameParser` instance. :param version: protocol version, the default is 13 :param kind: the kind of parser, and integer between 0 and 3 (check the :class:`FrameParser` documentation for details) :param extensions: not used at the moment :param protocols: not used at the mom...
def read_message_bytes_from_pipe(pipe_handle): """ (coroutine) Read message from this pipe. Return bytes. """ overlapped = OVERLAPPED() overlapped.hEvent = create_event() try: buff = create_string_buffer(BUFSIZE + 1) c_read = DWORD() success = windll.kernel32.ReadFi...
(coroutine) Read message from this pipe. Return bytes.
def setDragData(self, data, x=None, y=None): """ Sets the drag data for this chart item to the inputed data. :param data | <QMimeData> || None """ self._dragData[(x, y)] = data
Sets the drag data for this chart item to the inputed data. :param data | <QMimeData> || None
def GetRandomDatetime(): """Return a datetime in the next week.""" seconds_offset = random.randint(0, 60 * 60 * 24 * 7) dt = datetime.today() + timedelta(seconds=seconds_offset) return dt.replace(second=0, microsecond=0)
Return a datetime in the next week.
def example(script, explain, contents, requirements, output, outputfmt, details): """Prints the example help for the script.""" blank() cprint(script.upper(), "yellow") cprint(''.join(["=" for i in range(70)]) + '\n', "yellow") cprint("DETAILS", "blue") std(explain + '\n') cprint(requireme...
Prints the example help for the script.
def connect_delete_namespaced_service_proxy(self, name, namespace, **kwargs): # noqa: E501 """connect_delete_namespaced_service_proxy # noqa: E501 connect DELETE requests to proxy of Service # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous...
connect_delete_namespaced_service_proxy # noqa: E501 connect DELETE requests to proxy of Service # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.connect_delete_namespaced_service_pr...
def search_node_namespace_names(graph, query, namespace): """Search for nodes with the given namespace(s) and whose names containing a given string(s). :param pybel.BELGraph graph: A BEL graph :param query: The search query :type query: str or iter[str] :param namespace: The namespace(s) to filter ...
Search for nodes with the given namespace(s) and whose names containing a given string(s). :param pybel.BELGraph graph: A BEL graph :param query: The search query :type query: str or iter[str] :param namespace: The namespace(s) to filter :type namespace: str or iter[str] :return: An iterator ov...
def simxLoadModel(clientID, modelPathAndName, options, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' baseHandle = ct.c_int() if (sys.version_info[0] == 3) and (type(modelPathAndName) is str): modelPathAndName=modelPathAndName.en...
Please have a look at the function description/documentation in the V-REP user manual
def acl_show(self, msg, args): """Show current allow and deny blocks for the given acl.""" name = args[0] if len(args) > 0 else None if name is None: return "%s: The following ACLs are defined: %s" % (msg.user, ', '.join(self._acl.keys())) if name not in self._acl: ...
Show current allow and deny blocks for the given acl.
def set_scale(self, xscale=None, yscale=None, zscale=None, reset_camera=True): """ Scale all the datasets in the scene of the active renderer. Scaling in performed independently on the X, Y and Z axis. A scale of zero is illegal and will be replaced with one. Parameters ...
Scale all the datasets in the scene of the active renderer. Scaling in performed independently on the X, Y and Z axis. A scale of zero is illegal and will be replaced with one. Parameters ---------- xscale : float, optional Scaling of the x axis. Must be greater th...
def generate_message_doc(message_descriptor, locations, path, name_prefix=''): """Generate docs for message and nested messages and enums. Args: message_descriptor: descriptor_pb2.DescriptorProto instance for message to generate docs for. locations: Dictionary of location paths tupl...
Generate docs for message and nested messages and enums. Args: message_descriptor: descriptor_pb2.DescriptorProto instance for message to generate docs for. locations: Dictionary of location paths tuples to descriptor_pb2.SourceCodeInfo.Location instances. path: Path...
def check_application_state(self, request, callback): "Check optional state parameter." stored = request.session.get(self.session_key, None) returned = request.GET.get('state', None) check = False if stored is not None: if returned is not None: check =...
Check optional state parameter.
def roll_out_and_store(self, batch_info): """ Roll out environment and store result in the replay buffer """ self.model.train() if self.env_roller.is_ready_for_sampling(): rollout = self.env_roller.rollout(batch_info, self.model, self.settings.rollout_steps).to_device(self.device) ...
Roll out environment and store result in the replay buffer
def get_cookie_jar(self): """Returns our cookie jar.""" cookie_file = self._get_cookie_file() cookie_jar = LWPCookieJar(cookie_file) if os.path.exists(cookie_file): cookie_jar.load() else: safe_mkdir_for(cookie_file) # Save an empty cookie jar so we can change the file perms on it ...
Returns our cookie jar.
def save_to_internal(self, data): """save """ if self.filetype is "pickle": pickle.dump(data, open(self.location_internal, "wb")) elif self.filetype is "hickle": import hickle hickle.dump(data, open(self.location_internal, "wb")) else: ...
save
def make_int(value, missing=-1): """Convert string value to long, '' to missing""" if isinstance(value, six.string_types): if not value.strip(): return missing elif value is None: return missing return int(value)
Convert string value to long, '' to missing