code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def get_connection(self, host, port):
'''Open a socket connection to a given host and port and writes the Hadoop header
The Hadoop RPC protocol looks like this when creating a connection:
+---------------------------------------------------------------------+
| Header, 4 bytes ("hrpc")... | Open a socket connection to a given host and port and writes the Hadoop header
The Hadoop RPC protocol looks like this when creating a connection:
+---------------------------------------------------------------------+
| Header, 4 bytes ("hrpc") |
... |
def get_name_DID_info(self, name):
"""
Get a name's DID info
Returns None if not found
"""
db = get_db_state(self.working_dir)
did_info = db.get_name_DID_info(name)
if did_info is None:
return {'error': 'No such name', 'http_status': 404}
retu... | Get a name's DID info
Returns None if not found |
def ColorWithLightness(self, lightness):
'''Create a new instance based on this one with a new lightness value.
Parameters:
:lightness:
The lightness of the new color [0...1].
Returns:
A grapefruit.Color instance.
>>> Color.NewFromHsl(30, 1, 0.5).ColorWithLightness(0.25)
(0.5,... | Create a new instance based on this one with a new lightness value.
Parameters:
:lightness:
The lightness of the new color [0...1].
Returns:
A grapefruit.Color instance.
>>> Color.NewFromHsl(30, 1, 0.5).ColorWithLightness(0.25)
(0.5, 0.25, 0.0, 1.0)
>>> Color.NewFromHsl(30, 1,... |
def _cast_float(temp_dt):
"""returns utc timestamp"""
if type(temp_dt) == str:
fmt = '%Y-%m-%dT%H:%M:00'
base_dt = temp_dt[0:19]
tz_offset = eval(temp_dt[19:22])
temp_dt = datetime.datetime.strptime(base_dt, fmt) - \
datetime.timedelta(hours=tz_offset)
return ... | returns utc timestamp |
def unique_str(self):
""" A string that (ideally) uniquely represents this GC object. This
helps with naming files for caching. 'Unique' is defined as 'If
GC1 != GC2, then GC1.unique_str() != GC2.unique_str()'; conversely,
'If GC1 == GC2, then GC1.unique_str() == GC2.unique_str()'.
... | A string that (ideally) uniquely represents this GC object. This
helps with naming files for caching. 'Unique' is defined as 'If
GC1 != GC2, then GC1.unique_str() != GC2.unique_str()'; conversely,
'If GC1 == GC2, then GC1.unique_str() == GC2.unique_str()'.
The string should be filename-... |
def idf(self, term, transform=None):
r"""Calculate the Inverse Document Frequency of a term in the corpus.
Parameters
----------
term : str
The term to calculate the IDF of
transform : function
A function to apply to each document term before checking for... | r"""Calculate the Inverse Document Frequency of a term in the corpus.
Parameters
----------
term : str
The term to calculate the IDF of
transform : function
A function to apply to each document term before checking for the
presence of term
Re... |
def ev_to_s(offset_us, source_to_detector_m, array):
# delay values is normal 2.99 us with NONE actual MCP delay settings
"""convert energy (eV) to time (us)
Parameters:
===========
array: array (in eV)
offset_us: float. Delay of detector in us
source_to_detector_m: float. Distance source t... | convert energy (eV) to time (us)
Parameters:
===========
array: array (in eV)
offset_us: float. Delay of detector in us
source_to_detector_m: float. Distance source to detector in m
Returns:
========
time: array in s |
def step1(self, username, password):
"""First authentication step."""
self._check_initialized()
context = AtvSRPContext(
str(username), str(password),
prime=constants.PRIME_2048,
generator=constants.PRIME_2048_GEN)
self.session = SRPClientSession(
... | First authentication step. |
def mass_tot(self, rho0, Rs):
"""
total mass within the profile
:param rho0:
:param a:
:param s:
:return:
"""
m_tot = 2*np.pi*rho0*Rs**3
return m_tot | total mass within the profile
:param rho0:
:param a:
:param s:
:return: |
def list_commands(self, ctx):
"""List commands from folder."""
rv = []
files = [_ for _ in next(os.walk(self.folder))[2] if not _.startswith("_") and _.endswith(".py")]
for filename in files:
rv.append(filename[:-3])
rv.sort()
return rv | List commands from folder. |
def query_string(cls,
query,
default_field=None,
default_operator=None,
analyzer=None,
allow_leading_wildcard=None,
lowercase_expanded_terms=None,
enable_position_increments... | http://www.elasticsearch.org/guide/reference/query-dsl/query-string-query.html
A query that uses a query parser in order to parse its content.
> query = ElasticQuery().query_string('this AND that OR thus', default_field='content') |
def get(self, fragment_info):
"""
Get the value associated with the given key.
:param fragment_info: the text key
:type fragment_info: tuple of str ``(language, text)``
:raises: KeyError if the key is not present in the cache
"""
if not self.is_cached(fragment_i... | Get the value associated with the given key.
:param fragment_info: the text key
:type fragment_info: tuple of str ``(language, text)``
:raises: KeyError if the key is not present in the cache |
def __package_app(tasks_pkg, dist_dir, custom_main=None, extra_data=None):
"""
Packages the `tasks_pkg` (as zip) to `dist_dir`. Also copies the 'main' python file to
`dist_dir`, to be submitted to spark. Same for `extra_data`.
Parameters
----------
tasks_pkg (str): Path to the python package co... | Packages the `tasks_pkg` (as zip) to `dist_dir`. Also copies the 'main' python file to
`dist_dir`, to be submitted to spark. Same for `extra_data`.
Parameters
----------
tasks_pkg (str): Path to the python package containing tasks
dist_dir (str): Path to the directory where the packaged code should... |
def parse_spec(spec, relative_to=None, subproject_roots=None):
"""Parses a target address spec and returns the path from the root of the repo to this Target
and Target name.
:API: public
:param string spec: Target address spec.
:param string relative_to: path to use for sibling specs, ie: ':another_in_same_... | Parses a target address spec and returns the path from the root of the repo to this Target
and Target name.
:API: public
:param string spec: Target address spec.
:param string relative_to: path to use for sibling specs, ie: ':another_in_same_build_family',
interprets the missing spec_path part as `relativ... |
def validate_hier_intervals(intervals_hier):
'''Validate a hierarchical segment annotation.
Parameters
----------
intervals_hier : ordered list of segmentations
Raises
------
ValueError
If any segmentation does not span the full duration of the top-level
segmentation.
... | Validate a hierarchical segment annotation.
Parameters
----------
intervals_hier : ordered list of segmentations
Raises
------
ValueError
If any segmentation does not span the full duration of the top-level
segmentation.
If any segmentation does not start at 0. |
def _parse_caption(self, node, state):
"""Parse a Caption of the node.
:param node: The lxml node to parse
:param state: The global state necessary to place the node in context
of the document as a whole.
"""
if node.tag not in ["caption", "figcaption"]: # captions ... | Parse a Caption of the node.
:param node: The lxml node to parse
:param state: The global state necessary to place the node in context
of the document as a whole. |
def guest_inspect_stats(self, userid_list):
"""Get the statistics including cpu and mem of the guests
:param userid_list: a single userid string or a list of guest userids
:returns: dictionary describing the cpu statistics of the vm
in the form {'UID1':
{
... | Get the statistics including cpu and mem of the guests
:param userid_list: a single userid string or a list of guest userids
:returns: dictionary describing the cpu statistics of the vm
in the form {'UID1':
{
'guest_cpus': xx,
'use... |
def read (self, size = -1): # File-like object.
"""This reads at most "size" bytes from the file (less if the read hits
EOF before obtaining size bytes). If the size argument is negative or
omitted, read all data until EOF is reached. The bytes are returned as
a string object. An... | This reads at most "size" bytes from the file (less if the read hits
EOF before obtaining size bytes). If the size argument is negative or
omitted, read all data until EOF is reached. The bytes are returned as
a string object. An empty string is returned when EOF is encountered
immediate... |
async def event_wait(event: asyncio.Event, timeout=None):
'''
Wait on an an asyncio event with an optional timeout
Returns:
true if the event got set, None if timed out
'''
if timeout is None:
await event.wait()
return True
try:
await asyncio.wait_for(event.wait... | Wait on an an asyncio event with an optional timeout
Returns:
true if the event got set, None if timed out |
def parse_peddy_csv(self, f, pattern):
""" Parse csv output from peddy """
parsed_data = dict()
headers = None
s_name_idx = None
for l in f['f'].splitlines():
s = l.split(",")
if headers is None:
headers = s
try:
... | Parse csv output from peddy |
def __generate(self):
"""Generates dates patterns"""
base = []
texted = []
for pat in ALL_PATTERNS:
data = pat.copy()
data['pattern'] = data['pattern']
data['right'] = True
data['basekey'] = data['key']
base.append(data)
... | Generates dates patterns |
def fmtval(value, colorstr=None, precision=None, spacing=True, trunc=True,
end=' '):
''' Formats and returns a given number according to specifications. '''
colwidth = opts.colwidth
# get precision
if precision is None:
precision = opts.precision
fmt = '%%.%sf' % precision
# ... | Formats and returns a given number according to specifications. |
def _combine_ranges_on_length(self, data_len, first, second):
'''
Combines a first range with a second range, where the second
range is considered within the scope of the first.
'''
first = get_true_slice(first, data_len)
second = get_true_slice(second, data_len)
... | Combines a first range with a second range, where the second
range is considered within the scope of the first. |
def handle(self, message):
"""
Dispatches messages to appropriate handler based on opcode
Args:
message (dict): Full message from Discord websocket connection
"""
opcode = message['op']
if opcode == 10:
self.on_hello(message)
elif opcode ... | Dispatches messages to appropriate handler based on opcode
Args:
message (dict): Full message from Discord websocket connection |
def usable_id(cls, id):
""" Retrieve id from input which can be num or id."""
try:
qry_id = int(id)
except Exception:
qry_id = None
if not qry_id:
msg = 'unknown identifier %s' % id
cls.error(msg)
return qry_id | Retrieve id from input which can be num or id. |
def fit_tomography_data(tomo_data, method='wizard', options=None):
"""
Reconstruct a density matrix or process-matrix from tomography data.
If the input data is state_tomography_data the returned operator will
be a density matrix. If the input data is process_tomography_data the
returned operator w... | Reconstruct a density matrix or process-matrix from tomography data.
If the input data is state_tomography_data the returned operator will
be a density matrix. If the input data is process_tomography_data the
returned operator will be a Choi-matrix in the column-vectorization
convention.
Args:
... |
def respond_via_request(self, task):
"""
Handle response after 55 second.
:param task:
:return:
"""
warn(f"Detected slow response into webhook. "
f"(Greater than {RESPONSE_TIMEOUT} seconds)\n"
f"Recommended to use 'async_task' decorator from Dis... | Handle response after 55 second.
:param task:
:return: |
def to_python(self,value):
"""
Validates that the value is in self.choices and can be coerced to the right type.
"""
if value==self.emptyValue or value in EMPTY_VALUES:
return self.emptyValue
try:
value=self.coerce(value)
except(ValueErro... | Validates that the value is in self.choices and can be coerced to the right type. |
def default_exchange_proposed_fn(prob_exchange):
"""Default exchange proposal function, for replica exchange MC.
With probability `prob_exchange` propose combinations of replica for exchange.
When exchanging, create combinations of adjacent replicas in
[Replica Exchange Monte Carlo](
https://en.wikipedia.org... | Default exchange proposal function, for replica exchange MC.
With probability `prob_exchange` propose combinations of replica for exchange.
When exchanging, create combinations of adjacent replicas in
[Replica Exchange Monte Carlo](
https://en.wikipedia.org/wiki/Parallel_tempering)
```
exchange_fn = defau... |
def get_relationship_admin_session_for_family(self, family_id):
"""Gets the ``OsidSession`` associated with the relationship administration service for the given family.
arg: family_id (osid.id.Id): the ``Id`` of the ``Family``
return: (osid.relationship.RelationshipAdminSession) - a
... | Gets the ``OsidSession`` associated with the relationship administration service for the given family.
arg: family_id (osid.id.Id): the ``Id`` of the ``Family``
return: (osid.relationship.RelationshipAdminSession) - a
``RelationshipAdminSession``
raise: NotFound - no family ... |
def topk(timestep: int,
batch_size: int,
beam_size: int,
inactive: mx.nd.NDArray,
scores: mx.nd.NDArray,
hypotheses: List[ConstrainedHypothesis],
best_ids: mx.nd.NDArray,
best_word_ids: mx.nd.NDArray,
seq_scores: mx.nd.NDArray) -> Tuple[np.array, n... | Builds a new topk list such that the beam contains hypotheses having completed different numbers of constraints.
These items are built from three different types: (1) the best items across the whole
scores matrix, (2) the set of words that must follow existing constraints, and (3) k-best items from each row.
... |
def expool(name):
"""
Confirm the existence of a kernel variable in the kernel pool.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/expool_c.html
:param name: Name of the variable whose value is to be returned.
:type name: str
:return: True when the variable is in the pool.
:rtype... | Confirm the existence of a kernel variable in the kernel pool.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/expool_c.html
:param name: Name of the variable whose value is to be returned.
:type name: str
:return: True when the variable is in the pool.
:rtype: bool |
def parse_date(self, value):
"""A lazy method to parse anything to date.
If input data type is:
- string: parse date from it
- integer: use from ordinal
- datetime: use date part
- date: just return it
"""
if value is None:
raise Exception("U... | A lazy method to parse anything to date.
If input data type is:
- string: parse date from it
- integer: use from ordinal
- datetime: use date part
- date: just return it |
def _update_armed_status(self, message=None, status=None, status_stay=None):
"""
Uses the provided message to update the armed state.
:param message: message to use to update
:type message: :py:class:`~alarmdecoder.messages.Message`
:param status: armed status, overrides message... | Uses the provided message to update the armed state.
:param message: message to use to update
:type message: :py:class:`~alarmdecoder.messages.Message`
:param status: armed status, overrides message bits
:type status: bool
:param status_stay: armed stay status, overrides message... |
def play(quiet, session_file, shell, speed, prompt, commentecho):
"""Play a session file."""
run(
session_file.readlines(),
shell=shell,
speed=speed,
quiet=quiet,
test_mode=TESTING,
prompt_template=prompt,
commentecho=commentecho,
) | Play a session file. |
def get_log(db, job_id):
"""
Extract the logs as a big string
:param db: a :class:`openquake.server.dbapi.Db` instance
:param job_id: a job ID
"""
logs = db('SELECT * FROM log WHERE job_id=?x ORDER BY id', job_id)
out = []
for log in logs:
time = str(log.timestamp)[:-4] # strip... | Extract the logs as a big string
:param db: a :class:`openquake.server.dbapi.Db` instance
:param job_id: a job ID |
def list(self, request, *args, **kwargs):
"""
Each customer is associated with a group of users that represent customer owners. The link is maintained
through **api/customer-permissions/** endpoint.
To list all visible links, run a **GET** query against a list.
Response will con... | Each customer is associated with a group of users that represent customer owners. The link is maintained
through **api/customer-permissions/** endpoint.
To list all visible links, run a **GET** query against a list.
Response will contain a list of customer owners and their brief data.
... |
def authorization_middleware(get_response):
""" Django middleware to parse incoming access tokens, validate them and
set an authorization function on the request.
The decision to use a generic middleware rather than an
AuthenticationMiddleware is explicitly made, because inctances of the
latter com... | Django middleware to parse incoming access tokens, validate them and
set an authorization function on the request.
The decision to use a generic middleware rather than an
AuthenticationMiddleware is explicitly made, because inctances of the
latter come with a number of assumptions (i.e. that user.is_au... |
def _parse(jsonOutput):
'''
Parses JSON response from Tika REST API server
:param jsonOutput: JSON output from Tika Server
:return: a dictionary having 'metadata' and 'content' values
'''
parsed={}
if not jsonOutput:
return parsed
parsed["status"] = jsonOutput[0]
if json... | Parses JSON response from Tika REST API server
:param jsonOutput: JSON output from Tika Server
:return: a dictionary having 'metadata' and 'content' values |
def _set_lsp_reoptimize_timer(self, v, load=False):
"""
Setter method for lsp_reoptimize_timer, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/lsp/secondary_path/lsp_reoptimize_timer (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_lsp_reopti... | Setter method for lsp_reoptimize_timer, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/lsp/secondary_path/lsp_reoptimize_timer (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_lsp_reoptimize_timer is considered as a private
method. Backends looki... |
def is_Linear(self):
"""Returns True if expression is linear (a polynomial with degree 1 or 0) (read-only)."""
coeff_dict = self.expression.as_coefficients_dict()
for key in coeff_dict.keys():
if len(key.free_symbols) < 2 and (key.is_Add or key.is_Mul or key.is_Atom):
... | Returns True if expression is linear (a polynomial with degree 1 or 0) (read-only). |
def send(message, request_context=None, binary=False):
"""Sends a message to websocket.
:param str message: data to send
:param request_context:
:raises IOError: If unable to send a message.
"""
if binary:
return uwsgi.websocket_send_binary(message, request_context)
return uwsgi.... | Sends a message to websocket.
:param str message: data to send
:param request_context:
:raises IOError: If unable to send a message. |
def interact_GxG(pheno,snps1,snps2=None,K=None,covs=None):
"""
Epistasis test between two sets of SNPs
Args:
pheno: [N x 1] SP.array of 1 phenotype for N individuals
snps1: [N x S1] SP.array of S1 SNPs for N individuals
snps2: [N x S2] SP.array of S2 SNPs for N individuals
... | Epistasis test between two sets of SNPs
Args:
pheno: [N x 1] SP.array of 1 phenotype for N individuals
snps1: [N x S1] SP.array of S1 SNPs for N individuals
snps2: [N x S2] SP.array of S2 SNPs for N individuals
K: [N x N] SP.array of LMM-covariance/kinship koefficients (opti... |
def is_identity(self):
"""If `self` is I, returns True, otherwise False."""
if not self.terms:
return True
return len(self.terms) == 1 and not self.terms[0].ops and self.terms[0].coeff == 1.0 | If `self` is I, returns True, otherwise False. |
def send_data(self):
"""Send data packets from the local file to the server"""
if not self.connection._sock:
raise err.InterfaceError("(0, '')")
conn = self.connection
try:
with open(self.filename, 'rb') as open_file:
packet_size = min(conn.max_al... | Send data packets from the local file to the server |
def doc_files(self):
"""Returns list of doc files that should be used for %doc in specfile.
Returns:
List of doc files from the archive - only basenames, not full
paths.
"""
doc_files = []
for doc_file_re in settings.DOC_FILES_RE:
doc_files.ext... | Returns list of doc files that should be used for %doc in specfile.
Returns:
List of doc files from the archive - only basenames, not full
paths. |
def build_dir():
'''
Build the directory used for templates.
'''
tag_arr = ['add', 'edit', 'view', 'list', 'infolist']
path_arr = [os.path.join(CRUD_PATH, x) for x in tag_arr]
for wpath in path_arr:
if os.path.exists(wpath):
continue
os.makedirs(wpath) | Build the directory used for templates. |
def _convert_scalar_indexer(self, key, kind=None):
"""
We don't allow integer or float indexing on datetime-like when using
loc.
Parameters
----------
key : label of the slice bound
kind : {'ix', 'loc', 'getitem', 'iloc'} or None
"""
assert kind ... | We don't allow integer or float indexing on datetime-like when using
loc.
Parameters
----------
key : label of the slice bound
kind : {'ix', 'loc', 'getitem', 'iloc'} or None |
def _replaces(self):
"""tge"""
return {concat(a, c, b[1:])
for a, b in self.slices[:-1]
for c in ALPHABET} | tge |
def _parse_row(self, i):
"""Parses row
:param i: index of row to parse
"""
row = self.data[i]
for j in range(len(row)):
self.data[i][j] = self._parse_value(self.data[i][j]) | Parses row
:param i: index of row to parse |
def add_project(self, path):
"""
Adds a project.
:param path: Project path.
:type path: unicode
:return: Method success.
:rtype: bool
"""
if not foundations.common.path_exists(path):
return False
path = os.path.normpath(path)
... | Adds a project.
:param path: Project path.
:type path: unicode
:return: Method success.
:rtype: bool |
def check_for_lime(self, pattern):
"""
Check to see if LiME has loaded on the remote system
:type pattern: str
:param pattern: pattern to check output against
:type listen_port: int
:param listen_port: port LiME is listening for connections on
"""
check =... | Check to see if LiME has loaded on the remote system
:type pattern: str
:param pattern: pattern to check output against
:type listen_port: int
:param listen_port: port LiME is listening for connections on |
def pick_peaks(nc, L=16):
"""Obtain peaks from a novelty curve using an adaptive threshold."""
offset = nc.mean() / 20.
nc = filters.gaussian_filter1d(nc, sigma=4) # Smooth out nc
th = filters.median_filter(nc, size=L) + offset
#th = filters.gaussian_filter(nc, sigma=L/2., mode="nearest") + offse... | Obtain peaks from a novelty curve using an adaptive threshold. |
def blank_dc(self, n_coarse_chan):
""" Blank DC bins in coarse channels.
Note: currently only works if entire file is read
"""
if n_coarse_chan < 1:
logger.warning('Coarse channel number < 1, unable to blank DC bin.')
return None
if not n_coarse_chan % ... | Blank DC bins in coarse channels.
Note: currently only works if entire file is read |
def bam_needs_processing(data):
"""Check if a work input needs processing for parallelization.
"""
return ((data.get("work_bam") or data.get("align_bam")) and
(any(tz.get_in(["config", "algorithm", x], data) for x in
["variantcaller", "mark_duplicates", "recalibrate", "realign",... | Check if a work input needs processing for parallelization. |
def timing(name, delta, rate=1, tags=None):
"""Sends new timing information. `delta` is in milliseconds.
>>> import statsdecor
>>> statsdecor.timing('my.metric', 314159265359)
"""
return client().timing(name, delta, rate=rate, tags=tags) | Sends new timing information. `delta` is in milliseconds.
>>> import statsdecor
>>> statsdecor.timing('my.metric', 314159265359) |
def get_subset(self, subset):
"""
Retrieve a subset of items
Accepts a single argument: a list of item IDs
"""
if len(subset) > 50:
raise ze.TooManyItems("You may only retrieve 50 items per call")
# remember any url parameters that have been set
params... | Retrieve a subset of items
Accepts a single argument: a list of item IDs |
def on_recv_rsp(self, rsp_pb):
"""receive response callback function"""
ret_code, msg, _= SubAccPush.unpack_rsp(rsp_pb)
if self._notify_obj is not None:
self._notify_obj.on_async_sub_acc_push(ret_code, msg)
return ret_code, msg | receive response callback function |
def _keplerian_to_keplerian_mean(cls, coord, center):
"""Conversion from Keplerian to Keplerian Mean
The difference is the use of Mean anomaly instead of True anomaly
"""
a, e, i, Ω, ω, ν = coord
if e < 1:
# Elliptic case
cos_E = (e + cos(ν)) / (1 + e * ... | Conversion from Keplerian to Keplerian Mean
The difference is the use of Mean anomaly instead of True anomaly |
def stmt_star_handler(
self,
stmts,
prev_node_to_avoid=None
):
"""Handle stmt* expressions in an AST node.
Links all statements together in a list of statements, accounting for statements with multiple last nodes.
"""
break_nodes = list()
cfg_statemen... | Handle stmt* expressions in an AST node.
Links all statements together in a list of statements, accounting for statements with multiple last nodes. |
def add(self, parent, obj_type, **attributes):
""" IXN API add command
@param parent: object parent - object will be created under this parent.
@param object_type: object type.
@param attributes: additional attributes.
@return: IXN object reference.
"""
return s... | IXN API add command
@param parent: object parent - object will be created under this parent.
@param object_type: object type.
@param attributes: additional attributes.
@return: IXN object reference. |
def start_consuming(self, to_tuple=False, auto_decode=True):
"""Start consuming messages.
:param bool to_tuple: Should incoming messages be converted to a
tuple before delivery.
:param bool auto_decode: Auto-decode strings when possible.
:raises AMQPChanne... | Start consuming messages.
:param bool to_tuple: Should incoming messages be converted to a
tuple before delivery.
:param bool auto_decode: Auto-decode strings when possible.
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQP... |
def _height_is_big_enough(image, height):
"""Check that the image height is superior to `height`"""
if height > image.size[1]:
raise ImageSizeError(image.size[1], height) | Check that the image height is superior to `height` |
def rotate(data, axis=(1., 0, 0), angle=0., center=None, mode="constant", interpolation="linear"):
"""
rotates data around axis by a given angle
Parameters
----------
data: ndarray
3d array
axis: tuple
axis to rotate by angle about
axis = (x,y,z)
angle: float
cen... | rotates data around axis by a given angle
Parameters
----------
data: ndarray
3d array
axis: tuple
axis to rotate by angle about
axis = (x,y,z)
angle: float
center: tuple or None
origin of rotation (cz,cy,cx) in pixels
if None, center is the middle of dat... |
def get_deviations(self):
"""get the deviations of the ensemble value from the mean vector
Returns
-------
en : pyemu.Ensemble
Ensemble of deviations from the mean
"""
mean_vec = self.mean()
df = self.loc[:,:].copy()
for col in df.co... | get the deviations of the ensemble value from the mean vector
Returns
-------
en : pyemu.Ensemble
Ensemble of deviations from the mean |
def start_archive(self, session_id, has_audio=True, has_video=True, name=None, output_mode=OutputModes.composed, resolution=None):
"""
Starts archiving an OpenTok session.
Clients must be actively connected to the OpenTok session for you to successfully start
recording an archive.
... | Starts archiving an OpenTok session.
Clients must be actively connected to the OpenTok session for you to successfully start
recording an archive.
You can only record one archive at a time for a given session. You can only record archives
of sessions that use the OpenTok Media Router (... |
def _get_float_remainder(fvalue, signs=9):
"""
Get remainder of float, i.e. 2.05 -> '05'
@param fvalue: input value
@type fvalue: C{integer types}, C{float} or C{Decimal}
@param signs: maximum number of signs
@type signs: C{integer types}
@return: remainder
@rtype: C{str}
@raise ... | Get remainder of float, i.e. 2.05 -> '05'
@param fvalue: input value
@type fvalue: C{integer types}, C{float} or C{Decimal}
@param signs: maximum number of signs
@type signs: C{integer types}
@return: remainder
@rtype: C{str}
@raise ValueError: fvalue is negative
@raise ValueError: s... |
def get_encrypted_field(base_class):
"""
A get or create method for encrypted fields, we cache the field in
the module to avoid recreation. This also allows us to always return
the same class reference for a field.
:type base_class: models.Field[T]
:rtype: models.Field[EncryptedMixin, T]
""... | A get or create method for encrypted fields, we cache the field in
the module to avoid recreation. This also allows us to always return
the same class reference for a field.
:type base_class: models.Field[T]
:rtype: models.Field[EncryptedMixin, T] |
def parse_data_line(self, sline):
"""
Parses the data line and builds the dictionary.
:param sline: a split data line to parse
:returns: the number of rows to jump and parse the next data line or return the code error -1
"""
# if there are less values founded than headers... | Parses the data line and builds the dictionary.
:param sline: a split data line to parse
:returns: the number of rows to jump and parse the next data line or return the code error -1 |
def pid_exists(pid):
"""Check whether pid exists in the current process table."""
if pid < 0:
return False
try:
os.kill(pid, 0)
except OSError as e:
return e.errno == errno.EPERM
else:
return True | Check whether pid exists in the current process table. |
def setup_mturk_connection(self):
''' Connect to turk '''
if ((self.aws_access_key_id == 'YourAccessKeyId') or
(self.aws_secret_access_key == 'YourSecretAccessKey')):
print "AWS access key not set in ~/.psiturkconfig; please enter a valid access key."
assert False... | Connect to turk |
def has_axon(neuron, treefun=_read_neurite_type):
'''Check if a neuron has an axon
Arguments:
neuron(Neuron): The neuron object to test
treefun: Optional function to calculate the tree type of
neuron's neurites
Returns:
CheckResult with result
'''
return CheckResult... | Check if a neuron has an axon
Arguments:
neuron(Neuron): The neuron object to test
treefun: Optional function to calculate the tree type of
neuron's neurites
Returns:
CheckResult with result |
def forget(self, obj):
'''
Forgets about an entity (automatically called when an entity is
deleted). Call this to ensure that an entity that you've modified is
not automatically saved on ``session.commit()`` .
'''
self._init()
self.known.pop(obj._pk, None)
... | Forgets about an entity (automatically called when an entity is
deleted). Call this to ensure that an entity that you've modified is
not automatically saved on ``session.commit()`` . |
def IntegerLike(msg=None):
'''
Checks whether a value is:
- int, or
- long, or
- float without a fractional part, or
- str or unicode composed only of digits
'''
def fn(value):
if not any([
isinstance(value, numbers.Integral),
(isinstance(v... | Checks whether a value is:
- int, or
- long, or
- float without a fractional part, or
- str or unicode composed only of digits |
def add_middleware(middleware: EFBMiddleware):
"""
Register a middleware with the coordinator.
Args:
middleware (EFBMiddleware): Middleware to register
"""
global middlewares
if isinstance(middleware, EFBMiddleware):
middlewares.append(middleware)
else:
raise TypeErr... | Register a middleware with the coordinator.
Args:
middleware (EFBMiddleware): Middleware to register |
def attach(self, media: typing.Union[InputMedia, typing.Dict]):
"""
Attach media
:param media:
"""
if isinstance(media, dict):
if 'type' not in media:
raise ValueError(f"Invalid media!")
media_type = media['type']
if media_typ... | Attach media
:param media: |
def server_powerstatus(host=None,
admin_username=None,
admin_password=None,
module=None):
'''
return the power status for the passed module
CLI Example:
.. code-block:: bash
salt dell drac.server_powerstatus
'''
ret ... | return the power status for the passed module
CLI Example:
.. code-block:: bash
salt dell drac.server_powerstatus |
def _append_params(oauth_params, params):
"""Append OAuth params to an existing set of parameters.
Both params and oauth_params is must be lists of 2-tuples.
Per `section 3.5.2`_ and `3.5.3`_ of the spec.
.. _`section 3.5.2`: https://tools.ietf.org/html/rfc5849#section-3.5.2
.. _`3.5.3`: https://... | Append OAuth params to an existing set of parameters.
Both params and oauth_params is must be lists of 2-tuples.
Per `section 3.5.2`_ and `3.5.3`_ of the spec.
.. _`section 3.5.2`: https://tools.ietf.org/html/rfc5849#section-3.5.2
.. _`3.5.3`: https://tools.ietf.org/html/rfc5849#section-3.5.3 |
def get_and_write(self, iso_path, local_path, blocksize=8192):
# type: (str, str, int) -> None
'''
(deprecated) Fetch a single file from the ISO and write it out to the
specified file. Note that this will overwrite the contents of the local
file if it already exists. Also note ... | (deprecated) Fetch a single file from the ISO and write it out to the
specified file. Note that this will overwrite the contents of the local
file if it already exists. Also note that 'iso_path' must be an
absolute path to the file. Finally, the 'iso_path' can be an ISO9660
path, a Ro... |
def readmegen():
"""
Build documentation.
"""
hitchpylibrarytoolkit.readmegen(
_storybook(), DIR.project, DIR.key, DIR.gen, "commandlib"
) | Build documentation. |
def comparison(self, lhs, rhs):
"""
(2.6, 2.7) comparison: expr (comp_op expr)*
(3.0, 3.1) comparison: star_expr (comp_op star_expr)*
(3.2-) comparison: expr (comp_op expr)*
"""
if len(rhs) > 0:
return ast.Compare(left=lhs, ops=list(map(lambda x: x[0], rhs)),
... | (2.6, 2.7) comparison: expr (comp_op expr)*
(3.0, 3.1) comparison: star_expr (comp_op star_expr)*
(3.2-) comparison: expr (comp_op expr)* |
def get_bug_report():
"""Generate information for a bug report
:return: information for bug report
"""
platform_info = BugReporter.get_platform_info()
module_info = {
'version': hal_version.__version__,
'build': hal_version.__build__
}
re... | Generate information for a bug report
:return: information for bug report |
def close_document(self, path):
"""
Closes a text document.
:param path: Path of the document to close.
"""
to_close = []
for widget in self.widgets(include_clones=True):
p = os.path.normpath(os.path.normcase(widget.file.path))
path = os.path.normp... | Closes a text document.
:param path: Path of the document to close. |
def sense_dep(self, target):
"""Search for a DEP Target in active or passive communication mode.
"""
# Set timeout for PSL_RES and ATR_RES
self.chipset.rf_configuration(0x02, b"\x0B\x0B\x0A")
return super(Device, self).sense_dep(target) | Search for a DEP Target in active or passive communication mode. |
def _prepare_uimodules(self):
"""Prepare the UI Modules from a list of namespaced paths."""
for key, value in self._config.get(config.UI_MODULES, {}).iteritems():
self._config[config.UI_MODULES][key] = self._import_class(value)
self._config[config.UI_MODULES] = dict(self._config[conf... | Prepare the UI Modules from a list of namespaced paths. |
async def load_message_field(obj, msg, field, field_archiver=None):
"""
Loads message field from the object. Field is defined by the message field specification.
Returns loaded value, supports field reference.
:param reader:
:param msg:
:param field:
:param field_archiver:
:return:
... | Loads message field from the object. Field is defined by the message field specification.
Returns loaded value, supports field reference.
:param reader:
:param msg:
:param field:
:param field_archiver:
:return: |
def clear(self):
""" clear all tree data
"""
self._delete_child_storage(self.root_node)
self._delete_node_storage(self.root_node)
self.root_node = BLANK_NODE | clear all tree data |
def sevenths_inv(reference_labels, estimated_labels):
"""Compare chords along MIREX 'sevenths' rules. Chords with qualities
outside [maj, maj7, 7, min, min7, N] are ignored.
Examples
--------
>>> (ref_intervals,
... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab')
>>> (est_inter... | Compare chords along MIREX 'sevenths' rules. Chords with qualities
outside [maj, maj7, 7, min, min7, N] are ignored.
Examples
--------
>>> (ref_intervals,
... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab')
>>> (est_intervals,
... est_labels) = mir_eval.io.load_labeled_interva... |
def create_folder(self, folder_name, parent_kind_str, parent_uuid):
"""
Send POST to /folders to create a new folder with specified name and parent.
:param folder_name: str name of the new folder
:param parent_kind_str: str type of parent folder has(dds-folder,dds-project)
:param... | Send POST to /folders to create a new folder with specified name and parent.
:param folder_name: str name of the new folder
:param parent_kind_str: str type of parent folder has(dds-folder,dds-project)
:param parent_uuid: str uuid of the parent object
:return: requests.Response containin... |
def _one_q_sic_prep(index, qubit):
"""Prepare the index-th SIC basis state."""
if index == 0:
return Program()
theta = 2 * np.arccos(1 / np.sqrt(3))
zx_plane_rotation = Program([
RX(-pi / 2, qubit),
RZ(theta - pi, qubit),
RX(-pi / 2, qubit),
])
if index == 1:
... | Prepare the index-th SIC basis state. |
def volume_show(name, profile=None, **kwargs):
'''
Create a block storage volume
name
Name of the volume
profile
Profile to use
CLI Example:
.. code-block:: bash
salt '*' nova.volume_show myblock profile=openstack
'''
conn = _auth(profile, **kwargs)
retu... | Create a block storage volume
name
Name of the volume
profile
Profile to use
CLI Example:
.. code-block:: bash
salt '*' nova.volume_show myblock profile=openstack |
def libvlc_vlm_del_media(p_instance, psz_name):
'''Delete a media (VOD or broadcast).
@param p_instance: the instance.
@param psz_name: the media to delete.
@return: 0 on success, -1 on error.
'''
f = _Cfunctions.get('libvlc_vlm_del_media', None) or \
_Cfunction('libvlc_vlm_del_media', (... | Delete a media (VOD or broadcast).
@param p_instance: the instance.
@param psz_name: the media to delete.
@return: 0 on success, -1 on error. |
def script(experiment, projects):
"""
Prepare a slurm script that executes the experiment for a given project.
Args:
experiment: The experiment we want to execute
projects: All projects we generate an array job for.
"""
benchbuild_c = local[local.path(sys.argv[0])]
slurm_script ... | Prepare a slurm script that executes the experiment for a given project.
Args:
experiment: The experiment we want to execute
projects: All projects we generate an array job for. |
def grab_literal(template, l_del):
"""Parse a literal from the template"""
global _CURRENT_LINE
try:
# Look for the next tag and move the template to it
literal, template = template.split(l_del, 1)
_CURRENT_LINE += literal.count('\n')
return (literal, template)
# There... | Parse a literal from the template |
def append_ISO19115_keywords(keywords):
"""Append ISO19115 from setting to keywords.
:param keywords: The keywords destination.
:type keywords: dict
"""
# Map setting's key and metadata key
ISO19115_mapping = {
'ISO19115_ORGANIZATION': 'organisation',
'ISO19115_URL': 'url',
... | Append ISO19115 from setting to keywords.
:param keywords: The keywords destination.
:type keywords: dict |
def _parseLine(cls, line):
"""Parsers a single line of text and returns an AudioClipSpec
Line format:
<number> <number> [<text>]
Returns: list(AudioClipSpec) or None
"""
r = cls._PROG.match(line)
if not r:
raise ValueError("Error: parsing '%s'. ... | Parsers a single line of text and returns an AudioClipSpec
Line format:
<number> <number> [<text>]
Returns: list(AudioClipSpec) or None |
def directory_files(path):
"""Yield directory file names."""
for entry in os.scandir(path):
if not entry.name.startswith('.') and entry.is_file():
yield entry.name | Yield directory file names. |
def permute_point(p, permutation=None):
"""
Permutes the point according to the permutation keyword argument. The
default permutation is "012" which does not change the order of the
coordinate. To rotate counterclockwise, use "120" and to rotate clockwise
use "201"."""
if not permutation:
... | Permutes the point according to the permutation keyword argument. The
default permutation is "012" which does not change the order of the
coordinate. To rotate counterclockwise, use "120" and to rotate clockwise
use "201". |
def poll(self, poll_rate=None, timeout=None):
"""Return the status of a task or timeout.
There are several API calls that trigger asynchronous tasks, such as
synchronizing a repository, or publishing or promoting a content view.
It is possible to check on the status of a task if you kno... | Return the status of a task or timeout.
There are several API calls that trigger asynchronous tasks, such as
synchronizing a repository, or publishing or promoting a content view.
It is possible to check on the status of a task if you know its UUID.
This method polls a task once every `... |
def _vcap_from_service_definition(service_def):
"""Turn a service definition into a vcap services
containing a single service.
"""
if 'credentials' in service_def:
credentials = service_def['credentials']
else:
credentials = service_def
service = {}
service['credentials'] = ... | Turn a service definition into a vcap services
containing a single service. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.