code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def head_object(Bucket=None, IfMatch=None, IfModifiedSince=None, IfNoneMatch=None, IfUnmodifiedSince=None, Key=None, Range=None, VersionId=None, SSECustomerAlgorithm=None, SSECustomerKey=None, SSECustomerKeyMD5=None, RequestPayer=None, PartNumber=None):
"""
The HEAD operation retrieves metadata from an object w... | The HEAD operation retrieves metadata from an object without returning the object itself. This operation is useful if you're only interested in an object's metadata. To use HEAD, you must have READ access to the object.
See also: AWS API Documentation
:example: response = client.head_object(
B... |
def _display(self, sent, now, chunk, mbps):
""" Display intermediate progress. """
if self.parent is not None:
self.parent._display(self.parent.offset + sent, now, chunk, mbps)
return
elapsed = now - self.startTime
if sent > 0 and self.total is not None and sent... | Display intermediate progress. |
def format(self, sql, params):
"""
Formats the SQL query to use ordinal parameters instead of named
parameters.
*sql* (|string|) is the SQL query.
*params* (|dict|) maps each named parameter (|string|) to value
(|object|). If |self.named| is "numeric", then *params* can be
simply a |sequence| of values ... | Formats the SQL query to use ordinal parameters instead of named
parameters.
*sql* (|string|) is the SQL query.
*params* (|dict|) maps each named parameter (|string|) to value
(|object|). If |self.named| is "numeric", then *params* can be
simply a |sequence| of values mapped by index.
Returns a 2-|tuple|... |
def splitPrefix(name):
"""
Split the name into a tuple (I{prefix}, I{name}). The first element in
the tuple is I{None} when the name does't have a prefix.
@param name: A node name containing an optional prefix.
@type name: basestring
@return: A tuple containing the (2) parts of I{name}
@rty... | Split the name into a tuple (I{prefix}, I{name}). The first element in
the tuple is I{None} when the name does't have a prefix.
@param name: A node name containing an optional prefix.
@type name: basestring
@return: A tuple containing the (2) parts of I{name}
@rtype: (I{prefix}, I{name}) |
def dropSpans(spans, text):
"""
Drop from text the blocks identified in :param spans:, possibly nested.
"""
spans.sort()
res = ''
offset = 0
for s, e in spans:
if offset <= s: # handle nesting
if offset < s:
res += text[offset:s]
offse... | Drop from text the blocks identified in :param spans:, possibly nested. |
def add_page(self, page=None):
""" May generate and add a PDFPage separately, or use this to generate
a default page."""
if page is None:
self.page = PDFPage(self.orientation_default, self.layout_default, self.margins)
else:
self.page = page
sel... | May generate and add a PDFPage separately, or use this to generate
a default page. |
def netconf_config_change_datastore(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
netconf_config_change = ET.SubElement(config, "netconf-config-change", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-notifications")
datastore = ET.SubElement(netconf_c... | Auto Generated Code |
def full_value(self):
"""Returns the full value with the path also (ie, name = value (path))
:returns: String
"""
s = self.name_value()
s += self.path_value()
s += "\n\n"
return s | Returns the full value with the path also (ie, name = value (path))
:returns: String |
def array_controller_by_model(self, model):
"""Returns array controller instance by model
:returns Instance of array controller
"""
for member in self.get_members():
if member.model == model:
return member | Returns array controller instance by model
:returns Instance of array controller |
def tile_read(source, bounds, tilesize, **kwargs):
"""
Read data and mask.
Attributes
----------
source : str or rasterio.io.DatasetReader
input file path or rasterio.io.DatasetReader object
bounds : list
Mercator tile bounds (left, bottom, right, top)
tilesize : int
... | Read data and mask.
Attributes
----------
source : str or rasterio.io.DatasetReader
input file path or rasterio.io.DatasetReader object
bounds : list
Mercator tile bounds (left, bottom, right, top)
tilesize : int
Output image size
kwargs: dict, optional
These wil... |
def _is_monotonic(coord, axis=0):
"""
>>> _is_monotonic(np.array([0, 1, 2]))
True
>>> _is_monotonic(np.array([2, 1, 0]))
True
>>> _is_monotonic(np.array([0, 2, 1]))
False
"""
if coord.shape[axis] < 3:
return True
else:
n = coord.shape[axis]
delta_pos = (co... | >>> _is_monotonic(np.array([0, 1, 2]))
True
>>> _is_monotonic(np.array([2, 1, 0]))
True
>>> _is_monotonic(np.array([0, 2, 1]))
False |
def set_env(self):
"""Put info about coverage into the env so that subprocesses can activate coverage."""
if self.cov_source is None:
os.environ['COV_CORE_SOURCE'] = ''
else:
os.environ['COV_CORE_SOURCE'] = UNIQUE_SEP.join(self.cov_source)
os.environ['COV_CORE_DA... | Put info about coverage into the env so that subprocesses can activate coverage. |
def to_regex(regex, flags=0):
"""
Given a string, this function returns a new re.RegexObject.
Given a re.RegexObject, this function just returns the same object.
:type regex: string|re.RegexObject
:param regex: A regex or a re.RegexObject
:type flags: int
:param flags: See Python's re.com... | Given a string, this function returns a new re.RegexObject.
Given a re.RegexObject, this function just returns the same object.
:type regex: string|re.RegexObject
:param regex: A regex or a re.RegexObject
:type flags: int
:param flags: See Python's re.compile().
:rtype: re.RegexObject
:r... |
def _get_dst_resolution(self, dst_res=None):
"""Get default resolution, i.e. the highest resolution or smallest cell size."""
if dst_res is None:
dst_res = min(self._res_indices.keys())
return dst_res | Get default resolution, i.e. the highest resolution or smallest cell size. |
def reply(self, user, msg, errors_as_replies=True):
"""Fetch a reply from the RiveScript brain.
Arguments:
user (str): A unique user ID for the person requesting a reply.
This could be e.g. a screen name or nickname. It's used internally
to store user variabl... | Fetch a reply from the RiveScript brain.
Arguments:
user (str): A unique user ID for the person requesting a reply.
This could be e.g. a screen name or nickname. It's used internally
to store user variables (including topic and history), so if your
bo... |
def make_attrstring(attr):
"""Returns an attribute string in the form key="val" """
attrstring = ' '.join(['%s="%s"' % (k, v) for k, v in attr.items()])
return '%s%s' % (' ' if attrstring != '' else '', attrstring) | Returns an attribute string in the form key="val" |
def at_depth(self, depth):
"""
Returns a generator yielding all nodes in the tree at a specific depth
:param depth:
An integer >= 0 of the depth of nodes to yield
:return:
A generator yielding PolicyTreeNode objects
"""
for child in list(self.ch... | Returns a generator yielding all nodes in the tree at a specific depth
:param depth:
An integer >= 0 of the depth of nodes to yield
:return:
A generator yielding PolicyTreeNode objects |
def status(self):
"""Returns the status of the executor via probing the execution providers."""
if self.provider:
status = self.provider.status(self.engines)
else:
status = []
return status | Returns the status of the executor via probing the execution providers. |
def apply(self, func, skills):
"""Run a function on all skills in parallel"""
def run_item(skill):
try:
func(skill)
return True
except MsmException as e:
LOG.error('Error running {} on {}: {}'.format(
func.__nam... | Run a function on all skills in parallel |
def complete_url(self, url):
""" Completes a given URL with this instance's URL base. """
if self.base_url:
return urlparse.urljoin(self.base_url, url)
else:
return url | Completes a given URL with this instance's URL base. |
def expire_leaderboard_at_for(self, leaderboard_name, timestamp):
'''
Expire the given leaderboard at a specific UNIX timestamp. Do not use this with
leaderboards that utilize member data as there is no facility to cascade the
expiration out to the keys for the member data.
@par... | Expire the given leaderboard at a specific UNIX timestamp. Do not use this with
leaderboards that utilize member data as there is no facility to cascade the
expiration out to the keys for the member data.
@param leaderboard_name [String] Name of the leaderboard.
@param timestamp [int] U... |
def request_show(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/requests#show-request"
api_path = "/api/v2/requests/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/requests#show-request |
def pick_peaks(nc, L=16, offset_denom=0.1):
"""Obtain peaks from a novelty curve using an adaptive threshold."""
offset = nc.mean() * float(offset_denom)
th = filters.median_filter(nc, size=L) + offset
#th = filters.gaussian_filter(nc, sigma=L/2., mode="nearest") + offset
#import pylab as plt
#p... | Obtain peaks from a novelty curve using an adaptive threshold. |
def at(*args, **kwargs): # pylint: disable=C0103
'''
Add a job to the queue.
The 'timespec' follows the format documented in the
at(1) manpage.
CLI Example:
.. code-block:: bash
salt '*' at.at <timespec> <cmd> [tag=<tag>] [runas=<user>]
salt '*' at.at 12:05am '/sbin/reboot' ... | Add a job to the queue.
The 'timespec' follows the format documented in the
at(1) manpage.
CLI Example:
.. code-block:: bash
salt '*' at.at <timespec> <cmd> [tag=<tag>] [runas=<user>]
salt '*' at.at 12:05am '/sbin/reboot' tag=reboot
salt '*' at.at '3:05am +3 days' 'bin/myscri... |
def CopyToIsoFormat(cls, timestamp, timezone=pytz.UTC, raise_error=False):
"""Copies the timestamp to an ISO 8601 formatted string.
Args:
timestamp: The timestamp which is an integer containing the number
of micro seconds since January 1, 1970, 00:00:00 UTC.
timezone: Optional time... | Copies the timestamp to an ISO 8601 formatted string.
Args:
timestamp: The timestamp which is an integer containing the number
of micro seconds since January 1, 1970, 00:00:00 UTC.
timezone: Optional timezone (instance of pytz.timezone).
raise_error: Boolean that if set to True w... |
def API520_B(Pset, Pback, overpressure=0.1):
r'''Calculates capacity correction due to backpressure on balanced
spring-loaded PRVs in vapor service. For pilot operated valves,
this is always 1. Applicable up to 50% of the percent gauge backpressure,
For use in API 520 relief valve sizing. 1D interpolati... | r'''Calculates capacity correction due to backpressure on balanced
spring-loaded PRVs in vapor service. For pilot operated valves,
this is always 1. Applicable up to 50% of the percent gauge backpressure,
For use in API 520 relief valve sizing. 1D interpolation among a table with
53 backpressures is per... |
def compute_logarithmic_scale(min_, max_, min_scale, max_scale):
"""Compute an optimal scale for logarithmic"""
if max_ <= 0 or min_ <= 0:
return []
min_order = int(floor(log10(min_)))
max_order = int(ceil(log10(max_)))
positions = []
amplitude = max_order - min_order
if amplitude <=... | Compute an optimal scale for logarithmic |
def from_location(cls, location):
"""Try to create a Ladybug location from a location string.
Args:
locationString: Location string
Usage:
l = Location.from_location(locationString)
"""
if not location:
return cls()
try:
... | Try to create a Ladybug location from a location string.
Args:
locationString: Location string
Usage:
l = Location.from_location(locationString) |
async def join_voice_channel(self, guild_id, channel_id):
"""
Alternative way to join a voice channel if node is known.
"""
voice_ws = self.get_voice_ws(guild_id)
await voice_ws.voice_state(guild_id, channel_id) | Alternative way to join a voice channel if node is known. |
def results(context, history_log):
"""Process provided history log and results files."""
if context.obj is None:
context.obj = {}
context.obj['history_log'] = history_log
if context.invoked_subcommand is None:
context.invoke(show, item=1) | Process provided history log and results files. |
def show_bounds(self, mesh=None, bounds=None, show_xaxis=True,
show_yaxis=True, show_zaxis=True, show_xlabels=True,
show_ylabels=True, show_zlabels=True, italic=False,
bold=True, shadow=False, font_size=None,
font_family=Non... | Adds bounds axes. Shows the bounds of the most recent input
mesh unless mesh is specified.
Parameters
----------
mesh : vtkPolydata or unstructured grid, optional
Input mesh to draw bounds axes around
bounds : list or tuple, optional
Bounds to override ... |
def _bnd(self, xloc, dist, cache):
"""Distribution bounds."""
return numpy.log(evaluation.evaluate_bound(
dist, numpy.e**xloc, cache=cache)) | Distribution bounds. |
def macro_body(self, node, frame):
"""Dump the function def of a macro or call block."""
frame = frame.inner()
frame.symbols.analyze_node(node)
macro_ref = MacroRef(node)
explicit_caller = None
skip_special_params = set()
args = []
for idx, arg in enumera... | Dump the function def of a macro or call block. |
def get_mapping(self, doc_type=None, indices=None, raw=False):
"""
Register specific mapping definition for a specific type against one or more indices.
(See :ref:`es-guide-reference-api-admin-indices-get-mapping`)
"""
if doc_type is None and indices is None:
path = ... | Register specific mapping definition for a specific type against one or more indices.
(See :ref:`es-guide-reference-api-admin-indices-get-mapping`) |
def link(self, camera):
""" Link this camera with another camera of the same type
Linked camera's keep each-others' state in sync.
Parameters
----------
camera : instance of Camera
The other camera to link.
"""
cam1, cam2 = self, camera
# Rem... | Link this camera with another camera of the same type
Linked camera's keep each-others' state in sync.
Parameters
----------
camera : instance of Camera
The other camera to link. |
def thumbnail_preview(src_path):
''' Returns the path to small thumbnail preview. '''
try:
assert(exists(src_path))
width = '1980'
dest_dir = mkdtemp(prefix='pyglass')
cmd = [QLMANAGE, '-t', '-s', width, src_path, '-o', dest_dir]
assert(check_call(cmd) == 0)
src_filename = basename(src_pa... | Returns the path to small thumbnail preview. |
def _update(self, rect, delta_y, force_update_margins=False):
""" Updates panels """
helper = TextHelper(self.editor)
if not self:
return
for zones_id, zone in self._panels.items():
if zones_id == Panel.Position.TOP or \
zones_id == Panel.Position.B... | Updates panels |
def low_mem_sq(m, step=100000):
"""np.dot(m, m.T) with low mem usage, by doing it in small steps"""
if not m.flags.c_contiguous:
raise ValueError('m must be C ordered for this to work with less mem.')
# -- can make this even faster with pre-allocating arrays, but not worth it
# right now
# m... | np.dot(m, m.T) with low mem usage, by doing it in small steps |
def init_app(self, app, minters_entry_point_group=None,
fetchers_entry_point_group=None):
"""Flask application initialization.
Initialize:
* The CLI commands.
* Initialize the logger (Default: `app.debug`).
* Initialize the default admin object link endpoint.... | Flask application initialization.
Initialize:
* The CLI commands.
* Initialize the logger (Default: `app.debug`).
* Initialize the default admin object link endpoint.
(Default: `{"rec": "recordmetadata.details_view"}` if
`invenio-records` is installed, otherwi... |
def createpath(path, mode, exists_ok=True):
"""
Create directories in the indicated path.
:param path:
:param mode:
:param exists_ok:
:return:
"""
try:
os.makedirs(path, mode)
except OSError, e:
if e.errno != errno.EEXIST or not exists_ok:
raise e | Create directories in the indicated path.
:param path:
:param mode:
:param exists_ok:
:return: |
def find_locales(self) -> Dict[str, gettext.GNUTranslations]:
"""
Load all compiled locales from path
:return: dict with locales
"""
translations = {}
for name in os.listdir(self.path):
if not os.path.isdir(os.path.join(self.path, name)):
con... | Load all compiled locales from path
:return: dict with locales |
def batch_split_words(self, sentences: List[str]) -> List[List[Token]]:
"""
Spacy needs to do batch processing, or it can be really slow. This method lets you take
advantage of that if you want. Default implementation is to just iterate of the sentences
and call ``split_words``, but th... | Spacy needs to do batch processing, or it can be really slow. This method lets you take
advantage of that if you want. Default implementation is to just iterate of the sentences
and call ``split_words``, but the ``SpacyWordSplitter`` will actually do batched
processing. |
def navigation_info(request):
'''Expose whether to display the navigation header and footer'''
if request.GET.get('wafer_hide_navigation') == "1":
nav_class = "wafer-invisible"
else:
nav_class = "wafer-visible"
context = {
'WAFER_NAVIGATION_VISIBILITY': nav_class,
}
retur... | Expose whether to display the navigation header and footer |
def get_precision_regex():
"""Build regular expression used to extract precision
metric from command output"""
expr = re.escape(PRECISION_FORMULA)
expr += r'=\s*(\S*)\s.*\s([A-Z]*)'
return re.compile(expr) | Build regular expression used to extract precision
metric from command output |
def _col_name(index):
"""
Converts a column index to a column name.
>>> _col_name(0)
'A'
>>> _col_name(26)
'AA'
"""
for exp in itertools.count(1):
limit = 26 ** exp
if index < limit:
return ''.join(chr(ord('A') + index // (26 ** i) % 26) for i in range(exp-1... | Converts a column index to a column name.
>>> _col_name(0)
'A'
>>> _col_name(26)
'AA' |
def mqc_load_userconfig(paths=()):
""" Overwrite config defaults with user config files """
# Load and parse installation config file if we find it
mqc_load_config(os.path.join( os.path.dirname(MULTIQC_DIR), 'multiqc_config.yaml'))
# Load and parse a user config file if we find it
mqc_load_config(... | Overwrite config defaults with user config files |
def middleware(self, *args, **kwargs):
"""Decorate and register middleware
:param args: captures all of the positional arguments passed in
:type args: tuple(Any)
:param kwargs: captures the keyword arguments passed in
:type kwargs: dict(Any)
:return: The middleware functi... | Decorate and register middleware
:param args: captures all of the positional arguments passed in
:type args: tuple(Any)
:param kwargs: captures the keyword arguments passed in
:type kwargs: dict(Any)
:return: The middleware function to use as the decorator
:rtype: fn |
def get_paths(self):
"""Get all paths from the root to the leaves.
For example, given a chain like `{'a':{'b':{'c':None}}}`,
this method would return `[['a', 'b', 'c']]`.
Returns:
A list of lists of paths.
"""
paths = []
for key, child in six.iterite... | Get all paths from the root to the leaves.
For example, given a chain like `{'a':{'b':{'c':None}}}`,
this method would return `[['a', 'b', 'c']]`.
Returns:
A list of lists of paths. |
def f_store(self, recursive=True, store_data=pypetconstants.STORE_DATA,
max_depth=None):
"""Stores a group node to disk
:param recursive:
Whether recursively all children should be stored too. Default is ``True``.
:param store_data:
For how to choose '... | Stores a group node to disk
:param recursive:
Whether recursively all children should be stored too. Default is ``True``.
:param store_data:
For how to choose 'store_data' see :ref:`more-on-storing`.
:param max_depth:
In case `recursive` is `True`, you c... |
def _get_data(self) -> BaseFrameManager:
"""Perform the map step
Returns:
A BaseFrameManager object.
"""
def iloc(partition, row_internal_indices, col_internal_indices):
return partition.iloc[row_internal_indices, col_internal_indices]
masked_data = sel... | Perform the map step
Returns:
A BaseFrameManager object. |
def _fmt_structured(d):
"""Formats '{k1:v1, k2:v2}' => 'time=... pid=... k1=v1 k2=v2'
Output is lexically sorted, *except* the time and pid always
come first, to assist with human scanning of the data.
"""
timeEntry = datetime.datetime.utcnow().strftime(
"time=%Y-%m-... | Formats '{k1:v1, k2:v2}' => 'time=... pid=... k1=v1 k2=v2'
Output is lexically sorted, *except* the time and pid always
come first, to assist with human scanning of the data. |
def arg(*args, **kwargs):
"""Return an attrib() that can be fed as a command-line argument.
This function is a wrapper for an attr.attrib to create a corresponding
command line argument for it. Use it with the same arguments as argparse's
add_argument().
Example:
>>> @attrs
... class MyFe... | Return an attrib() that can be fed as a command-line argument.
This function is a wrapper for an attr.attrib to create a corresponding
command line argument for it. Use it with the same arguments as argparse's
add_argument().
Example:
>>> @attrs
... class MyFeature(Feature):
... my_nu... |
def decimal_format(value, TWOPLACES=Decimal(100) ** -2):
'Format a decimal.Decimal like to 2 decimal places.'
if not isinstance(value, Decimal):
value = Decimal(str(value))
return value.quantize(TWOPLACES) | Format a decimal.Decimal like to 2 decimal places. |
def maybe_inspect_zip(models):
r'''
Detect if models is a list of protocolbuffer files or a ZIP file.
If the latter, then unzip it and return the list of protocolbuffer files
that were inside.
'''
if not(is_zip_file(models)):
return models
if len(models) > 1:
return models
... | r'''
Detect if models is a list of protocolbuffer files or a ZIP file.
If the latter, then unzip it and return the list of protocolbuffer files
that were inside. |
def create_session(self, session_request, protocol):
"""CreateSession.
[Preview API] Creates a session, a wrapper around a feed that can store additional metadata on the packages published to it.
:param :class:`<SessionRequest> <azure.devops.v5_0.provenance.models.SessionRequest>` session_reques... | CreateSession.
[Preview API] Creates a session, a wrapper around a feed that can store additional metadata on the packages published to it.
:param :class:`<SessionRequest> <azure.devops.v5_0.provenance.models.SessionRequest>` session_request: The feed and metadata for the session
:param str prot... |
def generate_cutV_genomic_CDR3_segs(self):
"""Add palindromic inserted nucleotides to germline V sequences.
The maximum number of palindromic insertions are appended to the
germline V segments so that delV can index directly for number of
nucleotides to delete from a segment.
... | Add palindromic inserted nucleotides to germline V sequences.
The maximum number of palindromic insertions are appended to the
germline V segments so that delV can index directly for number of
nucleotides to delete from a segment.
Sets the attribute cutV_genomic_CDR3_se... |
def get_container_service(access_token, subscription_id, resource_group, service_name):
'''Get details about an Azure Container Server
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group n... | Get details about an Azure Container Server
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
service_name (str): Name of container service.
Returns:
HTTP response... |
def hook_drop(self):
""" Install hooks for drop operations.
"""
widget = self.widget
widget.setAcceptDrops(True)
widget.dragEnterEvent = self.dragEnterEvent
widget.dragMoveEvent = self.dragMoveEvent
widget.dragLeaveEvent = self.dragLeaveEvent
widget.dropE... | Install hooks for drop operations. |
def send(self, stanza):
"""Send a stanza somwhere.
The default implementation sends it via the `uplink` if it is defined
or raises the `NoRouteError`.
:Parameters:
- `stanza`: the stanza to send.
:Types:
- `stanza`: `pyxmpp.stanza.Stanza`"""
if s... | Send a stanza somwhere.
The default implementation sends it via the `uplink` if it is defined
or raises the `NoRouteError`.
:Parameters:
- `stanza`: the stanza to send.
:Types:
- `stanza`: `pyxmpp.stanza.Stanza` |
def update_user_password(new_pwd_user_id, new_password,**kwargs):
"""
Update a user's password
"""
#check_perm(kwargs.get('user_id'), 'edit_user')
try:
user_i = db.DBSession.query(User).filter(User.id==new_pwd_user_id).one()
user_i.password = bcrypt.hashpw(str(new_password).encod... | Update a user's password |
def read_samples(self, sr=None, offset=0, duration=None):
"""
Return the samples from the track in the container.
Uses librosa for resampling, if needed.
Args:
sr (int): If ``None``, uses the sampling rate given by the file,
otherwise resamples to the g... | Return the samples from the track in the container.
Uses librosa for resampling, if needed.
Args:
sr (int): If ``None``, uses the sampling rate given by the file,
otherwise resamples to the given sampling rate.
offset (float): The time in seconds, from wher... |
def bootstrap_repl(which_ns: str) -> types.ModuleType:
"""Bootstrap the REPL with a few useful vars and returned the
bootstrapped module so it's functions can be used by the REPL
command."""
repl_ns = runtime.Namespace.get_or_create(sym.symbol("basilisp.repl"))
ns = runtime.Namespace.get_or_create(s... | Bootstrap the REPL with a few useful vars and returned the
bootstrapped module so it's functions can be used by the REPL
command. |
def loads(s: str, **kwargs) -> JsonObj:
""" Convert a json_str into a JsonObj
:param s: a str instance containing a JSON document
:param kwargs: arguments see: json.load for details
:return: JsonObj representing the json string
"""
if isinstance(s, (bytes, bytearray)):
s = s.decode(json... | Convert a json_str into a JsonObj
:param s: a str instance containing a JSON document
:param kwargs: arguments see: json.load for details
:return: JsonObj representing the json string |
def load_profiles_from_file(self, fqfn):
"""Load profiles from file.
Args:
fqfn (str): Fully qualified file name.
"""
if self.args.verbose:
print('Loading profiles from File: {}{}{}'.format(c.Style.BRIGHT, c.Fore.MAGENTA, fqfn))
with open(fqfn, 'r+') as f... | Load profiles from file.
Args:
fqfn (str): Fully qualified file name. |
def on_train_begin(self, **kwargs):
"Call watch method to log model topology, gradients & weights"
# Set self.best, method inherited from "TrackerCallback" by "SaveModelCallback"
super().on_train_begin()
# Ensure we don't call "watch" multiple times
if not WandbCallback.watch_c... | Call watch method to log model topology, gradients & weights |
def scoped_session_decorator(func):
"""Manage contexts and add debugging to db sessions."""
@wraps(func)
def wrapper(*args, **kwargs):
with sessions_scope(session):
# The session used in func comes from the funcs globals, but
# it will be a proxied thread local var from the ... | Manage contexts and add debugging to db sessions. |
def copy(self):
"""Create a new copy of selfe. does not do a deep copy for payload
:return: copied range
:rtype: GenomicRange
"""
return type(self)(self.chr,
self.start+self._start_offset,
self.end,
self.payload,
... | Create a new copy of selfe. does not do a deep copy for payload
:return: copied range
:rtype: GenomicRange |
def webapi_request(url, method='GET', caller=None, session=None, params=None):
"""Low level function for calling Steam's WebAPI
.. versionchanged:: 0.8.3
:param url: request url (e.g. ``https://api.steampowered.com/A/B/v001/``)
:type url: :class:`str`
:param method: HTTP method (GET or POST)
:... | Low level function for calling Steam's WebAPI
.. versionchanged:: 0.8.3
:param url: request url (e.g. ``https://api.steampowered.com/A/B/v001/``)
:type url: :class:`str`
:param method: HTTP method (GET or POST)
:type method: :class:`str`
:param caller: caller reference, caller.last_response is... |
def calculate_incorrect_name_dict(graph: BELGraph) -> Mapping[str, List[str]]:
"""Get missing names grouped by namespace."""
missing = defaultdict(list)
for namespace, name in _iterate_namespace_name(graph):
missing[namespace].append(name)
return dict(missing) | Get missing names grouped by namespace. |
def state_name(self):
"""Get a human-readable value of the state
Returns:
str: Name of the current state
"""
if self.state == 1:
return 'New Issue'
elif self.state == 2:
return 'Shutdown in 1 week'
elif self.state == 3:
r... | Get a human-readable value of the state
Returns:
str: Name of the current state |
def _validate_target(self, y):
"""
Raises a value error if the target is not a classification target.
"""
# Ignore None values
if y is None:
return
y_type = type_of_target(y)
if y_type not in ("binary", "multiclass"):
raise YellowbrickValu... | Raises a value error if the target is not a classification target. |
def origin(self, origin):
"""Set the origin. Pass a length three tuple of floats"""
ox, oy, oz = origin[0], origin[1], origin[2]
self.SetOrigin(ox, oy, oz)
self.Modified() | Set the origin. Pass a length three tuple of floats |
def migrator(self):
"""Create migrator and setup it with fake migrations."""
migrator = Migrator(self.database)
for name in self.done:
self.run_one(name, migrator)
return migrator | Create migrator and setup it with fake migrations. |
def getResponsible(self):
"""Return all manager info of responsible departments
"""
managers = {}
for department in self.getDepartments():
manager = department.getManager()
if manager is None:
continue
manager_id = manager.getId()
... | Return all manager info of responsible departments |
def create_selection():
""" Create a selection expression """
operation = Forward()
nested = Group(Suppress("(") + operation + Suppress(")")).setResultsName("nested")
select_expr = Forward()
functions = select_functions(select_expr)
maybe_nested = functions | nested | Group(var_val)
operatio... | Create a selection expression |
def get_class_field(cls, field_name):
"""
Add management of dynamic fields: if a normal field cannot be retrieved,
check if it can be a dynamic field and in this case, create a copy with
the given name and associate it to the model.
"""
try:
field = super(Mode... | Add management of dynamic fields: if a normal field cannot be retrieved,
check if it can be a dynamic field and in this case, create a copy with
the given name and associate it to the model. |
def decode(self, encoding=None, errors='strict'):
"""Decode using the codec registered for encoding. encoding defaults to the default encoding.
errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors
raise a UnicodeDecodeError. Other possib... | Decode using the codec registered for encoding. encoding defaults to the default encoding.
errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors
raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other nam... |
def _get_chain_by_sid(sid):
"""Return None if not found."""
try:
return d1_gmn.app.models.Chain.objects.get(sid__did=sid)
except d1_gmn.app.models.Chain.DoesNotExist:
pass | Return None if not found. |
def main(host):
client = capnp.TwoPartyClient(host)
# Pass "calculator" to ez_restore (there's also a `restore` function that
# takes a struct or AnyPointer as an argument), and then cast the returned
# capability to it's proper type. This casting is due to capabilities not
# having a reference to ... | Make a request that just evaluates the literal value 123.
What's interesting here is that evaluate() returns a "Value", which is
another interface and therefore points back to an object living on the
server. We then have to call read() on that object to read it.
However, even though we are making two ... |
def _histplot_bins(column, bins=100):
"""Helper to get bins for histplot."""
col_min = np.min(column)
col_max = np.max(column)
return range(col_min, col_max + 2, max((col_max - col_min) // bins, 1)) | Helper to get bins for histplot. |
def topological_order_dfs(graph):
"""Topological sorting by depth first search
:param graph: directed graph in listlist format, cannot be listdict
:returns: list of vertices in order
:complexity: `O(|V|+|E|)`
"""
n = len(graph)
order = []
times_seen = [-1] * n
for start in range(n):... | Topological sorting by depth first search
:param graph: directed graph in listlist format, cannot be listdict
:returns: list of vertices in order
:complexity: `O(|V|+|E|)` |
def required_items(element, children, attributes):
"""Check an xml element to include given attributes and children.
:param element: ElementTree element
:param children: list of XPaths to check
:param attributes: list of attributes names to check
:raises NotValidXmlException: if some argument is mi... | Check an xml element to include given attributes and children.
:param element: ElementTree element
:param children: list of XPaths to check
:param attributes: list of attributes names to check
:raises NotValidXmlException: if some argument is missing
:raises NotValidXmlException: if some child is m... |
def _recover_network_failure(self):
"""Recover from a network failure"""
if self.auto_reconnect and not self._is_closing:
connected = False
while not connected:
log_msg = "* ATTEMPTING RECONNECT"
if self._retry_new_version:
log_... | Recover from a network failure |
def set_user_jobs(session, job_ids):
"""
Replace the currently authenticated user's list of jobs with a new list of
jobs
"""
jobs_data = {
'jobs[]': job_ids
}
response = make_put_request(session, 'self/jobs', json_data=jobs_data)
json_data = response.json()
if response.status... | Replace the currently authenticated user's list of jobs with a new list of
jobs |
def is_negated(self):
"""A negated query is one in which every clause has a presence of
prohibited. These queries require some special processing to return
the expected results.
"""
return all(
clause.presence == QueryPresence.PROHIBITED for clause in self.clauses
... | A negated query is one in which every clause has a presence of
prohibited. These queries require some special processing to return
the expected results. |
def find_node(self, attribute):
"""
Returns the Node with given attribute.
:param attribute: Attribute.
:type attribute: GraphModelAttribute
:return: Node.
:rtype: GraphModelNode
"""
for model in GraphModel._GraphModel__models_instances.itervalues():
... | Returns the Node with given attribute.
:param attribute: Attribute.
:type attribute: GraphModelAttribute
:return: Node.
:rtype: GraphModelNode |
def associations(self, subject, object=None):
"""
Given a subject-object pair (e.g. gene id to ontology class id), return all association
objects that match.
"""
if object is None:
if self.associations_by_subj is not None:
return self.associations_by_... | Given a subject-object pair (e.g. gene id to ontology class id), return all association
objects that match. |
def create_ingest_point(self, privateStreamName, publicStreamName):
"""
Creates an RTMP ingest point, which mandates that streams pushed into
the EMS have a target stream name which matches one Ingest Point
privateStreamName.
:param privateStreamName: The name that RTMP Target S... | Creates an RTMP ingest point, which mandates that streams pushed into
the EMS have a target stream name which matches one Ingest Point
privateStreamName.
:param privateStreamName: The name that RTMP Target Stream Names must
match.
:type privateStreamName: str
:param... |
def update_rec(self, rec, name, value):
"""Update current GOTerm with optional record."""
# 'def' is a reserved word in python, do not use it as a Class attr.
if name == "def":
name = "defn"
# If we have a relationship, then we will split this into a further
# dictio... | Update current GOTerm with optional record. |
def write(self, output_filepath):
"""
serialize the ExmaraldaFile instance and write it to a file.
Parameters
----------
output_filepath : str
relative or absolute path to the Exmaralda file to be created
"""
with open(output_filepath, 'w') as out_fil... | serialize the ExmaraldaFile instance and write it to a file.
Parameters
----------
output_filepath : str
relative or absolute path to the Exmaralda file to be created |
def extended_fade_in(self, segment, duration):
"""Add a fade-in to a segment that extends the beginning of the
segment.
:param segment: Segment to fade in
:type segment: :py:class:`radiotool.composer.Segment`
:param duration: Duration of fade-in (in seconds)
:returns: Th... | Add a fade-in to a segment that extends the beginning of the
segment.
:param segment: Segment to fade in
:type segment: :py:class:`radiotool.composer.Segment`
:param duration: Duration of fade-in (in seconds)
:returns: The fade that has been added to the composition
:rty... |
def _schedule_dependencies(dag):
"""
Computes an ordering < of tasks so that for any two tasks t and t' we have that if t depends on t' then
t' < t. In words, all dependencies of a task precede the task in this ordering.
:param dag: A directed acyclic graph representing dependencie... | Computes an ordering < of tasks so that for any two tasks t and t' we have that if t depends on t' then
t' < t. In words, all dependencies of a task precede the task in this ordering.
:param dag: A directed acyclic graph representing dependencies between tasks.
:type dag: DirectedGraph
... |
def stringfy(expr, sym_const=None, sym_states=None, sym_algebs=None):
"""Convert the right-hand-side of an equation into CVXOPT matrix operations"""
if not sym_const:
sym_const = []
if not sym_states:
sym_states = []
if not sym_algebs:
sym_algebs = []
expr_str = []
if typ... | Convert the right-hand-side of an equation into CVXOPT matrix operations |
def deployment_absent(name, namespace='default', **kwargs):
'''
Ensures that the named deployment is absent from the given namespace.
name
The name of the deployment
namespace
The name of the namespace
'''
ret = {'name': name,
'changes': {},
'result': Fal... | Ensures that the named deployment is absent from the given namespace.
name
The name of the deployment
namespace
The name of the namespace |
def parse_gradient_rgb_args(args):
""" Parse one or two rgb args given with --gradientrgb.
Raises InvalidArg for invalid rgb values.
Returns a tuple of (start_rgb, stop_rgb), where the stop_rgb may be
None if only one arg value was given and start_rgb may be None if
no values were gi... | Parse one or two rgb args given with --gradientrgb.
Raises InvalidArg for invalid rgb values.
Returns a tuple of (start_rgb, stop_rgb), where the stop_rgb may be
None if only one arg value was given and start_rgb may be None if
no values were given. |
def compensate_system_time_change(self, difference): # pragma: no cover,
# pylint: disable=too-many-branches
# not with unit tests
"""Compensate a system time change of difference for all hosts/services/checks/notifs
:param difference: difference in seconds
:type difference: in... | Compensate a system time change of difference for all hosts/services/checks/notifs
:param difference: difference in seconds
:type difference: int
:return: None |
def repair_central_directory(zipFile, is_file_instance): # source: https://bitbucket.org/openpyxl/openpyxl/src/93604327bce7aac5e8270674579af76d390e09c0/openpyxl/reader/excel.py?at=default&fileviewer=file-view-default
''' trims trailing data from the central directory
code taken from http://stackoverflow.com/a/7... | trims trailing data from the central directory
code taken from http://stackoverflow.com/a/7457686/570216, courtesy of Uri Cohen |
def PC_varExplained(Y,standardized=True):
"""
Run PCA and calculate the cumulative fraction of variance
Args:
Y: phenotype values
standardize: if True, phenotypes are standardized
Returns:
var: cumulative distribution of variance explained
"""
# figuring out the number of... | Run PCA and calculate the cumulative fraction of variance
Args:
Y: phenotype values
standardize: if True, phenotypes are standardized
Returns:
var: cumulative distribution of variance explained |
def export_content_groups(self, group_id, export_type, skip_notifications=None):
"""
Export content.
Begin a content export job for a course, group, or user.
You can use the {api:ProgressController#show Progress API} to track the
progress of the export. The migra... | Export content.
Begin a content export job for a course, group, or user.
You can use the {api:ProgressController#show Progress API} to track the
progress of the export. The migration's progress is linked to with the
_progress_url_ value.
When the export... |
def get_cluster_name(self):
"""
Name identifying this RabbitMQ cluster.
"""
return self._get(
url=self.url + '/api/cluster-name',
headers=self.headers,
auth=self.auth
) | Name identifying this RabbitMQ cluster. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.