code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def commit(self, message, author, parents=None, branch=None, date=None,
**kwargs):
"""
Performs in-memory commit (doesn't check workdir in any way) and
returns newly created ``Changeset``. Updates repository's
``revisions``.
:param message: message of the commit
... | Performs in-memory commit (doesn't check workdir in any way) and
returns newly created ``Changeset``. Updates repository's
``revisions``.
:param message: message of the commit
:param author: full username, i.e. "Joe Doe <joe.doe@example.com>"
:param parents: single parent or seq... |
def post_build(self, container_builder, container):
"""
This method make sure the flask configuration is fine, and
check the if ioc.extra.jinja2 service is available. If so, the
flask instance will use this service, by keeping the flask template
loader and the one registered a... | This method make sure the flask configuration is fine, and
check the if ioc.extra.jinja2 service is available. If so, the
flask instance will use this service, by keeping the flask template
loader and the one registered at the jinja2 |
def load_py_instance(self, is_spout):
"""Loads user defined component (spout/bolt)"""
try:
if is_spout:
spout_proto = self.pplan_helper.get_my_spout()
py_classpath = spout_proto.comp.class_name
self.logger.info("Loading Spout from: %s", py_classpath)
else:
bolt_proto ... | Loads user defined component (spout/bolt) |
def export(self, nidm_version, export_dir):
"""
Create prov entities and activities.
"""
if nidm_version['num'] in ["1.0.0", "1.1.0"]:
self.label = self.label.replace("Supra-Threshold", "Significant")
# FIXME deal with multiple contrasts
atts = (
... | Create prov entities and activities. |
def login(self, email=None, password=None, gsfId=None, authSubToken=None):
"""Login to your Google Account.
For first time login you should provide:
* email
* password
For the following logins you need to provide:
* gsfId
* authSubToken"""
... | Login to your Google Account.
For first time login you should provide:
* email
* password
For the following logins you need to provide:
* gsfId
* authSubToken |
def write_checktime (self, url_data):
"""Write url_data.checktime."""
self.write(self.part("checktime") + self.spaces("checktime"))
self.writeln(_("%.3f seconds") % url_data.checktime,
color=self.colordltime) | Write url_data.checktime. |
def request_phone(cls, text, *,
resize=None, single_use=None, selective=None):
"""
Creates a new button that will request
the user's phone number upon being clicked.
``resize``, ``single_use`` and ``selective`` are documented in `text`.
"""
return c... | Creates a new button that will request
the user's phone number upon being clicked.
``resize``, ``single_use`` and ``selective`` are documented in `text`. |
def parents(self):
"""
Returns list of parents changesets.
"""
return [self.repository.get_changeset(parent.rev())
for parent in self._ctx.parents() if parent.rev() >= 0] | Returns list of parents changesets. |
def inverse_transform(self, X, copy=None):
"""
Scale back the data to the original representation.
:param X: Scaled data matrix.
:type X: numpy.ndarray, shape [n_samples, n_features]
:param bool copy: Copy the X data matrix.
:return: X data matrix with the scaling operat... | Scale back the data to the original representation.
:param X: Scaled data matrix.
:type X: numpy.ndarray, shape [n_samples, n_features]
:param bool copy: Copy the X data matrix.
:return: X data matrix with the scaling operation reverted.
:rtype: numpy.ndarray, shape [n_samples, ... |
def start_tag(self, indent):
"""
Generate the string for the element's start tag.
"""
return u"%s<%s%s/>" % (indent, self.tagName, u"".join(u" %s=\"%s\"" % keyvalue for keyvalue in self.attributes.items())) | Generate the string for the element's start tag. |
def setup_manager_context():
"""
Creates a initialized context manager which shuts down at the end of the
`with` block.
usage:
>>> with setup_manager_context() as setup_manager:
... setup_manager.load_config(...)
... # ... Run match
"""
setup_manager = SetupManager()
set... | Creates a initialized context manager which shuts down at the end of the
`with` block.
usage:
>>> with setup_manager_context() as setup_manager:
... setup_manager.load_config(...)
... # ... Run match |
def quartus_prop(self, buff: List[str], intfName: str, name: str, value,
escapeStr=True):
"""
Set property on interface in Quartus TCL
:param buff: line buffer for output
:param intfName: name of interface to set property on
:param name: property name
... | Set property on interface in Quartus TCL
:param buff: line buffer for output
:param intfName: name of interface to set property on
:param name: property name
:param value: property value
:param escapeStr: flag, if True put string properties to extra "" |
def fit_transform(self, X, y=None, **params):
"""Learn vocabulary and return document id matrix.
This is equivalent to fit followed by transform.
Args:
X : iterable
an iterable which yields either str, unicode or file objects.
Returns:
list : docume... | Learn vocabulary and return document id matrix.
This is equivalent to fit followed by transform.
Args:
X : iterable
an iterable which yields either str, unicode or file objects.
Returns:
list : document id matrix.
list: label id matrix. |
def get_templates(model):
""" Return a list of templates usable by a model. """
for template_name, template in templates.items():
if issubclass(template.model, model):
yield (template_name, template.layout._meta.verbose_name) | Return a list of templates usable by a model. |
def get_all_files(folder):
"""
Generator that loops through all absolute paths of the files within folder
Parameters
----------
folder: str
Root folder start point for recursive search.
Yields
------
fpath: str
Absolute path of one file in the folders
"""
for path, dirl... | Generator that loops through all absolute paths of the files within folder
Parameters
----------
folder: str
Root folder start point for recursive search.
Yields
------
fpath: str
Absolute path of one file in the folders |
def _input_to_raw_value(self, value: int) -> float:
"""
Convert the value read from evdev to a 0.0 to 1.0 range.
:internal:
:param value:
a value ranging from the defined minimum to the defined maximum value.
:return:
0.0 at minimum, 1.0 at maximum, line... | Convert the value read from evdev to a 0.0 to 1.0 range.
:internal:
:param value:
a value ranging from the defined minimum to the defined maximum value.
:return:
0.0 at minimum, 1.0 at maximum, linearly interpolating between those two points. |
def build_prev_op(self):
"""
Compose 'list-map' which allows to jump to previous
op, given offset of current op as index.
"""
code = self.code
codelen = len(code)
# 2.x uses prev 3.x uses prev_op. Sigh
# Until we get this sorted out.
self.prev = se... | Compose 'list-map' which allows to jump to previous
op, given offset of current op as index. |
def longest_service_name(self):
"""Length of the longest service name."""
return max([len(service_handle.service.name) for service_handle in self.service_handles] + [0]) | Length of the longest service name. |
def get_update_tile(self, params, values):
""" Get the amount of support size required for a particular update."""
doglobal, particles = self._update_type(params)
if doglobal:
return self.shape.copy()
# 1) store the current parameters of interest
values0 = self.get_v... | Get the amount of support size required for a particular update. |
def tags(self):
"""Returns a `set` of unique tags contained in `raw_content`."""
if not self.raw_content:
return set()
return {word.strip("#").lower() for word in self.raw_content.split() if word.startswith("#") and len(word) > 1} | Returns a `set` of unique tags contained in `raw_content`. |
def source_lines(self):
"""
Returns the lines of source code containing the entirety of this range.
"""
return [self.source_buffer.source_line(line)
for line in range(self.line(), self.end().line() + 1)] | Returns the lines of source code containing the entirety of this range. |
def shellne(command):
"""
Runs 'commands' on the underlying shell; any stderr is echo'd to the
console.
Raises a RuntimeException on any shell exec errors.
"""
child = os.popen(command)
data = child.read()
err = child.close()
if err:
raise RuntimeError('%s faile... | Runs 'commands' on the underlying shell; any stderr is echo'd to the
console.
Raises a RuntimeException on any shell exec errors. |
def to_dict(self):
"""Converts this object to an (ordered) dictionary of field-value pairs.
>>> m = MRZ(['IDAUT10000999<6<<<<<<<<<<<<<<<', '7109094F1112315AUT<<<<<<<<<<<6', 'MUSTERFRAU<<ISOLDE<<<<<<<<<<<<']).to_dict()
>>> assert m['type'] == 'ID' and m['country'] == 'AUT' and m['number'] == '10... | Converts this object to an (ordered) dictionary of field-value pairs.
>>> m = MRZ(['IDAUT10000999<6<<<<<<<<<<<<<<<', '7109094F1112315AUT<<<<<<<<<<<6', 'MUSTERFRAU<<ISOLDE<<<<<<<<<<<<']).to_dict()
>>> assert m['type'] == 'ID' and m['country'] == 'AUT' and m['number'] == '10000999<'
>>> assert m[... |
def _dissect_roles(metadata):
"""Given a model's ``metadata``, iterate over the roles.
Return values are the role identifier and role type as a tuple.
"""
for role_key in cnxepub.ATTRIBUTED_ROLE_KEYS:
for user in metadata.get(role_key, []):
if user['type'] != 'cnx-id':
... | Given a model's ``metadata``, iterate over the roles.
Return values are the role identifier and role type as a tuple. |
def p_annotation(self, p):
"""annotation : ANNOTATION ID EQ ID args NL
| ANNOTATION ID EQ ID DOT ID args NL"""
if len(p) < 8:
args, kwargs = p[5]
p[0] = AstAnnotationDef(
self.path, p.lineno(1), p.lexpos(1), p[2], p[4], None, args, kwargs)
... | annotation : ANNOTATION ID EQ ID args NL
| ANNOTATION ID EQ ID DOT ID args NL |
def list_states(self, saltenv):
'''
Return a list of all available sls modules on the master for a given
environment
'''
states = set()
for path in self.file_list(saltenv):
if salt.utils.platform.is_windows():
path = path.replace('\\', '/')
... | Return a list of all available sls modules on the master for a given
environment |
def JSONList(*args, **kwargs):
"""Stores a list as JSON on database, with mutability support.
If kwargs has a param `unique_sorted` (which evaluated to True),
list values are made unique and sorted.
"""
type_ = JSON
try:
if kwargs.pop("unique_sorted"):
type_ = JSONUniqueList... | Stores a list as JSON on database, with mutability support.
If kwargs has a param `unique_sorted` (which evaluated to True),
list values are made unique and sorted. |
def get_resources(self, types=None, names=None, languages=None):
"""
Get resources.
types = a list of resource types to search for (None = all)
names = a list of resource names to search for (None = all)
languages = a list of resource languages to search for (None = all)... | Get resources.
types = a list of resource types to search for (None = all)
names = a list of resource names to search for (None = all)
languages = a list of resource languages to search for (None = all)
Return a dict of the form {type_: {name: {language: data}}} which
m... |
def padded_split(value, sep, maxsplit=None, pad=None):
"""
Modified split() to include padding
See http://code.activestate.com/lists/python-ideas/3366/
:attr value: see str.split()
:attr sep: see str.split()
:attr maxsplit: see str.split()
:attr pad: Value to use for padding maxsplit
>... | Modified split() to include padding
See http://code.activestate.com/lists/python-ideas/3366/
:attr value: see str.split()
:attr sep: see str.split()
:attr maxsplit: see str.split()
:attr pad: Value to use for padding maxsplit
>>> padded_split('text/html', ';', 1)
['text/html', None]
>>... |
def _show_no_gui():
"""Popup with information about how to register a new GUI
In the event of no GUI being registered or available,
this information dialog will appear to guide the user
through how to get set up with one.
"""
messagebox = QtWidgets.QMessageBox()
messagebox.setIcon(message... | Popup with information about how to register a new GUI
In the event of no GUI being registered or available,
this information dialog will appear to guide the user
through how to get set up with one. |
def _helioXYZ(self,*args,**kwargs):
"""Calculate heliocentric rectangular coordinates"""
obs, ro, vo= self._parse_radec_kwargs(kwargs)
thiso= self(*args,**kwargs)
if not len(thiso.shape) == 2: thiso= thiso.reshape((thiso.shape[0],1))
if len(thiso[:,0]) != 4 and len(thiso[:,0]) !=... | Calculate heliocentric rectangular coordinates |
def pull_image(self, image, progress_callback=None):
"""
Pull image from docker repository
:params image: Image name
:params progress_callback: A function that receive a log message about image download progress
"""
try:
yield from self.query("GET", "images/... | Pull image from docker repository
:params image: Image name
:params progress_callback: A function that receive a log message about image download progress |
def pending():
"""Show the number of pending signals by signal type."""
signalbus = current_app.extensions['signalbus']
pending = []
total_pending = 0
for signal_model in signalbus.get_signal_models():
count = signal_model.query.count()
if count > 0:
pending.append((coun... | Show the number of pending signals by signal type. |
def attach_protocol(self, proto):
"""
returns a Deferred that fires once we've set this object up to
track the protocol. Fails if we already have a protocol.
"""
if self._protocol is not None:
raise RuntimeError("Already have a protocol.")
# make sure we have ... | returns a Deferred that fires once we've set this object up to
track the protocol. Fails if we already have a protocol. |
def print_traceback(self, always_print=False):
"""
Prints the traceback to console - if there is any traceback, otherwise does nothing.
:param always_print: print the traceback, even if there is nothing in the buffer (default: false)
"""
if self._exception or always_print:
... | Prints the traceback to console - if there is any traceback, otherwise does nothing.
:param always_print: print the traceback, even if there is nothing in the buffer (default: false) |
def __try_to_json(self, request, attr):
"""
Try to run __json__ on the given object.
Raise TypeError is __json__ is missing
:param request: Pyramid Request object
:type request: <Request>
:param obj: Object to JSONify
:type obj: any object that has __json__ metho... | Try to run __json__ on the given object.
Raise TypeError is __json__ is missing
:param request: Pyramid Request object
:type request: <Request>
:param obj: Object to JSONify
:type obj: any object that has __json__ method
:exception: TypeError |
def _is_univariate_marginal(self, index_points):
"""True if the given index_points would yield a univariate marginal.
Args:
index_points: the set of index set locations at which to compute the
marginal Gaussian distribution. If this set is of size 1, the marginal is
univariate.
Returns:
... | True if the given index_points would yield a univariate marginal.
Args:
index_points: the set of index set locations at which to compute the
marginal Gaussian distribution. If this set is of size 1, the marginal is
univariate.
Returns:
is_univariate: Boolean indicating whether the marg... |
def help_center_article_subscription_show(self, article_id, id, locale=None, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/subscriptions#show-article-subscription"
api_path = "/api/v2/help_center/articles/{article_id}/subscriptions/{id}.json"
api_path = api_path.format(arti... | https://developer.zendesk.com/rest_api/docs/help_center/subscriptions#show-article-subscription |
def get_next_action(self, request, application, roles):
""" Retrieve the next state. """
application.reopen()
link, is_secret = base.get_email_link(application)
emails.send_invite_email(application, link, is_secret)
messages.success(
request,
"Sent an invi... | Retrieve the next state. |
def _build_obs_point(self, sensor_info, obs_recs):
"""
Pulls bin/profile height info out and calcs a z.
TODO: currently extremely naive
Returns a 2-tuple: point, remaining obs_recs
"""
cur_point = sensor_info["location"]["point"]
keys = [m["name"] for m in obs_... | Pulls bin/profile height info out and calcs a z.
TODO: currently extremely naive
Returns a 2-tuple: point, remaining obs_recs |
def _joinrealpath(self, path, rest, seen):
"""Join two paths, normalizing and eliminating any symbolic links
encountered in the second path.
Taken from Python source and adapted.
"""
curdir = self.filesystem._matching_string(path, '.')
pardir = self.filesystem._matching_s... | Join two paths, normalizing and eliminating any symbolic links
encountered in the second path.
Taken from Python source and adapted. |
def process_op(self, rc, nbytes, overlap):
"""
Handles the possible completion or re-queueing if conditions haven't
been met (the `complete` callable returns false) of a overlapped request.
"""
act = overlap.object
overlap.object = None
if act in self.token... | Handles the possible completion or re-queueing if conditions haven't
been met (the `complete` callable returns false) of a overlapped request. |
def _get_converter(self, converter_str):
"""find converter function reference by name
find converter by name, converter name follows this convention:
Class.method
or:
method
The first type of converter class/function must be available in
current modul... | find converter function reference by name
find converter by name, converter name follows this convention:
Class.method
or:
method
The first type of converter class/function must be available in
current module.
The second type of converter must be avai... |
def thread_view(request, pk):
''' View an individual thread. '''
if request.is_ajax():
if not request.user.is_authenticated():
return HttpResponse(json.dumps(dict()),
content_type="application/json")
try:
user_profile = UserProfile.objects.... | View an individual thread. |
def changecolourmode(self, newcolour):
"""Auxiliary method to change the colour mode.
Give me a colour (either an int, or a 3-tuple, values 0 to 255) and I decide if the image mode has to
be switched from "L" to "RGB".
"""
if type(newcolour) != type(0) and self.pilimage.mode != "... | Auxiliary method to change the colour mode.
Give me a colour (either an int, or a 3-tuple, values 0 to 255) and I decide if the image mode has to
be switched from "L" to "RGB". |
def validate(self, input, is_substitute): # ToDo: apply 'no substitute' for initial load validations
"""
Performs validation
:param input: object to validate
:param is_substitute: will be used for what-if in the future
:return: validation result if violated or None
"""
... | Performs validation
:param input: object to validate
:param is_substitute: will be used for what-if in the future
:return: validation result if violated or None |
def _findAll(self, name, attrs, text, limit, generator, **kwargs):
"Iterates over a generator looking for things that match."
if isinstance(name, SoupStrainer):
strainer = name
# (Possibly) special case some findAll*(...) searches
elif text is None and not limit and not attr... | Iterates over a generator looking for things that match. |
def is_sub_plate(self, other):
"""
Determines if this plate is a sub-plate of another plate -
i.e. has the same meta data but a restricted set of values
:param other: The other plate
:return: True if this plate is a sub-plate of the other plate
"""
if all(v in se... | Determines if this plate is a sub-plate of another plate -
i.e. has the same meta data but a restricted set of values
:param other: The other plate
:return: True if this plate is a sub-plate of the other plate |
def create_session(
self,
kind: SessionKind,
proxy_user: str = None,
jars: List[str] = None,
py_files: List[str] = None,
files: List[str] = None,
driver_memory: str = None,
driver_cores: int = None,
executor_memory: str = None,
executor_cor... | Create a new session in Livy.
The py_files, files, jars and archives arguments are lists of URLs,
e.g. ["s3://bucket/object", "hdfs://path/to/file", ...] and must be
reachable by the Spark driver process. If the provided URL has no
scheme, it's considered to be relative to the default ... |
def hasFeature(featureList, feature):
""" return the controlCode for a feature or None
@param feature: feature to look for
@param featureList: feature list as returned by L{getFeatureRequest()}
@return: feature value or None
"""
for f in featureList:
if f[0] == feature or Features[... | return the controlCode for a feature or None
@param feature: feature to look for
@param featureList: feature list as returned by L{getFeatureRequest()}
@return: feature value or None |
def _next_token(sql):
""" This is a basic tokenizer for our limited purposes.
It splits a SQL statement up into a series of segments, where a segment is one of:
- identifiers
- left or right parentheses
- multi-line comments
- single line comments
- white-space sequences
- string literals
- consecutiv... | This is a basic tokenizer for our limited purposes.
It splits a SQL statement up into a series of segments, where a segment is one of:
- identifiers
- left or right parentheses
- multi-line comments
- single line comments
- white-space sequences
- string literals
- consecutive strings of characters that... |
def flatten_evidence(stmts, collect_from=None):
"""Add evidence from *supporting* stmts to evidence for *supported* stmts.
Parameters
----------
stmts : list of :py:class:`indra.statements.Statement`
A list of top-level statements with associated supporting statements
resulting from bui... | Add evidence from *supporting* stmts to evidence for *supported* stmts.
Parameters
----------
stmts : list of :py:class:`indra.statements.Statement`
A list of top-level statements with associated supporting statements
resulting from building a statement hierarchy with
:py:meth:`comb... |
def register(xmlstream,
query_xso,
timeout=60,
):
"""
Create a new account on the server.
:param query_xso: XSO with the information needed for the registration.
:type query_xso: :class:`~aioxmpp.ibr.Query`
:param xmlstream: Specifies the stream connected to ... | Create a new account on the server.
:param query_xso: XSO with the information needed for the registration.
:type query_xso: :class:`~aioxmpp.ibr.Query`
:param xmlstream: Specifies the stream connected to the server where
the account will be created.
:type xmlstream: :class:`aiox... |
def save_model(model: AbstractModel, name_suffix: str, on_failure: str) -> None:
"""
Save the given model with the given name_suffix. On failure, take the specified action.
:param model: the model to be saved
:param name_suffix: name to be used for saving
:param on_failure: acti... | Save the given model with the given name_suffix. On failure, take the specified action.
:param model: the model to be saved
:param name_suffix: name to be used for saving
:param on_failure: action to be taken on failure; one of :py:attr:`SAVE_FAILURE_ACTIONS`
:raise IOError: on save fai... |
def unpack_rsp(cls, rsp_pb):
"""Convert from PLS response to user response"""
if rsp_pb.retType != RET_OK:
return RET_ERROR, rsp_pb.retMsg, None
order_id = str(rsp_pb.s2c.orderID)
return RET_OK, "", order_id | Convert from PLS response to user response |
def run(cmd, cwd=None, silent=None, return_output=False, raises=True, **subprocess_args):
"""
Runs a CLI command.
:param list/str cmd: Command with args to run.
:param str cwd: Change directory to cwd before running
:param bool/int silent: Suppress stdout/stderr.
If True... | Runs a CLI command.
:param list/str cmd: Command with args to run.
:param str cwd: Change directory to cwd before running
:param bool/int silent: Suppress stdout/stderr.
If True, completely silent.
If 2, print cmd output on error.
:param bool retu... |
def get_user_password (self):
"""Get tuple (user, password) from configured authentication.
Both user and password can be None.
"""
if self.userinfo:
# URL itself has authentication info
return urllib.splitpasswd(self.userinfo)
return self.aggregate.config... | Get tuple (user, password) from configured authentication.
Both user and password can be None. |
def add_comment(self, text):
"""Comment on the submission using the specified text.
:returns: A Comment object for the newly created comment.
"""
# pylint: disable=W0212
response = self.reddit_session._add_comment(self.fullname, text)
# pylint: enable=W0212
self... | Comment on the submission using the specified text.
:returns: A Comment object for the newly created comment. |
def spell(word: str, engine: str = "pn") -> List[str]:
"""
:param str word: word to check spelling
:param str engine:
* pn - Peter Norvig's algorithm (default)
:return: list of words
"""
return DEFAULT_SPELL_CHECKER.spell(word) | :param str word: word to check spelling
:param str engine:
* pn - Peter Norvig's algorithm (default)
:return: list of words |
def Publish(self, event_name, msg, delay=0):
"""Sends the message to event listeners."""
events_lib.Events.PublishEvent(event_name, msg, delay=delay) | Sends the message to event listeners. |
def add_convolution(self, name, kernel_channels, output_channels, height,
width, stride_height, stride_width, border_mode, groups, W, b, has_bias,
is_deconv = False, output_shape = None,
input_name = 'data', output_name = 'out',
dilation_factors = [1,1],
paddi... | Add a convolution layer to the network.
Please see the ConvolutionLayerParams in Core ML neural network
protobuf message for more information about input and output blob dimensions.
Parameters
----------
name: str
The name of this layer.
kernel_channels: int... |
def getCentreAndSpreadOffsets(spaceShape,
spreadShape,
stepSize=1):
"""
Generates centre offsets and spread offsets for block-mode based training
regimes - star, cross, block.
Parameters:
-----------------------------------------------
space... | Generates centre offsets and spread offsets for block-mode based training
regimes - star, cross, block.
Parameters:
-----------------------------------------------
spaceShape: The (height, width) of the 2-D space to explore. This
sets the number of center-points.
spreadShape: The... |
def open(self):
"""Open a connection to the device."""
device_type = 'cisco_ios'
if self.transport == 'telnet':
device_type = 'cisco_ios_telnet'
self.device = ConnectHandler(device_type=device_type,
host=self.hostname,
... | Open a connection to the device. |
def flatten(attrs, inputs, proto_obj):
"""Flattens the input array into a 2-D array by collapsing the higher dimensions."""
#Mxnet does not have axis support. By default uses axis=1
if 'axis' in attrs and attrs['axis'] != 1:
raise RuntimeError("Flatten operator only supports axis=1")
new_attrs =... | Flattens the input array into a 2-D array by collapsing the higher dimensions. |
def get_next_valid_time_from_t(self, timestamp):
"""Get next valid time for time range
:param timestamp: time we compute from
:type timestamp: int
:return: timestamp of the next valid time (LOCAL TIME)
:rtype: int | None
"""
if self.is_time_valid(timestamp):
... | Get next valid time for time range
:param timestamp: time we compute from
:type timestamp: int
:return: timestamp of the next valid time (LOCAL TIME)
:rtype: int | None |
def request(self, _cache_key, _cache_ignore, _cache_timeout, **kwargs):
"""
This is a wrapper function that handles the caching of the request.
See DefaultHandler.with_cache for reference.
"""
if _cache_key:
# Pop the request's session cookies from the cache key.
... | This is a wrapper function that handles the caching of the request.
See DefaultHandler.with_cache for reference. |
def get(self, name, *subkey):
"""
retrieves a data item, or loads it if it
is not present.
"""
if subkey == []:
return self.get_atomic(name)
else:
return self.get_subkey(name, tuple(subkey)) | retrieves a data item, or loads it if it
is not present. |
async def handle_disconnect_callback(self):
"""Reconnect automatically unless stopping."""
self.is_connected = False
if self.disconnect_callback:
self.disconnect_callback()
if self.reconnect:
self.logger.debug("Protocol disconnected...reconnecting")
aw... | Reconnect automatically unless stopping. |
def write_lammpsdata(structure, filename, atom_style='full'):
"""Output a LAMMPS data file.
Outputs a LAMMPS data file in the 'full' atom style format. Assumes use
of 'real' units. See http://lammps.sandia.gov/doc/atom_style.html for
more information on atom styles.
Parameters
----------
... | Output a LAMMPS data file.
Outputs a LAMMPS data file in the 'full' atom style format. Assumes use
of 'real' units. See http://lammps.sandia.gov/doc/atom_style.html for
more information on atom styles.
Parameters
----------
structure : parmed.Structure
ParmEd structure object
f... |
def drop_table(model, keyspaces=None, connections=None):
"""
Drops the table indicated by the model, if it exists.
If `keyspaces` is specified, the table will be dropped for all specified keyspaces. Note that the `Model.__keyspace__` is ignored in that case.
If `connections` is specified, the table wi... | Drops the table indicated by the model, if it exists.
If `keyspaces` is specified, the table will be dropped for all specified keyspaces. Note that the `Model.__keyspace__` is ignored in that case.
If `connections` is specified, the table will be synched for all specified connections. Note that the `Model.__c... |
def _tValueForPointOnCubicCurve(point, cubicCurve, isHorizontal=0):
"""
Finds a t value on a curve from a point.
The points must be originaly be a point on the curve.
This will only back trace the t value, needed to split the curve in parts
"""
pt1, pt2, pt3, pt4 = cubicCurve
a, b, c, d = be... | Finds a t value on a curve from a point.
The points must be originaly be a point on the curve.
This will only back trace the t value, needed to split the curve in parts |
def get_privatekey(keydata):
"""Load the private key from a PEM encoded string."""
key = serialization.load_pem_private_key(
keydata,
password=None,
backend=default_backend(),
)
return key | Load the private key from a PEM encoded string. |
def getPrevUrl(self, url, data):
"""Find previous URL."""
if 'chapter04' in url:
return url.replace('chapter04', 'chapter03')
if 'chapter03' in url:
return url.replace('chapter03', 'chapter02')
if 'chapter02' in url:
return url.replace('chapter02', 'ch... | Find previous URL. |
def main():
"""
Example application that opens a serial device and prints messages to the terminal.
"""
try:
# Retrieve the specified serial device.
device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE))
# Set up an event handler and open the device
device.on_messa... | Example application that opens a serial device and prints messages to the terminal. |
def send(self, cmd):
"""Send the given command thru the websocket"""
with self.ws_sendlock:
self.ws.send(json.dumps(cmd)) | Send the given command thru the websocket |
def render_vars(self):
"""Template variables."""
return {
'records': [
{
'message': record.getMessage(),
'time': dt.datetime.fromtimestamp(record.created).strftime('%H:%M:%S'),
} for record in self.handler.records
... | Template variables. |
def recall(y, y_pred):
"""Recall score
recall = true_positives / (true_positives + false_negatives)
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
recall : float... | Recall score
recall = true_positives / (true_positives + false_negatives)
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
recall : float |
def select_as_multiple(self, keys, where=None, selector=None, columns=None,
start=None, stop=None, iterator=False,
chunksize=None, auto_close=False, **kwargs):
""" Retrieve pandas objects from multiple tables
Parameters
----------
ke... | Retrieve pandas objects from multiple tables
Parameters
----------
keys : a list of the tables
selector : the table to apply the where criteria (defaults to keys[0]
if not supplied)
columns : the columns I want back
start : integer (defaults to None), row num... |
def add(self, other):
"""
Add an Interval to the IntervalSet by taking the union of the given Interval object with the existing
Interval objects in self.
This has no effect if the Interval is already represented.
:param other: an Interval to add to this IntervalSet.
"""
... | Add an Interval to the IntervalSet by taking the union of the given Interval object with the existing
Interval objects in self.
This has no effect if the Interval is already represented.
:param other: an Interval to add to this IntervalSet. |
def meryl(args):
"""
%prog meryl folder
Run meryl on Illumina reads.
"""
p = OptionParser(meryl.__doc__)
p.add_option("-k", default=19, type="int", help="Kmer size")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
folder, = ... | %prog meryl folder
Run meryl on Illumina reads. |
def organization_related(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/organizations#show-organizations-related-information"
api_path = "/api/v2/organizations/{id}/related.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/organizations#show-organizations-related-information |
def calc_windowed_sum(aa_mut_pos,
germ_aa,
somatic_aa,
window=[3]):
"""Calculate the sum of mutations within a window around a particular mutated
codon.
Parameters
----------
aa_mut_pos : list
list of mutated amino acid posit... | Calculate the sum of mutations within a window around a particular mutated
codon.
Parameters
----------
aa_mut_pos : list
list of mutated amino acid positions
germ_aa : list
Reference amino acid
somatic_aa : list
Somatic amino acid (if missense)
window : list
... |
def gen(self, num, cat=None, cat_group=None, preferred=None, preferred_ratio=0.5, max_recursion=None, auto_process=True):
"""Generate ``num`` rules from category ``cat``, optionally specifying
preferred category groups ``preferred`` that should be preferred at
probability ``preferred_ratio`` ove... | Generate ``num`` rules from category ``cat``, optionally specifying
preferred category groups ``preferred`` that should be preferred at
probability ``preferred_ratio`` over other randomly-chosen rule definitions.
:param int num: The number of rules to generate
:param str cat: The name o... |
def _get_stockprices(symbols, chart_range='1y'):
'''Get stock data (key stats and previous) from IEX.
Just deal with IEX's 100 stocks limit per request.
'''
def fetch(symbols):
charts = _ensure_dict(
iexfinance.stocks.Stock(symbols).get_chart(range=chart_range),
symbols
... | Get stock data (key stats and previous) from IEX.
Just deal with IEX's 100 stocks limit per request. |
def lowres_tensor(shape, underlying_shape, offset=None, sd=None):
"""Produces a tensor paramaterized by a interpolated lower resolution tensor.
This is like what is done in a laplacian pyramid, but a bit more general. It
can be a powerful way to describe images.
Args:
shape: desired shape of resulting t... | Produces a tensor paramaterized by a interpolated lower resolution tensor.
This is like what is done in a laplacian pyramid, but a bit more general. It
can be a powerful way to describe images.
Args:
shape: desired shape of resulting tensor
underlying_shape: shape of the tensor being resized into final ... |
def _get_value(self, key, context):
"""Works out whether key is a value or if it's a variable referencing a
value in context and returns the correct value.
"""
string_quotes = ('"', "'")
if key[0] in string_quotes and key[-1] in string_quotes:
return key[1:-1]
... | Works out whether key is a value or if it's a variable referencing a
value in context and returns the correct value. |
def node(self, nodeid):
"""Creates a new node with the specified name, with `MockSocket` instances as incoming and outgoing sockets.
Returns the implementation object created for the node from the cls, args and address specified, and the sockets.
`cls` must be a callable that takes the insock a... | Creates a new node with the specified name, with `MockSocket` instances as incoming and outgoing sockets.
Returns the implementation object created for the node from the cls, args and address specified, and the sockets.
`cls` must be a callable that takes the insock and outsock, and the specified args ... |
def rmultivariate_hypergeometric(n, m, size=None):
"""
Random multivariate hypergeometric variates.
Parameters:
- `n` : Number of draws.
- `m` : Number of items in each categoy.
"""
N = len(m)
urn = np.repeat(np.arange(N), m)
if size:
draw = np.array([[urn[i] for i in ... | Random multivariate hypergeometric variates.
Parameters:
- `n` : Number of draws.
- `m` : Number of items in each categoy. |
def setCurrentSchemaPath(self, path):
"""
Sets the current item based on the inputed column.
:param path | <str>
"""
if not path:
return False
parts = path.split('.')
name = parts[0]
next = parts[1:]
... | Sets the current item based on the inputed column.
:param path | <str> |
def write_gexf(docgraph, output_file):
"""
takes a document graph, converts it into GEXF format and writes it to
a file.
"""
dg_copy = deepcopy(docgraph)
remove_root_metadata(dg_copy)
layerset2str(dg_copy)
attriblist2str(dg_copy)
nx_write_gexf(dg_copy, output_file) | takes a document graph, converts it into GEXF format and writes it to
a file. |
def parent_is_inet():
""" Check if parent is inet
Check if our parent seems ot be a superserver, aka inetd/xinetd.
This is done by checking if sys.__stdin__ is a network socket.
:return: bool
"""
result = False
sock = socket.fromfd(
sys.__stdin__.fileno(),
socket.AF_INET,
... | Check if parent is inet
Check if our parent seems ot be a superserver, aka inetd/xinetd.
This is done by checking if sys.__stdin__ is a network socket.
:return: bool |
def generate_doc_length_stats(self):
"""Analyze document length statistics for padding strategy"""
heuristic = self.heuristic_pct
histdf = (pd.DataFrame([(a, b) for a, b in self.document_length_histogram.items()],
columns=['bin', 'doc_count'])
.so... | Analyze document length statistics for padding strategy |
def iter_chunks(chunksize, *iterables):
"""Iterates over zipped iterables in chunks."""
iterables = iter(zip(*iterables))
while 1:
chunk = tuple(islice(iterables, chunksize))
if not chunk:
return
yield chunk | Iterates over zipped iterables in chunks. |
def center_of_mass(self):
"""
Calculates the center of mass of the slab
"""
weights = [s.species.weight for s in self]
center_of_mass = np.average(self.frac_coords,
weights=weights, axis=0)
return center_of_mass | Calculates the center of mass of the slab |
def nl_wait_for_ack(sk):
"""Wait for ACK.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L1058
Waits until an ACK is received for the latest not yet acknowledged Netlink message.
Positional arguments:
sk -- Netlink socket (nl_sock class instance).
Returns:
Number of received ... | Wait for ACK.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L1058
Waits until an ACK is received for the latest not yet acknowledged Netlink message.
Positional arguments:
sk -- Netlink socket (nl_sock class instance).
Returns:
Number of received messages or a negative error cod... |
def daily_returns(self, start, end=None):
"""Returns the daily returns for the given period.
Parameters
----------
start : datetime
The inclusive starting session label.
end : datetime, optional
The inclusive ending session label. If not provided, treat
... | Returns the daily returns for the given period.
Parameters
----------
start : datetime
The inclusive starting session label.
end : datetime, optional
The inclusive ending session label. If not provided, treat
``start`` as a scalar key.
Return... |
def sens_power_board_send(self, timestamp, pwr_brd_status, pwr_brd_led_status, pwr_brd_system_volt, pwr_brd_servo_volt, pwr_brd_mot_l_amp, pwr_brd_mot_r_amp, pwr_brd_servo_1_amp, pwr_brd_servo_2_amp, pwr_brd_servo_3_amp, pwr_brd_servo_4_amp, pwr_brd_aux_amp, force_mavlink1=False):
'''
Mo... | Monitoring of power board status
timestamp : Timestamp (uint64_t)
pwr_brd_status : Power board status register (uint8_t)
pwr_brd_led_status : Power board leds status (uint8_t)
pwr_brd_system_volt : Power board syst... |
def generateVariant(self, referenceName, position, randomNumberGenerator):
"""
Generate a random variant for the specified position using the
specified random number generator. This generator should be seeded
with a value that is unique to this position so that the same variant
w... | Generate a random variant for the specified position using the
specified random number generator. This generator should be seeded
with a value that is unique to this position so that the same variant
will always be produced regardless of the order it is generated in. |
def add_capability(capability,
source=None,
limit_access=False,
image=None,
restart=False):
'''
Install a capability
Args:
capability (str): The capability to install
source (Optional[str]): The optional source of t... | Install a capability
Args:
capability (str): The capability to install
source (Optional[str]): The optional source of the capability. Default
is set by group policy and can be Windows Update.
limit_access (Optional[bool]): Prevent DISM from contacting Windows
Update ... |
def tokentype(self, s):
"""Parses string and returns a (Tokenizer.TYPE, value) tuple."""
a = s[0] if len(s)>0 else ""
b = s[1] if len(s)>1 else ""
if a.isdigit() or (a in ["+","-"] and b.isdigit()):
return self.parse_number(s)
elif a == '"': return self.parse_string(... | Parses string and returns a (Tokenizer.TYPE, value) tuple. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.