code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def weighted_rand(weights, round_result=False):
"""
Generate a non-uniform random value based on a list of weight tuples.
Treats weights as coordinates for a probability distribution curve and
rolls accordingly. Constructs a piece-wise linear curve according to
coordinates given in ``weights`` and ... | Generate a non-uniform random value based on a list of weight tuples.
Treats weights as coordinates for a probability distribution curve and
rolls accordingly. Constructs a piece-wise linear curve according to
coordinates given in ``weights`` and rolls random values in the
curve's bounding box until a ... |
def _put_attributes_using_post(self, domain_or_name, item_name, attributes,
replace=True, expected_value=None):
"""
Monkey-patched version of SDBConnection.put_attributes that uses POST instead of GET
The GET version is subject to the URL length limit which kicks in before th... | Monkey-patched version of SDBConnection.put_attributes that uses POST instead of GET
The GET version is subject to the URL length limit which kicks in before the 256 x 1024 limit
for attribute values. Using POST prevents that.
https://github.com/BD2KGenomics/toil/issues/502 |
def _get_roles_query(self, session, identifier):
"""
:type identifier: string
"""
return (session.query(Role).
join(role_membership_table, Role.pk_id == role_membership_table.c.role_id).
join(User, role_membership_table.c.user_id == User.pk_id).
... | :type identifier: string |
def show(dataset_uri):
"""Show the descriptive metadata in the readme."""
try:
dataset = dtoolcore.ProtoDataSet.from_uri(
uri=dataset_uri,
config_path=CONFIG_PATH
)
except dtoolcore.DtoolCoreTypeError:
dataset = dtoolcore.DataSet.from_uri(
uri=data... | Show the descriptive metadata in the readme. |
def Result(self, res):
"""Inform about the result of the test. If res is not a string, displays
'yes' or 'no' depending on whether res is evaluated as true or false.
The result is only displayed when self.did_show_result is not set.
"""
if isinstance(res, str):
text =... | Inform about the result of the test. If res is not a string, displays
'yes' or 'no' depending on whether res is evaluated as true or false.
The result is only displayed when self.did_show_result is not set. |
def create_anonymous_client(cls):
"""Factory: return client with anonymous credentials.
.. note::
Such a client has only limited access to "public" buckets:
listing their contents and downloading their blobs.
:rtype: :class:`google.cloud.storage.client.Client`
:r... | Factory: return client with anonymous credentials.
.. note::
Such a client has only limited access to "public" buckets:
listing their contents and downloading their blobs.
:rtype: :class:`google.cloud.storage.client.Client`
:returns: Instance w/ anonymous credentials and... |
def get_all_memberships(
self, limit_to=100, max_calls=None, parameters=None,
since_when=None, start_record=0, verbose=False):
"""
Retrieve all memberships updated since "since_when"
Loop over queries of size limit_to until either a non-full queryset
is returned,... | Retrieve all memberships updated since "since_when"
Loop over queries of size limit_to until either a non-full queryset
is returned, or max_depth is reached (used in tests). Then the
recursion collapses to return a single concatenated list. |
def includeme(config):
"""
Include `crabpy_pyramid` in this `Pyramid` application.
:param pyramid.config.Configurator config: A Pyramid configurator.
"""
settings = _parse_settings(config.registry.settings)
base_settings = _get_proxy_settings(settings)
# http caching tween
if not sett... | Include `crabpy_pyramid` in this `Pyramid` application.
:param pyramid.config.Configurator config: A Pyramid configurator. |
def on_key_press(self, event):
"""Pan and zoom with the keyboard."""
# Zooming with the keyboard.
key = event.key
if event.modifiers:
return
# Pan.
if self.enable_keyboard_pan and key in self._arrows:
self._pan_keyboard(key)
# Zoom.
... | Pan and zoom with the keyboard. |
def send_message(self, payload):
""" Create a post request to the message sender
"""
self.l.info("Creating outbound message request")
result = ms_client.create_outbound(payload)
self.l.info("Created outbound message request")
return result | Create a post request to the message sender |
def fetch(self, category=CATEGORY_MESSAGE, offset=DEFAULT_OFFSET, chats=None):
"""Fetch the messages the bot can read from the server.
The method retrieves, from the Telegram server, the messages
sent with an offset equal or greater than the given.
A list of chats, groups and channels ... | Fetch the messages the bot can read from the server.
The method retrieves, from the Telegram server, the messages
sent with an offset equal or greater than the given.
A list of chats, groups and channels identifiers can be set
using the parameter `chats`. When it is set, only those
... |
def url_unparse(components):
"""The reverse operation to :meth:`url_parse`. This accepts arbitrary
as well as :class:`URL` tuples and returns a URL as a string.
:param components: the parsed URL as tuple which should be converted
into a URL string.
"""
scheme, netloc, path, ... | The reverse operation to :meth:`url_parse`. This accepts arbitrary
as well as :class:`URL` tuples and returns a URL as a string.
:param components: the parsed URL as tuple which should be converted
into a URL string. |
def token_list_len(tokenlist):
"""
Return the amount of characters in this token list.
:param tokenlist: List of (token, text) or (token, text, mouse_handler)
tuples.
"""
ZeroWidthEscape = Token.ZeroWidthEscape
return sum(len(item[1]) for item in tokenlist if item[0] != Ze... | Return the amount of characters in this token list.
:param tokenlist: List of (token, text) or (token, text, mouse_handler)
tuples. |
def plot_somas(somas):
'''Plot set of somas on same figure as spheres, each with different color'''
_, ax = common.get_figure(new_fig=True, subplot=111,
params={'projection': '3d', 'aspect': 'equal'})
for s in somas:
common.plot_sphere(ax, s.center, s.radius, color=rand... | Plot set of somas on same figure as spheres, each with different color |
def to_properties(cls, config, compact=False, indent=2, key_stack=[]):
"""Convert HOCON input into a .properties output
:return: .properties string representation
:type return: basestring
:return:
"""
def escape_value(value):
return value.replace('=', '\\=')... | Convert HOCON input into a .properties output
:return: .properties string representation
:type return: basestring
:return: |
def scan_processes_and_threads(self):
"""
Populates the snapshot with running processes and threads.
Tipically you don't need to call this method directly, if unsure use
L{scan} instead.
@note: This method uses the Toolhelp API.
@see: L{scan_modules}
@raise Wi... | Populates the snapshot with running processes and threads.
Tipically you don't need to call this method directly, if unsure use
L{scan} instead.
@note: This method uses the Toolhelp API.
@see: L{scan_modules}
@raise WindowsError: An error occured while updating the snapshot.
... |
def options(self, context, module_options):
'''
ACTION Enable/Disable RDP (choices: enable, disable)
'''
if not 'ACTION' in module_options:
context.log.error('ACTION option not specified!')
exit(1)
if module_options['ACTION'].lower() not in ['enable... | ACTION Enable/Disable RDP (choices: enable, disable) |
def flair_template_sync(self, editable, limit, # pylint: disable=R0912
static, sort, use_css, use_text):
"""Synchronize templates with flair that already exists on the site.
:param editable: Indicates that all the options should be editable.
:param limit: The minimu... | Synchronize templates with flair that already exists on the site.
:param editable: Indicates that all the options should be editable.
:param limit: The minimum number of users that must share the flair
before it is added as a template.
:param static: A list of flair templates that w... |
def set_iscsi_initiator_info(self, initiator_iqn):
"""Set iSCSI initiator information in iLO.
:param initiator_iqn: Initiator iqn for iLO.
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the system is
in the bios boot mode.
"""
... | Set iSCSI initiator information in iLO.
:param initiator_iqn: Initiator iqn for iLO.
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the system is
in the bios boot mode. |
def dump_response_data(response_schema,
response_data,
status_code=200,
headers=None,
response_format=None):
"""
Dumps response data as JSON using the given schema.
Forces JSON encoding even if the client did not sp... | Dumps response data as JSON using the given schema.
Forces JSON encoding even if the client did not specify the `Accept` header properly.
This is friendlier to client and test software, even at the cost of not distinguishing
HTTP 400 and 406 errors. |
def create_dir(self, directory_path, perm_bits=PERM_DEF):
"""Create `directory_path`, and all the parent directories.
Helper method to set up your test faster.
Args:
directory_path: The full directory path to create.
perm_bits: The permission bits as set by `chmod`.
... | Create `directory_path`, and all the parent directories.
Helper method to set up your test faster.
Args:
directory_path: The full directory path to create.
perm_bits: The permission bits as set by `chmod`.
Returns:
The newly created FakeDirectory object.
... |
def retention_schedule(name, retain, strptime_format=None, timezone=None):
'''
Apply retention scheduling to backup storage directory.
.. versionadded:: 2016.11.0
:param name:
The filesystem path to the directory containing backups to be managed.
:param retain:
Delete the backups,... | Apply retention scheduling to backup storage directory.
.. versionadded:: 2016.11.0
:param name:
The filesystem path to the directory containing backups to be managed.
:param retain:
Delete the backups, except for the ones we want to keep.
The N below should be an integer but may ... |
def info(name, root=None):
'''
Return information for the specified user
name
User to get the information for
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.info root
'''
if root is not None:
getspnam = functools.parti... | Return information for the specified user
name
User to get the information for
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.info root |
def rotate(self, angle, axis=(1, 0, 0), axis_point=(0, 0, 0), rad=False):
"""Rotate ``Actor`` around an arbitrary `axis` passing through `axis_point`."""
if rad:
anglerad = angle
else:
anglerad = angle / 57.29578
axis = utils.versor(axis)
a = np.cos(angler... | Rotate ``Actor`` around an arbitrary `axis` passing through `axis_point`. |
def refresh(self):
'''Refetch instance data from the API.
'''
response = requests.get('%s/guides/%s' % (API_BASE_URL, self.id))
attributes = response.json()
self.category = Category(attributes['category'])
self.url = attributes['url']
self.title = attributes['titl... | Refetch instance data from the API. |
def write_report(self, output_file):
"""Writes a report with the test results for the current assembly
Parameters
----------
output_file : str
Name of the output assembly file.
"""
logger.debug("Writing the assembly report into: {}".format(
outp... | Writes a report with the test results for the current assembly
Parameters
----------
output_file : str
Name of the output assembly file. |
def _append(self, menu):
'''append this menu item to a menu'''
from wx_loader import wx
menu.AppendMenu(-1, self.name, self.wx_menu()) | append this menu item to a menu |
def _handle_end_relation(self):
"""
Handle closing relation element
"""
self._result.append(Relation(result=self._result, **self._curr))
self._curr = {} | Handle closing relation element |
def Incr(self, x, term=1):
"""Increments the freq/prob associated with the value x.
Args:
x: number value
term: how much to increment by
"""
self.d[x] = self.d.get(x, 0) + term | Increments the freq/prob associated with the value x.
Args:
x: number value
term: how much to increment by |
def salsa20_8(B):
'''Salsa 20/8 stream cypher; Used by BlockMix. See http://en.wikipedia.org/wiki/Salsa20'''
# Create a working copy
x = B[:]
# Expanded form of this code. The expansion is significantly faster but
# this is much easier to understand
# ROUNDS = (
# (4, 0, 12, 7), (8, ... | Salsa 20/8 stream cypher; Used by BlockMix. See http://en.wikipedia.org/wiki/Salsa20 |
def check_network_role(self, public_key):
""" Check the public key of a node on the network to see if they are
permitted to participate. The roles being checked are the
following, from first to last:
"network"
"default"
The first role that is ... | Check the public key of a node on the network to see if they are
permitted to participate. The roles being checked are the
following, from first to last:
"network"
"default"
The first role that is set will be the one used to enforce if the
... |
def proxy_schema(self):
"""
Get the Proxy-Schema option of a request.
:return: the Proxy-Schema values or None if not specified by the request
:rtype : String
"""
for option in self.options:
if option.number == defines.OptionRegistry.PROXY_SCHEME.number:
... | Get the Proxy-Schema option of a request.
:return: the Proxy-Schema values or None if not specified by the request
:rtype : String |
def cfg_to_args(config):
"""Compatibility helper to use setup.cfg in setup.py."""
kwargs = {}
opts_to_args = {
'metadata': [
('name', 'name'),
('author', 'author'),
('author-email', 'author_email'),
('maintainer', 'maintainer'),
('maintaine... | Compatibility helper to use setup.cfg in setup.py. |
def select_color(cpcolor, evalcolor, idx=0):
""" Selects item color for plotting.
:param cpcolor: color for control points grid item
:type cpcolor: str, list, tuple
:param evalcolor: color for evaluated points grid item
:type evalcolor: str, list, tuple
:param idx: index of the current geometry... | Selects item color for plotting.
:param cpcolor: color for control points grid item
:type cpcolor: str, list, tuple
:param evalcolor: color for evaluated points grid item
:type evalcolor: str, list, tuple
:param idx: index of the current geometry object
:type idx: int
:return: a list of col... |
def search_alert_entities(self, **kwargs): # noqa: E501
"""Search over a customer's non-deleted alerts # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.search_... | Search over a customer's non-deleted alerts # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.search_alert_entities(async_req=True)
>>> result = thread.get()
... |
def get_aliases(self):
"""
RETURN LIST OF {"alias":a, "index":i} PAIRS
ALL INDEXES INCLUDED, EVEN IF NO ALIAS {"alias":Null}
"""
for index, desc in self.get_metadata().indices.items():
if not desc["aliases"]:
yield wrap({"index": index})
el... | RETURN LIST OF {"alias":a, "index":i} PAIRS
ALL INDEXES INCLUDED, EVEN IF NO ALIAS {"alias":Null} |
def set(self, value):
"""This parameter method attempts to set a specific value for this parameter. The value will be validated first, and if it can not be set. An error message will be set in the error property of this parameter"""
if self.validate(value):
#print "Parameter " + self.id + " ... | This parameter method attempts to set a specific value for this parameter. The value will be validated first, and if it can not be set. An error message will be set in the error property of this parameter |
def accuracy_thresh(y_pred:Tensor, y_true:Tensor, thresh:float=0.5, sigmoid:bool=True)->Rank0Tensor:
"Compute accuracy when `y_pred` and `y_true` are the same size."
if sigmoid: y_pred = y_pred.sigmoid()
return ((y_pred>thresh)==y_true.byte()).float().mean() | Compute accuracy when `y_pred` and `y_true` are the same size. |
def aggregate_groups(self, ct_agg, nr_groups, skip_key,
carray_factor, groupby_cols, agg_ops,
dtype_dict, bool_arr=None):
'''Perform aggregation and place the result in the given ctable.
Args:
ct_agg (ctable): the table to hold the aggregati... | Perform aggregation and place the result in the given ctable.
Args:
ct_agg (ctable): the table to hold the aggregation
nr_groups (int): the number of groups (number of rows in output table)
skip_key (int): index of the output row to remove from results (used for filtering)
... |
def sys_pipes_forever(encoding=_default_encoding):
"""Redirect all C output to sys.stdout/err
This is not a context manager; it turns on C-forwarding permanently.
"""
global _mighty_wurlitzer
if _mighty_wurlitzer is None:
_mighty_wurlitzer = sys_pipes(encoding)
_mighty_wurlitzer.__e... | Redirect all C output to sys.stdout/err
This is not a context manager; it turns on C-forwarding permanently. |
def consume(self):
"""
Chops the tail off the stream starting at 0 and ending at C{tell()}.
The stream pointer is set to 0 at the end of this function.
@since: 0.4
"""
try:
bytes = self.read()
except IOError:
bytes = ''
self.trunc... | Chops the tail off the stream starting at 0 and ending at C{tell()}.
The stream pointer is set to 0 at the end of this function.
@since: 0.4 |
def update_dict_key_value(
in_dict,
keys,
value,
delimiter=DEFAULT_TARGET_DELIM,
ordered_dict=False):
'''
Ensures that in_dict contains the series of recursive keys defined in keys.
Also updates the dict, that is at the end of `in_dict` traversed with `keys`,
with... | Ensures that in_dict contains the series of recursive keys defined in keys.
Also updates the dict, that is at the end of `in_dict` traversed with `keys`,
with `value`.
:param dict in_dict: The dictionary to work with
:param str keys: The delimited string with one or more keys.
:param any value: The... |
def __update_service_status(self, statuscode):
"""Set the internal status of the service object, and notify frontend."""
if self.__service_status != statuscode:
self.__service_status = statuscode
self.__send_service_status_to_frontend() | Set the internal status of the service object, and notify frontend. |
def copy(self: BoardT, *, stack: Union[bool, int] = True) -> BoardT:
"""
Creates a copy of the board.
Defaults to copying the entire move stack. Alternatively, *stack* can
be ``False``, or an integer to copy a limited number of moves.
"""
board = super().copy()
... | Creates a copy of the board.
Defaults to copying the entire move stack. Alternatively, *stack* can
be ``False``, or an integer to copy a limited number of moves. |
def get_class(classname, all=False):
"""Retrieve a class from the registry.
:raises: marshmallow.exceptions.RegistryError if the class cannot be found
or if there are multiple entries for the given class name.
"""
try:
classes = _registry[classname]
except KeyError:
raise Re... | Retrieve a class from the registry.
:raises: marshmallow.exceptions.RegistryError if the class cannot be found
or if there are multiple entries for the given class name. |
def get_path(self, api_info):
"""Get the path portion of the URL to the method (for RESTful methods).
Request path can be specified in the method, and it could have a base
path prepended to it.
Args:
api_info: API information for this API, possibly including a base path.
This is the api_... | Get the path portion of the URL to the method (for RESTful methods).
Request path can be specified in the method, and it could have a base
path prepended to it.
Args:
api_info: API information for this API, possibly including a base path.
This is the api_info property on the class that's bee... |
def sort_by(self, sb):
"""Sort results"""
self._dataset = self._dataset.sort(key=lambda x: x.pubdate, reverse=True)
return self | Sort results |
def read(filename, loader=None, implicit_tuple=True, allow_errors=False):
"""Load but don't evaluate a GCL expression from a file."""
with open(filename, 'r') as f:
return reads(f.read(),
filename=filename,
loader=loader,
implicit_tuple=implicit_tuple,
... | Load but don't evaluate a GCL expression from a file. |
async def get_auth(request):
"""Returns the user_id associated with a particular request.
Args:
request: aiohttp Request object.
Returns:
The user_id associated with the request, or None if no user is
associated with the request.
Raises:
RuntimeError: Middleware is not... | Returns the user_id associated with a particular request.
Args:
request: aiohttp Request object.
Returns:
The user_id associated with the request, or None if no user is
associated with the request.
Raises:
RuntimeError: Middleware is not installed |
def raw_request(self, method, resource, access_token=None, **kwargs):
"""
Makes a HTTP request and returns the raw
:class:`~requests.Response` object.
"""
headers = self._pop_headers(kwargs)
headers['Authorization'] = self._get_authorization_header(access_token)
... | Makes a HTTP request and returns the raw
:class:`~requests.Response` object. |
def groupby_task_class(self):
"""
Returns a dictionary mapping the task class to the list of tasks in the flow
"""
# Find all Task classes
class2tasks = OrderedDict()
for task in self.iflat_tasks():
cls = task.__class__
if cls not in class2tasks: c... | Returns a dictionary mapping the task class to the list of tasks in the flow |
def get_relative_airmass(zenith, model='kastenyoung1989'):
'''
Gives the relative (not pressure-corrected) airmass.
Gives the airmass at sea-level when given a sun zenith angle (in
degrees). The ``model`` variable allows selection of different
airmass models (described below). If ``model`` is not i... | Gives the relative (not pressure-corrected) airmass.
Gives the airmass at sea-level when given a sun zenith angle (in
degrees). The ``model`` variable allows selection of different
airmass models (described below). If ``model`` is not included or is
not valid, the default model is 'kastenyoung1989'.
... |
def complete_path(curr_dir, last_dir):
"""Return the path to complete that matches the last entered component.
If the last entered component is ~, expanded path would not
match, so return all of the available paths.
:param curr_dir: str
:param last_dir: str
:return: str
"""
if not last_d... | Return the path to complete that matches the last entered component.
If the last entered component is ~, expanded path would not
match, so return all of the available paths.
:param curr_dir: str
:param last_dir: str
:return: str |
def lock_retention_policy(self, client=None):
"""Lock the bucket's retention policy.
:raises ValueError:
if the bucket has no metageneration (i.e., new or never reloaded);
if the bucket has no retention policy assigned;
if the bucket's retention policy is already loc... | Lock the bucket's retention policy.
:raises ValueError:
if the bucket has no metageneration (i.e., new or never reloaded);
if the bucket has no retention policy assigned;
if the bucket's retention policy is already locked. |
def flush_on_close(self, stream):
"""Flush tornado iostream write buffer and prevent further writes.
Returns a future that resolves when the stream is flushed.
"""
assert get_thread_ident() == self.ioloop_thread_id
# Prevent futher writes
stream.KATCPServer_closing = Tr... | Flush tornado iostream write buffer and prevent further writes.
Returns a future that resolves when the stream is flushed. |
def write_to_file(src, dst):
"""Write data from `src` into `dst`.
Args:
src (iterable): iterable that yields blocks of data to write
dst (file-like object): file-like object that must support
.write(block)
Returns:
number of bytes written to `dst`
"""
n = 0
... | Write data from `src` into `dst`.
Args:
src (iterable): iterable that yields blocks of data to write
dst (file-like object): file-like object that must support
.write(block)
Returns:
number of bytes written to `dst` |
def _set_default_versions(self, config):
"""Retrieve pre-computed version information for expensive to retrieve versions.
Starting up GATK takes a lot of resources so we do it once at start of analysis.
"""
out = []
for name in ["gatk", "gatk4", "picard", "mutect"]:
v... | Retrieve pre-computed version information for expensive to retrieve versions.
Starting up GATK takes a lot of resources so we do it once at start of analysis. |
def p_class_constant_declaration(p):
'''class_constant_declaration : class_constant_declaration COMMA STRING EQUALS static_scalar
| CONST STRING EQUALS static_scalar'''
if len(p) == 6:
p[0] = p[1] + [ast.ClassConstant(p[3], p[5], lineno=p.lineno(2))]
else:
p... | class_constant_declaration : class_constant_declaration COMMA STRING EQUALS static_scalar
| CONST STRING EQUALS static_scalar |
def decamel(string):
""""Split CamelCased words.
CamelCase -> Camel Case, dromedaryCase -> dromedary Case.
"""
regex = re.compile(r'(\B[A-Z][a-z]*)')
return regex.sub(r' \1', string) | Split CamelCased words.
CamelCase -> Camel Case, dromedaryCase -> dromedary Case. |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: SyncListPermissionContext for this SyncListPermissionInstance
:rtype: twilio.rest.sync.v1.service... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: SyncListPermissionContext for this SyncListPermissionInstance
:rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncLi... |
def _post(url, headers, body, retries=3, timeout=3.0):
"""Try 3 times to request the content.
:param headers: The HTTP headers
:type headers: dict
:param body: The body of the HTTP post
:type body: str
:param retries: The number of times to retry before giving up
:type retries: int
:par... | Try 3 times to request the content.
:param headers: The HTTP headers
:type headers: dict
:param body: The body of the HTTP post
:type body: str
:param retries: The number of times to retry before giving up
:type retries: int
:param timeout: The time to wait for the post to complete, before ... |
def download_data(url, signature, data_home=None, replace=False, extract=True):
"""
Downloads the zipped data set specified at the given URL, saving it to
the data directory specified by ``get_data_home``. This function verifies
the download with the given signature and extracts the archive.
Parame... | Downloads the zipped data set specified at the given URL, saving it to
the data directory specified by ``get_data_home``. This function verifies
the download with the given signature and extracts the archive.
Parameters
----------
url : str
The URL of the dataset on the Internet to GET
... |
def matches_from_list(item,options,fuzzy=90,fname_match=True,fuzzy_fragment=None,guess=False):
'''Returns the members of ``options`` that best matches ``item``. Will prioritize
exact matches, then filename-style matching, then fuzzy matching. Returns a tuple of item,
index, match type, and fuzziness (if app... | Returns the members of ``options`` that best matches ``item``. Will prioritize
exact matches, then filename-style matching, then fuzzy matching. Returns a tuple of item,
index, match type, and fuzziness (if applicable)
:item: string to match
:options: list of examples... |
def dump(dct, jfile, overwrite=False, dirlevel=0, sort_keys=True,
indent=2, default_name='root.json', **kwargs):
""" output dict to json
Parameters
----------
dct : dict
jfile : str or file_like
if file_like, must have write method
overwrite : bool
whether to overwrite ... | output dict to json
Parameters
----------
dct : dict
jfile : str or file_like
if file_like, must have write method
overwrite : bool
whether to overwrite existing files
dirlevel : int
if jfile is path to folder,
defines how many key levels to set as sub-folders
... |
def value(self, observations):
""" Calculate only value head for given state """
input_data = self.input_block(observations)
base_output = self.value_backbone(input_data)
value_output = self.value_head(base_output)
return value_output | Calculate only value head for given state |
def modify(*units):
"""set the unit defined by in-game tag with desired properties
NOTE: all units must be owned by the same player or the command fails."""
ret = []
for unit in units: # add one command for each attribute
for attr, idx in [("energy", 1), ("life", 2), ("shields", 3)]: # see debug... | set the unit defined by in-game tag with desired properties
NOTE: all units must be owned by the same player or the command fails. |
def centralManager_didDisconnectPeripheral_error_(self, manager, peripheral, error):
"""Called when a device is disconnected."""
logger.debug('centralManager_didDisconnectPeripheral called')
# Get the device and remove it from the device list, then fire its
# disconnected event.
... | Called when a device is disconnected. |
def update_description(self, description):
"""
Update the description) of an IOC
This creates the description node if it is not present.
:param description: Value to set the description too
:return: True
"""
desc_node = self.metadata.find('description')
i... | Update the description) of an IOC
This creates the description node if it is not present.
:param description: Value to set the description too
:return: True |
def uncertain_conditional(Xnew_mu, Xnew_var, feat, kern, q_mu, q_sqrt, *,
mean_function=None, full_output_cov=False, full_cov=False, white=False):
"""
Calculates the conditional for uncertain inputs Xnew, p(Xnew) = N(Xnew_mu, Xnew_var).
See ``conditional`` documentation for further... | Calculates the conditional for uncertain inputs Xnew, p(Xnew) = N(Xnew_mu, Xnew_var).
See ``conditional`` documentation for further reference.
:param Xnew_mu: mean of the inputs, size N x Din
:param Xnew_var: covariance matrix of the inputs, size N x Din x Din
:param feat: gpflow.InducingFeature object... |
def google(rest):
"Look up a phrase on google"
API_URL = 'https://www.googleapis.com/customsearch/v1?'
try:
key = pmxbot.config['Google API key']
except KeyError:
return "Configure 'Google API key' in config"
# Use a custom search that searches everything normally
# http://stackoverflow.com/a/11206266/70170
... | Look up a phrase on google |
def parse_data_to_internal(self, data=None):
"""
Parse data and save to pickle/hickle
"""
if data is None:
data = parse.getdata(open(self.location_dat, "rb"),
argnum=self.argnum, close=True)
if self.filetype is "pickle":
pi... | Parse data and save to pickle/hickle |
def find_line(scihdu, refhdu):
"""Obtain bin factors and corner location to extract
and bin the appropriate subset of a reference image to
match a science image.
If the science image has zero offset and is the same size and
binning as the reference image, ``same_size`` will be set to
`True`. Ot... | Obtain bin factors and corner location to extract
and bin the appropriate subset of a reference image to
match a science image.
If the science image has zero offset and is the same size and
binning as the reference image, ``same_size`` will be set to
`True`. Otherwise, the values of ``rx``, ``ry``,... |
def count(self, val=True):
"""Get the number of bits in the array with the specified value.
Args:
val: A boolean value to check against the array's value.
Returns:
An integer of the number of bits in the array equal to val.
"""
return sum((elem.count(val... | Get the number of bits in the array with the specified value.
Args:
val: A boolean value to check against the array's value.
Returns:
An integer of the number of bits in the array equal to val. |
def get_min_inc_exc(self, inc_set=None, exc_set=None):
"""Get the user-specified Evidence codes. Return smaller set: include/exclude"""
if inc_set is None and exc_set is None:
return {}
inc = self.get_evcodes(inc_set, exc_set)
exc = set(self.code2nt.keys()).difference(inc)
... | Get the user-specified Evidence codes. Return smaller set: include/exclude |
def percent_encode(text, encode_set=DEFAULT_ENCODE_SET, encoding='utf-8'):
'''Percent encode text.
Unlike Python's ``quote``, this function accepts a blacklist instead of
a whitelist of safe characters.
'''
byte_string = text.encode(encoding)
try:
mapping = _percent_encoder_map_cache[e... | Percent encode text.
Unlike Python's ``quote``, this function accepts a blacklist instead of
a whitelist of safe characters. |
def periodic_callback(self):
"""Periodic cleanup tasks to maintain this adapter, should be called every second
"""
if self.stopped:
return
# Check if we should start scanning again
if not self.scanning and len(self._connections) == 0 and self.connecting_count == 0:
... | Periodic cleanup tasks to maintain this adapter, should be called every second |
async def contains_albums(self, *albums: Sequence[Union[str, Album]]) -> List[bool]:
"""Check if one or more albums is already saved in the current Spotify user’s ‘Your Music’ library.
Parameters
----------
albums : Union[Album, str]
A sequence of artist objects or spotify I... | Check if one or more albums is already saved in the current Spotify user’s ‘Your Music’ library.
Parameters
----------
albums : Union[Album, str]
A sequence of artist objects or spotify IDs |
def main(dimension, iterations):
""" Main function to execute gbest GC PSO algorithm.
"""
objective_function = minimize(functions.sphere)
stopping_condition = max_iterations(iterations)
(solution, metrics) = optimize(objective_function=objective_function,
domain=Do... | Main function to execute gbest GC PSO algorithm. |
def Engauge_2d_parser(lines, flat=False):
'''Not exposed function to read a 2D file generated by engauge-digitizer;
for curve fitting.
'''
z_values = []
x_lists = []
y_lists = []
working_xs = []
working_ys = []
new_curve = True
for line in lines:
if line.strip() == '... | Not exposed function to read a 2D file generated by engauge-digitizer;
for curve fitting. |
def index(self, config):
"""
Traverse the reports config definition and instantiate reportlets.
This method also places figures in their final location.
"""
for subrep_cfg in config:
# First determine whether we need to split by some ordering
# (ie. sessio... | Traverse the reports config definition and instantiate reportlets.
This method also places figures in their final location. |
def dict2DingoObjDict(data):
"""
Turn a dictionary of the form used by DINGO
(i.e., a key is mapped to either another dictionary,
a list or a value) into a DingoObjDict.
"""
info_tuple = dict2tuple(data)
info_dict = tuple2dict(info_tuple, constructor=DingoObjDict)
return info_dict | Turn a dictionary of the form used by DINGO
(i.e., a key is mapped to either another dictionary,
a list or a value) into a DingoObjDict. |
def _next_unscanned_addr(self, alignment=None):
"""
Find the next address that we haven't processed
:param alignment: Assures the address returns must be aligned by this number
:return: An address to process next, or None if all addresses have been processed
"""
# TODO:... | Find the next address that we haven't processed
:param alignment: Assures the address returns must be aligned by this number
:return: An address to process next, or None if all addresses have been processed |
def aes_encrypt(base64_encryption_key, data):
"""Encrypt data with AES-CBC and sign it with HMAC-SHA256
Arguments:
base64_encryption_key (str): a base64-encoded string containing an AES encryption key
and HMAC signing key as generated by generate_encryption_key()
data (str): a byte ... | Encrypt data with AES-CBC and sign it with HMAC-SHA256
Arguments:
base64_encryption_key (str): a base64-encoded string containing an AES encryption key
and HMAC signing key as generated by generate_encryption_key()
data (str): a byte string containing the data to be encrypted
Retur... |
def count(self, val):
"""Return the number of occurrences of *val* in the list."""
# pylint: disable=arguments-differ
_maxes = self._maxes
if not _maxes:
return 0
pos_left = bisect_left(_maxes, val)
if pos_left == len(_maxes):
return 0
... | Return the number of occurrences of *val* in the list. |
def adapt_array(arr):
"""
http://stackoverflow.com/a/31312102/190597 (SoulNibbler)
"""
out = io.BytesIO()
np.save(out, arr)
out.seek(0)
return sqlite3.Binary(out.read()) | http://stackoverflow.com/a/31312102/190597 (SoulNibbler) |
def serialize_number(x, fmt=SER_BINARY, outlen=None):
""" Serializes `x' to a string of length `outlen' in format `fmt' """
ret = b''
if fmt == SER_BINARY:
while x:
x, r = divmod(x, 256)
ret = six.int2byte(int(r)) + ret
if outlen is not None:
assert len(re... | Serializes `x' to a string of length `outlen' in format `fmt' |
def setupDock(self):
"""Setup empty Dock at startup. """
self.dock = QtWidgets.QDockWidget("Classes", self)
self.dock.setWidget(self.tree)
self.dock.setFeatures(QtWidgets.QDockWidget.NoDockWidgetFeatures)
self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.dock) | Setup empty Dock at startup. |
def get_damage(self, amount: int, target) -> int:
"""
Override to modify the damage dealt to a target from the given amount.
"""
if target.immune:
self.log("%r is immune to %s for %i damage", target, self, amount)
return 0
return amount | Override to modify the damage dealt to a target from the given amount. |
def _check_file_syntax(filename, temp_dir, override_lang=None, enforce=True):
"""
Checks that the code in FILENAME parses, attempting to autodetect
the language if necessary.
Raises IOError if the file cannot be read.
Raises DXSyntaxError if there is a problem and "enforce" is True.
"""
de... | Checks that the code in FILENAME parses, attempting to autodetect
the language if necessary.
Raises IOError if the file cannot be read.
Raises DXSyntaxError if there is a problem and "enforce" is True. |
def quiver(
x,
y,
z,
u,
v,
w,
size=default_size * 10,
size_selected=default_size_selected * 10,
color=default_color,
color_selected=default_color_selected,
marker="arrow",
**kwargs
):
"""Create a quiver plot, which is like a scatter plot but with arrows pointing in th... | Create a quiver plot, which is like a scatter plot but with arrows pointing in the direction given by u, v and w.
:param x: {x}
:param y: {y}
:param z: {z}
:param u: {u_dir}
:param v: {v_dir}
:param w: {w_dir}
:param size: {size}
:param size_selected: like size, but for selected glyphs
... |
def make_list(obj, cast=True):
"""
Converts an object *obj* to a list and returns it. Objects of types *tuple* and *set* are
converted if *cast* is *True*. Otherwise, and for all other types, *obj* is put in a new list.
"""
if isinstance(obj, list):
return list(obj)
if isinstance(obj, ty... | Converts an object *obj* to a list and returns it. Objects of types *tuple* and *set* are
converted if *cast* is *True*. Otherwise, and for all other types, *obj* is put in a new list. |
def interpolate_to_grid(x, y, z, interp_type='linear', hres=50000,
minimum_neighbors=3, gamma=0.25, kappa_star=5.052,
search_radius=None, rbf_func='linear', rbf_smooth=0,
boundary_coords=None):
r"""Interpolate given (x,y), observation (z) pairs... | r"""Interpolate given (x,y), observation (z) pairs to a grid based on given parameters.
Parameters
----------
x: array_like
x coordinate
y: array_like
y coordinate
z: array_like
observation value
interp_type: str
What type of interpolation to use. Available optio... |
def _print_pgfplot_libs_message(data):
"""Prints message to screen indicating the use of PGFPlots and its
libraries."""
pgfplotslibs = ",".join(list(data["pgfplots libs"]))
tikzlibs = ",".join(list(data["tikz libs"]))
print(70 * "=")
print("Please add the following lines to your LaTeX preamble:... | Prints message to screen indicating the use of PGFPlots and its
libraries. |
def _get_instance_repo(self, namespace):
"""
Returns the instance repository for the specified CIM namespace
within the mock repository. This is the original instance variable,
so any modifications will change the mock repository.
Validates that the namespace exists in the mock ... | Returns the instance repository for the specified CIM namespace
within the mock repository. This is the original instance variable,
so any modifications will change the mock repository.
Validates that the namespace exists in the mock repository.
If the instance repository does not cont... |
def _check_init(self, node):
"""check that the __init__ method call super or ancestors'__init__
method
"""
if not self.linter.is_message_enabled(
"super-init-not-called"
) and not self.linter.is_message_enabled("non-parent-init-called"):
return
kla... | check that the __init__ method call super or ancestors'__init__
method |
def create_vehicle_icon(self, name, colour, follow=False, vehicle_type=None):
'''add a vehicle to the map'''
from MAVProxy.modules.mavproxy_map import mp_slipmap
if vehicle_type is None:
vehicle_type = self.vehicle_type_name
if name in self.have_vehicle and self.have_vehicle[... | add a vehicle to the map |
def clear(self):
"""Clear variable nodes for next computation."""
for n in self.nodes():
if self.nodes[n]["type"] == "variable":
self.nodes[n]["value"] = None
elif self.nodes[n]["type"] == "function":
self.nodes[n]["func_visited"] = False | Clear variable nodes for next computation. |
def size(self) -> Optional[int]:
"""Size of the payload."""
if not self._parts:
return 0
total = 0
for part, encoding, te_encoding in self._parts:
if encoding or te_encoding or part.size is None:
return None
total += int(
... | Size of the payload. |
def _absf(ins):
''' Absolute value of top of the stack (48 bits)
'''
output = _float_oper(ins.quad[2])
output.append('res 7, e') # Just resets the sign bit!
output.extend(_fpush())
return output | Absolute value of top of the stack (48 bits) |
def fit(self, scores, y_true):
"""Train calibration
Parameters
----------
scores : (n_samples, ) array-like
Uncalibrated scores.
y_true : (n_samples, ) array-like
True labels (dtype=bool).
"""
# to force equal priors, randomly select (and... | Train calibration
Parameters
----------
scores : (n_samples, ) array-like
Uncalibrated scores.
y_true : (n_samples, ) array-like
True labels (dtype=bool). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.