code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def readColorLUT(infile, distance_modulus, mag_1, mag_2, mag_err_1, mag_err_2):
"""
Take in a color look-up table and return the signal color evaluated for each object.
Consider making the argument a Catalog object rather than magnitudes and uncertainties.
"""
reader = pyfits.open(infile)
dist... | Take in a color look-up table and return the signal color evaluated for each object.
Consider making the argument a Catalog object rather than magnitudes and uncertainties. |
def Group(params, name=None, type=None):
"""Groups together Params for adding under the 'What' section.
Args:
params(list of :func:`Param`): Parameter elements to go in this group.
name(str): Group name. NB ``None`` is valid, since the group may be
best identified by its type.
... | Groups together Params for adding under the 'What' section.
Args:
params(list of :func:`Param`): Parameter elements to go in this group.
name(str): Group name. NB ``None`` is valid, since the group may be
best identified by its type.
type(str): Type of group, e.g. 'complex' (for... |
def opendocx(file):
'''Open a docx file, return a document XML tree'''
mydoc = zipfile.ZipFile(file)
xmlcontent = mydoc.read('word/document.xml')
document = etree.fromstring(xmlcontent)
return document | Open a docx file, return a document XML tree |
def new_from_list(cls, content, fill_title=True, **kwargs):
"""Populates the Table with a list of tuples of strings.
Args:
content (list): list of tuples of strings. Each tuple is a row.
fill_title (bool): if true, the first tuple in the list will
be set as title... | Populates the Table with a list of tuples of strings.
Args:
content (list): list of tuples of strings. Each tuple is a row.
fill_title (bool): if true, the first tuple in the list will
be set as title |
def block(self, event, emptyEvents = ()):
'''
Return a recently popped event to queue, and block all later events until unblock.
Only the sub-queue directly containing the event is blocked, so events in other queues may still be processed.
It is illegal to call block and unblock... | Return a recently popped event to queue, and block all later events until unblock.
Only the sub-queue directly containing the event is blocked, so events in other queues may still be processed.
It is illegal to call block and unblock in different queues with a same event.
:para... |
def get_interpolated_data(df: pd.DataFrame, e_min=np.nan, e_max=np.nan, e_step=np.nan):
"""return the interpolated x and y axis for the given x range [e_min, e_max] with step defined
:param df: input data frame
:type df: pandas.DataFrame
:param e_min: left energy range in eV of new interpolated data
... | return the interpolated x and y axis for the given x range [e_min, e_max] with step defined
:param df: input data frame
:type df: pandas.DataFrame
:param e_min: left energy range in eV of new interpolated data
:type e_min: float
:param e_max: right energy range in eV of new interpolated data
:t... |
def choose_language(self, lang, request):
"""Deal with the multiple corner case of choosing the language."""
# Can be an empty string or None
if not lang:
lang = get_language_from_request(request)
# Raise a 404 if the language is not in not in the list
if lang not i... | Deal with the multiple corner case of choosing the language. |
def _apply_shadow_vars(avg_grads):
"""
Create shadow variables on PS, and replace variables in avg_grads
by these shadow variables.
Args:
avg_grads: list of (grad, var) tuples
"""
ps_var_grads = []
for grad, var in avg_grads:
assert var.na... | Create shadow variables on PS, and replace variables in avg_grads
by these shadow variables.
Args:
avg_grads: list of (grad, var) tuples |
async def reinvoke(self, *, call_hooks=False, restart=True):
"""|coro|
Calls the command again.
This is similar to :meth:`~.Context.invoke` except that it bypasses
checks, cooldowns, and error handlers.
.. note::
If you want to bypass :exc:`.UserInputError` derive... | |coro|
Calls the command again.
This is similar to :meth:`~.Context.invoke` except that it bypasses
checks, cooldowns, and error handlers.
.. note::
If you want to bypass :exc:`.UserInputError` derived exceptions,
it is recommended to use the regular :meth:`~.... |
def install_json_params(self, ij=None):
"""Return install.json params in a dict with name param as key.
Args:
ij (dict, optional): Defaults to None. The install.json contents.
Returns:
dict: A dictionary containing the install.json input params with name as key.
... | Return install.json params in a dict with name param as key.
Args:
ij (dict, optional): Defaults to None. The install.json contents.
Returns:
dict: A dictionary containing the install.json input params with name as key. |
def authenticate(self, driver):
"""Authenticate using the SSH protocol specific FSM."""
# 0 1 2 3
events = [driver.press_return_re, driver.password_re, self.device.prompt_re, pexpect.TIMEOUT]
transitions = [
... | Authenticate using the SSH protocol specific FSM. |
def ensure_local_repo(self):
"""Given a Dusty repo object, clone the remote into Dusty's local repos
directory if it does not already exist."""
if os.path.exists(self.managed_path):
logging.debug('Repo {} already exists'.format(self.remote_path))
return
logging.i... | Given a Dusty repo object, clone the remote into Dusty's local repos
directory if it does not already exist. |
def _dict_merge(dct, merge_dct):
"""Recursive dict merge.
Inspired by :meth:``dict.update()``, instead of updating only top-level
keys, dict_merge recurses down into dicts nested to an arbitrary depth,
updating keys. The ``merge_dct`` is merged into ``dct``.
From https://gist.github.com/angstwad/b... | Recursive dict merge.
Inspired by :meth:``dict.update()``, instead of updating only top-level
keys, dict_merge recurses down into dicts nested to an arbitrary depth,
updating keys. The ``merge_dct`` is merged into ``dct``.
From https://gist.github.com/angstwad/bf22d1822c38a92ec0a9
Arguments:
... |
def shell(name=None, **attrs):
"""Creates a new :class:`Shell` with a function as callback. This
works otherwise the same as :func:`command` just that the `cls`
parameter is set to :class:`Shell`.
"""
attrs.setdefault('cls', Shell)
return click.command(name, **attrs) | Creates a new :class:`Shell` with a function as callback. This
works otherwise the same as :func:`command` just that the `cls`
parameter is set to :class:`Shell`. |
def register_monitors(self, *monitors):
"""
Register monitors they should be tuple of name and Theano variable.
"""
for key, node in monitors:
if key not in self._registered_monitors:
node *= 1.0 # Avoid CudaNdarray
self.training_monitors.appen... | Register monitors they should be tuple of name and Theano variable. |
def generate(self, state, size, dataset, backward=False):
"""Generate a sequence.
Parameters
----------
state : `str` or `iterable` of `str`
Initial state.
size : `int`
State size.
dataset : `str`
Dataset key.
backward : `bool`... | Generate a sequence.
Parameters
----------
state : `str` or `iterable` of `str`
Initial state.
size : `int`
State size.
dataset : `str`
Dataset key.
backward : `bool`, optional
Link direction.
Returns
-----... |
def mutator(*cache_names):
"""Decorator for ``Document`` methods that change the document.
This decorator ensures that the object's caches are kept in sync
when changes are made.
"""
def deco(fn):
@wraps(fn)
def _fn(self, *args, **kwargs):
try:
return fn... | Decorator for ``Document`` methods that change the document.
This decorator ensures that the object's caches are kept in sync
when changes are made. |
def delete_dcnm_out_part(self, tenant_id, fw_dict, is_fw_virt=False):
"""Delete the DCNM OUT partition and update the result. """
res = fw_const.DCNM_OUT_PART_DEL_SUCCESS
tenant_name = fw_dict.get('tenant_name')
ret = True
try:
self._delete_partition(tenant_id, tenant... | Delete the DCNM OUT partition and update the result. |
def _init(self, clnt):
'''initialize api by YunpianClient'''
assert clnt, "clnt is None"
self._clnt = clnt
self._apikey = clnt.apikey()
self._version = clnt.conf(YP_VERSION, defval=VERSION_V2)
self._charset = clnt.conf(HTTP_CHARSET, defval=CHARSET_UTF8)
self._name... | initialize api by YunpianClient |
def anonymize_user(doc):
"""Preprocess an event by anonymizing user information.
The anonymization is done by removing fields that can uniquely identify a
user, such as the user's ID, session ID, IP address and User Agent, and
hashing them to produce a ``visitor_id`` and ``unique_session_id``. To
f... | Preprocess an event by anonymizing user information.
The anonymization is done by removing fields that can uniquely identify a
user, such as the user's ID, session ID, IP address and User Agent, and
hashing them to produce a ``visitor_id`` and ``unique_session_id``. To
further secure the method, a rand... |
def closest(self, dt1, dt2, *dts):
from functools import reduce
"""
Get the farthest date from the instance.
:type dt1: datetime.datetime
:type dt2: datetime.datetime
:type dts: list[datetime.datetime,]
:rtype: DateTime
"""
dt1 = pendulum.instan... | Get the farthest date from the instance.
:type dt1: datetime.datetime
:type dt2: datetime.datetime
:type dts: list[datetime.datetime,]
:rtype: DateTime |
async def start_pipe_server(
client_connected_cb,
*,
path,
loop=None,
limit=DEFAULT_LIMIT
):
"""
Start listening for connection using Windows named pipes.
"""
path = path.replace('/', '\\')
loop = loop or asyncio.get_event_loop()
def factory():
reader = asyncio.Strea... | Start listening for connection using Windows named pipes. |
def to_pytime(self):
"""
Converts sql time object into Python's time object
this will truncate nanoseconds to microseconds
@return: naive time
"""
nanoseconds = self._nsec
hours = nanoseconds // 1000000000 // 60 // 60
nanoseconds -= hours * 60 * 60 * 10000... | Converts sql time object into Python's time object
this will truncate nanoseconds to microseconds
@return: naive time |
def make_wrapper(self, callable_):
"""Given a free-standing function 'callable', return a new
callable that will call 'callable' and report all exceptins,
using 'call_and_report_errors'."""
assert callable(callable_)
def wrapper(*args, **kw):
return self.call_and_repo... | Given a free-standing function 'callable', return a new
callable that will call 'callable' and report all exceptins,
using 'call_and_report_errors'. |
def identify_hosting_service(repo_url, hosting_services=HOSTING_SERVICES):
"""
Determines the hosting service of `repo_url`.
:param repo_url: Repo URL of unknown type.
:returns: Hosting service or raises UnknownHostingService exception.
"""
repo_url = unicode(repo_url)
for service in hostin... | Determines the hosting service of `repo_url`.
:param repo_url: Repo URL of unknown type.
:returns: Hosting service or raises UnknownHostingService exception. |
def series2cat(df:DataFrame, *col_names):
"Categorifies the columns `col_names` in `df`."
for c in listify(col_names): df[c] = df[c].astype('category').cat.as_ordered() | Categorifies the columns `col_names` in `df`. |
def get_folder_id(folder_name, auth, url):
"""
Helper function takes str input of folder name and returns str numerical id of the folder.
:param folder_name: str name of the folder
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS in... | Helper function takes str input of folder name and returns str numerical id of the folder.
:param folder_name: str name of the folder
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
... |
def hex_digit(coord, digit=1):
"""
Returns either the first or second digit of the hexadecimal representation of the given coordinate.
:param coord: hexadecimal coordinate, int
:param digit: 1 or 2, meaning either the first or second digit of the hexadecimal
:return: int, either the first or second ... | Returns either the first or second digit of the hexadecimal representation of the given coordinate.
:param coord: hexadecimal coordinate, int
:param digit: 1 or 2, meaning either the first or second digit of the hexadecimal
:return: int, either the first or second digit |
def delete_country_by_id(cls, country_id, **kwargs):
"""Delete Country
Delete an instance of Country by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_country_by_id(country_id,... | Delete Country
Delete an instance of Country by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_country_by_id(country_id, async=True)
>>> result = thread.get()
:param a... |
def search_full(self, regex, return_string=True, advance_pointer=True):
"""
Search from the current position.
If `return_string` is false and a match is found, returns the number of
characters matched (from the current position *up to* the end of the
match).
>>> s =... | Search from the current position.
If `return_string` is false and a match is found, returns the number of
characters matched (from the current position *up to* the end of the
match).
>>> s = Scanner("test string")
>>> s.search_full(r' ')
'test '
... |
def get_validation_fields(self):
'''get_validation_fields returns a list of tuples (each a field)
we only require the exp_id to coincide with the folder name, for the sake
of reproducibility (given that all are served from sample image or Github
organization). All other fields a... | get_validation_fields returns a list of tuples (each a field)
we only require the exp_id to coincide with the folder name, for the sake
of reproducibility (given that all are served from sample image or Github
organization). All other fields are optional.
To specify runtime v... |
def to_list(var):
"""Checks if given value is a list, tries to convert, if it is not."""
if var is None:
return []
if isinstance(var, str):
var = var.split('\n')
elif not isinstance(var, list):
try:
var = list(var)
except TypeError:
raise ValueErro... | Checks if given value is a list, tries to convert, if it is not. |
def dispatch(self, request, *args, **kwargs):
"""
Redefine parent's method.
Called on each new request from user.
Main difference between Django's approach and ours - we don't push
a 'request' to a method call. We use 'self.request' instead.
"""
# this part copi... | Redefine parent's method.
Called on each new request from user.
Main difference between Django's approach and ours - we don't push
a 'request' to a method call. We use 'self.request' instead. |
def _configure(
self, target, conf=None, logger=None, callconf=None, keepstate=None,
modules=None
):
"""Configure this class with input conf only if auto_conf or
configure is true.
This method should be overriden for specific conf
:param target: object to co... | Configure this class with input conf only if auto_conf or
configure is true.
This method should be overriden for specific conf
:param target: object to configure. self targets by default.
:param Configuration conf: configuration model to configure. Default is
this conf.
... |
def process_streamer(self, streamer, callback=None):
"""Start streaming a streamer.
Args:
streamer (DataStreamer): The streamer itself.
callback (callable): An optional callable that will be called as:
callable(index, success, highest_id_received_from_other_side)... | Start streaming a streamer.
Args:
streamer (DataStreamer): The streamer itself.
callback (callable): An optional callable that will be called as:
callable(index, success, highest_id_received_from_other_side) |
def _ensure_like_indices(time, panels):
"""
Makes sure that time and panels are conformable.
"""
n_time = len(time)
n_panel = len(panels)
u_panels = np.unique(panels) # this sorts!
u_time = np.unique(time)
if len(u_time) == n_time:
time = np.tile(u_time, len(u_panels))
if le... | Makes sure that time and panels are conformable. |
def get_stop_words(self, language, fail_safe=False):
"""
Returns a StopWord object initialized with the stop words collection
requested by ``language``.
If the requested language is not available a StopWordError is raised.
If ``fail_safe`` is set to True, an empty StopWord object... | Returns a StopWord object initialized with the stop words collection
requested by ``language``.
If the requested language is not available a StopWordError is raised.
If ``fail_safe`` is set to True, an empty StopWord object is returned. |
def _to_r(o, as_data=False, level=0):
"""Helper function to convert python data structures to R equivalents
TODO: a single model for transforming to r to handle
* function args
* lists as function args
"""
if o is None:
return "NA"
if isinstance(o, basestring):
return o
... | Helper function to convert python data structures to R equivalents
TODO: a single model for transforming to r to handle
* function args
* lists as function args |
async def register(self, service):
"""Registers a new local service.
Returns:
bool: ``True`` on success
The register endpoint is used to add a new service,
with an optional health check, to the local agent.
The request body must look like::
{
... | Registers a new local service.
Returns:
bool: ``True`` on success
The register endpoint is used to add a new service,
with an optional health check, to the local agent.
The request body must look like::
{
"ID": "redis1",
"Name":... |
def display(self):
"""
Displays an overview containing descriptive stats for the Series
provided.
"""
print('Stats for %s from %s - %s' % (self.name, self.start, self.end))
if type(self.rf) is float:
print('Annual risk-free rate considered: %s' % (fmtp(self.rf... | Displays an overview containing descriptive stats for the Series
provided. |
def get_serialize_format(self, mimetype):
""" Get the serialization format for the given mimetype """
format = self.formats.get(mimetype, None)
if format is None:
format = formats.get(mimetype, None)
return format | Get the serialization format for the given mimetype |
def users(self, params):
"""
This is a private API and requires whitelisting from Twitter.
This endpoint will allow partners to add, update and remove users from a given
tailored_audience_id.
The endpoint will also accept multiple user identifier types per user as well.
... | This is a private API and requires whitelisting from Twitter.
This endpoint will allow partners to add, update and remove users from a given
tailored_audience_id.
The endpoint will also accept multiple user identifier types per user as well. |
def get_method_by_idx(self, idx):
"""
Return a specific method by using an index
:param idx: the index of the method
:type idx: int
:rtype: None or an :class:`EncodedMethod` object
"""
if self.__cached_methods_idx == None:
self.__cached_method... | Return a specific method by using an index
:param idx: the index of the method
:type idx: int
:rtype: None or an :class:`EncodedMethod` object |
def save_process():
'''process for saving a graph'''
from MAVProxy.modules.lib import wx_processguard
from MAVProxy.modules.lib.wx_loader import wx
from MAVProxy.modules.lib.wxgrapheditor import GraphDialog
app = wx.App(False)
frame = GraphDialog('Graph Editor',
mestate.l... | process for saving a graph |
def p_always(self, p):
'always : ALWAYS senslist always_statement'
p[0] = Always(p[2], p[3], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | always : ALWAYS senslist always_statement |
def simple_profile(self, sex=None):
"""
Generates a basic profile with personal informations
"""
SEX = ["F", "M"]
if sex not in SEX:
sex = self.random_element(SEX)
if sex == 'F':
name = self.generator.name_female()
elif sex == 'M':
... | Generates a basic profile with personal informations |
def get_taskfileinfo_selection(self, ):
"""Return a taskfileinfo that the user chose from the available options
:returns: the chosen taskfileinfo
:rtype: :class:`jukeboxcore.filesys.TaskFileInfo`
:raises: None
"""
sel = OptionSelector(self.reftrack)
sel.exec_()
... | Return a taskfileinfo that the user chose from the available options
:returns: the chosen taskfileinfo
:rtype: :class:`jukeboxcore.filesys.TaskFileInfo`
:raises: None |
def _get_all_data(self, start_date, end_date):
"""Get the needed data from all of the vars in the calculation."""
return [self._get_input_data(var, start_date, end_date)
for var in _replace_pressure(self.variables,
self.dtype_in_vert)] | Get the needed data from all of the vars in the calculation. |
def view_count(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/views#get-view-count"
api_path = "/api/v2/views/{id}/count.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/views#get-view-count |
def set_buffer(library, session, mask, size):
"""Sets the size for the formatted I/O and/or low-level I/O communication buffer(s).
Corresponds to viSetBuf function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:para... | Sets the size for the formatted I/O and/or low-level I/O communication buffer(s).
Corresponds to viSetBuf function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param mask: Specifies the type of buffer. (Constants.READ... |
def get(self, mac):
"""Get data from API as instance of ResponseModel.
Keyword arguments:
mac -- MAC address or OUI for searching
"""
data = {
self._FORMAT_F: 'json',
self._SEARCH_F: mac
}
response = self.__decode_str(self.__call... | Get data from API as instance of ResponseModel.
Keyword arguments:
mac -- MAC address or OUI for searching |
def path(self, goal):
"""Get the shortest way between two nodes of the graph
Args:
goal (str): Name of the targeted node
Return:
list of Node
"""
if goal == self.name:
return [self]
if goal not in self.routes:
raise ValueE... | Get the shortest way between two nodes of the graph
Args:
goal (str): Name of the targeted node
Return:
list of Node |
def read_files(path):
"""
For a directory full of files, retrieve it
as a dict with file_name:text
"""
template = {}
for file_name in os.listdir(path):
with open(os.path.join(path, file_name), 'r') as f:
template[file_name] = replace_whitespace(
f.read(), inse... | For a directory full of files, retrieve it
as a dict with file_name:text |
def delete_edge(self, ind_node, dep_node):
""" Delete an edge from the graph.
Args:
ind_node (str): The independent node to delete an edge from.
dep_node (str): The dependent node that has a dependency on the
ind_node.
Raises:
Key... | Delete an edge from the graph.
Args:
ind_node (str): The independent node to delete an edge from.
dep_node (str): The dependent node that has a dependency on the
ind_node.
Raises:
KeyError: Raised when the edge doesn't already exist. |
def dump_all_keys_or_addrs(wallet_obj):
'''
Offline-enabled mechanism to dump addresses
'''
print_traversal_warning()
puts('\nDo you understand this warning?')
if not confirm(user_prompt=DEFAULT_PROMPT, default=False):
puts(colored.red('Dump Cancelled!'))
return
mpub = wal... | Offline-enabled mechanism to dump addresses |
def _replace_auth_key(
user,
key,
enc='ssh-rsa',
comment='',
options=None,
config='.ssh/authorized_keys'):
'''
Replace an existing key
'''
auth_line = _format_auth_line(key, enc, comment, options or [])
lines = []
full = _get_config_file(user, co... | Replace an existing key |
def render(opts, functions, states=None, proxy=None, context=None):
'''
Returns the render modules
'''
if context is None:
context = {}
pack = {'__salt__': functions,
'__grains__': opts.get('grains', {}),
'__context__': context}
if states:
pack['__states... | Returns the render modules |
def build(self):
"""Generic entrypoint of `SymbolTableBuilder` class."""
self.load_builtins()
self.load_functions(self.tree)
self.visit(self.tree) | Generic entrypoint of `SymbolTableBuilder` class. |
def wait(self, timeout=None):
"""
Waits for the client to stop its loop
"""
self.__stopped.wait(timeout)
return self.__stopped.is_set() | Waits for the client to stop its loop |
def check(self, val):
"""Make sure given value is consistent with this `Key` specification.
NOTE: if `type` is 'None', then `listable` also is *not* checked.
"""
# If there is no `type` requirement, everything is allowed
if self.type is None:
return True
is_... | Make sure given value is consistent with this `Key` specification.
NOTE: if `type` is 'None', then `listable` also is *not* checked. |
def onStart(self, *args, **kwarg):
"""
Verify user input and kick off the client's program if valid
"""
with transactUI(self):
config = self.navbar.getActiveConfig()
config.resetErrors()
if config.isValid():
self.clientRunner.ru... | Verify user input and kick off the client's program if valid |
def get_datarect(self):
"""Get the approximate bounding box of the displayed image.
Returns
-------
rect : tuple
Bounding box in data coordinates in the form of
``(x1, y1, x2, y2)``.
"""
x1, y1, x2, y2 = self._org_x1, self._org_y1, self._org_x2, ... | Get the approximate bounding box of the displayed image.
Returns
-------
rect : tuple
Bounding box in data coordinates in the form of
``(x1, y1, x2, y2)``. |
def timezone(zone):
r''' Return a datetime.tzinfo implementation for the given timezone
>>> from datetime import datetime, timedelta
>>> utc = timezone('UTC')
>>> eastern = timezone('US/Eastern')
>>> eastern.zone
'US/Eastern'
>>> timezone(u'US/Eastern') is eastern
True
>>> utc_dt = ... | r''' Return a datetime.tzinfo implementation for the given timezone
>>> from datetime import datetime, timedelta
>>> utc = timezone('UTC')
>>> eastern = timezone('US/Eastern')
>>> eastern.zone
'US/Eastern'
>>> timezone(u'US/Eastern') is eastern
True
>>> utc_dt = datetime(2002, 10, 27, 6... |
def symmetric_difference_update(self, other):
"""
Throws out all intervals except those only in self or other,
not both.
"""
other = set(other)
ivs = list(self)
for iv in ivs:
if iv in other:
self.remove(iv)
other.remove... | Throws out all intervals except those only in self or other,
not both. |
def _update_model(self, completions):
"""
Creates a QStandardModel that holds the suggestion from the completion
models for the QCompleter
:param completionPrefix:
"""
# build the completion model
cc_model = QtGui.QStandardItemModel()
self._tooltips.clear... | Creates a QStandardModel that holds the suggestion from the completion
models for the QCompleter
:param completionPrefix: |
def delete_subscription(self):
"""Delete subscription for this thread.
:returns: bool
"""
url = self._build_url('subscription', base_url=self._api)
return self._boolean(self._delete(url), 204, 404) | Delete subscription for this thread.
:returns: bool |
def _parse_metadata_and_message_count(response):
'''
Extracts approximate messages count header.
'''
metadata = _parse_metadata(response)
metadata.approximate_message_count = _to_int(response.headers.get('x-ms-approximate-messages-count'))
return metadata | Extracts approximate messages count header. |
def get_chunk_ranges(self, symbol, chunk_range=None, reverse=False):
"""
Returns a generator of (Start, End) tuples for each chunk in the symbol
Parameters
----------
symbol: str
the symbol for the given item in the DB
chunk_range: None, or a range object
... | Returns a generator of (Start, End) tuples for each chunk in the symbol
Parameters
----------
symbol: str
the symbol for the given item in the DB
chunk_range: None, or a range object
allows you to subset the chunks by range
reverse: boolean
re... |
def TimeField(formatter=types.DEFAULT_TIME_FORMAT, default=NOTHING,
required=True, repr=True, cmp=True, key=None):
"""
Create new time field on a model.
:param formatter: time formatter string (default: "%H:%M:%S")
:param default: any time or string that can be converted to a time value
... | Create new time field on a model.
:param formatter: time formatter string (default: "%H:%M:%S")
:param default: any time or string that can be converted to a time value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in obje... |
def newCatalog(sgml):
"""create a new Catalog. """
ret = libxml2mod.xmlNewCatalog(sgml)
if ret is None:raise treeError('xmlNewCatalog() failed')
return catalog(_obj=ret) | create a new Catalog. |
def is_valid(self):
"""Return whether the current values of the form fields are all valid.
"""
self.cleaned_data = {}
self.changed_fields = []
self.validated = False
self._errors = {}
self._named_errors = {}
cleaned_data = {}
changed_fields = []
... | Return whether the current values of the form fields are all valid. |
def readValuesPyBigWig(self, reference, start, end):
"""
Use pyBigWig package to read a BigWig file for the
given range and return a protocol object.
pyBigWig returns an array of values that fill the query range.
Not sure if it is possible to get the step and span.
This... | Use pyBigWig package to read a BigWig file for the
given range and return a protocol object.
pyBigWig returns an array of values that fill the query range.
Not sure if it is possible to get the step and span.
This method trims NaN values from the start and end.
pyBigWig throws... |
def closeEvent(self, event):
"""Handles closing of the window. If configs were edited, ask user to continue.
:param event: the close event
:type event: QCloseEvent
:returns: None
:rtype: None
:raises: None
"""
if self.inimodel.get_edited():
r ... | Handles closing of the window. If configs were edited, ask user to continue.
:param event: the close event
:type event: QCloseEvent
:returns: None
:rtype: None
:raises: None |
def on_trial_result(self, trial_runner, trial, result):
"""If bracket is finished, all trials will be stopped.
If a given trial finishes and bracket iteration is not done,
the trial will be paused and resources will be given up.
This scheduler will not start trials but will stop trials... | If bracket is finished, all trials will be stopped.
If a given trial finishes and bracket iteration is not done,
the trial will be paused and resources will be given up.
This scheduler will not start trials but will stop trials.
The current running trial will not be handled,
as... |
def _upload_file_aws_cli(local_fname, bucket, keyname, config=None, mditems=None):
"""Streaming upload via the standard AWS command line interface.
"""
s3_fname = "s3://%s/%s" % (bucket, keyname)
args = ["--sse", "--expected-size", str(os.path.getsize(local_fname))]
if config:
if config.get(... | Streaming upload via the standard AWS command line interface. |
def get_mopheader(expnum, ccd, version='p', prefix=None):
"""
Retrieve the mopheader, either from cache or from vospace
@param expnum:
@param ccd:
@param version:
@param prefix:
@return: Header
"""
prefix = prefix is None and "" or prefix
mopheader_uri = dbimages_uri(expnum=expn... | Retrieve the mopheader, either from cache or from vospace
@param expnum:
@param ccd:
@param version:
@param prefix:
@return: Header |
def define_charset(self, code, mode):
"""Define ``G0`` or ``G1`` charset.
:param str code: character set code, should be a character
from ``"B0UK"``, otherwise ignored.
:param str mode: if ``"("`` ``G0`` charset is defined, if
``")"`` -- we oper... | Define ``G0`` or ``G1`` charset.
:param str code: character set code, should be a character
from ``"B0UK"``, otherwise ignored.
:param str mode: if ``"("`` ``G0`` charset is defined, if
``")"`` -- we operate on ``G1``.
.. warning:: User-defined... |
def get_patient_mhc_haplotype(job, patient_dict):
"""
Convenience function to get the mhc haplotype from the patient dict
:param dict patient_dict: dict of patient info
:return: The MHCI and MHCII haplotypes
:rtype: toil.fileStore.FileID
"""
haplotype_archive = job.fileStore.readGlobalFile(... | Convenience function to get the mhc haplotype from the patient dict
:param dict patient_dict: dict of patient info
:return: The MHCI and MHCII haplotypes
:rtype: toil.fileStore.FileID |
def _compute_error(self):
""" Evaluate the absolute error of the Nystroem approximation for each column """
# err_i = sum_j R_{k,ij} A_{k,ji} - d_i
self._err = np.sum(np.multiply(self._R_k, self._C_k.T), axis=0) - self._d | Evaluate the absolute error of the Nystroem approximation for each column |
def aliased_slot_names(self, slot_names: List[SlotDefinitionName]) -> Set[str]:
""" Return the aliased slot names for all members of the list
@param slot_names: actual slot names
@return: aliases w/ duplicates removed
"""
return {self.aliased_slot_name(sn) for sn in slot_names} | Return the aliased slot names for all members of the list
@param slot_names: actual slot names
@return: aliases w/ duplicates removed |
def read(self):
'''Read some number of messages'''
found = Client.read(self)
# Redistribute our ready state if necessary
if self.needs_distribute_ready():
self.distribute_ready()
# Finally, return all the results we've read
return found | Read some number of messages |
def associate(self, id_option_vip, id_environment_vip):
"""Create a relationship of OptionVip with EnvironmentVip.
:param id_option_vip: Identifier of the Option VIP. Integer value and greater than zero.
:param id_environment_vip: Identifier of the Environment VIP. Integer value and greater tha... | Create a relationship of OptionVip with EnvironmentVip.
:param id_option_vip: Identifier of the Option VIP. Integer value and greater than zero.
:param id_environment_vip: Identifier of the Environment VIP. Integer value and greater than zero.
:return: Following dictionary
::
... |
def cleanup(self):
'''
remove sockets on shutdown
'''
log.debug('ConCache cleaning up')
if os.path.exists(self.cache_sock):
os.remove(self.cache_sock)
if os.path.exists(self.update_sock):
os.remove(self.update_sock)
if os.path.exists(self.u... | remove sockets on shutdown |
def validate(self, result, spec): # noqa Yes, it's too complex.
"""Validate that the result has the correct structure."""
if spec is None:
# None matches anything.
return
if isinstance(spec, dict):
if not isinstance(result, dict):
raise ValueE... | Validate that the result has the correct structure. |
def sourcehook(self, newfile, encoding='utf-8'):
"Hook called on a filename to be sourced."
from codecs import open
if newfile[0] == '"':
newfile = newfile[1:-1]
# This implements cpp-like semantics for relative-path inclusion.
if isinstance(self.infile, basestr... | Hook called on a filename to be sourced. |
def setup_logging(fail_silently=False):
"""
Setup logging configuration
Finds the most user-facing log config on disk and uses it
"""
config = None
paths = list(get_config_paths(filename='logconfig.yml', reversed=True))
for path in paths:
if not os.path.exists(path):
co... | Setup logging configuration
Finds the most user-facing log config on disk and uses it |
def check(self, password: str) -> bool:
"""
Checks the given password with the one stored
in the database
"""
return (
pbkdf2_sha512.verify(password, self.password) or
pbkdf2_sha512.verify(password,
pbkdf2_sha512.encrypt(se... | Checks the given password with the one stored
in the database |
def add_trial(self, trial):
"""Adds a new trial to this TrialRunner.
Trials may be added at any time.
Args:
trial (Trial): Trial to queue.
"""
trial.set_verbose(self._verbose)
self._trials.append(trial)
with warn_if_slow("scheduler.on_trial_add"):
... | Adds a new trial to this TrialRunner.
Trials may be added at any time.
Args:
trial (Trial): Trial to queue. |
def summary_plot(
pymc_obj, name='model', format='png', suffix='-summary', path='./',
alpha=0.05, chain=None, quartiles=True, hpd=True, rhat=True, main=None,
xlab=None, x_range=None, custom_labels=None, chain_spacing=0.05, vline_pos=0):
"""
Model summary plot
Generates a "forest plot" of 100*(1... | Model summary plot
Generates a "forest plot" of 100*(1-alpha)% credible intervals for either the
set of nodes in a given model, or a specified set of nodes.
:Arguments:
pymc_obj: PyMC object, trace or array
A trace from an MCMC sample or a PyMC object with one or more traces.
... |
def calibrate_counts(array, attributes, index):
"""Calibration for counts channels."""
offset = np.float32(attributes["corrected_counts_offsets"][index])
scale = np.float32(attributes["corrected_counts_scales"][index])
array = (array - offset) * scale
return array | Calibration for counts channels. |
def addresses(self):
"""
Access the addresses
:returns: twilio.rest.api.v2010.account.address.AddressList
:rtype: twilio.rest.api.v2010.account.address.AddressList
"""
if self._addresses is None:
self._addresses = AddressList(self._version, account_sid=self._... | Access the addresses
:returns: twilio.rest.api.v2010.account.address.AddressList
:rtype: twilio.rest.api.v2010.account.address.AddressList |
def unpickle(pickle_file):
"""Unpickle a python object from the given path."""
pickle = None
with open(pickle_file, "rb") as pickle_f:
pickle = dill.load(pickle_f)
if not pickle:
LOG.error("Could not load python object from file")
return pickle | Unpickle a python object from the given path. |
def interactions_iter(self, nbunch=None, t=None):
"""Return an iterator over the interaction present in a given snapshot.
Edges are returned as tuples
in the order (node, neighbor).
Parameters
----------
nbunch : iterable container, optional (default= all nodes)
... | Return an iterator over the interaction present in a given snapshot.
Edges are returned as tuples
in the order (node, neighbor).
Parameters
----------
nbunch : iterable container, optional (default= all nodes)
A container of nodes. The container will be iterated
... |
def appendMissingSignatures(self):
""" Store which accounts/keys are supposed to sign the transaction
This method is used for an offline-signer!
"""
missing_signatures = self.get("missing_signatures", [])
for pub in missing_signatures:
wif = self.blockchain.walle... | Store which accounts/keys are supposed to sign the transaction
This method is used for an offline-signer! |
def select_good_pixel_region(hits, col_span, row_span, min_cut_threshold=0.2, max_cut_threshold=2.0):
'''Takes the hit array and masks all pixels with a certain occupancy.
Parameters
----------
hits : array like
If dim > 2 the additional dimensions are summed up.
min_cut_threshold : float
... | Takes the hit array and masks all pixels with a certain occupancy.
Parameters
----------
hits : array like
If dim > 2 the additional dimensions are summed up.
min_cut_threshold : float
A number to specify the minimum threshold, which pixel to take. Pixels are masked if
occupancy... |
def get_default(self, ctx):
"""Given a context variable this calculates the default value."""
# Otherwise go with the regular default.
if callable(self.default):
rv = self.default()
else:
rv = self.default
return self.type_cast_value(ctx, rv) | Given a context variable this calculates the default value. |
def cleanup_sweep_threads():
'''
Not used. Keeping this function in case we decide not to use
daemonized threads and it becomes necessary to clean up the
running threads upon exit.
'''
for dict_name, obj in globals().items():
if isinstance(obj, (TimedDict,)):
logging.info(
... | Not used. Keeping this function in case we decide not to use
daemonized threads and it becomes necessary to clean up the
running threads upon exit. |
def explain_feature(featurename):
'''print the location of single feature and its version
if the feature is located inside a git repository,
this will also print the git-rev and modified files
'''
import os
import featuremonkey
import importlib
import subprocess
def guess_version(... | print the location of single feature and its version
if the feature is located inside a git repository,
this will also print the git-rev and modified files |
def update(self, status=values.unset, announce_url=values.unset,
announce_method=values.unset):
"""
Update the ConferenceInstance
:param ConferenceInstance.UpdateStatus status: The new status of the resource
:param unicode announce_url: The URL we should call to announce ... | Update the ConferenceInstance
:param ConferenceInstance.UpdateStatus status: The new status of the resource
:param unicode announce_url: The URL we should call to announce something into the conference
:param unicode announce_method: he HTTP method used to call announce_url
:returns: U... |
def fix_e224(self, result):
"""Remove extraneous whitespace around operator."""
target = self.source[result['line'] - 1]
offset = result['column'] - 1
fixed = target[:offset] + target[offset:].replace('\t', ' ')
self.source[result['line'] - 1] = fixed | Remove extraneous whitespace around operator. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.