text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def _inputhook_tk(inputhook_context):
"""
Inputhook for Tk.
Run the Tk eventloop until prompt-toolkit needs to process the next input.
"""
# Get the current TK application.
import _tkinter # Keep this imports inline!
from six.moves import tkinter
root = tkinter._default_root
def wa... | 0.003163 |
def render(self, validate=True):
"""Render the training program to perform the calculations.
The program can be rendered several times to produce new
information given the same input parameters.
Parameters
----------
validate
Boolean that indicates whethe... | 0.001274 |
def Parser(version):
"""
Returns an options parser object initialized with the standard
SCons options.
"""
formatter = SConsIndentedHelpFormatter(max_help_position=30)
op = SConsOptionParser(option_class=SConsOption,
add_help_option=False,
... | 0.000902 |
def geo(self, column=None, value=None, **kwargs):
"""
Locate a facility through geographic location.
>>> RADInfo().geo('geometric_type_code', '001')
"""
return self._resolve_call('RAD_GEO_LOCATION', column, value, **kwargs) | 0.007576 |
def interpolate(self, column_hours, method='linear', limit=24, limit_direction='both', **kwargs):
"""
Wrapper function for ``pandas.Series.interpolate`` that can be used to
"disaggregate" values using various interpolation methods.
Parameters
----------
column_hours : di... | 0.005698 |
def retrieveVals(self):
"""Retrieve values for graphs."""
ntpinfo = NTPinfo()
stats = ntpinfo.getHostOffset(self._remoteHost)
if stats:
graph_name = 'ntp_host_stratum_%s' % self._remoteHost
if self.hasGraph(graph_name):
self.setGraphVal(graph_name,... | 0.003289 |
def convert(cls, value, from_base, to_base):
"""
Convert value from a base to a base.
:param value: the value to convert
:type value: sequence of int
:param int from_base: base of value
:param int to_base: base of result
:returns: the conversion result
:r... | 0.002469 |
def set_attribute_label(span, resource_type, resource_labels, attribute_key,
canonical_key=None, label_value_prefix=''):
"""Set a label to span that can be used for tracing.
:param span: Span object
:param resource_type: resource type
:param resource_labels: collection of labels
... | 0.001083 |
def SoS_exec(script: str, _dict: dict = None,
return_result: bool = True) -> None:
'''Execute a statement.'''
if _dict is None:
_dict = env.sos_dict.dict()
if not return_result:
exec(
compile(script, filename=stmtHash.hash(script), mode='exec'), _dict)
retur... | 0.002024 |
def get_transition (self, input_symbol, state):
'''This returns (action, next state) given an input_symbol and state.
This does not modify the FSM state, so calling this method has no side
effects. Normally you do not call this method directly. It is called by
process().
The se... | 0.004292 |
def execute_sql(self, statement):
"""
Executes a single SQL statement.
:param statement: SQL string
:return: String response
:rtype: str
"""
path = '/archive/{}/sql'.format(self._instance)
req = archive_pb2.ExecuteSqlRequest()
req.statement = stat... | 0.003091 |
def validate_header(header, header_auth, raw_header, data_key):
"""Validates the header using the header authentication data.
:param header: Deserialized header
:type header: aws_encryption_sdk.structures.MessageHeader
:param header_auth: Deserialized header auth
:type header_auth: aws_encryption_s... | 0.002125 |
def from_cli_single_ifo(opt, ifo, **kwargs):
"""
Get the strain for a single ifo when using the multi-detector CLI
"""
single_det_opt = copy_opts_for_single_ifo(opt, ifo)
return from_cli(single_det_opt, **kwargs) | 0.00431 |
def format_content(content):
"""Given a Status contents in HTML, converts it into lines of plain text.
Returns a generator yielding lines of content.
"""
paragraphs = parse_html(content)
first = True
for paragraph in paragraphs:
if not first:
yield ""
for line in... | 0.002653 |
def _build_command(self, cmd, **kwargs):
"""
_build_command: string (binary data) ... -> binary data
_build_command will construct a command packet according to the
specified command's specification in api_commands. It will expect
named arguments for all fields other than those ... | 0.001618 |
def system_entropy():
"""Return the system's entropy bit count, or -1 if unknown."""
arg = ['cat', '/proc/sys/kernel/random/entropy_avail']
proc = Popen(arg, stdout=PIPE, stderr=DEVNULL)
response = proc.communicate()[0]
return int(response) if response else -1 | 0.006667 |
def except_token(source, start, token, throw=True):
"""Token can be only a single char. Returns position after token if found. Otherwise raises syntax error if throw
otherwise returns None"""
start = pass_white(source, start)
if start < len(source) and source[start] == token:
return start + 1
... | 0.004866 |
def attach_bundle(self, bundle):
"""Attaches a bundle object
:param bundle: :class:`flask_journey.BlueprintBundle` object
:raises:
- IncompatibleBundle if the bundle is not of type `BlueprintBundle`
- ConflictingPath if a bundle already exists at bundle.path
... | 0.005525 |
def _true_anomaly(M,ecc,itermax=8):
r"""
Calculation of true and eccentric anomaly in Kepler orbits.
``M`` is the phase of the star, ``ecc`` is the eccentricity
See p.39 of Hilditch, 'An Introduction To Close Binary Stars':
Kepler's equation:
.. math::
E - e\sin E = \frac{2\pi}{P}(t... | 0.005653 |
def nearest(items, pivot):
'''Find nearest value in array, including datetimes
Args
----
items: iterable
List of values from which to find nearest value to `pivot`
pivot: int or float
Value to find nearest of in `items`
Returns
-------
nearest: int or float
Valu... | 0.002445 |
def _compute_term_3(self, C, mag, R):
"""
(a12 + a13.*M + a14.*M.*M + a15.*M.*M.*M).*(d(r).^2)
"""
return (
(C['a12'] + C['a13'] * mag + C['a14'] * np.power(mag, 2) +
C['a15'] * np.power(mag, 3)) * np.power(R, 2)
) | 0.007168 |
def convert_youtube_audio(directory, output_directory, youtube_id, channels,
sample, output_filename=None):
"""Converts downloaded YouTube audio to HDF5 format.
Requires `ffmpeg` to be installed and available on the command line
(i.e. available on your `PATH`).
Parameters
... | 0.000503 |
def name(self) -> str:
"""Return name relevant to direction."""
if self.direction == DIRECTION_IN:
return self.raw.get('Input.Name', '')
return self.raw.get('Output.Name', '') | 0.009479 |
def update(self):
"""
Reload the keys if necessary
This is a forced update, will happen even if cache time has not elapsed.
Replaced keys will be marked as inactive and not removed.
"""
res = True # An update was successful
if self.source:
_k... | 0.003049 |
def _expand_space(self):
"""
Creates an internal list where the variables with dimensionality larger than one are expanded.
This list is the one that is used internally to do the optimization.
"""
## --- Expand the config space
self._expand_config_space()
## ---... | 0.010893 |
def parse_binary(self):
'''
when retrieving a NonRDF resource, parse binary data and make available
via generators
'''
# derive mimetype
self.mimetype = self.resource.rdf.graph.value(
self.resource.uri,
self.resource.rdf.prefixes.ebucore.hasMimeType).toPython()
# get binary content as stremable r... | 0.037328 |
def get_service(service, model_form='models', form_name=''):
"""
get the service name then load the model
:param service: the service name
:param model_form: could be 'models' or 'forms'
:param form_name: the name of the form is model_form is 'forms'
:type service: string
... | 0.00101 |
def _equally_weight_samples(samples, weights):
""" Convert samples to be equally weighted.
Samples are trimmed by discarding samples in accordance with a probability
determined by the corresponding weight.
This function has assumed you have normalised the weights properly.
If in doubt, convert wei... | 0.000834 |
def from_dataframe(cls,**kwargs):
"""class method constructor to create an Ensemble from
a pandas.DataFrame
Parameters
----------
**kwargs : dict
optional args to pass to the
Ensemble Constructor. Expects 'df' in kwargs.keys()
that must be a ... | 0.010811 |
def pipe_schedule(self, column=None, value=None, **kwargs):
"""
Particular discharge points at a permit facility that are governed by
effluent limitations and monitoring and submission requirements.
>>> PCS().pipe_schedule('state_submission_units', 'M')
"""
return self._... | 0.005333 |
def get_server_dir(self):
"""
Either downloads and/or unzips the server if necessary
return: the directory of the unzipped server
"""
if not self.args.server:
if self.args.skipunzip:
raise Stop(0, 'Unzip disabled, exiting')
log.info('Downl... | 0.001378 |
def _ensure_empty_image_ok(self):
"""
If ignore_empty was not set to True, we only allow empty HDU for first
HDU and if there is no data there already
"""
if self.ignore_empty:
return
if len(self) > 1:
raise RuntimeError(
"Cannot w... | 0.003724 |
def index_exists(self, table: str, indexname: str) -> bool:
"""Does an index exist? (Specific to MySQL.)"""
# MySQL:
sql = ("SELECT COUNT(*) FROM information_schema.statistics"
" WHERE table_name=? AND index_name=?")
row = self.fetchone(sql, table, indexname)
retur... | 0.005682 |
def chart_maker(Int, Top, start=100, outfile='chart.txt'):
"""
Makes a chart for performing IZZI experiments. Print out the file and
tape it to the oven. This chart will help keep track of the different
steps.
Z : performed in zero field - enter the temperature XXX.0 in the sio
formatted me... | 0.001476 |
def format_ubuntu_dialog(df):
""" Print statements paired with replies, formatted for easy review """
s = ''
for i, record in df.iterrows():
statement = list(split_turns(record.Context))[-1] # <1>
reply = list(split_turns(record.Utterance))[-1] # <2>
s += 'Statement: {}\n'.format(s... | 0.002597 |
def dense_to_deeper_block(dense_layer, weighted=True):
'''deeper dense layer.
'''
units = dense_layer.units
weight = np.eye(units)
bias = np.zeros(units)
new_dense_layer = StubDense(units, units)
if weighted:
new_dense_layer.set_weights(
(add_noise(weight, np.array([0, 1]... | 0.00489 |
def location_handler(self, name):
"""Decorator that registers a function for parsing a request location.
The wrapped function receives a request, the name of the argument, and
the corresponding `Field <marshmallow.fields.Field>` object.
Example: ::
from webargs import core
... | 0.002861 |
def get_api_v1_info(api_prefix):
"""Return a dict with all the information specific for the v1 of the
api.
"""
websocket_root = base_ws_uri() + EVENTS_ENDPOINT
docs_url = [
'https://docs.bigchaindb.com/projects/server/en/v',
version.__version__,
'/http-client-server-api.html'... | 0.001348 |
def _main(self, transfer_future, **kwargs):
"""
:type transfer_future: s3transfer.futures.TransferFuture
:param transfer_future: The transfer future associated with the
transfer request that tasks are being submitted for
:param kwargs: Any additional kwargs that you may want... | 0.000903 |
def gen_schlumberger(self, M, N, a=None):
"""generate one Schlumberger sounding configuration, that is, one set
of configurations for one potential dipole MN.
Parameters
----------
M: int
electrode number for the first potential electrode
N: int
e... | 0.001512 |
def _set_wikidata(self):
"""
set attributes derived from Wikidata (action=wbentities)
"""
self.data['labels'] = {}
self.data['wikidata'] = {}
data = self._load_response('wikidata')
entities = data.get('entities')
item = entities.get(next(iter(entities)))
... | 0.001735 |
def setup(self, *args, **kwargs):
"""Set parameters for the compiler."""
if self.comp is None:
self.comp = Compiler(*args, **kwargs)
else:
self.comp.setup(*args, **kwargs) | 0.009132 |
def _netbsd_brshow(br=None):
'''
Internal, returns bridges and enslaved interfaces (NetBSD - brconfig)
'''
brconfig = _tool_path('brconfig')
if br:
cmd = '{0} {1}'.format(brconfig, br)
else:
cmd = '{0} -a'.format(brconfig)
brs = {}
start_int = False
for line in __s... | 0.000929 |
def find_user(search_params):
"""
Find user
Attempts to find a user by a set of search params. You must be in
application context.
"""
user = None
params = {prop: value for prop, value in search_params.items() if value}
if 'id' in params or 'email' in params:
user = user_service.... | 0.002849 |
def _merge_sections(sec_a, sec_b):
'''Merge two sections
Merges sec_a into sec_b and sets sec_a attributes to default
'''
sec_b.ids = list(sec_a.ids) + list(sec_b.ids[1:])
sec_b.ntype = sec_a.ntype
sec_b.pid = sec_a.pid
sec_a.ids = []
sec_a.pid = -1
sec_a.ntype = 0 | 0.0033 |
def _parse_response(self, response):
"""Parses the API response and raises appropriate errors if
raise_errors was set to True
"""
if not self._raise_errors:
return response
is_4xx_error = str(response.status_code)[0] == '4'
is_5xx_error = str(response.status_... | 0.003268 |
def scale(self, image, geometry, options):
"""
Wrapper for ``_scale``
"""
upscale = options['upscale']
x_image, y_image = map(float, self.get_image_size(image))
factor = self._calculate_scaling_factor(x_image, y_image, geometry, options)
if factor < 1 or upscale:... | 0.006186 |
def change_meta(self, para, new_value, log=True):
""" Changes the meta data
This function does nothing if None is passed as new_value.
To set a certain value to None pass the str 'None'
Parameters
----------
para: str
Meta data entry to change
new_v... | 0.001646 |
def _get_for_address(address, key):
"""Retrieve an attribute of or the physical interface that
the IP address provided could be bound to.
:param address (str): An individual IPv4 or IPv6 address without a net
mask or subnet prefix. For example, '192.168.1.1'.
:param key: 'iface' for the physica... | 0.000592 |
def to_python(fname, *args):
"""
Parse a NRML file and return an associated Python object. It works by
calling nrml.read() and node_to_obj() in sequence.
"""
[node] = read(fname)
return node_to_obj(node, fname, *args) | 0.004149 |
def remove_provenance_project_variables():
"""Removing variables from provenance data."""
project_context_scope = QgsExpressionContextUtils.projectScope(
QgsProject.instance())
existing_variable_names = project_context_scope.variableNames()
# Save the existing variables that's not provenance va... | 0.00058 |
def push_design_documents(self, design_path):
"""
Push the design documents stored in `design_path` to the server
"""
for db_name in os.listdir(design_path):
if db_name.startswith("__") or db_name.startswith("."):
continue
db_path = os.path.join(de... | 0.002886 |
def smoothing_worker(method=None, N=100, seed=None, fk=None, fk_info=None,
add_func=None, log_gamma=None):
"""Generic worker for off-line smoothing algorithms.
This worker may be used in conjunction with utils.multiplexer in order to
run in parallel (and eventually compare) off-line s... | 0.00504 |
def get_kwargs(func):
"""
Args:
func (function):
Returns:
tuple: keys, is_arbitrary
keys (list): kwargs keys
is_arbitrary (bool): has generic **kwargs
CommandLine:
python -m utool.util_inspect --test-get_kwargs
Ignore:
def func1(a, b, c):
... | 0.001844 |
def cal_g_bm3(p, g, k):
"""
calculate shear modulus at given pressure
:param p: pressure
:param g: [g0, g0p]
:param k: [v0, k0, k0p]
:return: shear modulus at high pressure
"""
v = cal_v_bm3(p, k)
v0 = k[0]
k0 = k[1]
kp = k[2]
g0 = g[0]
gp = g[1]
f = 0.5 * ((v / ... | 0.001783 |
def hasAttr(self, node, name, nsuri=None):
"""Return true if element has attribute with the given name and
optional nsuri. If nsuri is not specified, returns true if an
attribute exists with the given name with any namespace."""
if nsuri is None:
if node.hasAttribute(na... | 0.004706 |
def convert_attrs_to_bool(obj: Any,
attrs: Iterable[str],
default: bool = None) -> None:
"""
Applies :func:`convert_to_bool` to the specified attributes of an object,
modifying it in place.
"""
for a in attrs:
setattr(obj, a, convert_to_boo... | 0.002809 |
async def dispense(self, mount: top_types.Mount, volume: float = None,
rate: float = 1.0):
"""
Dispense a volume of liquid in microliters(uL) using this pipette
at the current location. If no volume is specified, `dispense` will
dispense all volume currently presen... | 0.001614 |
def schedule(code, interval, secret_key=None, url=None):
"""Schedule a string of `code` to be executed every `interval`
Specificying an `interval` of 0 indicates the event should only be run
one time and will not be rescheduled.
"""
if not secret_key:
secret_key = default_key()
if not url:
url = de... | 0.014862 |
def get_placeholders(self, format_string):
"""
Parses the format_string and returns a set of placeholders.
"""
placeholders = set()
# Tokenize the format string and process them
for token in self.tokens(format_string):
if token.group("placeholder"):
... | 0.00274 |
def stop_loss(self, accountID, **kwargs):
"""
Shortcut to create a Stop Loss Order in an Account
Args:
accountID : The ID of the Account
kwargs : The arguments to create a StopLossOrderRequest
Returns:
v20.response.Response containing the results fro... | 0.004184 |
def resolve_path(path, config_file):
"""Resolve path relative to config file location.
Args:
path: Path to be resolved.
config_file: Path to config file, which `path` is specified
relative to.
Returns:
Path relative to the `config_file` locat... | 0.003683 |
def _close_remaining_channels(self):
"""Forcefully close all open channels.
:return:
"""
for channel_id in list(self._channels):
self._channels[channel_id].set_state(Channel.CLOSED)
self._channels[channel_id].close()
self._cleanup_channel(channel_id) | 0.00627 |
def load(self, exclude_scopes: tuple = ('Optimizer',)) -> None:
"""Load model parameters from self.load_path"""
if not hasattr(self, 'sess'):
raise RuntimeError('Your TensorFlow model {} must'
' have sess attribute!'.format(self.__class__.__name__))
pat... | 0.004155 |
def new_multigraph(self, name, data=None, **attr):
"""Return a new instance of type MultiGraph, initialized with the given
data if provided.
:arg name: a name for the graph
:arg data: dictionary or NetworkX graph object providing initial state
"""
self._init_graph(name,... | 0.004566 |
def make_cell(table, span, widths, heights, use_headers):
"""
Convert the contents of a span of the table to a grid table cell
Parameters
----------
table : list of lists of str
The table of rows containg strings to convert to a grid table
span : list of lists of int
list of [ro... | 0.000583 |
def _norm(self, x):
"""Return the norm of ``x``.
This method is intended to be private. Public callers should
resort to `norm` which is type-checked.
"""
return float(np.sqrt(self.inner(x, x).real)) | 0.008368 |
def _create_db(self):
"""Creates a new databae or opens a connection to an existing one.
.. note::
You can't share sqlite3 connections between threads (by default)
hence we setup the db here. It has the upside of running async.
"""
log.debug("Creating sqlite data... | 0.003501 |
def join(self, file):
"""Find the named object in this tree's contents
:return: ``git.Blob`` or ``git.Tree`` or ``git.Submodule``
:raise KeyError: if given file or tree does not exist in tree"""
msg = "Blob or Tree named %r not found"
if '/' in file:
tree = self
... | 0.003084 |
def fit(self, X, y=None):
"""
X : ANTsImage | string | list of ANTsImage types | list of strings
images to register to fixed image
y : string | list of strings
labels for images
"""
moving_images = X if isinstance(X, (list,tuple)) else [X]
moving_... | 0.005076 |
def get_data_file_attachment(self, identifier, resource_id):
"""Get path to attached data file with given resource identifer. If no
data file with given id exists the result will be None.
Raise ValueError if an image archive with the given resource identifier
is attached to the model ru... | 0.002406 |
def decode(s):
"""
Converts text in the numbering format of pinyin ("ni3hao3") to text with the
appropriate tone marks ("nǐhǎo").
"""
s = s.lower()
r = ""
t = ""
for c in s:
if c >= 'a' and c <= 'z':
t += c
elif c == ':':
try:
if ... | 0.003238 |
def get_wsgi_server(
self, sock, wsgi_app, protocol=HttpOnlyProtocol, debug=False
):
"""Get the WSGI server used to process requests."""
return wsgi.Server(
sock,
sock.getsockname(),
wsgi_app,
protocol=protocol,
debug=debug,
... | 0.00838 |
def join_thread(thr):
# type: (threading.Thread) -> None
"""Join a thread
:type threading.Thread thr: thread to join
"""
if on_python2():
while True:
thr.join(timeout=1)
if not thr.isAlive():
break
else:
thr.join() | 0.003401 |
def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the encoding of the BigInteger to the output stream.
Args:
ostream (Stream): A buffer to contain the encoded bytes of a
BigInteger object. Usually a BytearrayStream object.
R... | 0.001376 |
def get_face_mask(self, subdomain):
"""Get faces which are fully in subdomain.
"""
if subdomain is None:
# https://stackoverflow.com/a/42392791/353337
return numpy.s_[:]
if subdomain not in self.subdomains:
self._mark_vertices(subdomain)
# A ... | 0.002448 |
def _var_isomorphic(a, b, check_varprops=True):
"""
Two Xmrs objects are isomorphic if they have the same structure as
determined by variable linkages between preds.
"""
# first some quick checks
if len(a.eps()) != len(b.eps()): return False
if len(a.variables()) != len(b.variables()): retur... | 0.002122 |
def delete_enterprise_learner_role_assignment(sender, instance, **kwargs): # pylint: disable=unused-argument
"""
Delete the associated enterprise learner role assignment record when deleting an EnterpriseCustomerUser record.
"""
if instance.user:
enterprise_learner_role, __ = SystemWideEnter... | 0.006766 |
def renderItem(self, item):
"""Renders the next available sticker.
Uses the template specified in the request ('template' parameter) by
default. If no template defined in the request, uses the default
template set by default in Setup > Stickers.
If the template specified doesn'... | 0.001652 |
def delete_request(
self,
alias,
uri,
data=None,
json=None,
params=None,
headers=None,
allow_redirects=None,
timeout=None):
""" Send a DELETE request on the session object found using the
given `a... | 0.002941 |
def _get_static_ndims(x,
expect_static=False,
expect_ndims=None,
expect_ndims_no_more_than=None,
expect_ndims_at_least=None):
"""Get static number of dimensions and assert that some expectations are met.
This function returns t... | 0.007227 |
def pq(self) -> PyQuery:
"""`PyQuery <https://pythonhosted.org/pyquery/>`_ representation
of the :class:`Element <Element>` or :class:`HTML <HTML>`.
"""
if self._pq is None:
self._pq = PyQuery(self.lxml)
return self._pq | 0.007353 |
def get_annotation_data_between_times(self, id_tier, start, end):
"""Gives the annotations within the times.
When the tier contains reference annotations this will be returned,
check :func:`get_ref_annotation_data_between_times` for the format.
:param str id_tier: Name of the tier.
... | 0.002278 |
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 | 0.008547 |
def build(dburl, sitedir, mode):
"""Build a site."""
if mode == 'force':
amode = ['-a']
else:
amode = []
oldcwd = os.getcwd()
os.chdir(sitedir)
db = StrictRedis.from_url(dburl)
job = get_current_job(db)
job.meta.update({'out': '', 'milestone': 0, 'total': 1, 'return': Non... | 0.000715 |
def get_deploy_key_repo(deploy_repo, keypath, key_ext=''):
"""
Return (repository of which deploy key is used, environment variable to store
the encryption key of deploy key, path of deploy key file)
"""
# deploy key of the original repo has write access to the wiki
deploy_key_repo = deploy_repo... | 0.006024 |
def enclosure_groups(self):
"""
Gets the EnclosureGroups API client.
Returns:
EnclosureGroups:
"""
if not self.__enclosure_groups:
self.__enclosure_groups = EnclosureGroups(self.__connection)
return self.__enclosure_groups | 0.00678 |
def atomic_write_file(path, content):
"""
file.write(...) is not atomic.
We write to a tmp file and then rename to target path since rename is atomic.
We do this to avoid the content of file is dirty read/partially read by others.
"""
# Write to a randomly tmp file
tmp_file = get_tmp_filename()
with ope... | 0.016129 |
def coords_for_computations(self):
"""
Return the coordinates from the center of the star for each element
(either centers or vertices depending on the setting in the mesh).
"""
# TODO: need to subtract the position offset if a Mesh (in orbit)
if self._compute_at_vertice... | 0.003565 |
def filterfalse(coro, iterable, limit=0, loop=None):
"""
Returns a list of all the values in coll which pass an asynchronous truth
test coroutine.
Operations are executed concurrently by default, but results
will be in order.
You can configure the concurrency via `limit` param.
This funct... | 0.000683 |
def create_birthday(min_age=18, max_age=80):
"""
Create a random birthday fomr someone between the ages of min_age and max_age
"""
age = random.randint(min_age, max_age)
start = datetime.date.today() - datetime.timedelta(days=random.randint(0, 365))
return start - datetime.timedelta(days=age * 3... | 0.009288 |
def write(self, data):
"""Provide as convenience for influxdb v0.9.0, this may change."""
self.request(
url="write",
method='POST',
params=None,
data=data,
expected_response_code=200
)
return True | 0.006944 |
def find_modules(import_path, include_packages=False, recursive=False):
"""Finds all the modules below a package. This can be useful to
automatically import all views / controllers so that their metaclasses /
function decorators have a chance to register themselves on the
application.
Packages are... | 0.000754 |
def execute(self, *args, **kwargs):
"""
Called when run through `call_command`. `args` are passed through,
while `kwargs` is the __dict__ of the return value of
`self.create_parser('', name)` updated with the kwargs passed to
`call_command`.
"""
# Remove internal ... | 0.002099 |
def merge_user_into_another_user_destination_user_id(self, id, destination_user_id):
"""
Merge user into another user.
Merge a user into another user.
To merge users, the caller must have permissions to manage both users. This
should be considered irreversible. This will d... | 0.008137 |
def normalize_digits_only(number, keep_non_digits=False):
"""Normalizes a string of characters representing a phone number.
This converts wide-ascii and arabic-indic numerals to European numerals,
and strips punctuation and alpha characters (optional).
Arguments:
number -- a string representing a ... | 0.001255 |
def validate_out(*validation_func, # type: ValidationFuncs
**kwargs):
# type: (...) -> Callable
"""
A decorator to apply function output validation to this function's output, with the provided base validation
function(s). You may use several such decorators on a given function as long ... | 0.007032 |
def reverse_transform(self, col):
"""Converts data back into original format.
Args:
col(pandas.DataFrame): Data to transform.
Returns:
pandas.DataFrame
"""
if isinstance(col, pd.Series):
col = col.to_frame()
output = pd.DataFrame(ind... | 0.004739 |
def splitpath(path):
"""Split a path in its components."""
c = []
head, tail = os.path.split(path)
while tail:
c.insert(0, tail)
head, tail = os.path.split(head)
return c | 0.004854 |
def get_pid(name, path=None):
'''
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
'''
if name not in list_(limit='running', path=path):
raise CommandExecutionError('Container {0} is not... | 0.005525 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.