text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def _index_loopbacks(self):
"""Finds all loopbacks and stores them in :attr:`loopbacks`"""
self.loopbacks = {}
try:
result = _util.check_output_(['losetup', '-a'])
for line in result.splitlines():
m = re.match(r'(.+): (.+) \((.+)\).*', line)
... | 0.00464 |
def condition_input(args, kwargs):
'''
Return a single arg structure for the publisher to safely use
'''
ret = []
for arg in args:
if (six.PY3 and isinstance(arg, six.integer_types) and salt.utils.jid.is_jid(six.text_type(arg))) or \
(six.PY2 and isinstance(arg, long)): # pylint: di... | 0.006202 |
def summary(self, sortOn=None):
"""
Summarize all the alignments for this title.
@param sortOn: A C{str} attribute to sort titles on. One of 'length',
'maxScore', 'medianScore', 'readCount', or 'title'.
@raise ValueError: If an unknown C{sortOn} value is given.
@retu... | 0.00318 |
def get_img_info(image):
"""Return the header and affine matrix from a Nifti file.
Parameters
----------
image: img-like object or str
Can either be:
- a file path to a Nifti image
- any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
If niimg... | 0.003846 |
def _process_state(cls, unprocessed, processed, state):
"""Preprocess a single state definition."""
assert type(state) is str, "wrong state name %r" % state
assert state[0] != '#', "invalid state name %r" % state
if state in processed:
return processed[state]
tokens =... | 0.002112 |
def modify_agent_property(self, agent_id, key, value):
'''
modify_agent_property(self, agent_id, key, value)
Modifies a single single property of an agent. If the property does not exists then it is created as a custom property.
:Parameters:
* *agent_id* (`string`) -- Identifie... | 0.008805 |
def next(self):
"""Goes one item ahead and returns it."""
rv = self.current
self.pos = (self.pos + 1) % len(self.items)
return rv | 0.012422 |
def _CallPlugin(self, cmd, input_json):
"""Calls the plugin and validates the response."""
# Calculate length of input
input_length = len(input_json)
length_bytes_le = struct.pack('<I', input_length)
request = length_bytes_le + input_json.encode()
# Call plugin
sign_process = subprocess.Pop... | 0.004517 |
def del_Unnamed(df):
"""
Deletes all the unnamed columns
:param df: pandas dataframe
"""
cols_del=[c for c in df.columns if 'Unnamed' in c]
return df.drop(cols_del,axis=1) | 0.015306 |
def _get_file(self, share_name, directory_name, file_name,
start_range=None, end_range=None, validate_content=False,
timeout=None, _context=None):
'''
Downloads a file's content, metadata, and properties. You can specify a
range if you don't need to download th... | 0.005549 |
def _make_list(predictions, targets):
"""Helper: make predictions and targets lists, check they match on length."""
# Our models sometimes return predictions in lists, make it a list always.
# TODO(lukaszkaiser): make abstractions for nested structures and refactor.
if not isinstance(predictions, (list, tuple)... | 0.012327 |
def reservations(self):
"""
Access the reservations
:returns: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationList
:rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationList
"""
if self._reservations is None:
self._reservatio... | 0.007533 |
async def close(self):
"""
Cleans up after the connection to the SMTP server has been closed
(voluntarily or not).
"""
if self.writer is not None:
# Close the transport:
try:
self.writer.close()
except OSError as exc:
... | 0.004866 |
def idle_task(self):
'''handle missing parameters'''
self.pstate.vehicle_name = self.vehicle_name
self.pstate.fetch_check(self.master) | 0.012658 |
def currency_to_protocol(amount):
"""
Convert a string of 'currency units' to 'protocol units'. For instance
converts 19.1 bitcoin to 1910000000 satoshis.
Input is a float, output is an integer that is 1e8 times larger.
It is hard to do this conversion because multiplying
floats causes roundin... | 0.00177 |
def generateLinearRDD(sc, nexamples, nfeatures, eps,
nParts=2, intercept=0.0):
"""
Generate an RDD of LabeledPoints.
"""
return callMLlibFunc(
"generateLinearRDDWrapper", sc, int(nexamples), int(nfeatures),
float(eps), int(nParts), float(... | 0.009063 |
def get_pages_for_display(self):
"""Return all pages needed for rendering all sub-levels for the current
menu"""
parent_page = self.parent_page_for_menu_items
pages = self.get_base_page_queryset().filter(
depth__gt=parent_page.depth,
depth__lte=parent_page.depth +... | 0.003509 |
def load_selected_bot(self):
"""
Loads all the values belonging to the new selected agent into the bot_config_groupbox
:return:
"""
# prevent processing from itself (clearing the other one processes this)
if not self.sender().selectedItems():
return
b... | 0.003653 |
def pause(self):
"""Set the execution mode to paused
"""
if self.state_machine_manager.active_state_machine_id is None:
logger.info("'Pause' is not a valid action to initiate state machine execution.")
return
if self.state_machine_manager.get_active_state_machine(... | 0.00726 |
def emit(self, event: str, *args, **kwargs) -> None:
""" Emit an event and run the subscribed functions.
:param event: Name of the event.
:type event: str
.. notes:
Passing in threads=True as a kwarg allows to run emitted events
as separate threads. This can sig... | 0.002509 |
def p_annotation_type_1(self, p):
"""annotation_type : ANNOTATION_TYPE LINE"""
try:
if six.PY2:
value = p[2].decode(encoding='utf-8')
else:
value = p[2]
self.builder.add_annotation_type(self.document, value)
except CardinalityEr... | 0.003012 |
def fidx(right, left, left_fk=None):
"""
Re-indexes a series or data frame (right) to align with
another (left) series or data frame via foreign key relationship.
The index of the right must be unique.
This is similar to misc.reindex, but allows for data frame
re-indexes and supports re-indexin... | 0.000473 |
def get_logger(name, level=None):
""" Return a setup logger for the given name
:param name: The name for the logger. It is advised to use __name__. The logger name will be prepended by \"jb.\".
:type name: str
:param level: the logging level, e.g. logging.DEBUG, logging.INFO etc
:type level: int
... | 0.00436 |
def set_gateway(self, gateway):
'''
:param crabpy.gateway.capakey.CapakeyGateway gateway: Gateway to use.
'''
self.gateway = gateway
self.sectie.set_gateway(gateway) | 0.009756 |
def lookup_tf(self, h):
'''Get stream IDs and term frequencies for a single hash.
This yields pairs of strings that can be retrieved using
:func:`streamcorpus_pipeline._kvlayer.get_kvlayer_stream_item`
and the corresponding term frequency.
..see:: :meth:`lookup`
'''
... | 0.003922 |
def get_bytes(self):
"""set_client_DH_params#f5045f1f nonce:int128 server_nonce:int128 encrypted_data:bytes = Set_client_DH_params_answer"""
ret = struct.pack("<I16s16s", set_client_DH_params.constructor, self.nonce, self.server_nonce)
bytes_io = BytesIO()
bytes_io.write(ret)
s... | 0.00995 |
def map(self, msg):
"""
Apply key function to ``msg`` to obtain a key. Return the routing table entry.
"""
k = self.key_function(msg)
key = k[0] if isinstance(k, (tuple, list)) else k
return self.routing_table[key] | 0.01145 |
def connect_get_namespaced_pod_attach(self, name, namespace, **kwargs): # noqa: E501
"""connect_get_namespaced_pod_attach # noqa: E501
connect GET requests to attach of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, ple... | 0.001053 |
def save(self, insert=False, changed=None, saved=None,
send_dispatch=True, version=False, version_fieldname=None,
version_exception=True):
"""
If insert=True, then it'll use insert() indead of update()
changed will be callback function, only when the non manytom... | 0.006208 |
def _yield_subpatches(patch, splits, name='split'):
"""
Iterator for subtables defined by a splits string
Parameters
----------
patch : obj
Patch object containing data to subset
splits : str
Specifies how a column of a dataset should be split. See Notes.
Yields
------
... | 0.002151 |
def solve(self, A, F, N, b):
"""
Solve linear system ``Ax = b`` using numeric factorization ``N`` and symbolic factorization ``F``.
Store the solution in ``b``.
Parameters
----------
A
Sparse matrix
F
Symbolic factorization
N
... | 0.005034 |
def processCommit(self, commit: Commit, sender: str) -> None:
"""
Validate and process the COMMIT specified.
If validation is successful, return the message to the node.
:param commit: an incoming COMMIT message
:param sender: name of the node that sent the COMMIT
"""
... | 0.002813 |
def rc(self):
"""Return the reverse complemented motif.
Returns
-------
m : Motif instance
New Motif instance with the reverse complement of the input motif.
"""
m = Motif()
m.pfm = [row[::-1] for row in self.pfm[::-1]]
m.pwm = [row[::-1] for ... | 0.005063 |
def perform_request(self, request_type, *args, **kwargs):
"""
Create and send a request.
`request_type` is the request type (string). This is used to look up a
plugin, whose request class is instantiated and passed the remaining
arguments passed to this function.
"""
... | 0.004202 |
def surface_brightness(self, x, y, kwargs_list, k=None):
"""
:param x: coordinate in units of arcsec relative to the center of the image
:type x: set or single 1d numpy array
"""
x = np.array(x, dtype=float)
y = np.array(y, dtype=float)
flux = np.zeros_like(x)
... | 0.007505 |
def ts(self, data, lon_cyclic=True, lon_str=LON_STR, lat_str=LAT_STR,
land_mask_str=LAND_MASK_STR, sfc_area_str=SFC_AREA_STR):
"""Create yearly time-series of region-averaged data.
Parameters
----------
data : xarray.DataArray
The array to create the regional time... | 0.001552 |
def waiters(self, path=None):
"""Iterate over all waiters.
This method will return the waiters in unspecified order
including the future or callback object that will be invoked
and a list containing the keys/value that are being matched.
Yields:
list, future or call... | 0.002699 |
def before_request(self) -> Optional[Response]:
"""Determine if a user is allowed to view this route."""
auth = request.authorization
if not auth or not self._check_auth(auth.username, auth.password):
return Response(
'Could not verify your access level for that URL.\... | 0.003442 |
def compile_schema(self, schema):
""" Compile the current schema into a callable validator
:return: Callable validator
:rtype: callable
:raises SchemaError: Schema compilation error
"""
compiler = self.get_schema_compiler(schema)
if compiler is None:
... | 0.006787 |
def seektime(self, disk):
"""
Gives seek latency on disk which is a very good indication to the `type` of the disk.
it's a very good way to verify if the underlying disk type is SSD or HDD
:param disk: disk path or name (/dev/sda, or sda)
:return: a dict as follows {'device': '<... | 0.009091 |
def regexNamer(regex, usePageUrl=False):
"""Get name from regular expression."""
@classmethod
def _namer(cls, imageUrl, pageUrl):
"""Get first regular expression group."""
url = pageUrl if usePageUrl else imageUrl
mo = regex.search(url)
if mo:
return mo.group(1)
... | 0.002976 |
def run(self, galaxy_data, results=None, mask=None):
"""
Run this phase.
Parameters
----------
galaxy_data
mask: Mask
The default masks passed in by the pipeline
results: autofit.tools.pipeline.ResultsCollection
An object describing the re... | 0.005517 |
def h6_mahe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""Compute the H6 mean absolute error.
.. image:: /pictures/H6.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
... | 0.00495 |
def default_rotations(*qubits):
"""
Generates the Quil programs for the tomographic pre- and post-rotations of any number of qubits.
:param list qubits: A list of qubits to perform tomography on.
"""
for gates in cartesian_product(TOMOGRAPHY_GATES.keys(), repeat=len(qubits)):
tomography_pro... | 0.006438 |
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join... | 0.003077 |
def encrypt(self, msg):
"""encrypts a message"""
iv = self.random_bytes(AES.block_size)
ctr = Counter.new(AES.block_size * 8, initial_value=self.bin2long(iv))
cipher = AES.AESCipher(self._cipherkey, AES.MODE_CTR, counter=ctr)
cipher_text = cipher.encrypt(msg)
intermediate... | 0.004728 |
def pull_image(self, image, progress_callback=None):
"""
Pull image from docker repository
:params image: Image name
:params progress_callback: A function that receive a log message about image download progress
"""
try:
yield from self.query("GET", "images/... | 0.003062 |
def rlecode_hqx(s):
"""
Run length encoding for binhex4.
The CPython implementation does not do run length encoding
of \x90 characters. This implementation does.
"""
if not s:
return ''
result = []
prev = s[0]
count = 1
# Add a dummy character to get the loop to go one ex... | 0.000775 |
def multiget_cached(object_key, argument_key=None, default_result=None,
result_fields=None, join_table_name=None, coerce_args_to_strings=False):
"""
:param object_key: the names of the attributes on the result object that are meant to match the function parameters
:param argument_key: th... | 0.007624 |
def serialize_rules(self, rules):
"""Creates a payload for the redis server."""
# TODO(mdietz): If/when we support other rule types, this comment
# will have to be revised.
# Action and direction are static, for now. The implementation may
# support 'deny' and 'egre... | 0.000928 |
def is_periodic_image(self, other, tolerance=1e-8, check_lattice=True):
"""
Returns True if sites are periodic images of each other.
Args:
other (PeriodicSite): Other site
tolerance (float): Tolerance to compare fractional coordinates
check_lattice (bool): Wh... | 0.002594 |
def apply(self, parent_environ=None):
"""Apply the context to the current python session.
Note that this updates os.environ and possibly sys.path, if
`parent_environ` is not provided.
Args:
parent_environ: Environment to interpret the context within,
default... | 0.003636 |
def connect(self, protocol=None):
"""! @brief Initialize DAP IO pins for JTAG or SWD"""
self._link.enter_debug(STLink.Protocol.SWD)
self._is_connected = True | 0.01105 |
def expand_user(path):
"""Expand '~'-style usernames in strings.
This is similar to :func:`os.path.expanduser`, but it computes and returns
extra information that will be useful if the input was being used in
computing completions, and you wish to return the completions with the
original '~' instea... | 0.000929 |
def build_url_name(cls, name, name_prefix=None):
"""
Given a ``name`` & an optional ``name_prefix``, this generates a name
for a URL.
:param name: The name for the URL (ex. 'detail')
:type name: string
:param name_prefix: (Optional) A prefix for the URL's name (for
... | 0.002381 |
def url(self):
"""The URL as a string of the resource."""
if not self._url[2].endswith('/'):
self._url[2] += '/'
return RestURL.url.__get__(self) | 0.01105 |
def as_cql_query(self, formatted=False):
"""
Returns a CQL query that can be used to recreate this type.
If `formatted` is set to :const:`True`, extra whitespace will
be added to make the query more readable.
"""
ret = "CREATE TYPE %s.%s (%s" % (
protect_name(... | 0.002273 |
def delete(self, request, bot_id, id, format=None):
"""
Delete existing Telegram Bot
---
responseMessages:
- code: 401
message: Not authenticated
"""
return super(TelegramBotDetail, self).delete(request, bot_id, id, format) | 0.010101 |
def data_available(dataset_name=None):
"""Check if the data set is available on the local machine already."""
try:
from itertools import zip_longest
except ImportError:
from itertools import izip_longest as zip_longest
dr = data_resources[dataset_name]
zip_urls = (dr['files'], )
... | 0.008032 |
def _parse_date_nate(dateString):
'''Parse a string according to the Nate 8-bit date format'''
m = _korean_nate_date_re.match(dateString)
if not m:
return
hour = int(m.group(5))
ampm = m.group(4)
if (ampm == _korean_pm):
hour += 12
hour = str(hour)
if len(hour) == 1:
... | 0.006006 |
def on_assert(self, node): # ('test', 'msg')
"""Assert statement."""
if not self.run(node.test):
self.raise_exception(node, exc=AssertionError, msg=node.msg)
return True | 0.009615 |
def _resizeCurrentColumnToContents(self, new_index, old_index):
"""Resize the current column to its contents."""
if new_index.column() not in self._autosized_cols:
# Ensure the requested column is fully into view after resizing
self._resizeVisibleColumnsToContents()
... | 0.005587 |
def vm_deploy(name, kwargs=None, call=None):
'''
Initiates the instance of the given VM on the target host.
.. versionadded:: 2016.3.0
name
The name of the VM to deploy.
host_id
The ID of the target host where the VM will be deployed. Can be used instead
of ``host_name``.
... | 0.00354 |
def unregister_language(self, name):
"""
Unregisters language with given name from the :obj:`LanguagesModel.languages` class property.
:param name: Language to unregister.
:type name: unicode
:return: Method success.
:rtype: bool
"""
if not self.get_lang... | 0.005148 |
def add_user_jobs(session, job_ids):
"""
Add a list of jobs to the currently authenticated user
"""
jobs_data = {
'jobs[]': job_ids
}
response = make_post_request(session, 'self/jobs', json_data=jobs_data)
json_data = response.json()
if response.status_code == 200:
return... | 0.00189 |
def copy(source, dest):
"""
use the vospace service to get a file.
@param source:
@param dest:
@return:
"""
logger.info("copying {} -> {}".format(source, dest))
return client.copy(source, dest) | 0.004405 |
def from_jwt(cls, jwt, key=''):
"""
Decode a JWT string into a Jwt object
:param str jwt: JWT string
:param Optional[str] key: key used to verify JWT signature, if not provided then validation
is skipped.
:raises JwtDecodeError if decoding JWT fa... | 0.003432 |
def update_group(self, group, process_id, wit_ref_name, page_id, section_id, group_id):
"""UpdateGroup.
[Preview API] Updates a group in the work item form.
:param :class:`<Group> <azure.devops.v5_0.work_item_tracking_process.models.Group>` group: The updated group.
:param str process_id... | 0.00625 |
def fit(self, X, y, **kwargs):
"""
Fits the estimator to calculate feature correlation to
dependent variable.
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m features
y : ndarray or Series of length n
... | 0.00196 |
def source_path(self):
"""The name in a form suitable for use in a filesystem.
Excludes the revision
"""
# Need to do this to ensure the function produces the
# bundle path when called from subclasses
names = [k for k, _, _ in self._name_parts]
parts = [self.so... | 0.005396 |
def get_json_encoders_for_type(self, type_to_encode: type) -> Optional[Iterable[JSONEncoder]]:
"""
Gets the registered JSON encoder for the given type.
:param type_to_encode: the type of object that is to be encoded
:return: the encoder for the given object else `None` if unknown
... | 0.006623 |
def lower_items(self):
"""Like iteritems(), but with all lowercase keys."""
return (
(lowerkey, keyval[1])
for (lowerkey, keyval)
in list(self._store.items())
) | 0.009091 |
def get_task(self, task=None):
"""
Returns a (task, description) tuple for a given task
"""
# Iterate over the grindstone tasks
for t in self.grindstone['tasks']:
# if they key matches the task
if key_of(t) == task:
# Return this task
... | 0.005076 |
def export_html(html, filename, image_tag = None, inline = True):
""" Export the contents of the ConsoleWidget as HTML.
Parameters:
-----------
html : str,
A utf-8 encoded Python string containing the Qt HTML to export.
filename : str
The file to be saved.
image_tag : callable... | 0.008518 |
def admin_tools_render_dashboard_css(
context, location='index', dashboard=None):
"""
Template tag that renders the dashboard css files, it takes two optional
arguments:
``location``
The location of the dashboard, it can be 'index' (for the admin index
dashboard) or 'app_index' ... | 0.001179 |
def _selectLines(self, startBlockNumber, endBlockNumber):
"""Select whole lines
"""
startBlock = self.document().findBlockByNumber(startBlockNumber)
endBlock = self.document().findBlockByNumber(endBlockNumber)
cursor = QTextCursor(startBlock)
cursor.setPosition(endBlock.p... | 0.004301 |
def request(self, endpoint, data=None, json=None, filename=None, save_to=None):
"""
Perform a REST API request to the backend H2O server.
:param endpoint: (str) The endpoint's URL, for example "GET /4/schemas/KeyV4"
:param data: data payload for POST (and sometimes GET) requests. This s... | 0.006134 |
def get_uuid(length=32, version=1):
"""
Returns a unique ID of a given length.
User `version=2` for cross-systems uniqueness.
"""
if version == 1:
return uuid.uuid1().hex[:length]
else:
return uuid.uuid4().hex[:length] | 0.003876 |
def hessian_component(self, index1, index2):
"""Compute the hessian of the energy for one atom pair"""
result = np.zeros((3, 3), float)
if index1 == index2:
for index3 in range(self.numc):
if self.scaling[index1, index3] > 0:
d_1 = 1/self.distances... | 0.006615 |
def query(self, query):
'''Returns an iterable of objects matching criteria expressed in `query`.
LoggingDatastore logs the access.
'''
self.logger.info('%s: query %s' % (self, query))
return super(LoggingDatastore, self).query(query) | 0.003891 |
def setParams(self, minSupport=0.3, minConfidence=0.8, itemsCol="items",
predictionCol="prediction", numPartitions=None):
"""
setParams(self, minSupport=0.3, minConfidence=0.8, itemsCol="items", \
predictionCol="prediction", numPartitions=None)
"""
kwa... | 0.007916 |
def listContents(self):
""" Return list of volumes or diffs in this Store's selected directory. """
items = list(self.extraKeys.items())
items.sort(key=lambda t: t[1])
(count, size) = (0, 0)
for (diff, path) in items:
if path.startswith("/"):
continu... | 0.006466 |
def _sub_ms_char(self, match):
"""Changes a MS smart quote character to an XML or HTML
entity, or an ASCII character."""
orig = match.group(1)
if self.smart_quotes_to == 'ascii':
sub = self.MS_CHARS_TO_ASCII.get(orig).encode()
else:
sub = self.MS_CHARS.get... | 0.003072 |
def displayNewKey(key):
"""Use ``gnupg.GPG.list_keys()`` to display details of the new key."""
if key.keyring:
gpg.keyring = key.keyring
if key.secring:
gpg.secring = key.secring
# Using '--fingerprint' twice will display subkey fingerprints too:
gpg.options = ['--fingerprint', '--... | 0.00157 |
def print_page(text):
"""Format the text and prints it on stdout.
Text is formatted by adding a ASCII frame around it and coloring the text.
Colors can be added to text using color tags, for example:
My [FG_BLUE]blue[NORMAL] text.
My [BG_BLUE]blue background[NORMAL] text.
"""
... | 0.001916 |
def schedule(cls, mapreduce_spec):
"""Schedule finalize task.
Args:
mapreduce_spec: mapreduce specification as MapreduceSpec.
"""
task_name = mapreduce_spec.mapreduce_id + "-finalize"
finalize_task = taskqueue.Task(
name=task_name,
url=(mapreduce_spec.params["base_path"] + "/f... | 0.002994 |
def send(self, message):
"""
Sends message to *mod-host*.
.. note::
Uses :class:`.ProtocolParser` for a high-level management.
As example, view :class:`.Host`
:param string message: Message that will be sent for *mod-host*
"""
print(message.enco... | 0.004454 |
def location(ip=None, key=None, field=None):
''' Get geolocation data for a given IP address
If field is specified, get specific field as text
Else get complete location data as JSON
'''
if field and (field not in field_list):
return 'Invalid field'
if field:
if ip:
... | 0.003774 |
def absolute(self):
"""
The FQDN as a string in absolute form
"""
if not self.is_valid:
raise ValueError('invalid FQDN `{0}`'.format(self.fqdn))
if self.is_valid_absolute:
return self.fqdn
return '{0}.'.format(self.fqdn) | 0.006803 |
def cmd_guess_labels(*args):
"""
Arguments: <document id> [-- [--apply]]
Guess the labels that should be set on the document.
Example: paperwork-shell guess_labels -- 20161207_1144_00_8 --apply
Possible JSON replies:
--
{
"status": "error", "exception": "yyy",
... | 0.000473 |
def send_request(self, job_request, message_expiry_in_seconds=None):
"""
Send a JobRequest, and return a request ID.
The context and control_extra arguments may be used to include extra values in the
context and control headers, respectively.
:param job_request: The job request... | 0.006061 |
def record_set(session_factory, bucket, key_prefix, start_date, specify_hour=False):
"""Retrieve all s3 records for the given policy output url
From the given start date.
"""
s3 = local_session(session_factory).client('s3')
records = []
key_count = 0
date = start_date.strftime('%Y/%m/%d'... | 0.0016 |
def load_class_by_name(name: str):
"""Given a dotted path, returns the class"""
mod_path, _, cls_name = name.rpartition('.')
mod = importlib.import_module(mod_path)
cls = getattr(mod, cls_name)
return cls | 0.004464 |
def do(self, command, files=None, use_long_polling=False, request_timeout=None, **query):
"""
Send a request to the api.
If the bot is set to return the json objects, it will look like this:
```json
{
"ok": bool,
"result": {...},
# optionally... | 0.006258 |
def pull_blob(self, digest, size=False, chunk_size=None):
"""
Download a blob from the registry given the hash of its content.
:param digest: Hash of the blob's content (prefixed by ``sha256:``).
:type digest: str
:param size: Whether to return the size of the blob too.
... | 0.004566 |
def format_sql_workload_type_update_settings(result):
'''
Formats the SqlWorkloadTypeUpdateSettings object removing arguments that are empty
'''
from collections import OrderedDict
# Only display parameters that have content
order_dict = OrderedDict()
if result.sql_workload_type is not None:... | 0.004902 |
def convert_to_wav(files):
'''Converts files to a format that pocketsphinx can deal wtih (16khz mono 16bit wav)'''
converted = []
for f in files:
new_name = f + '.temp.wav'
print(new_name)
if (os.path.exists(f + '.transcription.txt') is False) and (os.path.exists(new_name) is False):... | 0.008114 |
def dict_find_keys(dict_, val_list):
r"""
Args:
dict_ (dict):
val_list (list):
Returns:
dict: found_dict
CommandLine:
python -m utool.util_dict --test-dict_find_keys
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>>... | 0.001047 |
def last(self, n=1):
"""
Get the last element of an array. Passing **n** will return the last N
values in the array.
The **guard** check allows it to work with `_.map`.
"""
res = self.obj[-n:]
if len(res) is 1:
res = res[0]
return self._wrap(re... | 0.006211 |
def _feature_file(self, parallel = None, index = None):
"""Returns the name of an intermediate file for storing features."""
if index is None:
index = 0 if parallel is None or "SGE_TASK_ID" not in os.environ else int(os.environ["SGE_TASK_ID"])
return os.path.join(self.feature_directory, "Features_%02d... | 0.020896 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.