code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def get_live_data_flat_binary(self):
"""
Gets the live data packet in flatbuffer binary format. You'll need to do something like
GameTickPacket.GetRootAsGameTickPacket(binary, 0) to get the data out.
This is a temporary method designed to keep the integration test working. It returns th... | Gets the live data packet in flatbuffer binary format. You'll need to do something like
GameTickPacket.GetRootAsGameTickPacket(binary, 0) to get the data out.
This is a temporary method designed to keep the integration test working. It returns the raw bytes
of the flatbuffer so that it can be s... |
def getReverseRankMaps(self):
"""
Returns a list of dictionaries, one for each preference, that associates each position in
the ranking with a list of integer representations of the candidates ranked at that
position and returns a list of the number of times each preference is given.
... | Returns a list of dictionaries, one for each preference, that associates each position in
the ranking with a list of integer representations of the candidates ranked at that
position and returns a list of the number of times each preference is given. |
def function(self, addr=None, name=None, create=False, syscall=False, plt=None):
"""
Get a function object from the function manager.
Pass either `addr` or `name` with the appropriate values.
:param int addr: Address of the function.
:param str name: Name of the function.
... | Get a function object from the function manager.
Pass either `addr` or `name` with the appropriate values.
:param int addr: Address of the function.
:param str name: Name of the function.
:param bool create: Whether to create the function or not if the function does not exist.
... |
def set_stop_chars_left(self, stop_chars):
"""
Set stop characters for text on left from TLD.
Stop characters are used when determining end of URL.
:param set stop_chars: set of characters
:raises: TypeError
"""
if not isinstance(stop_chars, set):
rai... | Set stop characters for text on left from TLD.
Stop characters are used when determining end of URL.
:param set stop_chars: set of characters
:raises: TypeError |
def color_is_forced(**envars):
''' Look for clues in environment, e.g.:
- https://bixense.com/clicolors/
Arguments:
envars: Additional environment variables to check for
equality, i.e. ``MYAPP_COLOR_FORCED='1'``
Returns:
Bool: Forced
... | Look for clues in environment, e.g.:
- https://bixense.com/clicolors/
Arguments:
envars: Additional environment variables to check for
equality, i.e. ``MYAPP_COLOR_FORCED='1'``
Returns:
Bool: Forced |
def set_tag(self, tag):
'''
Sets the tag.
If the Entity belongs to the world it will check for tag conflicts.
'''
if self._world:
if self._world.get_entity_by_tag(tag):
raise NonUniqueTagError(tag)
self._tag = tag | Sets the tag.
If the Entity belongs to the world it will check for tag conflicts. |
def is_letter(uni_char):
"""Determine whether the given Unicode character is a Unicode letter"""
category = Category.get(uni_char)
return (category == Category.UPPERCASE_LETTER or
category == Category.LOWERCASE_LETTER or
category == Category.TITLECASE_LETTER or
category =... | Determine whether the given Unicode character is a Unicode letter |
def parse_note(cls, note):
"""Parse string annotation into object reference with optional name."""
if isinstance(note, tuple):
if len(note) != 2:
raise ValueError('tuple annotations must be length 2')
return note
try:
match = cls.re_note.match(... | Parse string annotation into object reference with optional name. |
def update_template(self, template_id, template_dict):
"""
Updates a template
:param template_id: the template id
:param template_dict: dict
:return: dict
"""
return self._create_put_request(
resource=TEMPLATES,
billomat_id=template_id,
... | Updates a template
:param template_id: the template id
:param template_dict: dict
:return: dict |
def _compile_seriesflow(self):
"""Post power flow computation of series device flow"""
string = '"""\n'
for device, pflow, series in zip(self.devices, self.pflow,
self.series):
if pflow and series:
string += 'system.' + device ... | Post power flow computation of series device flow |
def put_text(self, key, text):
"""Put the text into the storage associated with the key."""
with open(key, "w") as fh:
fh.write(text) | Put the text into the storage associated with the key. |
def lookup_casstype(casstype):
"""
Given a Cassandra type as a string (possibly including parameters), hand
back the CassandraType class responsible for it. If a name is not
recognized, a custom _UnrecognizedType subclass will be created for it.
Example:
>>> lookup_casstype('org.apache.cas... | Given a Cassandra type as a string (possibly including parameters), hand
back the CassandraType class responsible for it. If a name is not
recognized, a custom _UnrecognizedType subclass will be created for it.
Example:
>>> lookup_casstype('org.apache.cassandra.db.marshal.MapType(org.apache.cassan... |
def error_values_summary(error_values, **summary_df_kwargs):
"""Get summary statistics about calculation errors, including estimated
implementation errors.
Parameters
----------
error_values: pandas DataFrame
Of format output by run_list_error_values (look at it for more
details).
... | Get summary statistics about calculation errors, including estimated
implementation errors.
Parameters
----------
error_values: pandas DataFrame
Of format output by run_list_error_values (look at it for more
details).
summary_df_kwargs: dict, optional
See pandas_functions.su... |
def formatPathExpressions(seriesList):
"""
Returns a comma-separated list of unique path expressions.
"""
pathExpressions = sorted(set([s.pathExpression for s in seriesList]))
return ','.join(pathExpressions) | Returns a comma-separated list of unique path expressions. |
def add(self, item):
"""
Add a file to the manifest.
:param item: The pathname to add. This can be relative to the base.
"""
if not item.startswith(self.prefix):
item = os.path.join(self.base, item)
self.files.add(os.path.normpath(item)) | Add a file to the manifest.
:param item: The pathname to add. This can be relative to the base. |
def get_socket(host, port, timeout=None):
"""
Return a socket.
:param str host: the hostname to connect to
:param int port: the port number to connect to
:param timeout: if specified, set the socket timeout
"""
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
af, socktype, proto,... | Return a socket.
:param str host: the hostname to connect to
:param int port: the port number to connect to
:param timeout: if specified, set the socket timeout |
def get_max_id(self, object_type, role):
"""Get the highest used ID."""
if object_type == 'user':
objectclass = 'posixAccount'
ldap_attr = 'uidNumber'
elif object_type == 'group': # pragma: no cover
objectclass = 'posixGroup'
ldap_attr = 'gidNumbe... | Get the highest used ID. |
def _replace_numeric_markers(operation, string_parameters):
"""
Replaces qname, format, and numeric markers in the given operation, from
the string_parameters list.
Raises ProgrammingError on wrong number of parameters or bindings
when using qmark. There is no error checking on numeric parameters.
... | Replaces qname, format, and numeric markers in the given operation, from
the string_parameters list.
Raises ProgrammingError on wrong number of parameters or bindings
when using qmark. There is no error checking on numeric parameters. |
def infer_year(date):
"""Given a datetime-like object or string infer the year.
Parameters
----------
date : datetime-like object or str
Input date
Returns
-------
int
Examples
--------
>>> infer_year('2000')
2000
>>> infer_year('2000-01')
2000
>>> infe... | Given a datetime-like object or string infer the year.
Parameters
----------
date : datetime-like object or str
Input date
Returns
-------
int
Examples
--------
>>> infer_year('2000')
2000
>>> infer_year('2000-01')
2000
>>> infer_year('2000-01-31')
2000... |
def combine(self, expert_out, multiply_by_gates=True):
"""Sum together the expert output, weighted by the gates.
The slice corresponding to a particular batch element `b` is computed
as the sum over all experts `i` of the expert output, weighted by the
corresponding gate values. If `multiply_by_gates`... | Sum together the expert output, weighted by the gates.
The slice corresponding to a particular batch element `b` is computed
as the sum over all experts `i` of the expert output, weighted by the
corresponding gate values. If `multiply_by_gates` is set to False, the
gate values are ignored.
Args:
... |
def cancel_broadcast(self, broadcast_guid):
'''
Cancel a broadcast specified by guid
'''
subpath = 'broadcasts/%s/update' % broadcast_guid
broadcast = {'status': 'CANCELED'}
bcast_dict = self._call(subpath, method='POST', data=broadcast,
content_type='applicat... | Cancel a broadcast specified by guid |
def get_image(roi_rec, short, max_size, mean, std):
"""
read, resize, transform image, return im_tensor, im_info, gt_boxes
roi_rec should have keys: ["image", "boxes", "gt_classes", "flipped"]
0 --- x (width, second dim of im)
|
y (height, first dim of im)
"""
im = imdecode(roi_rec['imag... | read, resize, transform image, return im_tensor, im_info, gt_boxes
roi_rec should have keys: ["image", "boxes", "gt_classes", "flipped"]
0 --- x (width, second dim of im)
|
y (height, first dim of im) |
def get_inters(r, L, R_cut):
'''
Return points within a given cut-off of each other,
in a periodic system.
Uses a cell-list.
Parameters
----------
r: array, shape (n, d) where d is one of (2, 3).
A set of n point coordinates.
Coordinates are assumed to lie in [-L / 2, L / 2... | Return points within a given cut-off of each other,
in a periodic system.
Uses a cell-list.
Parameters
----------
r: array, shape (n, d) where d is one of (2, 3).
A set of n point coordinates.
Coordinates are assumed to lie in [-L / 2, L / 2].
L: float.
Bounds of the sy... |
def send_message(self, number, content):
"""
Send message
:param str number: phone number with cc (country code)
:param str content: body text of the message
"""
outgoing_message = TextMessageProtocolEntity(content.encode("utf-8") if sys.version_info >= (3, 0)
... | Send message
:param str number: phone number with cc (country code)
:param str content: body text of the message |
def clearLocatorCache(self, login, tableName):
"""
Parameters:
- login
- tableName
"""
self.send_clearLocatorCache(login, tableName)
self.recv_clearLocatorCache() | Parameters:
- login
- tableName |
def _check_token(self):
""" Simple Mercedes me API.
"""
need_token = (self._token_info is None or
self.auth_handler.is_token_expired(self._token_info))
if need_token:
new_token = \
self.auth_handler.refresh_access_token(
... | Simple Mercedes me API. |
def setup_exchange(self, exchange_name):
"""Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC
command. When it is complete, the on_exchange_declareok method will
be invoked by pika.
:param str|unicode exchange_name: The name of the exchange to declare
"""
... | Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC
command. When it is complete, the on_exchange_declareok method will
be invoked by pika.
:param str|unicode exchange_name: The name of the exchange to declare |
def chart_part(self):
"""
The |ChartPart| object containing the chart in this graphic frame.
"""
rId = self._element.chart_rId
chart_part = self.part.related_parts[rId]
return chart_part | The |ChartPart| object containing the chart in this graphic frame. |
def _make_writeable(filename):
"""
Make sure that the file is writeable. Useful if our source is
read-only.
"""
import stat
if sys.platform.startswith('java'):
# On Jython there is no os.access()
return
if not os.access(filename, os.W_OK):
st = os.stat(filename)
... | Make sure that the file is writeable. Useful if our source is
read-only. |
def _change_color(self, event):
"""Respond to motion of the hsv cursor."""
h = self.bar.get()
self.square.set_hue(h)
(r, g, b), (h, s, v), sel_color = self.square.get()
self.red.set(r)
self.green.set(g)
self.blue.set(b)
self.hue.set(h)
self.saturat... | Respond to motion of the hsv cursor. |
def p_expression_logical(self, p):
"""
expression : expression logical expression
"""
p[0] = Expression(left=p[1], operator=p[2], right=p[3]) | expression : expression logical expression |
def coarsen_line(line, level=2, exponential=False, draw=True):
"""
Coarsens the specified line (see spinmob.coarsen_data() for more information).
Parameters
----------
line
Matplotlib line instance.
level=2
How strongly to coarsen.
exponential=False
If True, use ... | Coarsens the specified line (see spinmob.coarsen_data() for more information).
Parameters
----------
line
Matplotlib line instance.
level=2
How strongly to coarsen.
exponential=False
If True, use the exponential method (great for log-x plots).
draw=True
Redra... |
def get_cipher(self):
"""
Return a new Cipher object for each time we want to encrypt/decrypt. This is because
pgcrypto expects a zeroed block for IV (initial value), but the IV on the cipher
object is cumulatively updated each time encrypt/decrypt is called.
"""
return s... | Return a new Cipher object for each time we want to encrypt/decrypt. This is because
pgcrypto expects a zeroed block for IV (initial value), but the IV on the cipher
object is cumulatively updated each time encrypt/decrypt is called. |
def read_relative_file(filename, relative_to=None):
"""Returns contents of the given file, which path is supposed relative
to this package."""
if relative_to is None:
relative_to = os.path.dirname(__file__)
with open(os.path.join(os.path.dirname(relative_to), filename)) as f:
return f.re... | Returns contents of the given file, which path is supposed relative
to this package. |
def findNestedClassLike(self, lst):
'''
Recursive helper function for finding nested classes and structs. If this node
is a class or struct, it is appended to ``lst``. Each node also calls each of
its child ``findNestedClassLike`` with the same list.
:Parameters:
`... | Recursive helper function for finding nested classes and structs. If this node
is a class or struct, it is appended to ``lst``. Each node also calls each of
its child ``findNestedClassLike`` with the same list.
:Parameters:
``lst`` (list)
The list each class or str... |
def list_actions(name, location='\\'):
r'''
List all actions that pertain to a task in the specified location.
:param str name: The name of the task for which list actions.
:param str location: A string value representing the location of the task
from which to list actions. Default is '\\' whi... | r'''
List all actions that pertain to a task in the specified location.
:param str name: The name of the task for which list actions.
:param str location: A string value representing the location of the task
from which to list actions. Default is '\\' which is the root for the
task schedul... |
def frames(self, flush=True):
""" Returns the latest color image from the stream
Raises:
Exception if opencv sensor gives ret_val of 0
"""
self.flush()
ret_val, frame = self._sensor.read()
if not ret_val:
raise Exception("Unable to retrieve frame f... | Returns the latest color image from the stream
Raises:
Exception if opencv sensor gives ret_val of 0 |
def get_dependent_items(self, item) -> typing.List:
"""Return the list of data items containing data that directly depends on data in this item."""
with self.__dependency_tree_lock:
return copy.copy(self.__dependency_tree_source_to_target_map.get(weakref.ref(item), list())) | Return the list of data items containing data that directly depends on data in this item. |
def pad(num, n=2, sign=False):
'''returns n digit string representation of the num'''
s = unicode(abs(num))
if len(s) < n:
s = '0' * (n - len(s)) + s
if not sign:
return s
if num >= 0:
return '+' + s
else:
return '-' + s | returns n digit string representation of the num |
def _pct_escape_handler(err):
'''
Encoding error handler that does percent-escaping of Unicode, to be used
with codecs.register_error
TODO: replace use of this with urllib.parse.quote as appropriate
'''
chunk = err.object[err.start:err.end]
replacements = _pct_encoded_replacements(chunk)
... | Encoding error handler that does percent-escaping of Unicode, to be used
with codecs.register_error
TODO: replace use of this with urllib.parse.quote as appropriate |
def clean(self, timeout=60):
"""Deletes the contents of the index.
This method blocks until the index is empty, because it needs to restore
values at the end of the operation.
:param timeout: The time-out period for the operation, in seconds (the
default is 60).
:ty... | Deletes the contents of the index.
This method blocks until the index is empty, because it needs to restore
values at the end of the operation.
:param timeout: The time-out period for the operation, in seconds (the
default is 60).
:type timeout: ``integer``
:return... |
def set_href_prefix(self, prefix):
"""
Set the prefix of any hrefs associated with this thing.
prefix -- the prefix
"""
self.href_prefix = prefix
for property_ in self.properties.values():
property_.set_href_prefix(prefix)
for action_name in self.ac... | Set the prefix of any hrefs associated with this thing.
prefix -- the prefix |
def get_status_code_and_schema_rst(self, responses):
'''
Function for prepare information about responses with example, prepare only
responses with status code from `101` to `299`
:param responses: -- dictionary that contains responses, with status code as key
:type responses: di... | Function for prepare information about responses with example, prepare only
responses with status code from `101` to `299`
:param responses: -- dictionary that contains responses, with status code as key
:type responses: dict
:return: |
def plot_groups_unplaced(self, fout_dir=".", **kws_usr):
"""Plot each GO group."""
# kws: go2color max_gos upper_trigger max_upper
plotobj = PltGroupedGos(self)
return plotobj.plot_groups_unplaced(fout_dir, **kws_usr) | Plot each GO group. |
def sampling_volume_value(self):
"""Returns the device samping volume value in m."""
svi = self.pdx.SamplingVolume
tli = self.pdx.TransmitLength
return self._sampling_volume_value(svi, tli) | Returns the device samping volume value in m. |
def set_color_scheme(self, foreground_color, background_color):
"""Set color scheme of the console (foreground and background)."""
self.ansi_handler.set_color_scheme(foreground_color, background_color)
background_color = QColor(background_color)
foreground_color = QColor(foreground_colo... | Set color scheme of the console (foreground and background). |
def get_privacy_options(user):
"""Get a user's privacy options to pass as an initial value to a PrivacyOptionsForm."""
privacy_options = {}
for ptype in user.permissions:
for field in user.permissions[ptype]:
if ptype == "self":
privacy_options["{}-{}".format(field, pty... | Get a user's privacy options to pass as an initial value to a PrivacyOptionsForm. |
def cumulative_detections(dates=None, template_names=None, detections=None,
plot_grouped=False, group_name=None, rate=False,
plot_legend=True, ax=None, **kwargs):
"""
Plot cumulative detections or detection rate in time.
Simple plotting function to take a... | Plot cumulative detections or detection rate in time.
Simple plotting function to take a list of either datetime objects or
:class:`eqcorrscan.core.match_filter.Detection` objects and plot
a cumulative detections list. Can take dates as a list of lists and will
plot each list separately, e.g. if you h... |
def _set_factory_context(factory_class, bundle_context):
# type: (type, Optional[BundleContext]) -> Optional[FactoryContext]
"""
Transforms the context data dictionary into its FactoryContext object form.
:param factory_class: A manipulated class
:param bundle_context: The class bundle context
... | Transforms the context data dictionary into its FactoryContext object form.
:param factory_class: A manipulated class
:param bundle_context: The class bundle context
:return: The factory context, None on error |
def remove_task_db(self, fid, force=False):
'''将任务从数据库中删除'''
self.remove_slice_db(fid)
sql = 'DELETE FROM upload WHERE fid=?'
self.cursor.execute(sql, [fid, ])
self.check_commit(force=force) | 将任务从数据库中删除 |
def parse_datetime(value):
"""Attempts to parse `value` into an instance of ``datetime.datetime``. If
`value` is ``None``, this function will return ``None``.
Args:
value: A timestamp. This can be a string or datetime.datetime value.
"""
if not value:
return None
elif isinstanc... | Attempts to parse `value` into an instance of ``datetime.datetime``. If
`value` is ``None``, this function will return ``None``.
Args:
value: A timestamp. This can be a string or datetime.datetime value. |
def total_border_pixels_from_mask_and_edge_pixels(mask, edge_pixels, masked_grid_index_to_pixel):
"""Compute the total number of borders-pixels in a masks."""
border_pixel_total = 0
for i in range(edge_pixels.shape[0]):
if check_if_border_pixel(mask, edge_pixels[i], masked_grid_index_to_pixel):
... | Compute the total number of borders-pixels in a masks. |
def get_view(self):
""" Get the root view to display. Make sure it is
properly initialized.
"""
view = self.view
if not view.is_initialized:
view.initialize()
if not view.proxy_is_active:
view.activate_proxy()
return view.proxy.wid... | Get the root view to display. Make sure it is
properly initialized. |
def reset(self):
"""Reset the input buffer and associated state."""
self.indent_spaces = 0
self._buffer[:] = []
self.source = ''
self.code = None
self._is_complete = False
self._full_dedent = False | Reset the input buffer and associated state. |
def geometry(AA):
'''Generates the geometry of the requested amino acid.
The amino acid needs to be specified by its single-letter
code. If an invalid code is specified, the function
returns the geometry of Glycine.'''
if(AA=='G'):
return GlyGeo()
elif(AA=='A'):
return AlaGeo()
... | Generates the geometry of the requested amino acid.
The amino acid needs to be specified by its single-letter
code. If an invalid code is specified, the function
returns the geometry of Glycine. |
def post_events(self, events):
"""
Posts a single event to the Keen IO API. The write key must be set first.
:param events: an Event to upload
"""
url = "{0}/{1}/projects/{2}/events".format(self.base_url, self.api_version,
sel... | Posts a single event to the Keen IO API. The write key must be set first.
:param events: an Event to upload |
def parse_file(src):
"""
find file in config and output to dest dir
"""
#clear the stack between parses
if config.dest_dir == None:
dest = src.dir
else:
dest = config.dest_dir
output = get_output(src)
output_file = dest + '/' + src.basename + '.min.js'
f = open(output... | find file in config and output to dest dir |
def get_logger(name, verbosity, stream):
"""
Returns simple console logger.
"""
logger = logging.getLogger(name)
logger.setLevel(
{0: DEFAULT_LOGGING_LEVEL, 1: logging.INFO, 2: logging.DEBUG}.get(min(2, verbosity), DEFAULT_LOGGING_LEVEL)
)
logger.handlers = []
handler = logging.S... | Returns simple console logger. |
def select_action(self, pos1, pos2, ctrl, shift):
"""Return a `sc_pb.Action` with the selection filled."""
assert pos1.surf.surf_type == pos2.surf.surf_type
assert pos1.surf.world_to_obs == pos2.surf.world_to_obs
action = sc_pb.Action()
action_spatial = pos1.action_spatial(action)
if pos1.worl... | Return a `sc_pb.Action` with the selection filled. |
def extract_rzip (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract an RZIP archive."""
cmdlist = [cmd, '-d', '-k']
if verbosity > 1:
cmdlist.append('-v')
outfile = util.get_single_outfile(outdir, archive)
cmdlist.extend(["-o", outfile, archive])
return cmdlist | Extract an RZIP archive. |
def combine_assignments(self, assignments):
"""Rewrite the current graph to combine "Assign" operations.
Combine similar Assign operations into grouped Assign operations.
This is useful when using the rewrite_stack_variables() optimization,
since variables can only be stacked if they are present in the... | Rewrite the current graph to combine "Assign" operations.
Combine similar Assign operations into grouped Assign operations.
This is useful when using the rewrite_stack_variables() optimization,
since variables can only be stacked if they are present in the same set
of Assign operations.
This funct... |
def which(name):
""" Returns the full path to executable in path matching provided name.
`name`
String value.
Returns string or ``None``.
"""
# we were given a filename, return it if it's executable
if os.path.dirname(name) != '':
if not os.path.isdir(name) and... | Returns the full path to executable in path matching provided name.
`name`
String value.
Returns string or ``None``. |
def collectInterest(self):
""" Collects user's daily interest, returns result
Returns
bool - True if successful, False otherwise
"""
if self.collectedInterest:
return False
pg = self.usr.getPage("http://www.neopets.com/bank.phtml")
... | Collects user's daily interest, returns result
Returns
bool - True if successful, False otherwise |
def y(self, y):
"""Project reversed y"""
if y is None:
return None
return (self.height * (y - self.box.ymin) / self.box.height) | Project reversed y |
def _copy_circuit_metadata(source_dag, coupling_map):
"""Return a copy of source_dag with metadata but empty.
Generate only a single qreg in the output DAG, matching the size of the
coupling_map."""
target_dag = DAGCircuit()
target_dag.name = source_dag.name
for creg in source_dag.cregs.values... | Return a copy of source_dag with metadata but empty.
Generate only a single qreg in the output DAG, matching the size of the
coupling_map. |
def extract_output(self, output_variables_list):
""" extract output variables
"""
variables_mapping = self.session_context.session_variables_mapping
output = {}
for variable in output_variables_list:
if variable not in variables_mapping:
logger.log_wa... | extract output variables |
def _rdistributive(self, expr, op_example):
"""
Recursively flatten the `expr` expression for the `op_example`
AND or OR operation instance exmaple.
"""
if expr.isliteral:
return expr
expr_class = expr.__class__
args = (self._rdistributive(arg, op_ex... | Recursively flatten the `expr` expression for the `op_example`
AND or OR operation instance exmaple. |
def _do_validate_sources_present(self, target):
"""Checks whether sources is empty, and either raises a TaskError or just returns False.
The specifics of this behavior are defined by whether the user sets --allow-empty to True/False:
--allow-empty=False will result in a TaskError being raised in the event ... | Checks whether sources is empty, and either raises a TaskError or just returns False.
The specifics of this behavior are defined by whether the user sets --allow-empty to True/False:
--allow-empty=False will result in a TaskError being raised in the event of an empty source
set. If --allow-empty=True, this... |
def atmos_worker(srcs, window, ij, args):
"""A simple atmospheric correction user function."""
src = srcs[0]
rgb = src.read(window=window)
rgb = to_math_type(rgb)
atmos = simple_atmo(rgb, args["atmo"], args["contrast"], args["bias"])
# should be scaled 0 to 1, scale to outtype
return scale... | A simple atmospheric correction user function. |
def extract_links(self, selector='', *args, **kwargs):
"""
Method for performing the link extraction for the crawler. \
The selector passed as the argument is a selector to point to the anchor tags \
that the crawler should pass through. A list of links is obtained, and the links \
are iterated through. The ... | Method for performing the link extraction for the crawler. \
The selector passed as the argument is a selector to point to the anchor tags \
that the crawler should pass through. A list of links is obtained, and the links \
are iterated through. The relative paths are converted into absolute paths and \
a ``Xp... |
def adupdates_simple(x, g, L, stepsize, inner_stepsizes, niter,
random=False):
"""Non-optimized version of ``adupdates``.
This function is intended for debugging. It makes a lot of copies and
performs no error checking.
"""
# Initializations
length = len(g)
ranges = [Li.... | Non-optimized version of ``adupdates``.
This function is intended for debugging. It makes a lot of copies and
performs no error checking. |
def get_signalcheck(self, sar, **params):
"""get_signalcheck - perform a signal check.
Parameters
----------
sar : dict
signal-api-request specified as a dictionary of parameters.
All of these parameters are optional. For details
check https://api.po... | get_signalcheck - perform a signal check.
Parameters
----------
sar : dict
signal-api-request specified as a dictionary of parameters.
All of these parameters are optional. For details
check https://api.postcode.nl/documentation/signal-api-example.
... |
def remove_bond(self, particle_pair):
"""Deletes a bond between a pair of Particles
Parameters
----------
particle_pair : indexable object, length=2, dtype=mb.Compound
The pair of Particles to remove the bond between
"""
from mbuild.port import Port
... | Deletes a bond between a pair of Particles
Parameters
----------
particle_pair : indexable object, length=2, dtype=mb.Compound
The pair of Particles to remove the bond between |
def new_chain(table='filter', chain=None, table_type=None, hook=None, priority=None, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Create new chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' nftables.new_chain filter input
salt '*' nftables.new_chain fil... | .. versionadded:: 2014.7.0
Create new chain to the specified table.
CLI Example:
.. code-block:: bash
salt '*' nftables.new_chain filter input
salt '*' nftables.new_chain filter input \\
table_type=filter hook=input priority=0
salt '*' nftables.new_chain filter ... |
def normalize(self):
"""
Normalizes the given data such that the area under the histogram/curve
comes to 1. Also re applies smoothing once done.
"""
median_diff = np.median(np.diff(self.x))
bin_edges = [self.x[0] - median_diff/2.0]
bin_edges.extend(median_diff/2.0... | Normalizes the given data such that the area under the histogram/curve
comes to 1. Also re applies smoothing once done. |
def import_model(cls, ins_name):
"""Import model class in models package
"""
try:
package_space = getattr(cls, 'package_space')
except AttributeError:
raise ValueError('package_space not exist')
else:
return import_object(ins_name, package_spac... | Import model class in models package |
def parse(self, what):
"""
:param what:
can be 'rlz-1/ref-asset1', 'rlz-2/sid-1', ...
"""
if '/' not in what:
key, spec = what, ''
else:
key, spec = what.split('/')
if spec and not spec.startswith(('ref-', 'sid-')):
raise Va... | :param what:
can be 'rlz-1/ref-asset1', 'rlz-2/sid-1', ... |
def add_to_inventory(self):
"""Adds lb IPs to stack inventory"""
if self.lb_attrs:
self.lb_attrs = self.consul.lb_details(
self.lb_attrs[A.loadbalancer.ID]
)
host = self.lb_attrs['virtualIps'][0]['address']
self.stack.add_lb_sec... | Adds lb IPs to stack inventory |
def has_builder(self):
"""Return whether this Node has a builder or not.
In Boolean tests, this turns out to be a *lot* more efficient
than simply examining the builder attribute directly ("if
node.builder: ..."). When the builder attribute is examined
directly, it ends up calli... | Return whether this Node has a builder or not.
In Boolean tests, this turns out to be a *lot* more efficient
than simply examining the builder attribute directly ("if
node.builder: ..."). When the builder attribute is examined
directly, it ends up calling __getattr__ for both the __len_... |
def sdot( U, V ):
'''
Computes the tensorproduct reducing last dimensoin of U with first dimension of V.
For matrices, it is equal to regular matrix product.
'''
nu = U.ndim
#nv = V.ndim
return np.tensordot( U, V, axes=(nu-1,0) ) | Computes the tensorproduct reducing last dimensoin of U with first dimension of V.
For matrices, it is equal to regular matrix product. |
def add_fileobj(self, fileobj, path, compress, flags=None):
"""Add the contents of a file object to the MAR file.
Args:
fileobj (file-like object): open file object
path (str): name of this file in the MAR file
compress (str): One of 'xz', 'bz2', or None. Defaults to... | Add the contents of a file object to the MAR file.
Args:
fileobj (file-like object): open file object
path (str): name of this file in the MAR file
compress (str): One of 'xz', 'bz2', or None. Defaults to None.
flags (int): permission of this file in the MAR file... |
def package_data(pkg, root_list):
"""Generic function to find package_data for `pkg` under `root`."""
data = []
for root in root_list:
for dirname, _, files in os.walk(os.path.join(pkg, root)):
for fname in files:
data.append(os.path.relpath(os.path.join(dirname, fname), ... | Generic function to find package_data for `pkg` under `root`. |
def init_fakemod_dict(fm,adict=None):
"""Initialize a FakeModule instance __dict__.
Kept as a standalone function and not a method so the FakeModule API can
remain basically empty.
This should be considered for private IPython use, used in managing
namespaces for %run.
Parameters
--------... | Initialize a FakeModule instance __dict__.
Kept as a standalone function and not a method so the FakeModule API can
remain basically empty.
This should be considered for private IPython use, used in managing
namespaces for %run.
Parameters
----------
fm : FakeModule instance
adict :... |
def ensure_index(self, index, mappings=None, settings=None, clear=False):
"""
Ensure if an index with mapping exists
"""
mappings = mappings or []
if isinstance(mappings, dict):
mappings = [mappings]
exists = self.indices.exists_index(index)
if exists ... | Ensure if an index with mapping exists |
def add_metrics(self, metrics: Iterable[float]) -> None:
"""
Helper to add multiple metrics at once.
"""
for metric in metrics:
self.add_metric(metric) | Helper to add multiple metrics at once. |
def is_deb_package_installed(pkg):
""" checks if a particular deb package is installed """
with settings(hide('warnings', 'running', 'stdout', 'stderr'),
warn_only=True, capture=True):
result = sudo('dpkg-query -l "%s" | grep -q ^.i' % pkg)
return not bool(result.return_code) | checks if a particular deb package is installed |
def ellipsis(text, length, symbol="..."):
"""Present a block of text of given length.
If the length of available text exceeds the requested length, truncate and
intelligently append an ellipsis.
"""
if len(text) > length:
pos = text.rfind(" ", 0, length)
if pos < 0:
... | Present a block of text of given length.
If the length of available text exceeds the requested length, truncate and
intelligently append an ellipsis. |
def _syndic_return(self, load):
'''
Receive a syndic minion return and format it to look like returns from
individual minions.
'''
# Verify the load
if any(key not in load for key in ('return', 'jid', 'id')):
return None
# if we have a load, save it
... | Receive a syndic minion return and format it to look like returns from
individual minions. |
def getSequence(title, db='nucleotide'):
"""
Get information about a sequence from Genbank.
@param title: A C{str} sequence title from a BLAST hit. Of the form
'gi|63148399|gb|DQ011818.1| Description...'.
@param db: The C{str} name of the Entrez database to consult.
NOTE: this uses the net... | Get information about a sequence from Genbank.
@param title: A C{str} sequence title from a BLAST hit. Of the form
'gi|63148399|gb|DQ011818.1| Description...'.
@param db: The C{str} name of the Entrez database to consult.
NOTE: this uses the network! Also, there is a 3 requests/second limit
i... |
def uptime(human_readable=False):
'''
.. versionadded:: 2015.8.0
Return the system uptime for the machine
Args:
human_readable (bool):
Return uptime in human readable format if ``True``, otherwise
return seconds. Default is ``False``
.. note::
... | .. versionadded:: 2015.8.0
Return the system uptime for the machine
Args:
human_readable (bool):
Return uptime in human readable format if ``True``, otherwise
return seconds. Default is ``False``
.. note::
Human readable format is ``days, hours:min... |
def p_try_statement_2(self, p):
"""try_statement : TRY block finally"""
p[0] = ast.Try(statements=p[2], fin=p[3]) | try_statement : TRY block finally |
def get_queryset(self, *args, **kwargs):
"""Django queryset.extra() is used here to add decryption sql to query."""
select_sql = {}
encrypted_fields = []
for f in self.model._meta.get_fields_with_model():
field = f[0]
if isinstance(field, PGPMixin):
... | Django queryset.extra() is used here to add decryption sql to query. |
def is_country(self, text):
"""Check if a piece of text is in the list of countries"""
ct_list = self._just_cts.keys()
if text in ct_list:
return True
else:
return False | Check if a piece of text is in the list of countries |
def invalidate_cache(user, size=None):
"""
Function to be called when saving or changing an user's avatars.
"""
sizes = set(settings.AVATAR_AUTO_GENERATE_SIZES)
if size is not None:
sizes.add(size)
for prefix in cached_funcs:
for size in sizes:
cache.delete(get_cache_... | Function to be called when saving or changing an user's avatars. |
def chimera_layout(G, scale=1., center=None, dim=2):
"""Positions the nodes of graph G in a Chimera cross topology.
NumPy (http://scipy.org) is required for this function.
Parameters
----------
G : NetworkX graph
Should be a Chimera graph or a subgraph of a
Chimera graph. If every ... | Positions the nodes of graph G in a Chimera cross topology.
NumPy (http://scipy.org) is required for this function.
Parameters
----------
G : NetworkX graph
Should be a Chimera graph or a subgraph of a
Chimera graph. If every node in G has a `chimera_index`
attribute, those are... |
def process_macros(self, content, source=None):
""" Processed all macros.
"""
macro_options = {'relative': self.relative, 'linenos': self.linenos}
classes = []
for macro_class in self.macros:
try:
macro = macro_class(logger=self.logger, embed=self.embe... | Processed all macros. |
def share_item(self, token, item_id, dest_folder_id):
"""
Share an item to the destination folder.
:param token: A valid token for the user in question.
:type token: string
:param item_id: The id of the item to be shared.
:type item_id: int | long
:param dest_fol... | Share an item to the destination folder.
:param token: A valid token for the user in question.
:type token: string
:param item_id: The id of the item to be shared.
:type item_id: int | long
:param dest_folder_id: The id of destination folder where the item is
shared ... |
def _compute_slices(self, start_idx, end_idx, assets):
"""
Compute the raw row indices to load for each asset on a query for the
given dates after applying a shift.
Parameters
----------
start_idx : int
Index of first date for which we want data.
end_... | Compute the raw row indices to load for each asset on a query for the
given dates after applying a shift.
Parameters
----------
start_idx : int
Index of first date for which we want data.
end_idx : int
Index of last date for which we want data.
as... |
def build(self, builder):
"""
Build XML by appending to builder
.. note:: Questions can contain translations
"""
builder.start("Question", {})
for translation in self.translations:
translation.build(builder)
builder.end("Question") | Build XML by appending to builder
.. note:: Questions can contain translations |
def parse_image_response(self, response):
"""
Parse multiple objects from the RETS feed. A lot of string methods are used to handle the response before
encoding it back into bytes for the object.
:param response: The response from the feed
:return: list of SingleObjectParser
... | Parse multiple objects from the RETS feed. A lot of string methods are used to handle the response before
encoding it back into bytes for the object.
:param response: The response from the feed
:return: list of SingleObjectParser |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.