code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def safe_dump(data, stream=None, **kwargs):
'''
Use a custom dumper to ensure that defaultdict and OrderedDict are
represented properly. Ensure that unicode strings are encoded unless
explicitly told not to.
'''
if 'allow_unicode' not in kwargs:
kwargs['allow_unicode'] = True
return ... | Use a custom dumper to ensure that defaultdict and OrderedDict are
represented properly. Ensure that unicode strings are encoded unless
explicitly told not to. |
def load(steps, reload=False):
"""
safely load steps in place, excluding those that fail
Args:
steps: the steps to load
"""
# work on collections by default for fewer isinstance() calls per call to load()
if reload:
_STEP_CACHE.clear()
if callable(steps):
steps = ste... | safely load steps in place, excluding those that fail
Args:
steps: the steps to load |
def resfinderreporter(self):
"""
Custom reports for ResFinder analyses. These reports link the gene(s) found to their resistance phenotypes
"""
# Initialise resistance dictionaries from the notes.txt file
resistance_classes = ResistanceNotes.classes(self.targetpath)
# Cre... | Custom reports for ResFinder analyses. These reports link the gene(s) found to their resistance phenotypes |
def proxyval(self, visited):
'''
Support for new-style classes.
Currently we just locate the dictionary using a transliteration to
python of _PyObject_GetDictPtr, ignoring descriptors
'''
# Guard against infinite loops:
if self.as_address() in visited:
... | Support for new-style classes.
Currently we just locate the dictionary using a transliteration to
python of _PyObject_GetDictPtr, ignoring descriptors |
def get_gatk_annotations(config, include_depth=True, include_baseqranksum=True,
gatk_input=True):
"""Retrieve annotations to use for GATK VariantAnnotator.
If include_depth is false, we'll skip annotating DP. Since GATK downsamples
this will undercount on high depth sequencing and ... | Retrieve annotations to use for GATK VariantAnnotator.
If include_depth is false, we'll skip annotating DP. Since GATK downsamples
this will undercount on high depth sequencing and the standard outputs
from the original callers may be preferable.
BaseQRankSum can cause issues with some MuTect2 and oth... |
def from_client_secrets_file(cls, client_secrets_file, scopes, **kwargs):
"""Creates a :class:`Flow` instance from a Google client secrets file.
Args:
client_secrets_file (str): The path to the client secrets .json
file.
scopes (Sequence[str]): The list of scopes... | Creates a :class:`Flow` instance from a Google client secrets file.
Args:
client_secrets_file (str): The path to the client secrets .json
file.
scopes (Sequence[str]): The list of scopes to request during the
flow.
kwargs: Any additional param... |
def xspec_cosmo(H0=None,q0=None,lambda_0=None):
"""
Define the Cosmology in use within the XSpec models. See Xspec manual for help:
http://heasarc.nasa.gov/xanadu/xspec/manual/XScosmo.html
All parameters can be modified or just a single parameter
:param H0: the hubble constant
:param q0:
... | Define the Cosmology in use within the XSpec models. See Xspec manual for help:
http://heasarc.nasa.gov/xanadu/xspec/manual/XScosmo.html
All parameters can be modified or just a single parameter
:param H0: the hubble constant
:param q0:
:param lambda_0:
:return: Either none or the current... |
def refresh_token(self, refresh_token):
'''return origin json'''
url = 'https://api.youku.com/oauth2/token.json'
data = {'client_id': self.client_id,
'grant_type': 'refresh_token',
'refresh_token': refresh_token}
r = requests.post(url, data=data)
c... | return origin json |
def readdir(path):
'''
.. versionadded:: 2014.1.0
Return a list containing the contents of a directory
CLI Example:
.. code-block:: bash
salt '*' file.readdir /path/to/dir/
'''
path = os.path.expanduser(path)
if not os.path.isabs(path):
raise SaltInvocationError('Dir... | .. versionadded:: 2014.1.0
Return a list containing the contents of a directory
CLI Example:
.. code-block:: bash
salt '*' file.readdir /path/to/dir/ |
def process(obj):
"""
Process each block of the merger object.
"""
#merge all static and templates and less files
merged = merge(obj)
#save the full file if name defined
if obj.get('full'):
print 'Saving: {} ({:.2f}kB)'.format(obj['full'], len(merged)/1024.0)
_save(obj['full... | Process each block of the merger object. |
def connection_lost(self, exc):
"""Stop when connection is lost."""
if exc:
self.log.exception('disconnected due to exception')
else:
self.log.info('disconnected because of close/abort.')
self._closed.set() | Stop when connection is lost. |
def print_status(self, indent="", recurse=False):
"""Print a summary of the job status for each `Link` in this `Chain`"""
print ("%s%30s : %15s : %20s" %
(indent, "Linkname", "Link Status", "Jobs Status"))
for link in self._links.values():
if hasattr(link, 'check_statu... | Print a summary of the job status for each `Link` in this `Chain` |
def revoke_access(src, dst='any', port=None, proto=None):
"""
Revoke access to an address or subnet
:param src: address (e.g. 192.168.1.234) or subnet
(e.g. 192.168.1.0/24).
:param dst: destiny of the connection, if the machine has multiple IPs and
connections to only on... | Revoke access to an address or subnet
:param src: address (e.g. 192.168.1.234) or subnet
(e.g. 192.168.1.0/24).
:param dst: destiny of the connection, if the machine has multiple IPs and
connections to only one of those have to accepted this is the
field has to b... |
def cut(list_, index=0):
"""Cut a list by index or arg"""
if isinstance(index, int):
cut_ = lambda x: x[index]
else:
cut_ = lambda x: getattr(x, index)
return list(map(cut_, list_)) | Cut a list by index or arg |
async def _build_rr_state_json(self, rr_id: str, timestamp: int) -> (str, int):
"""
Build rev reg state json at a given requested timestamp.
Return rev reg state json and its transaction time on the distributed ledger,
with upper bound at input timestamp of interest.
Raise Abse... | Build rev reg state json at a given requested timestamp.
Return rev reg state json and its transaction time on the distributed ledger,
with upper bound at input timestamp of interest.
Raise AbsentRevReg if no revocation registry exists on input rev reg id,
or BadRevStateTime if request... |
def Eps(value=None, loc=None):
"""A rule that accepts no tokens (epsilon) and returns ``value``."""
@llrule(loc, lambda parser: [])
def rule(parser):
return value
return rule | A rule that accepts no tokens (epsilon) and returns ``value``. |
def display(result, stream):
"""
Intelligently print the result (or pass if result is None).
:param result:
:return: None
"""
if result is None:
return
elif isinstance(result, basestring):
pass
elif isinstance(result, collections.Mapping):
result = u'\n'.join(u'%... | Intelligently print the result (or pass if result is None).
:param result:
:return: None |
def _update_pop(self, pop_size):
"""Assigns fitnesses to particles that are within bounds."""
valid_particles = []
invalid_particles = []
for part in self.population:
if any(x > 1 or x < -1 for x in part):
invalid_particles.append(part)
else:
... | Assigns fitnesses to particles that are within bounds. |
def start(self):
"""Start the connection to a transport."""
connect_thread = threading.Thread(target=self._connect)
connect_thread.start() | Start the connection to a transport. |
def nguHanhNapAm(diaChi, thienCan, xuatBanMenh=False):
"""Sử dụng Ngũ Hành nạp âm để tính Hành của năm.
Args:
diaChi (integer): Số thứ tự của địa chi (Tý=1, Sửu=2,...)
thienCan (integer): Số thứ tự của thiên can (Giáp=1, Ất=2,...)
Returns:
Trả về chữ viết tắt Hành của năm (K, T, H,... | Sử dụng Ngũ Hành nạp âm để tính Hành của năm.
Args:
diaChi (integer): Số thứ tự của địa chi (Tý=1, Sửu=2,...)
thienCan (integer): Số thứ tự của thiên can (Giáp=1, Ất=2,...)
Returns:
Trả về chữ viết tắt Hành của năm (K, T, H, O, M) |
def process_internal_commands(self):
'''This function processes internal commands
'''
with self._main_lock:
self.check_output_redirect()
program_threads_alive = {}
all_threads = threadingEnumerate()
program_threads_dead = []
with self.... | This function processes internal commands |
def decode(token, key, algorithms=None, options=None, audience=None,
issuer=None, subject=None, access_token=None):
"""Verifies a JWT string's signature and validates reserved claims.
Args:
token (str): A signed JWS to be verified.
key (str or dict): A key to attempt to verify the pa... | Verifies a JWT string's signature and validates reserved claims.
Args:
token (str): A signed JWS to be verified.
key (str or dict): A key to attempt to verify the payload with. Can be
individual JWK or JWK set.
algorithms (str or list): Valid algorithms that should be used to ve... |
def same_page(c):
"""Return true if all the components of c are on the same page of the document.
Page numbers are based on the PDF rendering of the document. If a PDF file is
provided, it is used. Otherwise, if only a HTML/XML document is provided, a
PDF is created and then used to determine the page ... | Return true if all the components of c are on the same page of the document.
Page numbers are based on the PDF rendering of the document. If a PDF file is
provided, it is used. Otherwise, if only a HTML/XML document is provided, a
PDF is created and then used to determine the page number of a Mention.
... |
def add_component(self, entity: int, component_instance: Any) -> None:
"""Add a new Component instance to an Entity.
Add a Component instance to an Entiy. If a Component of the same type
is already assigned to the Entity, it will be replaced.
:param entity: The Entity to associate the ... | Add a new Component instance to an Entity.
Add a Component instance to an Entiy. If a Component of the same type
is already assigned to the Entity, it will be replaced.
:param entity: The Entity to associate the Component with.
:param component_instance: A Component instance. |
def fetchone(table, cols="*", where=(), group="", order=(), limit=(), **kwargs):
"""Convenience wrapper for database SELECT and fetch one."""
return select(table, cols, where, group, order, limit, **kwargs).fetchone() | Convenience wrapper for database SELECT and fetch one. |
def policy_map_clss_set_set_dscp_dscp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
policy_map = ET.SubElement(config, "policy-map", xmlns="urn:brocade.com:mgmt:brocade-policer")
po_name_key = ET.SubElement(policy_map, "po-name")
po_name_key.te... | Auto Generated Code |
def _find_lang(langdict, lang, script, region):
"""Return the entry in the dictionary for the given language information."""
# Check if we should map this to a different locale.
full_locale = _full_locale(lang, script, region)
if (full_locale in _LOCALE_NORMALIZATION_MAP and
_LOCALE_NORMALIZATIO... | Return the entry in the dictionary for the given language information. |
def get_node_by_path(self, path):
"""Get a node from a node path.
Warning: use of this method assumes that sibling nodes have unique names,
if this is not assured the `get_node_by_coord` method can be used instead.
| Example with absolute node path:
| `node.get_node_by_path... | Get a node from a node path.
Warning: use of this method assumes that sibling nodes have unique names,
if this is not assured the `get_node_by_coord` method can be used instead.
| Example with absolute node path:
| `node.get_node_by_path('/root.name/child.name/gchild.name')`
... |
def enable_inheritance(path, objectType, clear=False):
'''
enable/disable inheritance on an object
Args:
path: The path to the object
objectType: The type of object (FILE, DIRECTORY, REGISTRY)
clear: True will remove non-Inherited ACEs from the ACL
Returns (dict): A dictionary ... | enable/disable inheritance on an object
Args:
path: The path to the object
objectType: The type of object (FILE, DIRECTORY, REGISTRY)
clear: True will remove non-Inherited ACEs from the ACL
Returns (dict): A dictionary containing the results
CLI Example:
.. code-block:: bash
... |
def print_infos(results):
"""Print informations in standard output
:param ReportResults results: the report result containing all compiled informations
"""
print('transactions: %i' % results.total_transactions)
print('timers: %i' % results.total_timers)
print('errors: %i' % results.total_errors... | Print informations in standard output
:param ReportResults results: the report result containing all compiled informations |
def InitAgeCheck(self):
"""make an interactive grid in which users can edit ages"""
self.panel = wx.Panel(self, style=wx.SIMPLE_BORDER)
text = """Step 6:
Fill in or correct any cells with information about ages.
The column for magic_method_codes can take multiple values in the form of a colon-d... | make an interactive grid in which users can edit ages |
def select_serial_number_row(self, serial_number):
"""Select row for identification number serial_number
Args:
serial_number: serial number
Returns:
pandas.DataFrame
"""
sheet = self.table
col = self.db_sheet_cols.id
rows = sheet.loc[:, c... | Select row for identification number serial_number
Args:
serial_number: serial number
Returns:
pandas.DataFrame |
def find_library_full_path(name):
"""
Similar to `from ctypes.util import find_library`, but try
to return full path if possible.
"""
from ctypes.util import find_library
if os.name == "posix" and sys.platform == "darwin":
# on Mac, ctypes already returns full path
return find_l... | Similar to `from ctypes.util import find_library`, but try
to return full path if possible. |
def load_include_path(paths):
"""
Scan for and add paths to the include path
"""
for path in paths:
# Verify the path is valid
if not os.path.isdir(path):
continue
# Add path to the system path, to avoid name clashes
# with mysql-connector for example ...
... | Scan for and add paths to the include path |
def _wait_for_disk_threads(self, terminate):
# type: (Uploader, bool) -> None
"""Wait for disk threads
:param Uploader self: this
:param bool terminate: terminate threads
"""
if terminate:
self._upload_terminate = terminate
for thr in self._disk_thread... | Wait for disk threads
:param Uploader self: this
:param bool terminate: terminate threads |
def _ctype_key_value(keys, vals):
"""
Returns ctype arrays for the key-value args, and the whether string keys are used.
For internal use only.
"""
if isinstance(keys, (tuple, list)):
assert(len(keys) == len(vals))
c_keys = []
c_vals = []
use_str_keys = None
f... | Returns ctype arrays for the key-value args, and the whether string keys are used.
For internal use only. |
def submitter(self, f):
"""Decorator to submit a coro-function as NewTask to self.loop with sem control.
Use default_callback frequency of loop."""
f = self._wrap_coro_function_with_sem(f)
@wraps(f)
def wrapped(*args, **kwargs):
return self.submit(f(*args, **kwargs))... | Decorator to submit a coro-function as NewTask to self.loop with sem control.
Use default_callback frequency of loop. |
def calculate_size(name, entry_processor):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(name)
data_size += calculate_size_data(entry_processor)
return data_size | Calculates the request payload size |
def get_relaxation(self, A_configuration, B_configuration, I):
"""Get the sparse SDP relaxation of a Bell inequality.
:param A_configuration: The definition of measurements of Alice.
:type A_configuration: list of list of int.
:param B_configuration: The definition of measurements of Bo... | Get the sparse SDP relaxation of a Bell inequality.
:param A_configuration: The definition of measurements of Alice.
:type A_configuration: list of list of int.
:param B_configuration: The definition of measurements of Bob.
:type B_configuration: list of list of int.
:param I: T... |
def from_veto_def(cls, veto):
"""Define a `DataQualityFlag` from a `VetoDef`
Parameters
----------
veto : :class:`~ligo.lw.lsctables.VetoDef`
veto definition to convert from
"""
name = '%s:%s' % (veto.ifo, veto.name)
try:
name += ':%d' % i... | Define a `DataQualityFlag` from a `VetoDef`
Parameters
----------
veto : :class:`~ligo.lw.lsctables.VetoDef`
veto definition to convert from |
def verify(self, **kwargs):
"""
Verifies that an instance of this class adheres to the given
restrictions.
:param kwargs: A set of keyword arguments
:return: True if it verifies OK otherwise False.
"""
super(MetadataStatement, self).verify(**kwargs)
if "s... | Verifies that an instance of this class adheres to the given
restrictions.
:param kwargs: A set of keyword arguments
:return: True if it verifies OK otherwise False. |
def _add_tag_manifest_file(zip_file, dir_name, tag_info_list):
"""Generate the tag manifest file and add it to the zip."""
_add_tag_file(
zip_file, dir_name, tag_info_list, _gen_tag_manifest_file_tup(tag_info_list)
) | Generate the tag manifest file and add it to the zip. |
def prepare_all_data(data_dir, block_pct_tokens_thresh=0.1):
"""
Prepare data for all HTML + gold standard blocks examples in ``data_dir``.
Args:
data_dir (str)
block_pct_tokens_thresh (float): must be in [0.0, 1.0]
Returns:
List[Tuple[str, List[float, int, List[str]], List[flo... | Prepare data for all HTML + gold standard blocks examples in ``data_dir``.
Args:
data_dir (str)
block_pct_tokens_thresh (float): must be in [0.0, 1.0]
Returns:
List[Tuple[str, List[float, int, List[str]], List[float, int, List[str]]]]
See Also:
:func:`prepare_data` |
def register(self, perm_func=None, model=None, allow_staff=None, allow_superuser=None,
allow_anonymous=None, unauthenticated_handler=None, request_types=None, name=None,
replace=False, _return_entry=False):
"""Register permission function & return the original function.
... | Register permission function & return the original function.
This is typically used as a decorator::
permissions = PermissionsRegistry()
@permissions.register
def can_do_something(user):
...
For internal use only: you can pass ``_return_entry=True``... |
def memoized_ignoreargs(func):
"""
A decorator. It performs memoization ignoring the arguments used to call
the function.
"""
def wrapper(*args, **kwargs):
if func not in _MEMOIZED_NOARGS:
res = func(*args, **kwargs)
_MEMOIZED_NOARGS[func] = res
return res... | A decorator. It performs memoization ignoring the arguments used to call
the function. |
def calc_rate_susceptibility(self, rate_std=None, params=None):
"""return the time tree estimation of evolutionary rates +/- one
standard deviation form the ML estimate.
Returns
-------
TreeTime.return_code : str
success or failure
"""
params = params... | return the time tree estimation of evolutionary rates +/- one
standard deviation form the ML estimate.
Returns
-------
TreeTime.return_code : str
success or failure |
def add_subsegment(self, subsegment):
"""
Add input subsegment as a child subsegment and increment
reference counter and total subsegments counter.
"""
super(Segment, self).add_subsegment(subsegment)
self.increment() | Add input subsegment as a child subsegment and increment
reference counter and total subsegments counter. |
def is_in_plane(self, pp, dist_tolerance):
"""
Determines if point pp is in the plane within the tolerance dist_tolerance
:param pp: point to be tested
:param dist_tolerance: tolerance on the distance to the plane within which point pp is considered in the plane
:return: True if ... | Determines if point pp is in the plane within the tolerance dist_tolerance
:param pp: point to be tested
:param dist_tolerance: tolerance on the distance to the plane within which point pp is considered in the plane
:return: True if pp is in the plane, False otherwise |
def _handle_get_application_request(self, app_id, semver, key, logical_id):
"""
Method that handles the get_application API call to the serverless application repo
This method puts something in the `_applications` dictionary because the plugin expects
something there in a later event.
... | Method that handles the get_application API call to the serverless application repo
This method puts something in the `_applications` dictionary because the plugin expects
something there in a later event.
:param string app_id: ApplicationId
:param string semver: SemanticVersion
... |
def remove_pickle_problems(obj):
"""doc_loader does not pickle correctly, causing Toil errors, remove from
objects.
"""
if hasattr(obj, "doc_loader"):
obj.doc_loader = None
if hasattr(obj, "embedded_tool"):
obj.embedded_tool = remove_pickle_problems(obj.embedded_tool)
if hasat... | doc_loader does not pickle correctly, causing Toil errors, remove from
objects. |
def recv_message(self, debug=False):
"""
Reading socket and receiving message from server. Check the CRC32.
"""
if debug:
packet = self.sock.recv(1024) # reads how many bytes to read
hexdump(packet)
packet_length_data = self.sock.recv(4) # reads how man... | Reading socket and receiving message from server. Check the CRC32. |
def inverse_kinematics(
self,
target_position_right,
target_orientation_right,
target_position_left,
target_orientation_left,
rest_poses,
):
"""
Helper function to do inverse kinematics for a given target position and
orientation in the PyBulle... | Helper function to do inverse kinematics for a given target position and
orientation in the PyBullet world frame.
Args:
target_position_{right, left}: A tuple, list, or numpy array of size 3 for position.
target_orientation_{right, left}: A tuple, list, or numpy array of size 4 ... |
def open(self):
'''Open a connection to the database.
If a connection appears to be open already, transactions are committed
and it is closed before proceeding. After establishing the connection,
the searchIndex table is prepared (and dropped if it already exists).
'''
i... | Open a connection to the database.
If a connection appears to be open already, transactions are committed
and it is closed before proceeding. After establishing the connection,
the searchIndex table is prepared (and dropped if it already exists). |
def getValidCertifications(self):
""" Returns the certifications fully valid
"""
certs = []
today = date.today()
for c in self.getCertifications():
validfrom = c.getValidFrom() if c else None
validto = c.getValidTo() if validfrom else None
if n... | Returns the certifications fully valid |
def choice_input(options=[], prompt='Press ENTER to continue.',
showopts=True, qopt=False):
"""Get input from a list of choices (q to quit)"""
choice = None
if showopts:
prompt = prompt + ' ' + str(options)
if qopt:
prompt = prompt + ' (q to quit)'
while not choice:
... | Get input from a list of choices (q to quit) |
def vectorizable_features(fcs):
'''Discovers the ordered set of vectorizable features in ``fcs``.
Returns a list of feature names, sorted lexicographically.
Feature names are only included if the corresponding
features are vectorizable (i.e., they are an instance of
:class:`collections.Mapping`).
... | Discovers the ordered set of vectorizable features in ``fcs``.
Returns a list of feature names, sorted lexicographically.
Feature names are only included if the corresponding
features are vectorizable (i.e., they are an instance of
:class:`collections.Mapping`). |
def get_remote_url(path, remote="origin"):
"""
Run git config --get remote.<remote>.url in path.
:param path: Path where git is to be run
:param remote: Remote name
:return: str or None
"""
path = get_path(path)
cmd = ["config", "--get", "remote.%s.url" % remote]
return __run_git(cm... | Run git config --get remote.<remote>.url in path.
:param path: Path where git is to be run
:param remote: Remote name
:return: str or None |
def visit_Assign(self, node):
"""
Implement assignment walker.
Parse class properties defined via the property() function
"""
# [[[cog
# cog.out("print(pcolor('Enter assign visitor', 'magenta'))")
# ]]]
# [[[end]]]
# ###
# Class-level assi... | Implement assignment walker.
Parse class properties defined via the property() function |
def methodcall(obj, method_name, *args, **kwargs):
"""Call a method of `obj`, either locally or remotely as appropriate.
obj may be an ordinary object, or a Remote object (or Ref or object Id)
If there are multiple remote arguments, they must be on the same engine.
kwargs:
prefer_local (bool,... | Call a method of `obj`, either locally or remotely as appropriate.
obj may be an ordinary object, or a Remote object (or Ref or object Id)
If there are multiple remote arguments, they must be on the same engine.
kwargs:
prefer_local (bool, optional): Whether to return cached local results if
... |
def read_namespaced_pod_disruption_budget_status(self, name, namespace, **kwargs):
"""
read status of the specified PodDisruptionBudget
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_... | read status of the specified PodDisruptionBudget
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_pod_disruption_budget_status(name, namespace, async_req=True)
>>> result = thread.ge... |
def A(self):
"""Spectral VAR coefficients.
.. math:: \mathbf{A}(f) = \mathbf{I} - \sum_{k=1}^{p} \mathbf{a}^{(k)}
\mathrm{e}^{-2\pi f}
"""
return fft(np.dstack([np.eye(self.m), -self.b]),
self.nfft * 2 - 1)[:, :, :self.nfft] | Spectral VAR coefficients.
.. math:: \mathbf{A}(f) = \mathbf{I} - \sum_{k=1}^{p} \mathbf{a}^{(k)}
\mathrm{e}^{-2\pi f} |
def matches_count(count, options):
"""
Returns whether the given count matches the given query options.
If no quantity options are specified, any count is considered acceptable.
Args:
count (int): The count to be validated.
options (Dict[str, int | Iterable[int]]): A dictionary of quer... | Returns whether the given count matches the given query options.
If no quantity options are specified, any count is considered acceptable.
Args:
count (int): The count to be validated.
options (Dict[str, int | Iterable[int]]): A dictionary of query options.
Returns:
bool: Whether ... |
def accumulate_from_superclasses(cls, propname):
''' Traverse the class hierarchy and accumulate the special sets of names
``MetaHasProps`` stores on classes:
Args:
name (str) : name of the special attribute to collect.
Typically meaningful values are: ``__container_props__``,
... | Traverse the class hierarchy and accumulate the special sets of names
``MetaHasProps`` stores on classes:
Args:
name (str) : name of the special attribute to collect.
Typically meaningful values are: ``__container_props__``,
``__properties__``, ``__properties_with_refs__`` |
def bin_to_edge_slice(s, n):
"""
Convert a bin slice into a bin edge slice.
"""
s = canonify_slice(s, n)
start = s.start
stop = s.stop
if start > stop:
_stop = start + 1
start = stop + 1
stop = _stop
start = max(start - 1, 0)
step = abs(s.step)
if stop <= ... | Convert a bin slice into a bin edge slice. |
def zip_strip_namespace(zip_src, namespace, logger=None):
""" Given a namespace, strips 'namespace__' from all files and filenames
in the zip
"""
namespace_prefix = "{}__".format(namespace)
lightning_namespace = "{}:".format(namespace)
zip_dest = zipfile.ZipFile(io.BytesIO(), "w", zipfile.ZI... | Given a namespace, strips 'namespace__' from all files and filenames
in the zip |
def tag(name, tag_name):
"""
Tag the named metric with the given tag.
"""
with LOCK:
# just to check if <name> exists
metric(name)
TAGS.setdefault(tag_name, set()).add(name) | Tag the named metric with the given tag. |
def _delete_fw(self, tenant_id, data):
"""Internal routine called when a FW is deleted. """
LOG.debug("In Delete fw data is %s", data)
in_sub = self.get_in_subnet_id(tenant_id)
out_sub = self.get_out_subnet_id(tenant_id)
arg_dict = self._create_arg_dict(tenant_id, data, in_sub, o... | Internal routine called when a FW is deleted. |
def enc(data, **kwargs):
'''
Alias to `{box_type}_encrypt`
box_type: secretbox, sealedbox(default)
'''
if 'keyfile' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'keyfile\' argument has been deprecated and will be removed in Salt '
'{version}. ... | Alias to `{box_type}_encrypt`
box_type: secretbox, sealedbox(default) |
def GetFormatSpecification(cls):
"""Retrieves the format specification.
Returns:
FormatSpecification: format specification.
"""
format_specification = specification.FormatSpecification(cls.NAME)
format_specification.AddNewSignature(b'ElfFile\x00', offset=0)
return format_specification | Retrieves the format specification.
Returns:
FormatSpecification: format specification. |
def _load_cell(args, schema):
"""Implements the BigQuery load magic used to load data from GCS to a table.
The supported syntax is:
%bigquery load -S|--source <source> -D|--destination <table> <other_args>
Args:
args: the arguments following '%bigquery load'.
schema: a JSON schema for the dest... | Implements the BigQuery load magic used to load data from GCS to a table.
The supported syntax is:
%bigquery load -S|--source <source> -D|--destination <table> <other_args>
Args:
args: the arguments following '%bigquery load'.
schema: a JSON schema for the destination table.
Returns:
A mes... |
def get_run_states(self) -> List[RunState]:
"""Get a list of RunStates from the ZoneMinder API."""
raw_states = self.get_state('api/states.json')
if not raw_states:
_LOGGER.warning("Could not fetch runstates from ZoneMinder")
return []
run_states = []
for... | Get a list of RunStates from the ZoneMinder API. |
def save_hex(hex_file, path):
"""
Given a string representation of a hex file, this function copies it to
the specified path thus causing the device mounted at that point to be
flashed.
If the hex_file is empty it will raise a ValueError.
If the filename at the end of the path does not end in ... | Given a string representation of a hex file, this function copies it to
the specified path thus causing the device mounted at that point to be
flashed.
If the hex_file is empty it will raise a ValueError.
If the filename at the end of the path does not end in '.hex' it will raise
a ValueError. |
def reload_solver(self, constraints=None):
"""
Reloads the solver. Useful when changing solver options.
:param list constraints: A new list of constraints to use in the reloaded solver instead of the current one
"""
if constraints is None:
constraints = self._sol... | Reloads the solver. Useful when changing solver options.
:param list constraints: A new list of constraints to use in the reloaded solver instead of the current one |
def packet_from_xml_packet(xml_pkt, psml_structure=None):
"""
Gets a TShark XML packet object or string, and returns a pyshark Packet objec.t
:param xml_pkt: str or xml object.
:param psml_structure: a list of the fields in each packet summary in the psml data. If given, packets will
be returned as... | Gets a TShark XML packet object or string, and returns a pyshark Packet objec.t
:param xml_pkt: str or xml object.
:param psml_structure: a list of the fields in each packet summary in the psml data. If given, packets will
be returned as a PacketSummary object.
:return: Packet object. |
def _create_any_group(self, parent_node, name, type_name, instance=None, constructor=None,
args=None, kwargs=None):
"""Generically creates a new group inferring from the `type_name`."""
if args is None:
args = []
if kwargs is None:
kwargs = {}
... | Generically creates a new group inferring from the `type_name`. |
def model_code_key_prefix(code_location_key_prefix, model_name, image):
"""Returns the s3 key prefix for uploading code during model deployment
The location returned is a potential concatenation of 2 parts
1. code_location_key_prefix if it exists
2. model_name or a name derived from the image
... | Returns the s3 key prefix for uploading code during model deployment
The location returned is a potential concatenation of 2 parts
1. code_location_key_prefix if it exists
2. model_name or a name derived from the image
Args:
code_location_key_prefix (str): the s3 key prefix from code_l... |
def parse(readDataInstance):
"""Returns a L{DataDirectory}-like object.
@type readDataInstance: L{ReadData}
@param readDataInstance: L{ReadData} object to read from.
@rtype: L{DataDirectory}
@return: The L{DataDirectory} object containing L{consts.IMAGE_NUMBEROF... | Returns a L{DataDirectory}-like object.
@type readDataInstance: L{ReadData}
@param readDataInstance: L{ReadData} object to read from.
@rtype: L{DataDirectory}
@return: The L{DataDirectory} object containing L{consts.IMAGE_NUMBEROF_DIRECTORY_ENTRIES} L{Directory} objects... |
def submit_cookbook(self, cookbook, params={}, _extra_params={}):
"""
Submit a cookbook.
"""
self._check_user_parameters(params)
files = {'cookbook': cookbook}
return self._submit(params, files, _extra_params=_extra_params) | Submit a cookbook. |
def get(self, request):
""" Returns a json representing the menu voices
in a format eaten by the js menu.
Raised ImproperlyConfigured exceptions can be viewed
in the browser console
"""
self.app_list = site.get_app_list(request)
self.apps_dict = self.c... | Returns a json representing the menu voices
in a format eaten by the js menu.
Raised ImproperlyConfigured exceptions can be viewed
in the browser console |
def convert_examples_to_features(examples, seq_length, tokenizer):
"""Loads a data file into a list of `InputFeature`s."""
features = []
for (ex_index, example) in enumerate(examples):
tokens_a = tokenizer.tokenize(example.text_a)
tokens_b = None
if example.text_b:
toke... | Loads a data file into a list of `InputFeature`s. |
def add_group(self, groupname, statements):
"""
Adds a group
@type groupname: bytes
@type statements: str
"""
msg = OmapiMessage.open(b"group")
msg.message.append(("create", struct.pack("!I", 1)))
msg.obj.append(("name", groupname))
msg.obj.append(("statements", statements))
response = self.query_se... | Adds a group
@type groupname: bytes
@type statements: str |
def from_httplib(ResponseCls, r, **response_kw):
"""
Given an :class:`httplib.HTTPResponse` instance ``r``, return a
corresponding :class:`urllib3.response.HTTPResponse` object.
Remaining parameters are passed to the HTTPResponse constructor, along
with ``original_response=r``.
... | Given an :class:`httplib.HTTPResponse` instance ``r``, return a
corresponding :class:`urllib3.response.HTTPResponse` object.
Remaining parameters are passed to the HTTPResponse constructor, along
with ``original_response=r``. |
def user_field(user, field, *args):
"""
Gets or sets (optional) user model fields. No-op if fields do not exist.
"""
if not field:
return
User = get_user_model()
try:
field_meta = User._meta.get_field(field)
max_length = field_meta.max_length
except FieldDoesNotExist:... | Gets or sets (optional) user model fields. No-op if fields do not exist. |
def set2d(self):
"""
Configures OpenGL to draw in 2D.
Note that wireframe mode is always disabled in 2D-Mode, but can be re-enabled by calling ``glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)``\ .
"""
# Light
glDisable(GL_LIGHTING)
# To avoid... | Configures OpenGL to draw in 2D.
Note that wireframe mode is always disabled in 2D-Mode, but can be re-enabled by calling ``glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)``\ . |
def __on_presence(self, data):
"""
Got a presence stanza
"""
room_jid = data['from'].bare
muc_presence = data['muc']
room = muc_presence['room']
nick = muc_presence['nick']
with self.__lock:
try:
# Get room state machine
... | Got a presence stanza |
def pack_req(cls, code, pl_ratio_min,
pl_ratio_max, trd_env, acc_id, trd_mkt, conn_id):
"""Convert from user request for trading days to PLS request"""
from futuquant.common.pb.Trd_GetPositionList_pb2 import Request
req = Request()
req.c2s.header.trdEnv = TRD_ENV_MAP[trd... | Convert from user request for trading days to PLS request |
def log_normalization(self, name="log_normalization"):
"""Computes the log normalizing constant, log(Z)."""
with self._name_scope(name):
return (self.df * self.scale_operator.log_abs_determinant() +
0.5 * self.df * self.dimension * math.log(2.) +
self._multi_lgamma(0.5 * self.d... | Computes the log normalizing constant, log(Z). |
def _index(self, model):
'''
Elasticsearch multi types has been removed
Use multi index unless set __msearch_index__.
'''
doc_type = model
if not isinstance(model, str):
doc_type = model.__table__.name
index_name = doc_type
if hasattr(model, "... | Elasticsearch multi types has been removed
Use multi index unless set __msearch_index__. |
def _begin_request(self):
"""
Actually start executing this request.
"""
headers = self.m2req.headers
self._request = HTTPRequest(connection=self,
method=headers.get("METHOD"),
uri=self.m2req.path,
version=headers.get("VERSION"),
h... | Actually start executing this request. |
def alpha3(self, code):
"""
Return the ISO 3166-1 three letter country code matching the provided
country code.
If no match is found, returns an empty string.
"""
code = self.alpha2(code)
try:
return self.alt_codes[code][0]
except KeyError:
... | Return the ISO 3166-1 three letter country code matching the provided
country code.
If no match is found, returns an empty string. |
def main():
"""
Creates the following structure:
/plugins
__init__.py
hello.py
/templates
blank.html
.gitignore
run_will.py
requirements.txt
Procfile
README.md
"""
print_head()
puts("Welcome to the will project generator.")
puts("")
if ar... | Creates the following structure:
/plugins
__init__.py
hello.py
/templates
blank.html
.gitignore
run_will.py
requirements.txt
Procfile
README.md |
def push(self, instance, action, success, idxs=_marker):
"""Adds an instance into the pool, to be reindexed on resume
"""
uid = api.get_uid(instance)
info = self.objects.get(uid, {})
idx = [] if idxs is _marker else idxs
info[action] = {'success': success, 'idxs': idx}
... | Adds an instance into the pool, to be reindexed on resume |
def extract_jwt_token(self, token):
"""
Extracts a data dictionary from a jwt token
"""
# Note: we disable exp verification because we will do it ourselves
with InvalidTokenHeader.handle_errors('failed to decode JWT token'):
data = jwt.decode(
token,
... | Extracts a data dictionary from a jwt token |
def modify_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay... | Modify an virtual server. modify an existing virtual. Only parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destinatio... |
def add_hyperedge(self, tail, head, attr_dict=None, **attr):
"""Adds a hyperedge to the hypergraph, along with any related
attributes of the hyperedge.
This method will automatically add any node from the tail and
head that was not in the hypergraph.
A hyperedge without a "weight... | Adds a hyperedge to the hypergraph, along with any related
attributes of the hyperedge.
This method will automatically add any node from the tail and
head that was not in the hypergraph.
A hyperedge without a "weight" attribute specified will be
assigned the default value of 1.
... |
def lstm_cell(inputs,
state,
num_units,
use_peepholes=False,
cell_clip=0.0,
initializer=None,
num_proj=None,
num_unit_shards=None,
num_proj_shards=None,
reuse=None,
name=None):
"... | Full LSTM cell. |
def setAnimated(self, state):
"""
Sets whether or not the popup widget should animate its opacity
when it is shown.
:param state | <bool>
"""
self._animated = state
self.setAttribute(Qt.WA_TranslucentBackground, state) | Sets whether or not the popup widget should animate its opacity
when it is shown.
:param state | <bool> |
def run(self, loopinfo=None, batch_size=1):
""" Run consumer
"""
logger.info("{}.Starting...".format(self.__class__.__name__))
if loopinfo:
while True:
for topic in self.topics:
self.call_kafka(topic, batch_size)
time.sleep(... | Run consumer |
def split(self, X, y=None, groups=None):
"""Generate indices to split data into training and test set.
Parameters
----------
X : array-like, of length n_samples
Training data, includes reaction's containers
y : array-like, of length n_samples
The target va... | Generate indices to split data into training and test set.
Parameters
----------
X : array-like, of length n_samples
Training data, includes reaction's containers
y : array-like, of length n_samples
The target variable for supervised learning problems.
gro... |
def fit_overlays(self, text, start=None, end=None, **kw):
"""
Get an overlay thet fits the range [start, end).
"""
for ovl in text.overlays:
if ovl.match(props=self.props_match, rng=(start, end)):
yield ovl | Get an overlay thet fits the range [start, end). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.