code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def print_xmlsec_errors(filename, line, func, error_object, error_subject, reason, msg):
"""
Auxiliary method. It overrides the default xmlsec debug message.
"""
info = []
if error_object != "unknown":
info.append("obj=" + error_object)
if error_subject != "unknown":
info.append... | Auxiliary method. It overrides the default xmlsec debug message. |
def set_metadata(self, obj, metadata, clear=False, prefix=None):
"""
Accepts a dictionary of metadata key/value pairs and updates the
specified object metadata with them.
If 'clear' is True, any existing metadata is deleted and only the
passed metadata is retained. Otherwise, th... | Accepts a dictionary of metadata key/value pairs and updates the
specified object metadata with them.
If 'clear' is True, any existing metadata is deleted and only the
passed metadata is retained. Otherwise, the values passed here update
the object's metadata.
By default, the s... |
def get_library(path=None, root=None, db=None):
import ambry.library as _l
"""Return the default library for this installation."""
rc = config(path=path, root=root, db=db )
return _l.new_library(rc) | Return the default library for this installation. |
def _cache_ops_associate(protocol, msgtype):
"""https://github.com/thom311/libnl/blob/libnl3_2_25/lib/cache_mngt.c#L111.
Positional arguments:
protocol -- Netlink protocol (integer).
msgtype -- Netlink message type (integer).
Returns:
nl_cache_ops instance with matching protocol containing mat... | https://github.com/thom311/libnl/blob/libnl3_2_25/lib/cache_mngt.c#L111.
Positional arguments:
protocol -- Netlink protocol (integer).
msgtype -- Netlink message type (integer).
Returns:
nl_cache_ops instance with matching protocol containing matching msgtype or None. |
def set_position(self, key, latlon, layer=None, rotation=0):
'''move an object on the map'''
self.object_queue.put(SlipPosition(key, latlon, layer, rotation)) | move an object on the map |
def _check_accept_keywords(approved, flag):
'''check compatibility of accept_keywords'''
if flag in approved:
return False
elif (flag.startswith('~') and flag[1:] in approved) \
or ('~'+flag in approved):
return False
else:
return True | check compatibility of accept_keywords |
def _get_gpu():
"""*DEPRECATED*. Allocates first available GPU using cudaSetDevice(), or returns 0 otherwise."""
# Note: this code executes, but Tensorflow subsequently complains that the "current context was not created by the StreamExecutor cuda_driver API"
system = platform.system()
if system == "Linux":
... | *DEPRECATED*. Allocates first available GPU using cudaSetDevice(), or returns 0 otherwise. |
def _is_contiguous(positions):
"""Given a non-empty list, does it consist of contiguous integers?"""
previous = positions[0]
for current in positions[1:]:
if current != previous + 1:
return False
previous = current
return True | Given a non-empty list, does it consist of contiguous integers? |
def merge_overlaps(self, threshold=0.0):
"""
Merge overlapping labels with the same value.
Two labels are considered overlapping,
if ``l2.start - l1.end < threshold``.
Args:
threshold (float): Maximal distance between two labels
to be c... | Merge overlapping labels with the same value.
Two labels are considered overlapping,
if ``l2.start - l1.end < threshold``.
Args:
threshold (float): Maximal distance between two labels
to be considered as overlapping.
(def... |
def polite_string(a_string):
"""Returns a "proper" string that should work in both Py3/Py2"""
if is_py3() and hasattr(a_string, 'decode'):
try:
return a_string.decode('utf-8')
except UnicodeDecodeError:
return a_string
return a_string | Returns a "proper" string that should work in both Py3/Py2 |
def _get_block_matches(self, attributes_a, attributes_b, filter_set_a=None, filter_set_b=None, delta=(0, 0, 0),
tiebreak_with_block_similarity=False):
"""
:param attributes_a: A dict of blocks to their attributes
:param attributes_b: A dict of blocks to their att... | :param attributes_a: A dict of blocks to their attributes
:param attributes_b: A dict of blocks to their attributes
The following parameters are optional.
:param filter_set_a: A set to limit attributes_a to the blocks in this set.
:param filter_set_b: A set to limit attribu... |
def openflow_controller_connection_address_connection_method(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
openflow_controller = ET.SubElement(config, "openflow-controller", xmlns="urn:brocade.com:mgmt:brocade-openflow")
controller_name_key = ET.SubEle... | Auto Generated Code |
def patch(self, nml_patch):
"""Update the namelist from another partial or full namelist.
This is different from the intrinsic `update()` method, which replaces
a namelist section. Rather, it updates the values within a section.
"""
for sec in nml_patch:
if sec not ... | Update the namelist from another partial or full namelist.
This is different from the intrinsic `update()` method, which replaces
a namelist section. Rather, it updates the values within a section. |
def accuracy(sess, model, x, y, batch_size=None, devices=None, feed=None,
attack=None, attack_params=None):
"""
Compute the accuracy of a TF model on some data
:param sess: TF session to use when training the graph
:param model: cleverhans.model.Model instance
:param x: numpy array containing inp... | Compute the accuracy of a TF model on some data
:param sess: TF session to use when training the graph
:param model: cleverhans.model.Model instance
:param x: numpy array containing input examples (e.g. MNIST().x_test )
:param y: numpy array containing example labels (e.g. MNIST().y_test )
:param batch_size: ... |
def request(self, path, method='GET', params=None):
"""Builds a request and gets a response."""
if params is None: params = {}
url = urljoin(self.endpoint, path)
headers = {
'Accept': 'application/json',
'Authorization': 'AccessKey ' + self.access_key,
... | Builds a request and gets a response. |
def clean_password(self, password, user=None):
"""
Validates a password. You can hook into this if you want to
restric the allowed password choices.
"""
min_length = app_settings.PASSWORD_MIN_LENGTH
if min_length and len(password) < min_length:
raise forms.Val... | Validates a password. You can hook into this if you want to
restric the allowed password choices. |
def status_codes_by_date_stats():
"""
Get stats for status codes by date.
Returns:
list: status codes + date grouped by type: 2xx, 3xx, 4xx, 5xx, attacks.
"""
def date_counter(queryset):
return dict(Counter(map(
lambda dt: ms_since_epoch(datetime.combine(
... | Get stats for status codes by date.
Returns:
list: status codes + date grouped by type: 2xx, 3xx, 4xx, 5xx, attacks. |
def _write_frames(self, handle):
'''Write our frame data to the given file handle.
Parameters
----------
handle : file
Write metadata and C3D motion frames to the given file handle. The
writer does not close the handle.
'''
assert handle.tell() ==... | Write our frame data to the given file handle.
Parameters
----------
handle : file
Write metadata and C3D motion frames to the given file handle. The
writer does not close the handle. |
def auto(cls, syslog=None, stderr=None, level=None, extended=None,
server=None):
"""Tries to guess a sound logging configuration.
"""
level = norm_level(level) or logging.INFO
if syslog is None and stderr is None:
if sys.stderr.isatty() or syslog_path() is None:
... | Tries to guess a sound logging configuration. |
def trace_buffer_capacity(self):
"""Retrieves the trace buffer's current capacity.
Args:
self (JLink): the ``JLink`` instance.
Returns:
The current capacity of the trace buffer. This is not necessarily
the maximum possible size the buffer could be configured with... | Retrieves the trace buffer's current capacity.
Args:
self (JLink): the ``JLink`` instance.
Returns:
The current capacity of the trace buffer. This is not necessarily
the maximum possible size the buffer could be configured with. |
def keyrelease(self, data):
"""
Release key. NOTE: keypress should be called before this
@param data: data to type.
@type data: string
@return: 1 on success.
@rtype: integer
"""
try:
window = self._get_front_most_window()
except (Inde... | Release key. NOTE: keypress should be called before this
@param data: data to type.
@type data: string
@return: 1 on success.
@rtype: integer |
def SRem(a: BitVec, b: BitVec) -> BitVec:
"""Create a signed remainder expression.
:param a:
:param b:
:return:
"""
return _arithmetic_helper(a, b, z3.SRem) | Create a signed remainder expression.
:param a:
:param b:
:return: |
def store_node_label_meta(self, x, y, tx, ty, rot):
"""
This function stored coordinates-related metadate for a node
This function should not be called by the user
:param x: x location of node label or number
:type x: np.float64
:param y: y location of node label or num... | This function stored coordinates-related metadate for a node
This function should not be called by the user
:param x: x location of node label or number
:type x: np.float64
:param y: y location of node label or number
:type y: np.float64
:param tx: text location x of n... |
def _mulf16(ins):
""" Multiplies 2 32bit (16.16) fixed point numbers. The result is pushed onto the stack.
"""
op1, op2 = tuple(ins.quad[2:])
if _f_ops(op1, op2) is not None:
op1, op2 = _f_ops(op1, op2)
if op2 == 1: # A * 1 => A
output = _f16_oper(op1)
output.a... | Multiplies 2 32bit (16.16) fixed point numbers. The result is pushed onto the stack. |
def scan(self,
proxy_scanner,
expected_num=20,
val_thr_num=4,
queue_timeout=3,
val_timeout=5,
out_file='proxies.json'):
"""Scan and validate proxies
Firstly, call the `scan` method of `proxy_scanner`, then using multiple
... | Scan and validate proxies
Firstly, call the `scan` method of `proxy_scanner`, then using multiple
threads to validate them.
Args:
proxy_scanner: A ProxyScanner object.
expected_num: Max number of valid proxies to be scanned.
val_thr_num: Number of threads us... |
def identify_misfeatured_regions(st, filter_size=5, sigma_cutoff=8.):
"""
Identifies regions of missing/misfeatured particles based on the
residuals' local deviation from uniform Gaussian noise.
Parameters
----------
st : :class:`peri.states.State`
The state in which to identify mis-fea... | Identifies regions of missing/misfeatured particles based on the
residuals' local deviation from uniform Gaussian noise.
Parameters
----------
st : :class:`peri.states.State`
The state in which to identify mis-featured regions.
filter_size : Int, best if odd.
The size of the filter... |
def _put (self, url_data):
"""Put URL in queue, increase number of unfished tasks."""
if self.shutdown or self.max_allowed_urls == 0:
return
log.debug(LOG_CACHE, "queueing %s", url_data.url)
key = url_data.cache_url
cache = url_data.aggregate.result_cache
if u... | Put URL in queue, increase number of unfished tasks. |
def _abs_pow_ufunc(self, fi, out, p):
"""Compute |F_i(x)|^p point-wise and write to ``out``."""
# Optimization for very common cases
if p == 0.5:
fi.ufuncs.absolute(out=out)
out.ufuncs.sqrt(out=out)
elif p == 2.0 and self.base_space.field == RealNumbers():
... | Compute |F_i(x)|^p point-wise and write to ``out``. |
def get_user_invitation_by_id(self, id):
"""Retrieve a UserInvitation object by ID."""
return self.db_adapter.get_object(self.UserInvitationClass, id=id) | Retrieve a UserInvitation object by ID. |
def parse_bibliography(source, loc, tokens):
"""
Combines the parsed entries into a Bibliography instance.
"""
bib = structures.Bibliography()
for entry in tokens:
bib.add(entry)
return bib | Combines the parsed entries into a Bibliography instance. |
def push(self, values: np.ndarray):
"""
Push values to buffer. If buffer can't store all values a ValueError is raised
"""
n = len(values)
if len(self) + n > self.size:
raise ValueError("Too much data to push to RingBuffer")
slide_1 = np.s_[self.right_index:m... | Push values to buffer. If buffer can't store all values a ValueError is raised |
def get_pplan(self, topologyName, callback=None):
""" get physical plan """
isWatching = False
# Temp dict used to return result
# if callback is not provided.
ret = {
"result": None
}
if callback:
isWatching = True
else:
def callback(data):
"""
Custo... | get physical plan |
async def _watch(self, node, conn, names):
"Watches the values at keys ``names``"
for name in names:
slot = self._determine_slot('WATCH', name)
dist_node = self.connection_pool.get_node_by_slot(slot)
if node.get('name') != dist_node['name']:
# raise er... | Watches the values at keys ``names`` |
def _process_worker(call_queue, result_queue):
"""Evaluates calls from call_queue and places the results in result_queue.
This worker is run in a separate process.
Args:
call_queue: A multiprocessing.Queue of _CallItems that will be read and
evaluated by the worker.
result_queu... | Evaluates calls from call_queue and places the results in result_queue.
This worker is run in a separate process.
Args:
call_queue: A multiprocessing.Queue of _CallItems that will be read and
evaluated by the worker.
result_queue: A multiprocessing.Queue of _ResultItems that will w... |
def get_template(self, template, def_name=None):
'''Retrieve a *Django* API template object for the given template name, using the app_path and template_subdir
settings in this object. This method still uses the corresponding Mako template and engine, but it
gives a Django API wrapper aro... | Retrieve a *Django* API template object for the given template name, using the app_path and template_subdir
settings in this object. This method still uses the corresponding Mako template and engine, but it
gives a Django API wrapper around it so you can use it the same as any Django template.
... |
def load(name):
"""Parse the tile map and add it to the world."""
global __tile_maps
# Remove the current map.
TileMapManager.unload()
TileMapManager.active_map = __tile_maps[name]
TileMapManager.active_map.parse_tilemap()
TileMapManager.active_map.parse_collisio... | Parse the tile map and add it to the world. |
def on_error(self, ex):
"""
Reimplemented from :meth:`~AsyncViewBase.on_error`
"""
if self._d:
self._d.errback()
self._d = None | Reimplemented from :meth:`~AsyncViewBase.on_error` |
def init(self, request, paypal_request, paypal_response):
"""Initialize a PayPalNVP instance from a HttpRequest."""
if request is not None:
from paypal.pro.helpers import strip_ip_port
self.ipaddress = strip_ip_port(request.META.get('REMOTE_ADDR', ''))
if (hasattr(req... | Initialize a PayPalNVP instance from a HttpRequest. |
def _default_template_args(self, content_template):
"""Initialize template args."""
def include(text, args):
template_name = pystache.render(text, args)
return self._renderer.render_name(template_name, args)
# Our base template calls include on the content_template.
ret = {'content_template'... | Initialize template args. |
def to_sequence_field(cls):
"""
Returns a callable instance that will convert a value to a Sequence.
:param cls: Valid class type of the items in the Sequence.
:return: instance of the SequenceConverter.
"""
class SequenceConverter(object):
def __init__(self, cls):
self._cl... | Returns a callable instance that will convert a value to a Sequence.
:param cls: Valid class type of the items in the Sequence.
:return: instance of the SequenceConverter. |
def _queue_declare_ok(self, args):
"""
confirms a queue definition
This method confirms a Declare method and confirms the name of
the queue, essential for automatically-named queues.
PARAMETERS:
queue: shortstr
Reports the name of the queue. If the ... | confirms a queue definition
This method confirms a Declare method and confirms the name of
the queue, essential for automatically-named queues.
PARAMETERS:
queue: shortstr
Reports the name of the queue. If the server generated
a queue name, this fie... |
def extract(code, tree, prefix=[]):
"""Extract Huffman code from a Huffman tree
:param tree: a node of the tree
:param prefix: a list with the 01 characters encoding the path from
the root to the node `tree`
:complexity: O(n)
"""
if isinstance(tree, list):
l, r = tre... | Extract Huffman code from a Huffman tree
:param tree: a node of the tree
:param prefix: a list with the 01 characters encoding the path from
the root to the node `tree`
:complexity: O(n) |
def objects_copy(self, source_bucket, source_key, target_bucket, target_key):
"""Updates the metadata associated with an object.
Args:
source_bucket: the name of the bucket containing the source object.
source_key: the key of the source object being copied.
target_bucket: the name of the buck... | Updates the metadata associated with an object.
Args:
source_bucket: the name of the bucket containing the source object.
source_key: the key of the source object being copied.
target_bucket: the name of the bucket that will contain the copied object.
target_key: the key of the copied objec... |
def add(self, actors):
"""Append input object to the internal list of actors to be shown.
:return: returns input actor for possible concatenation.
"""
if utils.isSequence(actors):
for a in actors:
if a not in self.actors:
self.actors.appen... | Append input object to the internal list of actors to be shown.
:return: returns input actor for possible concatenation. |
def remove_highlight_nodes(graph: BELGraph, nodes: Optional[Iterable[BaseEntity]]=None) -> None:
"""Removes the highlight from the given nodes, or all nodes if none given.
:param graph: A BEL graph
:param nodes: The list of nodes to un-highlight
"""
for node in graph if nodes is None else nodes:
... | Removes the highlight from the given nodes, or all nodes if none given.
:param graph: A BEL graph
:param nodes: The list of nodes to un-highlight |
def _strip_postfix(req):
"""
Strip req postfix ( -dev, 0.2, etc )
"""
# FIXME: use package_to_requirement?
match = re.search(r'^(.*?)(?:-dev|-\d.*)$', req)
if match:
# Strip off -dev, -0.2, etc.
req = match.group(1)
return req | Strip req postfix ( -dev, 0.2, etc ) |
def _process_resp(request_id, response, is_success_func):
"""
:param request_id: campus url identifying the request
:param response: the GET method response object
:param is_success_func: the name of the function for
verifying a success code
:return: True if successful, False otherwise.
... | :param request_id: campus url identifying the request
:param response: the GET method response object
:param is_success_func: the name of the function for
verifying a success code
:return: True if successful, False otherwise.
raise DataFailureException or a corresponding TrumbaException
if t... |
def shlex_quote(s):
"""Return a shell-escaped version of the string *s*.
Backported from Python 3.3 standard library module shlex.
"""
if is_py3: # use the latest version instead of backporting if it's available
return quote(s)
if not s:
return "''"
if _find_unsafe(s) is None... | Return a shell-escaped version of the string *s*.
Backported from Python 3.3 standard library module shlex. |
def register_dataset(self,
dataset,
expr,
deltas=None,
checkpoints=None,
odo_kwargs=None):
"""Explicitly map a datset to a collection of blaze expressions.
Parameters
---... | Explicitly map a datset to a collection of blaze expressions.
Parameters
----------
dataset : DataSet
The pipeline dataset to map to the given expressions.
expr : Expr
The baseline values.
deltas : Expr, optional
The deltas for the data.
... |
def needs_to_auth(self, dbname):
"""
Determines if the server needs to authenticate to the database.
NOTE: we stopped depending on is_auth() since its only a configuration
and may not be accurate
"""
log_debug("Checking if server '%s' needs to auth on db '%s'...." %
... | Determines if the server needs to authenticate to the database.
NOTE: we stopped depending on is_auth() since its only a configuration
and may not be accurate |
def dataset(directory, images_file, labels_file):
"""Download and parse MNIST dataset."""
images_file = download(directory, images_file)
labels_file = download(directory, labels_file)
check_image_file_header(images_file)
check_labels_file_header(labels_file)
def decode_image(image):
# Normalize from ... | Download and parse MNIST dataset. |
def dt_cluster(dt_list, dt_thresh=16.0):
"""Find clusters of similar datetimes within datetime list
"""
if not isinstance(dt_list[0], float):
o_list = dt2o(dt_list)
else:
o_list = dt_list
o_list_sort = np.sort(o_list)
o_list_sort_idx = np.argsort(o_list)
d = np.diff(o_list_so... | Find clusters of similar datetimes within datetime list |
def integrate_adaptive(rhs, jac, y0, x0, xend, atol, rtol, dx0=.0, dx_max=.0,
check_callable=False, check_indexing=False, **kwargs):
"""
Integrates a system of ordinary differential equations.
Parameters
----------
rhs: callable
Function with signature f(t, y, fout) w... | Integrates a system of ordinary differential equations.
Parameters
----------
rhs: callable
Function with signature f(t, y, fout) which modifies fout *inplace*.
jac: callable
Function with signature j(t, y, jmat_out, dfdx_out) which modifies
jmat_out and dfdx_out *inplace*.
... |
def clone(self):
"""
Return an independent copy of this layout with a completely separate
color_list and no drivers.
"""
args = {k: getattr(self, k) for k in self.CLONE_ATTRS}
args['color_list'] = copy.copy(self.color_list)
return self.__class__([], **args) | Return an independent copy of this layout with a completely separate
color_list and no drivers. |
def DirEntryScanner(**kw):
"""Return a prototype Scanner instance for "scanning"
directory Nodes for their in-memory entries"""
kw['node_factory'] = SCons.Node.FS.Entry
kw['recursive'] = None
return SCons.Scanner.Base(scan_in_memory, "DirEntryScanner", **kw) | Return a prototype Scanner instance for "scanning"
directory Nodes for their in-memory entries |
def build_single(scheme_file, templates, base_output_dir):
"""Build colorscheme for a single $scheme_file using all TemplateGroup
instances in $templates."""
scheme = get_yaml_dict(scheme_file)
scheme_slug = slugify(scheme_file)
format_scheme(scheme, scheme_slug)
scheme_name = scheme['scheme-na... | Build colorscheme for a single $scheme_file using all TemplateGroup
instances in $templates. |
def __create_db_and_container(self):
"""Call the get or create methods."""
db_id = self.config.database
container_name = self.config.container
self.db = self.__get_or_create_database(self.client, db_id)
self.container = self.__get_or_create_container(
self.client, con... | Call the get or create methods. |
def get(self, sid):
"""
Constructs a EventContext
:param sid: The sid
:returns: twilio.rest.taskrouter.v1.workspace.event.EventContext
:rtype: twilio.rest.taskrouter.v1.workspace.event.EventContext
"""
return EventContext(self._version, workspace_sid=self._solut... | Constructs a EventContext
:param sid: The sid
:returns: twilio.rest.taskrouter.v1.workspace.event.EventContext
:rtype: twilio.rest.taskrouter.v1.workspace.event.EventContext |
def metadata_add_description(self):
""" Metadata: add description """
service_description = {}
if (self.args.json):
service_description = json.loads(self.args.json)
if (self.args.url):
if "url" in service_description:
raise Exception("json service ... | Metadata: add description |
def parse_subdomain_missing_zonefiles_record(cls, rec):
"""
Parse a missing-zonefiles vector given by the domain.
Returns the list of zone file indexes on success
Raises ParseError on unparseable records
"""
txt_entry = rec['txt']
if isinstance(txt_entry, list):
... | Parse a missing-zonefiles vector given by the domain.
Returns the list of zone file indexes on success
Raises ParseError on unparseable records |
def json2value(json_string, params=Null, flexible=False, leaves=False):
"""
:param json_string: THE JSON
:param params: STANDARD JSON PARAMS
:param flexible: REMOVE COMMENTS
:param leaves: ASSUME JSON KEYS ARE DOT-DELIMITED
:return: Python value
"""
if not is_text(json_string):
L... | :param json_string: THE JSON
:param params: STANDARD JSON PARAMS
:param flexible: REMOVE COMMENTS
:param leaves: ASSUME JSON KEYS ARE DOT-DELIMITED
:return: Python value |
def validate(instance, schema, cls=None, *args, **kwargs):
"""
Validate an instance under the given schema.
>>> validate([2, 3, 4], {"maxItems" : 2})
Traceback (most recent call last):
...
ValidationError: [2, 3, 4] is too long
:func:`validate` will first verify that th... | Validate an instance under the given schema.
>>> validate([2, 3, 4], {"maxItems" : 2})
Traceback (most recent call last):
...
ValidationError: [2, 3, 4] is too long
:func:`validate` will first verify that the provided schema is itself
valid, since not doing so can lead to l... |
def param_changed_to(self, key, to_value, from_value=None):
"""
Returns true if the given parameter, with name key, has transitioned to the given value.
"""
last_value = getattr(self.last_manifest, key)
current_value = self.current_manifest.get(key)
if from_value is not N... | Returns true if the given parameter, with name key, has transitioned to the given value. |
def main(args): ## pylint: disable=too-many-branches
"""Entrypoint of the whole commandline application"""
EXNAME = os.path.basename(__file__ if WIN32 else sys.argv[0])
for ext in (".py", ".pyc", ".exe", "-script.py", "-script.pyc"): ## pragma: no cover
if EXNAME.endswith(ext): ## pragma: no co... | Entrypoint of the whole commandline application |
def create(cls, name, engines, policy=None, comment=None, **kwargs):
"""
Create a new validate policy task.
If a policy is not specified, the engines existing policy will
be validated. Override default validation settings as kwargs.
:param str name: name of task
... | Create a new validate policy task.
If a policy is not specified, the engines existing policy will
be validated. Override default validation settings as kwargs.
:param str name: name of task
:param engines: list of engines to validate
:type engines: list(Engine)
:... |
def get_channels_in(self, guild_id: str) -> List[Dict[str, Any]]:
"""Get a list of channels in the guild
Args:
guild_id: id of the guild to fetch channels from
Returns:
List of dictionary objects of channels in the guild. Note the different
types of channels... | Get a list of channels in the guild
Args:
guild_id: id of the guild to fetch channels from
Returns:
List of dictionary objects of channels in the guild. Note the different
types of channels: text, voice, DM, group DM.
https://discordapp.com/developers/d... |
def get_time_objects_from_model_timesteps(cls, times, start):
"""
Calculate the datetimes of the model timesteps
times should start at 0 and be in seconds
"""
modelTimestep = []
newtimes = []
for i in xrange(0, len(times)):
try:
mode... | Calculate the datetimes of the model timesteps
times should start at 0 and be in seconds |
def legend_title_header_element(feature, parent):
"""Retrieve legend title header string from definitions."""
_ = feature, parent # NOQA
header = legend_title_header['string_format']
return header.capitalize() | Retrieve legend title header string from definitions. |
def _drop_indices(self):
"""Drops the database indices relating to n-grams."""
self._logger.info('Dropping database indices')
self._conn.execute(constants.DROP_TEXTNGRAM_INDEX_SQL)
self._logger.info('Finished dropping database indices') | Drops the database indices relating to n-grams. |
def run():
"""Command for reflection database objects"""
parser = OptionParser(
version=__version__, description=__doc__,
)
parser.add_option(
'-u', '--url', dest='url',
help='Database URL (connection string)',
)
parser.add_option(
'-r', '--render', dest='render... | Command for reflection database objects |
def monthly_build_list_regex(self):
"""Return the regex for the folder containing builds of a month."""
# Regex for possible builds for the given date
return r'nightly/%(YEAR)s/%(MONTH)s/' % {
'YEAR': self.date.year,
'MONTH': str(self.date.month).zfill(2)} | Return the regex for the folder containing builds of a month. |
def execute(self, conn, block_name, origin_site_name, transaction=False):
"""
Update origin_site_name for a given block_name
"""
if not conn:
dbsExceptionHandler("dbsException-failed-connect2host", "Oracle/Block/UpdateStatus. \
Expects db connection from upper layer.", self.l... | Update origin_site_name for a given block_name |
def echo_warnings_via_pager(warnings: List[WarningTuple], sep: str = '\t') -> None:
"""Output the warnings from a BEL graph with Click and the system's pager."""
# Exit if no warnings
if not warnings:
click.echo('Congratulations! No warnings.')
sys.exit(0)
max_line_width = max(
... | Output the warnings from a BEL graph with Click and the system's pager. |
def create_matcher(dispatcher, parsers, apptags, matcher='ruled', hosts=tuple(), time_range=None,
time_period=(None, None), patterns=tuple(), invert=False, count=False,
files_with_match=None, max_count=0, only_matching=False, quiet=False,
thread=False, name_cache... | Create a matcher engine.
:return: A matcher function. |
def set_password(self, service, username, password):
"""Set password for the username of the service
"""
password = self._encrypt(password or '')
keyring_working_copy = copy.deepcopy(self._keyring)
service_entries = keyring_working_copy.get(service)
if not service_entries... | Set password for the username of the service |
def _add_child(self, collection, set, child):
"""Adds 'child' to 'collection', first checking 'set' to see if it's
already present."""
added = None
for c in child:
if c not in set:
set.add(c)
collection.append(c)
added = 1
... | Adds 'child' to 'collection', first checking 'set' to see if it's
already present. |
def resolve_inputs(self, layers):
'''Resolve the names of inputs for this layer into shape tuples.
Parameters
----------
layers : list of :class:`Layer`
A list of the layers that are available for resolving inputs.
Raises
------
theanets.util.Configu... | Resolve the names of inputs for this layer into shape tuples.
Parameters
----------
layers : list of :class:`Layer`
A list of the layers that are available for resolving inputs.
Raises
------
theanets.util.ConfigurationError :
If an input cannot ... |
def _document_structure(self):
"""Document the structure of the dataset."""
logger.debug("Documenting dataset structure")
key = self.get_structure_key()
text = json.dumps(self._structure_parameters, indent=2, sort_keys=True)
self.put_text(key, text)
key = self.get_dtool_... | Document the structure of the dataset. |
def ip_address_list(ips):
""" IP address range validation and expansion. """
# first, try it as a single IP address
try:
return ip_address(ips)
except ValueError:
pass
# then, consider it as an ipaddress.IPv[4|6]Network instance and expand it
return list(ipaddress.ip_network(u(ip... | IP address range validation and expansion. |
def cov_error(self, comp_cov, score_metric="frobenius"):
"""Computes the covariance error vs. comp_cov.
May require self.path_
Parameters
----------
comp_cov : array-like, shape = (n_features, n_features)
The precision to compare with.
This should normal... | Computes the covariance error vs. comp_cov.
May require self.path_
Parameters
----------
comp_cov : array-like, shape = (n_features, n_features)
The precision to compare with.
This should normally be the test sample covariance/precision.
scaling : bool
... |
def _get_trailing_whitespace(marker, s):
"""Return the whitespace content trailing the given 'marker' in string 's',
up to and including a newline.
"""
suffix = ''
start = s.index(marker) + len(marker)
i = start
while i < len(s):
if s[i] in ' \t':
suffix += s[i]
e... | Return the whitespace content trailing the given 'marker' in string 's',
up to and including a newline. |
async def ehlo(self, from_host=None):
"""
Sends a SMTP 'EHLO' command. - Identifies the client and starts the
session.
If given ``from`_host`` is None, defaults to the client FQDN.
For further details, please check out `RFC 5321 § 4.1.1.1`_.
Args:
from_host... | Sends a SMTP 'EHLO' command. - Identifies the client and starts the
session.
If given ``from`_host`` is None, defaults to the client FQDN.
For further details, please check out `RFC 5321 § 4.1.1.1`_.
Args:
from_host (str or None): Name to use to identify the client.
... |
def get_identity(identity):
""" Returns a (user_obj, None) tuple or a (None, group_obj) tuple depending on the considered
instance.
"""
if isinstance(identity, AnonymousUser):
return identity, None
if isinstance(identity, get_user_model()):
return identity, None
elif isinsta... | Returns a (user_obj, None) tuple or a (None, group_obj) tuple depending on the considered
instance. |
def template_filter(self, param=None):
"""Returns a decorator that adds the wrapped function to dictionary of template filters.
The wrapped function is keyed by either the supplied param (if supplied)
or by the wrapped functions name.
:param param: Optional name to use instead of the n... | Returns a decorator that adds the wrapped function to dictionary of template filters.
The wrapped function is keyed by either the supplied param (if supplied)
or by the wrapped functions name.
:param param: Optional name to use instead of the name of the function to be wrapped
:return:... |
def put(self, request, bot_id, id, format=None):
"""
Update existing Telegram chat state
---
serializer: TelegramChatStateSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request... | Update existing Telegram chat state
---
serializer: TelegramChatStateSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request |
def add_schema(self, database, schema):
"""Add a schema to the set of known schemas (case-insensitive)
:param str database: The database name to add.
:param str schema: The schema name to add.
"""
self.schemas.add((_lower(database), _lower(schema))) | Add a schema to the set of known schemas (case-insensitive)
:param str database: The database name to add.
:param str schema: The schema name to add. |
def load_lists(keys=[], values=[], name='NT'):
""" Map namedtuples given a pair of key, value lists. """
mapping = dict(zip(keys, values))
return mapper(mapping, _nt_name=name) | Map namedtuples given a pair of key, value lists. |
def from_etree(cls, etree_element):
"""
creates a ``SaltLayer`` instance from the etree representation of an
<layers> element from a SaltXMI file.
"""
ins = SaltElement.from_etree(etree_element)
# TODO: this looks dangerous, ask Stackoverflow about it!
# convert S... | creates a ``SaltLayer`` instance from the etree representation of an
<layers> element from a SaltXMI file. |
def pattern_filter(items, whitelist=None, blacklist=None, key=None):
"""This filters `items` by a regular expression `whitelist` and/or
`blacklist`, with the `blacklist` taking precedence. An optional `key`
function can be provided that will be passed each item.
"""
key = key or __return_self
if... | This filters `items` by a regular expression `whitelist` and/or
`blacklist`, with the `blacklist` taking precedence. An optional `key`
function can be provided that will be passed each item. |
def body(self, value):
"""Sets the request body; handles logging and length measurement."""
self.__body = value
if value is not None:
# Avoid calling len() which cannot exceed 4GiB in 32-bit python.
body_length = getattr(
self.__body, 'length', None) or le... | Sets the request body; handles logging and length measurement. |
def get_user_config_dir():
"""
Return the path to the user s-tui config directory
"""
user_home = os.getenv('XDG_CONFIG_HOME')
if user_home is None or not user_home:
config_path = os.path.expanduser(os.path.join('~', '.config', 's-tui'))
else:
config_path = os.path.join(user_home... | Return the path to the user s-tui config directory |
def draw_on_image(self,
image,
color=(0, 255, 0), color_face=None,
color_lines=None, color_points=None,
alpha=1.0, alpha_face=None,
alpha_lines=None, alpha_points=None,
size=1, size_lines=... | Draw all polygons onto a given image.
Parameters
----------
image : (H,W,C) ndarray
The image onto which to draw the bounding boxes.
This image should usually have the same shape as set in
``PolygonsOnImage.shape``.
color : iterable of int, optional
... |
def send_highspeed(self, data, progress_callback):
"""Send a script to a device at highspeed, reporting progress.
This method takes a binary blob and downloads it to the device as fast
as possible, calling the passed progress_callback periodically with
updates on how far it has gotten.
... | Send a script to a device at highspeed, reporting progress.
This method takes a binary blob and downloads it to the device as fast
as possible, calling the passed progress_callback periodically with
updates on how far it has gotten.
Args:
data (bytes): The binary blob that ... |
def solve_mbar(u_kn_nonzero, N_k_nonzero, f_k_nonzero, solver_protocol=None):
"""Solve MBAR self-consistent equations using some sequence of equation solvers.
Parameters
----------
u_kn_nonzero : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log un... | Solve MBAR self-consistent equations using some sequence of equation solvers.
Parameters
----------
u_kn_nonzero : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log unnormalized probabilities
for the nonempty states
N_k_nonzero : np.ndarray... |
def _get_config(config_file):
'''find, read and parse configuraton.'''
parser = ConfigParser.SafeConfigParser()
if os.path.lexists(config_file):
try:
log.info('Reading config: %s', config_file)
inp = open(config_file)
parser.readfp(inp)
return parser
... | find, read and parse configuraton. |
def listen(self, address, ssl=False, family=0, flags=0, ipc=False, backlog=128):
"""Create a new transport, bind it to *address*, and start listening
for new connections.
See :func:`create_server` for a description of *address* and the
supported keyword arguments.
"""
ha... | Create a new transport, bind it to *address*, and start listening
for new connections.
See :func:`create_server` for a description of *address* and the
supported keyword arguments. |
def _spectrogram_mono(self, x):
'''x.shape : (None, 1, len_src),
returns 2D batch of a mono power-spectrogram'''
x = K.permute_dimensions(x, [0, 2, 1])
x = K.expand_dims(x, 3) # add a dummy dimension (channel axis)
subsample = (self.n_hop, 1)
output_real = K.conv2d(x, se... | x.shape : (None, 1, len_src),
returns 2D batch of a mono power-spectrogram |
def _check_branching(X,Xsamples,restart,threshold=0.25):
"""\
Check whether time series branches.
Parameters
----------
X (np.array): current time series data.
Xsamples (np.array): list of previous branching samples.
restart (int): counts number of restart trials.
threshold (float, opti... | \
Check whether time series branches.
Parameters
----------
X (np.array): current time series data.
Xsamples (np.array): list of previous branching samples.
restart (int): counts number of restart trials.
threshold (float, optional): sets threshold for attractor
identification.
... |
def findHotspot( self, name ):
"""
Finds the hotspot based on the inputed name.
:param name | <str>
:return <XNodeHotspot> || None
"""
for hotspot in self._hotspots:
if ( hotspot.name() == name ):
return hotspot
... | Finds the hotspot based on the inputed name.
:param name | <str>
:return <XNodeHotspot> || None |
def main(inputstructs, inputpdbids):
"""Main function. Calls functions for processing, report generation and visualization."""
pdbid, pdbpath = None, None
# #@todo For multiprocessing, implement better stacktracing for errors
# Print title and version
title = "* Protein-Ligand Interaction Profiler v... | Main function. Calls functions for processing, report generation and visualization. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.