positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def ingest(self, co, classname=None, code_objects={}, show_asm=None):
"""
Pick out tokens from an uncompyle6 code object, and transform them,
returning a list of uncompyle6 Token's.
The transformations are made to assist the deparsing grammar.
"""
tokens, customize = sca... | Pick out tokens from an uncompyle6 code object, and transform them,
returning a list of uncompyle6 Token's.
The transformations are made to assist the deparsing grammar. |
def autoscale_eydata(self):
"""
Rescales the error so the next fit will give reduced chi squareds of 1.
Each data set will be scaled independently, and you may wish to run
this a few times until it converges.
"""
if not self.results:
self._error("You must com... | Rescales the error so the next fit will give reduced chi squareds of 1.
Each data set will be scaled independently, and you may wish to run
this a few times until it converges. |
def engagement_context(self):
"""
Access the engagement_context
:returns: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextList
:rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextList
"""
if self._engagement_context... | Access the engagement_context
:returns: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextList
:rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextList |
def _set_neighbor_route_map_name_direction_out(self, v, load=False):
"""
Setter method for neighbor_route_map_name_direction_out, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/ipv6/ipv6_unicast/af_ipv6_vrf/neighbor/af_ipv6_vrf_neighbor_address_holder/af_ipv6_neighbor_addr/neighbor_route... | Setter method for neighbor_route_map_name_direction_out, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/ipv6/ipv6_unicast/af_ipv6_vrf/neighbor/af_ipv6_vrf_neighbor_address_holder/af_ipv6_neighbor_addr/neighbor_route_map/neighbor_route_map_direction_out/neighbor_route_map_name_direction_out (comm... |
def build(self, _resource, _cache=True, updatecontent=True, **kwargs):
"""Build a schema class from input _resource.
:param _resource: object from where get the right schema.
:param bool _cache: use _cache system.
:param bool updatecontent: if True (default) update result.
:rtyp... | Build a schema class from input _resource.
:param _resource: object from where get the right schema.
:param bool _cache: use _cache system.
:param bool updatecontent: if True (default) update result.
:rtype: Schema. |
def get_trail_ids(cls, event, mode):
"""extract resources ids from a cloud trail event."""
resource_ids = ()
event_name = event['detail']['eventName']
event_source = event['detail']['eventSource']
for e in mode.get('events', []):
if not isinstance(e, dict):
... | extract resources ids from a cloud trail event. |
def copy(tree, source_filename):
""" Copy file in tree, show a progress bar during operations,
and return the sha1 sum of copied file.
"""
#_, ext = os.path.splitext(source_filename)
filehash = sha1()
with printer.progress(os.path.getsize(source_filename)) as update:
with open(source... | Copy file in tree, show a progress bar during operations,
and return the sha1 sum of copied file. |
def select_station(
candidates,
coverage_range=None,
min_fraction_coverage=0.9,
distance_warnings=(50000, 200000),
rank=1,
):
""" Select a station from a list of candidates that meets given data
quality criteria.
Parameters
----------
candidates : :any:`pandas.DataFrame`
... | Select a station from a list of candidates that meets given data
quality criteria.
Parameters
----------
candidates : :any:`pandas.DataFrame`
A dataframe of the form given by :any:`eeweather.rank_stations` or
:any:`eeweather.combine_ranked_stations`, specifically having at least
... |
def get_conda_path():
"""
Return anaconda or miniconda directory
:return: anaconda directory
"""
dstdir = ''
# try:
import subprocess
import re
# cond info --root work only for root environment
# p = subprocess.Popen(['conda', 'info', '--root'], stdout=subprocess.PIPE, stderr=s... | Return anaconda or miniconda directory
:return: anaconda directory |
def populate_from_path(bucket, source, checksum=True, key_prefix='',
chunk_size=None):
"""Populate a ``bucket`` from all files in path.
:param bucket: The bucket (instance or id) to create the object in.
:param source: The file or directory path.
:param checksum: If ``True`` then... | Populate a ``bucket`` from all files in path.
:param bucket: The bucket (instance or id) to create the object in.
:param source: The file or directory path.
:param checksum: If ``True`` then a MD5 checksum will be computed for each
file. (Default: ``True``)
:param key_prefix: The key prefix for... |
def to_html(self, buf=None, columns=None, col_space=None, header=True,
index=True, na_rep='NaN', formatters=None, float_format=None,
sparsify=None, index_names=True, justify=None, max_rows=None,
max_cols=None, show_dimensions=False, decimal='.',
bold_rows=... | Render a DataFrame as an HTML table.
%(shared_params)s
bold_rows : bool, default True
Make the row labels bold in the output.
classes : str or list or tuple, default None
CSS class(es) to apply to the resulting html table.
escape : bool, default True
C... |
def create_blazar_client(config, session):
"""Check the reservation, creates a new one if nescessary."""
return blazar_client.Client(session=session,
service_type="reservation",
region_name=os.environ["OS_REGION_NAME"]) | Check the reservation, creates a new one if nescessary. |
def shapes_match(a, b):
"""Recursively check if shapes of object `a` and `b` match.
Will walk lists, tuples and dicts.
Args:
a: object of type (numpy.ndarray,tf.Tensor,list,tuple,dict)
to check for matching shapes against `b`.
b: object to check for matching shape against `a`.
Returns:
A ... | Recursively check if shapes of object `a` and `b` match.
Will walk lists, tuples and dicts.
Args:
a: object of type (numpy.ndarray,tf.Tensor,list,tuple,dict)
to check for matching shapes against `b`.
b: object to check for matching shape against `a`.
Returns:
A boolean indicating whether th... |
def set_existing_extra_keywords(self):
"""Set extra keywords from the value from metadata."""
extra_keywords = self.parent.get_existing_keyword('extra_keywords')
for key, widgets in list(self.widgets_dict.items()):
value = extra_keywords.get(key)
if value is None:
... | Set extra keywords from the value from metadata. |
def item_selection_changed(self):
"""Item selection has changed"""
is_selection = len(self.selectedItems()) > 0
self.expand_selection_action.setEnabled(is_selection)
self.collapse_selection_action.setEnabled(is_selection) | Item selection has changed |
def zoom_out_pixel(self, curr_pixel):
""" return the curr_frag at a lower resolution"""
low_frag = curr_pixel[0]
high_frag = curr_pixel[1]
level = curr_pixel[2]
str_level = str(level)
if level < self.n_level - 1:
low_super = self.spec_level[str_level]["fragmen... | return the curr_frag at a lower resolution |
def pylxd_save_object(obj):
''' Saves an object (profile/image/container) and
translate its execpetion on failure
obj :
The object to save
This is an internal method, no CLI Example.
'''
try:
obj.save()
except pylxd.exceptions.LXDAPIException as e:
raise Command... | Saves an object (profile/image/container) and
translate its execpetion on failure
obj :
The object to save
This is an internal method, no CLI Example. |
def check_dtype(array, allowed):
"""Raises TypeError if the array is not of an allowed dtype.
:param array: array whose dtype is to be checked
:param allowed: instance or list of allowed dtypes
"""
if not hasattr(allowed, "__iter__"):
allowed = [allowed,]
if array.dtype not in allowed:
... | Raises TypeError if the array is not of an allowed dtype.
:param array: array whose dtype is to be checked
:param allowed: instance or list of allowed dtypes |
def list_config_variables(self, offset):
"""List defined config variables up to 9 at a time."""
names = sorted(self._config_variables)
names = names[offset:offset + 9]
count = len(names)
if len(names) < 9:
names += [0]*(9 - count)
return [count] + names | List defined config variables up to 9 at a time. |
def get_sub_rectangles(self, ims):
""" get_sub_rectangles(ims)
Calculate the minimal rectangles that need updating each frame.
Returns a two-element tuple containing the cropped images and a
list of x-y positions.
Calculating the subrectangles takes extra time, obviously. Howev... | get_sub_rectangles(ims)
Calculate the minimal rectangles that need updating each frame.
Returns a two-element tuple containing the cropped images and a
list of x-y positions.
Calculating the subrectangles takes extra time, obviously. However,
if the image sizes were reduced, th... |
def write(self, text):
"""Write text. An additional attribute terminator with a value of
None is added to the logging record to indicate that StreamHandler
should not add a newline."""
self.logger.log(self.loglevel, text, extra={'terminator': None}) | Write text. An additional attribute terminator with a value of
None is added to the logging record to indicate that StreamHandler
should not add a newline. |
def _enumload(l: Loader, value, type_) -> Enum:
"""
This loads something into an Enum.
It tries with basic types first.
If that fails, it tries to look for type annotations inside the
Enum, and tries to use those to load the value into something
that is compatible with the Enum.
Of course... | This loads something into an Enum.
It tries with basic types first.
If that fails, it tries to look for type annotations inside the
Enum, and tries to use those to load the value into something
that is compatible with the Enum.
Of course if that fails too, a ValueError is raised. |
def p_OptionalOrRequiredArgument_optional(p):
"""OptionalOrRequiredArgument : optional Type IDENTIFIER Default"""
p[0] = model.OperationArgument(
type=p[2], name=p[3], optional=True, default=p[4]) | OptionalOrRequiredArgument : optional Type IDENTIFIER Default |
def backup(schema, uuid, export_filter, export_format, filename, pretty, export_all, omit):
"""Exports all collections to (JSON-) files."""
export_format = export_format.upper()
if pretty:
indent = 4
else:
indent = 0
f = None
if filename:
try:
f = open(fil... | Exports all collections to (JSON-) files. |
def ifelse(arg, true_expr, false_expr):
"""
Shorthand for implementing ternary expressions
bool_expr.ifelse(0, 1)
e.g., in SQL: CASE WHEN bool_expr THEN 0 else 1 END
"""
# Result will be the result of promotion of true/false exprs. These
# might be conflicting types; same type resolution as... | Shorthand for implementing ternary expressions
bool_expr.ifelse(0, 1)
e.g., in SQL: CASE WHEN bool_expr THEN 0 else 1 END |
def _separate_exclude_cases(name, exclude_prefix):
""" Splits the excluded
Parameters
----------
name : str
Name of the country/region to convert.
exclude_prefix : list of valid regex strings
List of indicators which negate the subsequent country/region.... | Splits the excluded
Parameters
----------
name : str
Name of the country/region to convert.
exclude_prefix : list of valid regex strings
List of indicators which negate the subsequent country/region.
These prefixes and everything following will not b... |
def _format_feature(feature, weight, hl_spaces):
# type: (...) -> str
""" Format any feature.
"""
if isinstance(feature, FormattedFeatureName):
return feature.format()
elif (isinstance(feature, list) and
all('name' in x and 'sign' in x for x in feature)):
return _format_u... | Format any feature. |
def full_name(self):
"""Return full name of member"""
if self.prefix is not None:
return '.'.join([self.prefix, self.member])
return self.member | Return full name of member |
def omerc2cf(area):
"""Return the cf grid mapping for the omerc projection."""
proj_dict = area.proj_dict
args = dict(azimuth_of_central_line=proj_dict.get('alpha'),
latitude_of_projection_origin=proj_dict.get('lat_0'),
longitude_of_projection_origin=proj_dict.get('lonc'),
... | Return the cf grid mapping for the omerc projection. |
def _R2deriv(self,R,z,phi=0.,t=0.):
"""
NAME:
_R2deriv
PURPOSE:
evaluate the second radial derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPU... | NAME:
_R2deriv
PURPOSE:
evaluate the second radial derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
the second radial derivative
HISTO... |
def statistical_axes(fit, **kw):
"""
Hyperbolic error using a statistical process (either sampling
or noise errors)
Integrates covariance with error level
and degrees of freedom for plotting
confidence intervals.
Degrees of freedom is set to 2, which is the
relevant number of independe... | Hyperbolic error using a statistical process (either sampling
or noise errors)
Integrates covariance with error level
and degrees of freedom for plotting
confidence intervals.
Degrees of freedom is set to 2, which is the
relevant number of independent dimensions
to planar fitting of *a pri... |
def get_url_map():
"""
Loads custom/pypi/map.txt and builds a dict where map[package_name] = url
:return: dict, urls
"""
map = {}
path = os.path.join(
os.path.dirname(os.path.realpath(__file__)), # current working dir ../
"custom", # ../custom/
"pypi", # ../custom/pypi... | Loads custom/pypi/map.txt and builds a dict where map[package_name] = url
:return: dict, urls |
def get_d1str(self, goobj, reverse=False):
"""Get D1-string representing all parent terms which are depth-01 GO terms."""
return "".join(sorted(self.get_parents_letters(goobj), reverse=reverse)) | Get D1-string representing all parent terms which are depth-01 GO terms. |
def close(self, for_shutdown=False, **_kwargs):
"""
Only call super().close() if the server is shutting down (not between requests).
:param for_shutdown: If `False` (the default)
"""
if for_shutdown:
super(PySOAPyLibMCCache, self).close() | Only call super().close() if the server is shutting down (not between requests).
:param for_shutdown: If `False` (the default) |
def visit_spires_keyword_query(self, node):
"""Transform a :class:`SpiresKeywordQuery` into a :class:`KeywordOp`.
Notes:
In case the value being a :class:`SimpleValueBooleanQuery`, the subtree is transformed to chained
:class:`AndOp` queries containing :class:`KeywordOp`, whose ... | Transform a :class:`SpiresKeywordQuery` into a :class:`KeywordOp`.
Notes:
In case the value being a :class:`SimpleValueBooleanQuery`, the subtree is transformed to chained
:class:`AndOp` queries containing :class:`KeywordOp`, whose keyword is the keyword of the current node and
... |
def session_scope(session_cls=None):
"""Provide a transactional scope around a series of operations."""
session = session_cls() if session_cls else Session()
try:
yield session
session.commit()
except Exception:
session.rollback()
raise
finally:
session.close(... | Provide a transactional scope around a series of operations. |
def isset(alias_name):
"""Return a boolean if the docker link is set or not and is a valid looking docker link value.
Args:
alias_name: The link alias name
"""
warnings.warn('Will be removed in v1.0', DeprecationWarning, stacklevel=2)
raw_value = read(alias_name, allow_none=True)
if raw... | Return a boolean if the docker link is set or not and is a valid looking docker link value.
Args:
alias_name: The link alias name |
def get_cluster_graph(self, engine="fdp", graph_attr=None, node_attr=None, edge_attr=None):
"""
Generate directory graph in the DOT language. Directories are shown as clusters
.. warning::
This function scans the entire directory tree starting from top so the resulting
... | Generate directory graph in the DOT language. Directories are shown as clusters
.. warning::
This function scans the entire directory tree starting from top so the resulting
graph can be really big.
Args:
engine: Layout command used. ['dot', 'neato', 'twopi', 'circ... |
def visual(title, X, activation):
'''create a grid of images and save it as a final image
title : grid image name
X : array of images
'''
assert len(X.shape) == 4
X = X.transpose((0, 2, 3, 1))
if activation == 'sigmoid':
X = np.clip((X)*(255.0), 0, 255).astype(np.uint8)
elif act... | create a grid of images and save it as a final image
title : grid image name
X : array of images |
def show_window_option(self, option, g=False):
"""
Return a list of options for the window.
todo: test and return True/False for on/off string
Parameters
----------
option : str
g : bool, optional
Pass ``-g`` flag, global. Default False.
Ret... | Return a list of options for the window.
todo: test and return True/False for on/off string
Parameters
----------
option : str
g : bool, optional
Pass ``-g`` flag, global. Default False.
Returns
-------
str, int
Raises
-----... |
def column_definition(table_name, col_name):
"""
Get the source of a column function.
If a column is a registered Series and not a function then all that is
returned is {'type': 'series'}.
If the column is a registered function then the JSON returned has keys
"type", "filename", "lineno", "tex... | Get the source of a column function.
If a column is a registered Series and not a function then all that is
returned is {'type': 'series'}.
If the column is a registered function then the JSON returned has keys
"type", "filename", "lineno", "text", and "html". "text" is the raw
text of the functio... |
def make_insert(cls, table, insert_tuple):
"""
[Deprecated] Make INSERT query.
:param str table: Table name of executing the query.
:param list/tuple insert_tuple: Insertion data.
:return: Query of SQLite.
:rtype: str
:raises ValueError: If ``insert_tuple`` is em... | [Deprecated] Make INSERT query.
:param str table: Table name of executing the query.
:param list/tuple insert_tuple: Insertion data.
:return: Query of SQLite.
:rtype: str
:raises ValueError: If ``insert_tuple`` is empty |list|/|tuple|.
:raises simplesqlite.NameValidation... |
def from_string(string_data, file_format="xyz"):
"""
Uses OpenBabel to read a molecule from a string in all supported
formats.
Args:
string_data: String containing molecule data.
file_format: String specifying any OpenBabel supported formats.
Returns:
... | Uses OpenBabel to read a molecule from a string in all supported
formats.
Args:
string_data: String containing molecule data.
file_format: String specifying any OpenBabel supported formats.
Returns:
BabelMolAdaptor object |
def search(query, index=INDEX_NAME, doc_type=DOC_TYPE):
"""
Thin wrapper of the main query function to provide just the resulting objects
"""
results = raw_query(query, index=index, doc_type=doc_type)
return [r['_source'] for r in results] | Thin wrapper of the main query function to provide just the resulting objects |
def where_entry_tag(query, tag):
""" Generate a where clause for entries with the given tag """
if isinstance(tag, (list, set, tuple)):
tags = [t.lower() for t in tag]
return orm.select(e for e in query for t in e.tags if t.key in tags)
return orm.select(e for e in query for t in e.tags if t... | Generate a where clause for entries with the given tag |
def uniprot_ec(uniprot_id):
"""Retrieve the EC number annotation for a UniProt ID.
Args:
uniprot_id: Valid UniProt ID
Returns:
"""
r = requests.post('http://www.uniprot.org/uniprot/?query=%s&columns=ec&format=tab' % uniprot_id)
ec = r.content.decode('utf-8').splitlines()[1]
if le... | Retrieve the EC number annotation for a UniProt ID.
Args:
uniprot_id: Valid UniProt ID
Returns: |
def get_page_full(self, page_id):
""" Get full page info and full html code """
try:
result = self._request('/getpagefull/',
{'pageid': page_id})
return TildaPage(**result)
except NetworkError:
return [] | Get full page info and full html code |
def _calculate(self, startingPercentage, endPercentage, startDate, endDate):
"""This is the error calculation function that gets called by :py:meth:`BaseErrorMeasure.get_error`.
Both parameters will be correct at this time.
:param float startingPercentage: Defines the start of the interval. Th... | This is the error calculation function that gets called by :py:meth:`BaseErrorMeasure.get_error`.
Both parameters will be correct at this time.
:param float startingPercentage: Defines the start of the interval. This has to be a value in [0.0, 100.0].
It represents the value, where the err... |
def ensure_hexadecimal_string(self, value, command=None):
"""
Make sure the given value is a hexadecimal string.
:param value: The value to check (a string).
:param command: The command that produced the value (a string or :data:`None`).
:returns: The validated hexadecimal strin... | Make sure the given value is a hexadecimal string.
:param value: The value to check (a string).
:param command: The command that produced the value (a string or :data:`None`).
:returns: The validated hexadecimal string.
:raises: :exc:`~exceptions.ValueError` when `value` is not a hexade... |
def integer_entry(self, prompt, message=None, min=None, max=None, rofi_args=None, **kwargs):
"""Prompt the user to enter an integer.
Parameters
----------
prompt: string
Prompt to display to the user.
message: string, optional
Message to display under the... | Prompt the user to enter an integer.
Parameters
----------
prompt: string
Prompt to display to the user.
message: string, optional
Message to display under the entry line.
min, max: integer, optional
Minimum and maximum values to allow. If Non... |
def powmod(a, b, c):
"""
Uses GMP, if available, to do a^b mod c where a, b, c
are integers.
:return int: (a ** b) % c
"""
if a == 1:
return 1
if not HAVE_GMP or max(a, b, c) < _USE_MOD_FROM_GMP_SIZE:
return pow(a, b, c)
else:
return int(gmpy2.powmod(a, b, c)) | Uses GMP, if available, to do a^b mod c where a, b, c
are integers.
:return int: (a ** b) % c |
def getClsNames(item):
'''
Return a list of "fully qualified" class names for an instance.
Example:
for name in getClsNames(foo):
print(name)
'''
mro = inspect.getmro(item.__class__)
mro = [c for c in mro if c not in clsskip]
return ['%s.%s' % (c.__module__, c.__name__... | Return a list of "fully qualified" class names for an instance.
Example:
for name in getClsNames(foo):
print(name) |
def chunk(self, count):
"""
Chunk the results of the query
:param count: The chunk size
:type count: int
:return: The current chunk
:rtype: list
"""
for chunk in self._connection.select_many(
count, self.to_sql(), self.get_bindings(), not sel... | Chunk the results of the query
:param count: The chunk size
:type count: int
:return: The current chunk
:rtype: list |
def ShouldRetry(self, exception):
"""Returns true if should retry based on the passed-in exception.
:param (errors.HTTPFailure instance) exception:
:rtype:
boolean
"""
if self.current_retry_attempt_count < self._max_retry_attempt_count:
self.current_ret... | Returns true if should retry based on the passed-in exception.
:param (errors.HTTPFailure instance) exception:
:rtype:
boolean |
def get_balance(self):
"""Check the balance fot this account.
Returns a dictionary containing:
account_type: The account type
balance: The balance remaining on the account
currency: The currency used for the account balance. Assume GBP in not set"""
xml_root ... | Check the balance fot this account.
Returns a dictionary containing:
account_type: The account type
balance: The balance remaining on the account
currency: The currency used for the account balance. Assume GBP in not set |
def get_template_path(filename):
"""Find raw template in working directory or in sys.path.
template_path from config may refer to templates colocated with the Stacker
config, or files in remote package_sources. Here, we emulate python module
loading to find the path to the template.
Args:
... | Find raw template in working directory or in sys.path.
template_path from config may refer to templates colocated with the Stacker
config, or files in remote package_sources. Here, we emulate python module
loading to find the path to the template.
Args:
filename (str): Template filename.
... |
def import_data(args):
'''import additional data to the experiment'''
validate_file(args.filename)
validate_dispatcher(args)
content = load_search_space(args.filename)
args.port = get_experiment_port(args)
if args.port is not None:
if import_data_to_restful_server(args, content):
... | import additional data to the experiment |
def cli(ctx, feature_id, symbol, organism="", sequence=""):
"""Set a feature's description
Output:
A standard apollo feature dictionary ({"features": [{...}]})
"""
return ctx.gi.annotations.set_symbol(feature_id, symbol, organism=organism, sequence=sequence) | Set a feature's description
Output:
A standard apollo feature dictionary ({"features": [{...}]}) |
def order(self):
"""Return the order for this payment. """
from ..resources.orders import Order
url = self._get_link('order')
if url:
resp = self.client.orders.perform_api_call(self.client.orders.REST_READ, url)
return Order(resp, self.client) | Return the order for this payment. |
def _create_filter_by(self):
"""Transform the json-server filter arguments to model-resource ones."""
filter_by = []
for name, values in request.args.copy().lists(): # copy.lists works in py2 and py3
if name not in _SKIPPED_ARGUMENTS:
column = _re_column_name.search... | Transform the json-server filter arguments to model-resource ones. |
def collides(self,position,size):
'''Returns True if the word collides with another plotted word.'''
word_rect = pygame.Rect(position,self.word_size)
if word_rect.collidelistall(self.used_pos) == []:
return False
else:
return True | Returns True if the word collides with another plotted word. |
def post(self, uri=''):
"For sql queries that start with 'INSERT ...'"
# get node...
(node, rule_kw) = node_from_uri(uri, method=request.method)
rule_kw.update( node )
values = rule_kw
xhr_data = request.get_json()
if xhr_data:
values.update( xhr_dat... | For sql queries that start with 'INSERT ... |
def get_values(self):
"""Return a copy of field values on the current object.
This method is almost identical to ``vars(self).copy()``. However,
only instance attributes that correspond to a field are included in
the returned dict.
:return: A dict mapping field names to user-pr... | Return a copy of field values on the current object.
This method is almost identical to ``vars(self).copy()``. However,
only instance attributes that correspond to a field are included in
the returned dict.
:return: A dict mapping field names to user-provided values. |
def list_pod_disruption_budget_for_all_namespaces(self, **kwargs):
"""
list or watch objects of kind PodDisruptionBudget
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_pod_disruption_... | list or watch objects of kind PodDisruptionBudget
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_pod_disruption_budget_for_all_namespaces(async_req=True)
>>> result = thread.get()
:p... |
def transform_raw_abundance(biomf, fn=math.log10, sampleIDs=None, sample_abd=True):
"""
Function to transform the total abundance calculation for each sample ID to another
format based on user given transformation function.
:type biomf: A BIOM file.
:param biomf: OTU table format.
:param fn: M... | Function to transform the total abundance calculation for each sample ID to another
format based on user given transformation function.
:type biomf: A BIOM file.
:param biomf: OTU table format.
:param fn: Mathematical function which is used to transform smax to another format.
By defaul... |
def get_share_info(self, grantee_type=None, grantee_id=None,
grantee_name=None, owner=None, owner_type='name'):
"""
:returns: list of dict representing shares informations
"""
params = {}
if grantee_type:
if 'grantee' not in params.keys():
... | :returns: list of dict representing shares informations |
def get(self, query: Mapping[str, Any], context: PipelineContext = None) -> T:
"""Gets a query from the data source.
1) Extracts the query from the data source.
2) Inserts the result into any data sinks.
3) Transforms the result into the requested type if it wasn't already.
4) I... | Gets a query from the data source.
1) Extracts the query from the data source.
2) Inserts the result into any data sinks.
3) Transforms the result into the requested type if it wasn't already.
4) Inserts the transformed result into any data sinks.
Args:
query: The q... |
def cutout_data(self, x1, y1, x2, y2, xstep=1, ystep=1, astype=None):
"""cut out data area based on coords.
"""
view = np.s_[y1:y2:ystep, x1:x2:xstep]
data = self._slice(view)
if astype:
data = data.astype(astype, copy=False)
return data | cut out data area based on coords. |
def init_app(self, app):
"""Flask application initialization."""
self.init_config(app)
app.extensions['invenio-github'] = self
@app.before_first_request
def connect_signals():
"""Connect OAuthClient signals."""
from invenio_oauthclient.models import Remot... | Flask application initialization. |
def collection(name=None):
"""Render the collection page.
It renders it either with a collection specific template (aka
collection_{collection_name}.html) or with the default collection
template (collection.html).
"""
if name is None:
collection = Collection.query.get_or_404(1)
else... | Render the collection page.
It renders it either with a collection specific template (aka
collection_{collection_name}.html) or with the default collection
template (collection.html). |
def _combine_files(tsv_files, work_dir, data):
"""Combine multiple priority tsv files into a final sorted output.
"""
header = "\t".join(["caller", "sample", "chrom", "start", "end", "svtype",
"lof", "annotation", "split_read_support", "paired_support_PE", "paired_support_PR"])
s... | Combine multiple priority tsv files into a final sorted output. |
def parse_options():
"""
Parses command-line option
"""
try:
opts, args = getopt.getopt(sys.argv[1:], 'ac:e:hilms:t:vx',
['adapt', 'comp=', 'enum=', 'exhaust', 'help', 'incr', 'blo',
'minimize', 'solver=', 'trim=', 'verbose'])
except getopt.GetoptErro... | Parses command-line option |
def append(self, val):
"""Connect any new results to the resultset.
This is where all the heavy lifting is done for creating results:
- We add a datatype here, so that each result can handle
validation etc independently. This is so that scraper authors
don't need to worry about... | Connect any new results to the resultset.
This is where all the heavy lifting is done for creating results:
- We add a datatype here, so that each result can handle
validation etc independently. This is so that scraper authors
don't need to worry about creating and passing around datat... |
def set_file_logger(self, log_level, path, logger_name='internetarchive'):
"""Convenience function to quickly configure any level of
logging to a file.
:type log_level: str
:param log_level: A log level as specified in the `logging` module.
:type path: string
:param pat... | Convenience function to quickly configure any level of
logging to a file.
:type log_level: str
:param log_level: A log level as specified in the `logging` module.
:type path: string
:param path: Path to the log file. The file will be created if it doesn't already
... |
def print_commands(self, out=sys.stdout):
'''
utility method to print commands
and descriptions for @BotFather
'''
cmds = self.list_commands()
for ck in cmds:
if ck.printable:
out.write('%s\n' % ck) | utility method to print commands
and descriptions for @BotFather |
def import_links(self, links):
""" Import links, returns import result (http://confluence.jetbrains.net/display/YTD2/Import+Links)
Accepts result of getLinks()
Example: importLinks([{'login':'vadim', 'fullName':'vadim', 'email':'eee@ss.com', 'jabber':'fff@fff.com'},
... | Import links, returns import result (http://confluence.jetbrains.net/display/YTD2/Import+Links)
Accepts result of getLinks()
Example: importLinks([{'login':'vadim', 'fullName':'vadim', 'email':'eee@ss.com', 'jabber':'fff@fff.com'},
{'login':'maxim', 'fullName':'... |
def add_command(self, handler, name=None):
"""Add a subcommand `name` which invokes `handler`.
"""
if name is None:
name = docstring_to_subcommand(handler.__doc__)
# TODO: Prevent overwriting 'help'?
self._commands[name] = handler | Add a subcommand `name` which invokes `handler`. |
def get_item(self, item_id, expand=False):
"""Returns Hacker News `Item` object.
Fetches the data from url:
https://hacker-news.firebaseio.com/v0/item/<item_id>.json
e.g. https://hacker-news.firebaseio.com/v0/item/69696969.json
Args:
item_id (int or string): Un... | Returns Hacker News `Item` object.
Fetches the data from url:
https://hacker-news.firebaseio.com/v0/item/<item_id>.json
e.g. https://hacker-news.firebaseio.com/v0/item/69696969.json
Args:
item_id (int or string): Unique item id of Hacker News story,
comment... |
def allocate(self, amount, update=True):
"""
This allocates capital to the Security. This is the method used to
buy/sell the security.
A given amount of shares will be determined on the current price, a
commission will be calculated based on the parent's commission fn, and
... | This allocates capital to the Security. This is the method used to
buy/sell the security.
A given amount of shares will be determined on the current price, a
commission will be calculated based on the parent's commission fn, and
any remaining capital will be passed back up to parent as... |
def get_project_by_network_id(network_id,**kwargs):
"""
get a project complexmodel by a network_id
"""
user_id = kwargs.get('user_id')
projects_i = db.DBSession.query(Project).join(ProjectOwner).join(Network, Project.id==Network.project_id).filter(
... | get a project complexmodel by a network_id |
def new_title_bar(self, title, color=None):
"""Return an array of Pdf Objects which constitute a Header"""
# Build a title bar for top of page
w, t, c = '100%', 2, color or HexColor('#404040')
title = '<b>{0}</b>'.format(title)
if 'TitleBar' not in self.stylesheet:
tb... | Return an array of Pdf Objects which constitute a Header |
def json(self):
"""Custom JSON encoder"""
attributes = {
'type': self.type,
'filename': self.filename,
'line_number': self.lineno,
'hashed_secret': self.secret_hash,
}
if self.is_secret is not None:
attributes['is_secret'] = se... | Custom JSON encoder |
def read_surfrad(filename, map_variables=True):
"""Read in a daily NOAA SURFRAD[1] file.
Parameters
----------
filename: str
Filepath or url.
map_variables: bool
When true, renames columns of the Dataframe to pvlib variable names
where applicable. See variable SURFRAD_COLUMN... | Read in a daily NOAA SURFRAD[1] file.
Parameters
----------
filename: str
Filepath or url.
map_variables: bool
When true, renames columns of the Dataframe to pvlib variable names
where applicable. See variable SURFRAD_COLUMNS.
Returns
-------
Tuple of the form (data... |
def _set_metric(self, metric_name, metric_type, value, tags=None):
"""
Set a metric
"""
if metric_type == self.GAUGE:
self.gauge(metric_name, value, tags=tags)
else:
self.log.error('Metric type "{}" unknown'.format(metric_type)) | Set a metric |
def parameter_to_field(self, name):
"""
Promotes a parameter to a field by creating a new array of same
size as the other existing fields, filling it with the current
value of the parameter, and then removing that parameter.
"""
if name not in self._parameters:
... | Promotes a parameter to a field by creating a new array of same
size as the other existing fields, filling it with the current
value of the parameter, and then removing that parameter. |
def bytes(self):
""" Returns a t-uple with instruction bytes (integers)
"""
result = []
op = self.opcode.split(' ')
argi = 0
while op:
q = op.pop(0)
if q == 'XX':
for k in range(self.argbytes[argi] - 1):
op.pop... | Returns a t-uple with instruction bytes (integers) |
def attach_lb_to_subnets(self, name, subnets):
"""
Attaches load balancer to one or more subnets.
Attaching subnets that are already registered with the
Load Balancer has no effect.
:type name: string
:param name: The name of the Load Balancer
:type subnets: Li... | Attaches load balancer to one or more subnets.
Attaching subnets that are already registered with the
Load Balancer has no effect.
:type name: string
:param name: The name of the Load Balancer
:type subnets: List of strings
:param subnets: The name of the subnet(s) to ... |
def flatten_dict(self, obj):
"""Return an OrderedDict dict preserving order of keys in fieldnames
"""
return OrderedDict(zip(self.fieldnames, self.flatten(obj))) | Return an OrderedDict dict preserving order of keys in fieldnames |
def make_index(css_class, entities):
"""
Generate the HTML index (a short description and a link to the full
documentation) for a list of FunctionDocs or ClassDocs.
"""
def make_entry(entity):
return ('<dt><a href = "%(url)s">%(name)s</a></dt>\n' +
'<dd>%(doc)s</dd>') % {
... | Generate the HTML index (a short description and a link to the full
documentation) for a list of FunctionDocs or ClassDocs. |
def remove_overlaps(self, ufos, glyph_filter=lambda g: len(g)):
"""Remove overlaps in UFOs' glyphs' contours."""
from booleanOperations import union, BooleanOperationsError
for ufo in ufos:
font_name = self._font_name(ufo)
logger.info("Removing overlaps for " + font_name... | Remove overlaps in UFOs' glyphs' contours. |
def set_frame_parameters(self, profile_index: int, frame_parameters) -> None:
"""Set the frame parameters with the settings index and fire the frame parameters changed event.
If the settings index matches the current settings index, call set current frame parameters.
If the settings index matc... | Set the frame parameters with the settings index and fire the frame parameters changed event.
If the settings index matches the current settings index, call set current frame parameters.
If the settings index matches the record settings index, call set record frame parameters. |
def _ReadStructure(
self, file_object, file_offset, data_size, data_type_map, description):
"""Reads a structure.
Args:
file_object (FileIO): file-like object.
file_offset (int): offset of the data relative from the start of
the file-like object.
data_size (int): data size of ... | Reads a structure.
Args:
file_object (FileIO): file-like object.
file_offset (int): offset of the data relative from the start of
the file-like object.
data_size (int): data size of the structure.
data_type_map (dtfabric.DataTypeMap): data type map of the structure.
descript... |
def createBatchSystem(config):
"""
Creates an instance of the batch system specified in the given config.
:param toil.common.Config config: the current configuration
:rtype: batchSystems.abstractBatchSystem.AbstractBatchSystem
:return: an instance of a concrete subclass of Abs... | Creates an instance of the batch system specified in the given config.
:param toil.common.Config config: the current configuration
:rtype: batchSystems.abstractBatchSystem.AbstractBatchSystem
:return: an instance of a concrete subclass of AbstractBatchSystem |
def get_plugin_by_model(self, model_class):
"""
Return the corresponding plugin for a given model.
You can also use the :attr:`ContentItem.plugin <fluent_contents.models.ContentItem.plugin>` property directly.
This is the low-level function that supports that feature.
"""
... | Return the corresponding plugin for a given model.
You can also use the :attr:`ContentItem.plugin <fluent_contents.models.ContentItem.plugin>` property directly.
This is the low-level function that supports that feature. |
def error_response(message, status=400, code=None):
""""Return error message(in dict)."""
from django.http import JsonResponse
data = {'message': message}
if code:
data['code'] = code
LOG.error("Error response, status code is : {} | {}".format(status, data))
return JsonResponse(data=data... | Return error message(in dict). |
def run(host=DEFAULT_HOST, port=DEFAULT_PORT, path='.'):
"""Run the development server
"""
path = abspath(path)
c = Clay(path)
c.run(host=host, port=port) | Run the development server |
def close(self):
"""Close the AVR device connection and don't try to reconnect."""
self.log.warning('Closing connection to AVR')
self._closing = True
if self.protocol.transport:
self.protocol.transport.close() | Close the AVR device connection and don't try to reconnect. |
def has_preview_permission(self, request, obj=None):
"""
Return `True` if the user has permissions to preview a publishable
item.
NOTE: this method does not actually change who can or cannot preview
any particular item, just whether to show the preview link. The real
dci... | Return `True` if the user has permissions to preview a publishable
item.
NOTE: this method does not actually change who can or cannot preview
any particular item, just whether to show the preview link. The real
dcision is made by a combination of:
- `PublishingMiddleware` which... |
def process_cmap(cmap, ncolors=None, provider=None, categorical=False):
"""
Convert valid colormap specifications to a list of colors.
"""
providers_checked="matplotlib, bokeh, or colorcet" if provider is None else provider
if isinstance(cmap, Cycle):
palette = [rgb2hex(c) if isinstance(c, ... | Convert valid colormap specifications to a list of colors. |
def from_json(cls, json):
"""Create new DatastoreInputReader from the json, encoded by to_json.
Args:
json: json map representation of DatastoreInputReader.
Returns:
an instance of DatastoreInputReader with all data deserialized from json.
"""
return cls(
namespace_range.Namesp... | Create new DatastoreInputReader from the json, encoded by to_json.
Args:
json: json map representation of DatastoreInputReader.
Returns:
an instance of DatastoreInputReader with all data deserialized from json. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.