code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def dihedral(x, dih):
""" Perform any of 8 permutations of 90-degrees rotations or flips for image x. """
x = np.rot90(x, dih%4)
return x if dih<4 else np.fliplr(x) | Perform any of 8 permutations of 90-degrees rotations or flips for image x. |
def get_bounding_box(self):
""" Get the bounding box of a pointlist. """
pointlist = self.get_pointlist()
# Initialize bounding box parameters to save values
minx, maxx = pointlist[0][0]["x"], pointlist[0][0]["x"]
miny, maxy = pointlist[0][0]["y"], pointlist[0][0]["y"]
m... | Get the bounding box of a pointlist. |
def box_model_domain(num_points=2, **kwargs):
"""Creates a box model domain (a single abstract axis).
:param int num_points: number of boxes [default: 2]
:returns: Domain with single axis of type ``'abstract'``
and ``self.domain_type = 'box'``
:rty... | Creates a box model domain (a single abstract axis).
:param int num_points: number of boxes [default: 2]
:returns: Domain with single axis of type ``'abstract'``
and ``self.domain_type = 'box'``
:rtype: :class:`_Domain`
:Exampl... |
def get_key_from_envs(envs, key):
"""Return the value of a key from the given dict respecting namespaces.
Data can also be a list of data dicts.
"""
# if it barks like a dict, make it a list have to use `get` since dicts and
# lists both have __getitem__
if hasattr(envs, 'get'):
envs =... | Return the value of a key from the given dict respecting namespaces.
Data can also be a list of data dicts. |
def vcenter_discovery_ignore_delete_all_response_ignore_value(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
vcenter = ET.SubElement(config, "vcenter", xmlns="urn:brocade.com:mgmt:brocade-vswitch")
id_key = ET.SubElement(vcenter, "id")
id_key.te... | Auto Generated Code |
def htmlTable(tableData, reads1, reads2, square, matchAmbiguous, colors,
concise=False, showLengths=False, showGaps=False, showNs=False,
footer=False, div=False, gapChars='-'):
"""
Make an HTML table showing inter-sequence distances.
@param tableData: A C{defaultdict(dict)} keye... | Make an HTML table showing inter-sequence distances.
@param tableData: A C{defaultdict(dict)} keyed by read ids, whose values
are the dictionaries returned by compareDNAReads.
@param reads1: An C{OrderedDict} of C{str} read ids whose values are
C{Read} instances. These will be the rows of the t... |
def output_dict(self):
"""Get dictionary representation of output arrays.
Returns
-------
output_dict : dict of str to NDArray
The dictionary that maps name of output names to NDArrays.
Raises
------
ValueError : if there are duplicated names in the ... | Get dictionary representation of output arrays.
Returns
-------
output_dict : dict of str to NDArray
The dictionary that maps name of output names to NDArrays.
Raises
------
ValueError : if there are duplicated names in the outputs. |
def monitor(self):
"""Commit this batch after sufficient time has elapsed.
This simply sleeps for ``self._settings.max_latency`` seconds,
and then calls commit unless the batch has already been committed.
"""
# NOTE: This blocks; it is up to the calling code to call it
#... | Commit this batch after sufficient time has elapsed.
This simply sleeps for ``self._settings.max_latency`` seconds,
and then calls commit unless the batch has already been committed. |
def get_file_range(ase, offsets, timeout=None):
# type: (blobxfer.models.azure.StorageEntity,
# blobxfer.models.download.Offsets, int) -> bytes
"""Retrieve file range
:param blobxfer.models.azure.StorageEntity ase: Azure StorageEntity
:param blobxfer.models.download.Offsets offsets: download ... | Retrieve file range
:param blobxfer.models.azure.StorageEntity ase: Azure StorageEntity
:param blobxfer.models.download.Offsets offsets: download offsets
:param int timeout: timeout
:rtype: bytes
:return: content for file range |
def from_image(cls, image, partname):
"""
Return an |ImagePart| instance newly created from *image* and
assigned *partname*.
"""
return ImagePart(partname, image.content_type, image.blob, image) | Return an |ImagePart| instance newly created from *image* and
assigned *partname*. |
def checkPidFile(pidfile):
""" mostly comes from _twistd_unix.py which is not twisted public API :-/
except it returns an exception instead of exiting
"""
if os.path.exists(pidfile):
try:
with open(pidfile) as f:
pid = int(f.read())
except ValueError:
... | mostly comes from _twistd_unix.py which is not twisted public API :-/
except it returns an exception instead of exiting |
def privmsg(self, target, message, nowait=False):
"""send a privmsg to target"""
if message:
messages = utils.split_message(message, self.config.max_length)
if isinstance(target, DCCChat):
for message in messages:
target.send_line(message)
... | send a privmsg to target |
def get_template_setting(template_key, default=None):
""" Read template settings """
templates_var = getattr(settings, 'TEMPLATES', None)
if templates_var:
for tdict in templates_var:
if template_key in tdict:
return tdict[template_key]
return default | Read template settings |
def export(self):
"""
Returns a representation of the Mechanism Name which is suitable for direct string
comparison against other exported Mechanism Names. Its form is defined in the GSSAPI
specification (RFC 2743). It can also be re-imported by constructing a :class:`Name` with
... | Returns a representation of the Mechanism Name which is suitable for direct string
comparison against other exported Mechanism Names. Its form is defined in the GSSAPI
specification (RFC 2743). It can also be re-imported by constructing a :class:`Name` with
the `name_type` param set to :const:`g... |
def check_marginal_likelihoods(tree, feature):
"""
Sanity check: combined bottom-up and top-down likelihood of each node of the tree must be the same.
:param tree: ete3.Tree, the tree of interest
:param feature: str, character for which the likelihood is calculated
:return: void, stores the node ma... | Sanity check: combined bottom-up and top-down likelihood of each node of the tree must be the same.
:param tree: ete3.Tree, the tree of interest
:param feature: str, character for which the likelihood is calculated
:return: void, stores the node marginal likelihoods in the get_personalised_feature_name(fea... |
def play_beat(
self,
frequencys,
play_time,
sample_rate=44100,
volume=0.01
):
'''
引数で指定した条件でビートを鳴らす
Args:
frequencys: (左の周波数(Hz), 右の周波数(Hz))のtuple
play_time: 再生時間(秒)
sample_rate: サンプルレート
... | 引数で指定した条件でビートを鳴らす
Args:
frequencys: (左の周波数(Hz), 右の周波数(Hz))のtuple
play_time: 再生時間(秒)
sample_rate: サンプルレート
volume: 音量
Returns:
void |
def combination_step(self):
"""Update auxiliary state by a smart combination of previous
updates in the frequency domain (standard FISTA
:cite:`beck-2009-fast`).
"""
# Update t step
tprv = self.t
self.t = 0.5 * float(1. + np.sqrt(1. + 4. * tprv**2))
# Up... | Update auxiliary state by a smart combination of previous
updates in the frequency domain (standard FISTA
:cite:`beck-2009-fast`). |
def agg_grid(grid, agg=None):
"""
Many functions return a 2d list with a complex data type in each cell.
For instance, grids representing environments have a set of resources,
while reading in multiple data files at once will yield a list
containing the values for that cell from each file. In order ... | Many functions return a 2d list with a complex data type in each cell.
For instance, grids representing environments have a set of resources,
while reading in multiple data files at once will yield a list
containing the values for that cell from each file. In order to visualize
these data types it is he... |
def decompose_code(code):
"""
Decomposes a MARC "code" into tag, ind1, ind2, subcode
"""
code = "%-6s" % code
ind1 = code[3:4]
if ind1 == " ": ind1 = "_"
ind2 = code[4:5]
if ind2 == " ": ind2 = "_"
subcode = code[5:6]
if subcode == " ": subcode = None
return (code[0:3], ind1,... | Decomposes a MARC "code" into tag, ind1, ind2, subcode |
def get_mapping(self, meta_fields=True):
'''
Returns the mapping for the index as a dictionary.
:param meta_fields: Also include elasticsearch meta fields in the dictionary.
:return: a dictionary which can be used to generate the elasticsearch index mapping for this doctype.
'''... | Returns the mapping for the index as a dictionary.
:param meta_fields: Also include elasticsearch meta fields in the dictionary.
:return: a dictionary which can be used to generate the elasticsearch index mapping for this doctype. |
def normalize_variable_name(node, reachability_tester):
# type: (Dict[str, Any], ReferenceReachabilityTester) -> Optional[str]
""" Returns normalized variable name.
Normalizing means that variable names get explicit visibility by
visibility prefix such as: "g:", "s:", ...
Returns None if the specif... | Returns normalized variable name.
Normalizing means that variable names get explicit visibility by
visibility prefix such as: "g:", "s:", ...
Returns None if the specified node is unanalyzable.
A node is unanalyzable if:
- the node is not identifier-like
- the node is named dynamically |
def _get_container(self, path):
"""Return single container."""
cont = self.native_conn.get_container(path)
return self.cont_cls(self,
cont.name,
cont.object_count,
cont.size_used) | Return single container. |
def execute(self):
"""
Execute the query with optional timeout. The response to the execute
query is the raw payload received from the websocket and will contain
multiple dict keys and values. It is more common to call query.fetch_XXX
which will filter the return result based on ... | Execute the query with optional timeout. The response to the execute
query is the raw payload received from the websocket and will contain
multiple dict keys and values. It is more common to call query.fetch_XXX
which will filter the return result based on the method. Each result set
wil... |
def http_basic_auth_group_member_required(groups):
"""Decorator. Use it to specify a RPC method is available only to logged users with given permissions"""
if isinstance(groups, six.string_types):
# Check user is in a group
return auth.set_authentication_predicate(http_basic_auth_check_user, [a... | Decorator. Use it to specify a RPC method is available only to logged users with given permissions |
def get_neighbor_out_filter(neigh_ip_address):
"""Returns a neighbor out_filter for given ip address if exists."""
core = CORE_MANAGER.get_core_service()
ret = core.peer_manager.get_by_addr(neigh_ip_address).out_filters
return ret | Returns a neighbor out_filter for given ip address if exists. |
def multi_index(idx, dim):
"""
Single to multi-index using graded reverse lexicographical notation.
Parameters
----------
idx : int
Index in interger notation
dim : int
The number of dimensions in the multi-index notation
Returns
-------
out : tuple
Multi-in... | Single to multi-index using graded reverse lexicographical notation.
Parameters
----------
idx : int
Index in interger notation
dim : int
The number of dimensions in the multi-index notation
Returns
-------
out : tuple
Multi-index of `idx` with `len(out)=dim`
E... |
def update_event(self, event, action, flags):
"""
Called by libcouchbase to add/remove event watchers
"""
if action == PYCBC_EVACTION_UNWATCH:
if event.flags & LCB_READ_EVENT:
self.reactor.removeReader(event)
if event.flags & LCB_WRITE_EVENT:
... | Called by libcouchbase to add/remove event watchers |
def plot_reliability_diagram(confidence, labels, filepath):
"""
Takes in confidence values for predictions and correct
labels for the data, plots a reliability diagram.
:param confidence: nb_samples x nb_classes (e.g., output of softmax)
:param labels: vector of nb_samples
:param filepath: where to save the... | Takes in confidence values for predictions and correct
labels for the data, plots a reliability diagram.
:param confidence: nb_samples x nb_classes (e.g., output of softmax)
:param labels: vector of nb_samples
:param filepath: where to save the diagram
:return: |
def password_credentials(self, username, password, **kwargs):
"""
Retrieve access token by 'password credentials' grant.
https://tools.ietf.org/html/rfc6749#section-4.3
:param str username: The user name to obtain an access token for
:param str password: The user's password
... | Retrieve access token by 'password credentials' grant.
https://tools.ietf.org/html/rfc6749#section-4.3
:param str username: The user name to obtain an access token for
:param str password: The user's password
:rtype: dict
:return: Access token response |
def tile_2d(physical_shape, tile_shape,
outer_name="outer",
inner_name="inner",
cores_name=None):
"""2D tiling of a 3d physical mesh.
The "outer" mesh dimension corresponds to which tile.
The "inner" mesh dimension corresponds to the position within a tile
of processors.
... | 2D tiling of a 3d physical mesh.
The "outer" mesh dimension corresponds to which tile.
The "inner" mesh dimension corresponds to the position within a tile
of processors.
Optionally, if cores_name is specified, then a 3 dimensional logical mesh
is returned, with the third dimension representing the two diff... |
def _Members(self, group):
"""Unify members of a group and accounts with the group as primary gid."""
group.members = set(group.members).union(self.gids.get(group.gid, []))
return group | Unify members of a group and accounts with the group as primary gid. |
def _bfgs_inv_hessian_update(grad_delta, position_delta, normalization_factor,
inv_hessian_estimate):
"""Applies the BFGS update to the inverse Hessian estimate.
The BFGS update rule is (note A^T denotes the transpose of a vector/matrix A).
```None
rho = 1/(grad_delta^T * positi... | Applies the BFGS update to the inverse Hessian estimate.
The BFGS update rule is (note A^T denotes the transpose of a vector/matrix A).
```None
rho = 1/(grad_delta^T * position_delta)
U = (I - rho * position_delta * grad_delta^T)
H_1 = U * H_0 * U^T + rho * position_delta * position_delta^T
```
... |
def from_json(cls, json):
"""Creates an instance of the InputReader for the given input shard state.
Args:
json: The InputReader state as a dict-like object.
Returns:
An instance of the InputReader configured using the values of json.
"""
result = super(_ReducerReader, cls).from_json(j... | Creates an instance of the InputReader for the given input shard state.
Args:
json: The InputReader state as a dict-like object.
Returns:
An instance of the InputReader configured using the values of json. |
def print_progress_bar(self, task):
"""
Draws a progress bar on screen based on the given information using standard output (stdout).
:param task: TaskProgress object containing all required information to draw a progress bar at the given state.
"""
str_format = "{0:." + str(task... | Draws a progress bar on screen based on the given information using standard output (stdout).
:param task: TaskProgress object containing all required information to draw a progress bar at the given state. |
def _waitFor(self, timeout, notification, **kwargs):
"""Wait for a particular UI event to occur; this can be built
upon in NativeUIElement for specific convenience methods.
"""
callback = self._matchOther
retelem = None
callbackArgs = None
callbackKwargs = None
... | Wait for a particular UI event to occur; this can be built
upon in NativeUIElement for specific convenience methods. |
def _get(relative_path, genome=None):
"""
:param relative_path: relative path of the file inside the repository
:param genome: genome name. Can contain chromosome name after comma, like hg19-chr20,
in case of BED, the returning BedTool will be with added filter.
:return: BedTools obje... | :param relative_path: relative path of the file inside the repository
:param genome: genome name. Can contain chromosome name after comma, like hg19-chr20,
in case of BED, the returning BedTool will be with added filter.
:return: BedTools object if it's a BED file, or filepath |
def get_select_items(items):
"""Return list of possible select items."""
option_items = list()
for item in items:
if isinstance(item, dict) and defs.VALUE in item and defs.LABEL in item:
option_items.append(item[defs.VALUE])
else:
raise exceptions.ParametersFieldError... | Return list of possible select items. |
def _create_delete_one_query(self, row_id, ctx):
"""
Delete row by id query creation.
:param int row_id: Identifier of the deleted row.
:param ResourceQueryContext ctx: The context of this delete query.
"""
assert isinstance(ctx, ResourceQueryContext)
return sel... | Delete row by id query creation.
:param int row_id: Identifier of the deleted row.
:param ResourceQueryContext ctx: The context of this delete query. |
def transfer_to(self, cloudpath, bbox, block_size=None, compress=True):
"""
Transfer files from one storage location to another, bypassing
volume painting. This enables using a single CloudVolume instance
to transfer big volumes. In some cases, gsutil or aws s3 cli tools
may be more appropriate. Thi... | Transfer files from one storage location to another, bypassing
volume painting. This enables using a single CloudVolume instance
to transfer big volumes. In some cases, gsutil or aws s3 cli tools
may be more appropriate. This method is provided for convenience. It
may be optimized for better performance... |
def success(item):
'''Successful finish'''
try:
# mv to done
trg_queue = item.queue
os.rename(fsq_path.item(trg_queue, item.id, host=item.host),
os.path.join(fsq_path.done(trg_queue, host=item.host),
item.id))
except AttributeError, e:... | Successful finish |
def append_to_table(self, table):
"""Add this instance as a row on a `astropy.table.Table` """
table.add_row(dict(path=self.path,
key=self.key,
creator=self.creator,
timestamp=self.timestamp,
stat... | Add this instance as a row on a `astropy.table.Table` |
def _get_font_size(document, style):
"""Get font size defined for this style.
It will try to get font size from it's parent style if it is not defined by original style.
:Args:
- document (:class:`ooxml.doc.Document`): Document object
- style (:class:`ooxml.doc.Style`): Style object
:Ret... | Get font size defined for this style.
It will try to get font size from it's parent style if it is not defined by original style.
:Args:
- document (:class:`ooxml.doc.Document`): Document object
- style (:class:`ooxml.doc.Style`): Style object
:Returns:
Returns font size as a number. -... |
def connect(self, ctrl):
"""Connect to the device."""
if self.prompt:
self.prompt_re = self.driver.make_dynamic_prompt(self.prompt)
else:
self.prompt_re = self.driver.prompt_re
self.ctrl = ctrl
if self.protocol.connect(self.driver):
if self.pr... | Connect to the device. |
def _get_config_int(self, section: str, key: str, fallback: int=object()) -> int:
"""
Gets an int config value
:param section: Section
:param key: Key
:param fallback: Optional fallback value
"""
return self._config.getint(section, key, fallback=fallback) | Gets an int config value
:param section: Section
:param key: Key
:param fallback: Optional fallback value |
def init_batch(raw_constraints: List[Optional[RawConstraintList]],
beam_size: int,
start_id: int,
eos_id: int) -> List[Optional[ConstrainedHypothesis]]:
"""
:param raw_constraints: The list of raw constraints (list of list of IDs).
:param beam_size: The beam size... | :param raw_constraints: The list of raw constraints (list of list of IDs).
:param beam_size: The beam size.
:param start_id: The target-language vocabulary ID of the SOS symbol.
:param eos_id: The target-language vocabulary ID of the EOS symbol.
:return: A list of ConstrainedHypothesis objects (shape: (... |
def h3(data, *args, **kwargs):
"""Facade function to create 3D histograms.
Parameters
----------
data : array_like or list[array_like] or tuple[array_like]
Can be a single array (with three columns) or three different arrays
(for each component)
Returns
-------
physt.histog... | Facade function to create 3D histograms.
Parameters
----------
data : array_like or list[array_like] or tuple[array_like]
Can be a single array (with three columns) or three different arrays
(for each component)
Returns
-------
physt.histogram_nd.HistogramND |
def report_saved(report_stats):
"""Record the percent saved & print it."""
if Settings.verbose:
report = ''
truncated_filename = truncate_cwd(report_stats.final_filename)
report += '{}: '.format(truncated_filename)
total = new_percent_saved(report_stats)
if total:
... | Record the percent saved & print it. |
def _get_value(context, key):
"""
Retrieve a key's value from a context item.
Returns _NOT_FOUND if the key does not exist.
The ContextStack.get() docstring documents this function's intended behavior.
"""
if isinstance(context, dict):
# Then we consider the argument a "hash" for the ... | Retrieve a key's value from a context item.
Returns _NOT_FOUND if the key does not exist.
The ContextStack.get() docstring documents this function's intended behavior. |
def _find_files(root, includes, excludes, follow_symlinks):
"""List files inside a directory based on include and exclude rules.
This is a more advanced version of `glob.glob`, that accepts multiple
complex patterns.
Args:
root (str): base directory to list files from.
includes (list[s... | List files inside a directory based on include and exclude rules.
This is a more advanced version of `glob.glob`, that accepts multiple
complex patterns.
Args:
root (str): base directory to list files from.
includes (list[str]): inclusion patterns. Only files matching those
pat... |
def convert_objects(self, convert_dates=True, convert_numeric=False,
convert_timedeltas=True, copy=True):
"""
Attempt to infer better dtype for object columns.
.. deprecated:: 0.21.0
Parameters
----------
convert_dates : boolean, default True
... | Attempt to infer better dtype for object columns.
.. deprecated:: 0.21.0
Parameters
----------
convert_dates : boolean, default True
If True, convert to date where possible. If 'coerce', force
conversion, with unconvertible values becoming NaT.
convert_n... |
def parse_headers(
self,
lines: List[bytes]
) -> Tuple['CIMultiDictProxy[str]',
RawHeaders,
Optional[bool],
Optional[str],
bool,
bool]:
"""Parses RFC 5322 headers from a stream.
Line continuations are... | Parses RFC 5322 headers from a stream.
Line continuations are supported. Returns list of header name
and value pairs. Header name is in upper case. |
def _filter_xpath_grouping(xpath):
"""
This method removes the outer parentheses for xpath grouping.
The xpath converter will break otherwise.
Example:
"(//button[@type='submit'])[1]" becomes "//button[@type='submit'][1]"
"""
# First remove the first open parentheses
xpath = xpath[1:]
... | This method removes the outer parentheses for xpath grouping.
The xpath converter will break otherwise.
Example:
"(//button[@type='submit'])[1]" becomes "//button[@type='submit'][1]" |
def _get_db():
"""
Get database from server
"""
with cd(env.remote_path):
file_path = '/tmp/' + _sql_paths('remote', str(base64.urlsafe_b64encode(uuid.uuid4().bytes)).replace('=', ''))
run(env.python + ' manage.py dump_database | gzip > ' + file_path)
local_file_path = './bac... | Get database from server |
def get_io_write_task(self, fileobj, data, offset):
"""Get an IO write task for the requested set of data
This task can be ran immediately or be submitted to the IO executor
for it to run.
:type fileobj: file-like object
:param fileobj: The file-like object to write to
... | Get an IO write task for the requested set of data
This task can be ran immediately or be submitted to the IO executor
for it to run.
:type fileobj: file-like object
:param fileobj: The file-like object to write to
:type data: bytes
:param data: The data to write out
... |
def critical(self, event=None, *args, **kw):
"""
Process event and call :meth:`logging.Logger.critical` with the result.
"""
if not self._logger.isEnabledFor(logging.CRITICAL):
return
kw = self._add_base_info(kw)
kw['level'] = "critical"
return self._... | Process event and call :meth:`logging.Logger.critical` with the result. |
def mass_fractions(self):
r'''Dictionary of atom:mass-weighted fractional occurence of elements.
Useful when performing mass balances. For atom-fraction occurences, see
:obj:`atom_fractions`.
Examples
--------
>>> Chemical('water').mass_fractions
{'H': 0.11189834... | r'''Dictionary of atom:mass-weighted fractional occurence of elements.
Useful when performing mass balances. For atom-fraction occurences, see
:obj:`atom_fractions`.
Examples
--------
>>> Chemical('water').mass_fractions
{'H': 0.11189834407236524, 'O': 0.8881016559276347... |
def _summarize_peaks(peaks):
"""
merge peaks position if closer than 10
"""
previous = peaks[0]
new_peaks = [previous]
for pos in peaks:
if pos > previous + 10:
new_peaks.add(pos)
previous = pos
return new_peaks | merge peaks position if closer than 10 |
def log_run(self):
""" Log timestamp and raiden version to help with debugging """
version = get_system_spec()['raiden']
cursor = self.conn.cursor()
cursor.execute('INSERT INTO runs(raiden_version) VALUES (?)', [version])
self.maybe_commit() | Log timestamp and raiden version to help with debugging |
def GetDetectorData(detectorName):
""" GetDetectorData - function to return the locations and detector response
tensor of the detector described by detectorName.
detectorName - Name of required GW IFO. Can be 'H1', 'L1', 'V1', 'I1'
or 'K1'.
Returns detRespTensor - Detector response tensor of the IFO.
... | GetDetectorData - function to return the locations and detector response
tensor of the detector described by detectorName.
detectorName - Name of required GW IFO. Can be 'H1', 'L1', 'V1', 'I1'
or 'K1'.
Returns detRespTensor - Detector response tensor of the IFO.
detPosVector - Position vector of the IFO.
... |
def set_jenkins_rename_file(self, nodes_rename_file):
""" File with nodes renaming mapping:
Node,Comment
arm-build1,remove
arm-build2,keep
ericsson-build3,merge into ericsson-build1
....
Once set in the next enrichment the rename will be done
"""
... | File with nodes renaming mapping:
Node,Comment
arm-build1,remove
arm-build2,keep
ericsson-build3,merge into ericsson-build1
....
Once set in the next enrichment the rename will be done |
def reset(self):
"""
Clear all cell activity.
"""
self.L4.reset()
for module in self.L6aModules:
module.reset() | Clear all cell activity. |
def get_comment_lookup_session_for_book(self, book_id, proxy):
"""Gets the ``OsidSession`` associated with the comment lookup service for the given book.
arg: book_id (osid.id.Id): the ``Id`` of the ``Book``
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.commenting.CommentLo... | Gets the ``OsidSession`` associated with the comment lookup service for the given book.
arg: book_id (osid.id.Id): the ``Id`` of the ``Book``
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.commenting.CommentLookupSession) - a
``CommentLookupSession``
raise: ... |
def add_derived_identity(self, id_stmt):
"""Add pattern def for `id_stmt` and all derived identities.
The corresponding "ref" pattern is returned.
"""
p = self.add_namespace(id_stmt.main_module())
if id_stmt not in self.identities: # add named pattern def
self.iden... | Add pattern def for `id_stmt` and all derived identities.
The corresponding "ref" pattern is returned. |
def call_use_cached_files(tup):
"""Importable helper for multi-proc calling of ArtifactCache.use_cached_files on a cache instance.
Multiprocessing map/apply/etc require functions which can be imported, not bound methods.
To call a bound method, instead call a helper like this and pass tuple of the instance and a... | Importable helper for multi-proc calling of ArtifactCache.use_cached_files on a cache instance.
Multiprocessing map/apply/etc require functions which can be imported, not bound methods.
To call a bound method, instead call a helper like this and pass tuple of the instance and args.
The helper can then call the o... |
def trans_history(
self, from_=None, count=None, from_id=None, end_id=None,
order=None, since=None, end=None
):
"""
Returns the history of transactions.
To use this method you need a privilege of the info key.
:param int or None from_: transaction ID, from which the ... | Returns the history of transactions.
To use this method you need a privilege of the info key.
:param int or None from_: transaction ID, from which the display starts (default 0)
:param int or None count: number of transaction to be displayed (default 1000)
:param int or None from_id: tr... |
def find_checkpoints(model_path: str, size=4, strategy="best", metric: str = C.PERPLEXITY) -> List[str]:
"""
Finds N best points from .metrics file according to strategy.
:param model_path: Path to model.
:param size: Number of checkpoints to combine.
:param strategy: Combination strategy.
:par... | Finds N best points from .metrics file according to strategy.
:param model_path: Path to model.
:param size: Number of checkpoints to combine.
:param strategy: Combination strategy.
:param metric: Metric according to which checkpoints are selected. Corresponds to columns in model/metrics file.
:re... |
def add_permission_role(self, role, perm_view):
"""
Add permission-ViewMenu object to Role
:param role:
The role object
:param perm_view:
The PermissionViewMenu object
"""
if perm_view not in role.permissions:
try:
... | Add permission-ViewMenu object to Role
:param role:
The role object
:param perm_view:
The PermissionViewMenu object |
def set_window_size_callback(window, cbfun):
"""
Sets the size callback for the specified window.
Wrapper for:
GLFWwindowsizefun glfwSetWindowSizeCallback(GLFWwindow* window, GLFWwindowsizefun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes... | Sets the size callback for the specified window.
Wrapper for:
GLFWwindowsizefun glfwSetWindowSizeCallback(GLFWwindow* window, GLFWwindowsizefun cbfun); |
def log_request(request: str, trim_log_values: bool = False, **kwargs: Any) -> None:
"""Log a request"""
return log_(request, request_logger, logging.INFO, trim=trim_log_values, **kwargs) | Log a request |
def fix_config(self, options):
"""
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict
"""
opt = "db_url"
... | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict |
def create_raw(self, key, value):
"""Create method of CRUD operation for raw data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result of DB write.
"""
data = None
i... | Create method of CRUD operation for raw data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result of DB write. |
def call():
"""Execute command line helper."""
args = get_arguments()
# Set up logging
if args.debug:
log_level = logging.DEBUG
elif args.quiet:
log_level = logging.WARN
else:
log_level = logging.INFO
setup_logging(log_level)
abode = None
if not args.cache... | Execute command line helper. |
def idle_all_workers(self):
'''Set the global mode to :attr:`IDLE` and wait for workers to stop.
This can wait arbitrarily long before returning. The worst
case in "normal" usage involves waiting five minutes for a
"lost" job to expire; a well-behaved but very-long-running job
... | Set the global mode to :attr:`IDLE` and wait for workers to stop.
This can wait arbitrarily long before returning. The worst
case in "normal" usage involves waiting five minutes for a
"lost" job to expire; a well-behaved but very-long-running job
can extend its own lease further, and t... |
def sample(self, bqm, scalar=None, bias_range=1, quadratic_range=None,
ignored_variables=None, ignored_interactions=None,
ignore_offset=False, **parameters):
""" Scale and sample from the provided binary quadratic model.
if scalar is not given, problem is scaled based on b... | Scale and sample from the provided binary quadratic model.
if scalar is not given, problem is scaled based on bias and quadratic
ranges. See :meth:`.BinaryQuadraticModel.scale` and
:meth:`.BinaryQuadraticModel.normalize`
Args:
bqm (:obj:`dimod.BinaryQuadraticModel`):
... |
def safe_search_detection(
self, image, max_results=None, retry=None, timeout=None, additional_properties=None
):
"""
For the documentation see:
:py:class:`~airflow.contrib.operators.gcp_vision_operator.CloudVisionDetectImageSafeSearchOperator`
"""
client = self.annot... | For the documentation see:
:py:class:`~airflow.contrib.operators.gcp_vision_operator.CloudVisionDetectImageSafeSearchOperator` |
def salt_call():
'''
Directly call a salt command in the modules, does not require a running
salt minion to run.
'''
import salt.cli.call
if '' in sys.path:
sys.path.remove('')
client = salt.cli.call.SaltCall()
_install_signal_handlers(client)
client.run() | Directly call a salt command in the modules, does not require a running
salt minion to run. |
def download_file_content(self, file_id, etag=None):
'''Download file content.
Args:
file_id (str): The UUID of the file whose content is requested
etag (str): If the content is not changed since the provided ETag,
the content won't be downloaded. If the content ... | Download file content.
Args:
file_id (str): The UUID of the file whose content is requested
etag (str): If the content is not changed since the provided ETag,
the content won't be downloaded. If the content is changed, it
will be downloaded and returned w... |
def unzip(seq, elem_len=None):
"""Unzip a length n sequence of length m sequences into m seperate length
n sequences.
Parameters
----------
seq : iterable[iterable]
The sequence to unzip.
elem_len : int, optional
The expected length of each element of ``seq``. If not provided thi... | Unzip a length n sequence of length m sequences into m seperate length
n sequences.
Parameters
----------
seq : iterable[iterable]
The sequence to unzip.
elem_len : int, optional
The expected length of each element of ``seq``. If not provided this
will be infered from the len... |
def encode(self, key):
"""Encodes a user key into a particular format. The result of this method
will be used by swauth for storing user credentials.
If salt is not manually set in conf file, a random salt will be
generated and used.
:param key: User's secret key
:retur... | Encodes a user key into a particular format. The result of this method
will be used by swauth for storing user credentials.
If salt is not manually set in conf file, a random salt will be
generated and used.
:param key: User's secret key
:returns: A string representing user cre... |
def with_timeout(
timeout: Union[float, datetime.timedelta],
future: _Yieldable,
quiet_exceptions: "Union[Type[Exception], Tuple[Type[Exception], ...]]" = (),
) -> Future:
"""Wraps a `.Future` (or other yieldable object) in a timeout.
Raises `tornado.util.TimeoutError` if the input future does not
... | Wraps a `.Future` (or other yieldable object) in a timeout.
Raises `tornado.util.TimeoutError` if the input future does not
complete before ``timeout``, which may be specified in any form
allowed by `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or
an absolute time relative to `.IOLoop.time`)
... |
def dr( self, r1, r2, cutoff=None ):
"""
Calculate the distance between two fractional coordinates in the cell.
Args:
r1 (np.array): fractional coordinates for position 1.
r2 (np.array): fractional coordinates for position 2.
cutoff (optional:Bool): I... | Calculate the distance between two fractional coordinates in the cell.
Args:
r1 (np.array): fractional coordinates for position 1.
r2 (np.array): fractional coordinates for position 2.
cutoff (optional:Bool): If set, returns None for distances greater than the cutoff... |
def _is_accepted_input(self, input_string):
""" vlc input filtering """
ret = False
accept_filter = (self.volume_string, "http stream debug: ")
reject_filter = ()
for n in accept_filter:
if n in input_string:
ret = True
break
if... | vlc input filtering |
def main(print_cfg):
"""Main function which parses user options and generate jobs accordingly"""
parser = argparse.ArgumentParser(description="mvmany.py -- MVtest helper script.", epilog="""
mvmany.py should be run with all arguments you would pass to mvtest.py, except
for those which are specific to a single n... | Main function which parses user options and generate jobs accordingly |
def from_spec(spec, kwargs=None):
"""
Creates a distribution from a specification dict.
"""
distribution = util.get_object(
obj=spec,
predefined_objects=tensorforce.core.distributions.distributions,
kwargs=kwargs
)
assert isinstance(dis... | Creates a distribution from a specification dict. |
def sync(self, vault_client, opt):
"""Synchronizes the context to the Vault server. This
has the effect of updating every resource which is
in the context and has changes pending."""
active_mounts = []
for audit_log in self.logs():
audit_log.sync(vault_client)
... | Synchronizes the context to the Vault server. This
has the effect of updating every resource which is
in the context and has changes pending. |
def is_supported(cls, file=None, request=None, response=None,
url_info=None):
'''Given the hints, return whether the document is supported.
Args:
file: A file object containing the document.
request (:class:`.http.request.Request`): An HTTP request.
... | Given the hints, return whether the document is supported.
Args:
file: A file object containing the document.
request (:class:`.http.request.Request`): An HTTP request.
response (:class:`.http.request.Response`): An HTTP response.
url_info (:class:`.url.URLInfo`)... |
def read_sla(self,filename,params=None,force=False,timerange=None,datatype=None,**kwargs):
"""
Read AVISO Along-Track products
:return outStr: Output data structure containing all recorded parameters as specificied by NetCDF file PARAMETER list.
:author: Renaud Du... | Read AVISO Along-Track products
:return outStr: Output data structure containing all recorded parameters as specificied by NetCDF file PARAMETER list.
:author: Renaud Dussurget |
def outputMode(self, outputMode):
"""Specifies how data of a streaming DataFrame/Dataset is written to a streaming sink.
Options include:
* `append`:Only the new rows in the streaming DataFrame/Dataset will be written to
the sink
* `complete`:All the rows in the streaming Da... | Specifies how data of a streaming DataFrame/Dataset is written to a streaming sink.
Options include:
* `append`:Only the new rows in the streaming DataFrame/Dataset will be written to
the sink
* `complete`:All the rows in the streaming DataFrame/Dataset will be written to the sink
... |
def parse_url(cls, string): # pylint: disable=redefined-outer-name
"""
If it can be parsed as a version_guid with no preceding org + offering, returns a dict
with key 'version_guid' and the value,
If it can be parsed as a org + offering, returns a dict
with key 'id' and optiona... | If it can be parsed as a version_guid with no preceding org + offering, returns a dict
with key 'version_guid' and the value,
If it can be parsed as a org + offering, returns a dict
with key 'id' and optional keys 'branch' and 'version_guid'.
Raises:
InvalidKeyError: if str... |
def color_msg(msg, color):
" Return colored message "
return ''.join((COLORS.get(color, COLORS['endc']), msg, COLORS['endc'])) | Return colored message |
def blast_records_to_object(blast_records):
"""Transforms biopython's blast record into blast object defined in django-blastplus app. """
# container for transformed objects
blast_objects_list = []
for blast_record in blast_records:
br = BlastRecord(**{'query': blast_record.query,
... | Transforms biopython's blast record into blast object defined in django-blastplus app. |
def htmlFromThing(thing,title):
"""create pretty formatted HTML from a things dictionary."""
try:
thing2 = copy.copy(thing)
except:
print("crashed copying the thing! I can't document it.")
return False
stuff=analyzeThing(thing2)
names2=list(stuff.keys())
for i,na... | create pretty formatted HTML from a things dictionary. |
def rpc_get_oneline_docstring(self, filename, source, offset):
"""Return a oneline docstring for the symbol at offset"""
line, column = pos_to_linecol(source, offset)
definitions = run_with_debug(jedi, 'goto_definitions',
source=source, line=line, column=colu... | Return a oneline docstring for the symbol at offset |
def set_branching_model(self, project, repository, data):
"""
Set branching model
:param project:
:param repository:
:param data:
:return:
"""
url = 'rest/branch-utils/1.0/projects/{project}/repos/{repository}/branchmodel/configuration'.format(
... | Set branching model
:param project:
:param repository:
:param data:
:return: |
def delete_items_from_dict(d, to_delete):
"""Recursively deletes items from a dict,
if the item's value(s) is in ``to_delete``.
"""
if not isinstance(to_delete, list):
to_delete = [to_delete]
if isinstance(d, dict):
for single_to_delete in set(to_delete):
if single_to_del... | Recursively deletes items from a dict,
if the item's value(s) is in ``to_delete``. |
def set_cookie(self, key, value='', max_age=None, path='/', domain=None,
secure=False, httponly=False, expires=None):
"""Set a response cookie.
Parameters:
key
: The cookie name.
value
: The cookie value.
max_age
: The maximum ag... | Set a response cookie.
Parameters:
key
: The cookie name.
value
: The cookie value.
max_age
: The maximum age of the cookie in seconds, or as a
datetime.timedelta object.
path
: Restrict the cookie to this path (default: '/').... |
def initialize_weights(self, save_file):
"""Initialize the weights from the given save_file.
Assumes that the graph has been constructed, and the
save_file contains weights that match the graph. Used
to set the weights to a different version of the player
without redifining the e... | Initialize the weights from the given save_file.
Assumes that the graph has been constructed, and the
save_file contains weights that match the graph. Used
to set the weights to a different version of the player
without redifining the entire graph. |
def ensure_dir_exists(func):
"wrap a function that returns a dir, making sure it exists"
@functools.wraps(func)
def make_if_not_present():
dir = func()
if not os.path.isdir(dir):
os.makedirs(dir)
return dir
return make_if_not_present | wrap a function that returns a dir, making sure it exists |
def send_mail_worker(config, mail, event):
"""Worker task to send out an email, which blocks the process unless it is threaded"""
log = ""
try:
if config.mail_ssl:
server = SMTP_SSL(config.mail_server, port=config.mail_server_port, timeout=30)
else:
server = SMTP(con... | Worker task to send out an email, which blocks the process unless it is threaded |
def delete(self, queue, virtual_host='/'):
"""Delete a Queue.
:param str queue: Queue name
:param str virtual_host: Virtual host name
:raises ApiError: Raises if the remote server encountered an error.
:raises ApiConnectionError: Raises if there was a connectivity issue.
... | Delete a Queue.
:param str queue: Queue name
:param str virtual_host: Virtual host name
:raises ApiError: Raises if the remote server encountered an error.
:raises ApiConnectionError: Raises if there was a connectivity issue.
:rtype: dict |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.