code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
path = self._path(key)
# If the file doesn't exists, we obviously can't return the cache so we will
# just return null. Otherwise, we'll get the contents of the file and get
# the expiration UNIX timestamps from the start of the file's contents.
if not os.path.exists(pa... | def _get_payload(self, key) | Retrieve an item and expiry time from the cache by key.
:param key: The cache key
:type key: str
:rtype: dict | 6.336606 | 6.345307 | 0.998629 |
value = encode(str(self._expiration(minutes))) + encode(self.serialize(value))
path = self._path(key)
self._create_cache_directory(path)
with open(path, 'wb') as fh:
fh.write(value) | def put(self, key, value, minutes) | Store an item in the cache for a given number of minutes.
:param key: The cache key
:type key: str
:param value: The cache value
:type value: mixed
:param minutes: The lifetime in minutes of the cached value
:type minutes: int | 5.110263 | 6.187689 | 0.825876 |
raw = self._get_payload(key)
integer = int(raw['data']) + value
self.put(key, integer, int(raw['time']))
return integer | def increment(self, key, value=1) | Increment the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The increment value
:type value: int
:rtype: int or bool | 8.778008 | 9.477441 | 0.9262 |
path = self._path(key)
if os.path.exists(path):
os.remove(path)
return True
return False | def forget(self, key) | Remove an item from the cache.
:param key: The cache key
:type key: str
:rtype: bool | 3.752439 | 4.466887 | 0.840057 |
if os.path.isdir(self._directory):
for root, dirs, files in os.walk(self._directory, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name)) | def flush(self) | Remove all items from the cache. | 1.876764 | 1.764603 | 1.063561 |
hash_type, parts_count = self._HASHES[self._hash_type]
h = hash_type(encode(key)).hexdigest()
parts = [h[i:i+2] for i in range(0, len(h), 2)][:parts_count]
return os.path.join(self._directory, os.path.sep.join(parts), h) | def _path(self, key) | Get the full path for the given cache key.
:param key: The cache key
:type key: str
:rtype: str | 4.481484 | 4.79832 | 0.933969 |
opener = self.get_opener(path)
filename = opener.get_filename
try:
size = os.path.getsize(filename)
if size > 50 * 1024 * 1024:
logger.warning(
'Reading large resource to memory: %s. Size: %s bytes',
filenam... | def resource_string(self, path) | Args:
path: str, resource file url or resource file absolute/relative path.
Returns:
string, file content | 3.60341 | 3.844253 | 0.93735 |
self.path = path
opener = None
# FIXME this parser/matcher should use `urlparse` stdlib
for opener_name, signature in self.openers.items():
if self.path.startswith(signature[0]):
opener = signature[1](self.path)
break
if not op... | def get_opener(self, path) | Args:
path: str, resource file url or resource file absolute/relative path.
Returns:
file object | 4.74376 | 5.410892 | 0.876706 |
if len(names) == 1 and isinstance(names[0], list):
names = names[0]
return TaggedCache(self, TagSet(self, names)) | def tags(self, *names) | Begin executing a new tags operation.
:param names: The tags
:type names: tuple
:rtype: cachy.tagged_cache.TaggedCache | 4.465175 | 4.396452 | 1.015631 |
if not current_user.is_authenticated:
return {}
user_info = {
'id': current_user.get_id(),
}
if 'SENTRY_USER_ATTRS' in current_app.config:
for attr in current_app.config['SENTRY_USER_ATTRS']:
if hasattr(current_user, attr):
... | def get_user_info(self, request) | Implement custom getter. | 2.211404 | 2.098286 | 1.05391 |
my_user_agent = None
try:
my_user_agent = pkg_resources.require('netort')[0].version
except pkg_resources.DistributionNotFound:
my_user_agent = 'DistributionNotFound'
finally:
headers = {
"User-Agent": "Uploader/{uploader_ua}, ... | def create_job(self) | Create public Luna job
Returns:
job_id (basestring): Luna job id | 3.815074 | 3.715574 | 1.026779 |
type_ = meta.get('type')
if not type_:
raise ValueError('Metric type should be defined.')
if type_ in available_metrics:
metric_obj = available_metrics[type_](meta, self.routing_queue) # create metric object
metric_meta = pd.DataFrame({metric_obj.lo... | def new_metric(self, meta) | Create and register metric,
find subscribers for this metric (using meta as filter) and subscribe
Return:
metric (available_metrics[0]): one of Metric | 3.835938 | 3.632126 | 1.056114 |
if not _type:
raise ValueError('Metric type should be defined.')
if _type in available_metrics:
metric_obj = available_metrics[_type](None, self.routing_queue) # create metric object
metric_info = {'type': _type,
'source': source,... | def new_tank_metric(self, _type, name, hostname=None, group=None, source=None, *kw) | Create and register metric,
find subscribers for this metric (using meta as filter) and subscribe
Return:
metric (available_metrics[0]): one of Metric | 3.572757 | 3.377694 | 1.05775 |
sub_id = "subscriber_{uuid}".format(uuid=uuid.uuid4())
# register subscriber in manager
sub = pd.DataFrame({sub_id: filter_}).T
sub['callback'] = callback
self.subscribers = self.subscribers.append(sub)
# find metrics for subscriber using `filter`
this_s... | def subscribe(self, callback, filter_) | Create and register metric subscriber,
find metrics for this subscriber (using filter_) and subscribe
Args:
callback (object method): subscriber's callback
filter_ (dict): filter dict
filter sample:
{'type': 'metrics', 'source': 'gun'} | 6.346137 | 5.577316 | 1.137848 |
condition = []
if not filter_:
return filterable
elif filter_.get('type') == '__ANY__':
return filterable
else:
for key, value in filter_.items():
condition.append('{key} == "{value}"'.format(key=key, value=value))
try:... | def __filter(filterable, filter_, logic_operation='and') | filtering DataFrame using filter_ key-value conditions applying logic_operation
only find rows strictly fitting the filter_ criterion | 3.507779 | 3.017203 | 1.162593 |
condition = []
try:
subscribers_for_any = filterable.query('type == "__ANY__"')
except pd.core.computation.ops.UndefinedVariableError:
subscribers_for_any = pd.DataFrame()
if not filter_:
return filterable
else:
for existin... | def __reversed_filter(filterable, filter_, logic_operation='and') | reverse filtering DataFrame using filter_ key-value conditions applying logic_operation
find rows where existing filterable columns (and its values) fitting the filter_ criterion | 3.719544 | 3.488842 | 1.066126 |
from raven.contrib.celery import register_logger_signal, \
register_signal
from raven.contrib.flask import Sentry, make_client
from raven.handlers.logging import SentryHandler
# Installs sentry in app.extensions['sentry']
level = getattr(logging, app.config[... | def install_handler(self, app) | Install log handler. | 3.566326 | 3.540946 | 1.007168 |
data = super(RequestIdProcessor, self).process(data, **kwargs)
if g and hasattr(g, 'request_id'):
tags = data.get('tags', {})
tags['request_id'] = g.request_id
data['tags'] = tags
return data | def process(self, data, **kwargs) | Process event data. | 3.453627 | 3.303186 | 1.045544 |
value = self._redis.get(self._prefix + key)
if value is not None:
return self.unserialize(value) | def get(self, key) | Retrieve an item from the cache by key.
:param key: The cache key
:type key: str
:return: The cache value | 4.186332 | 6.369074 | 0.657291 |
value = self.serialize(value)
minutes = max(1, minutes)
self._redis.setex(self._prefix + key, minutes * 60, value) | def put(self, key, value, minutes) | Store an item in the cache for a given number of minutes.
:param key: The cache key
:type key: str
:param value: The cache value
:type value: mixed
:param minutes: The lifetime in minutes of the cached value
:type minutes: int | 4.270153 | 5.916372 | 0.721752 |
return self._redis.incrby(self._prefix + key, value) | def increment(self, key, value=1) | Increment the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The increment value
:type value: int
:rtype: int or bool | 6.448013 | 8.049298 | 0.801065 |
return self._redis.decr(self._prefix + key, value) | def decrement(self, key, value=1) | Decrement the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The decrement value
:type value: int
:rtype: int or bool | 6.279754 | 7.932921 | 0.791607 |
value = self.serialize(value)
self._redis.set(self._prefix + key, value) | def forever(self, key, value) | Store an item in the cache indefinitely.
:param key: The cache key
:type key: str
:param value: The value to store
:type value: mixed | 6.043335 | 8.896944 | 0.67926 |
return bool(self._redis.delete(self._prefix + key)) | def forget(self, key) | Remove an item from the cache.
:param key: The cache key
:type key: str
:rtype: bool | 8.434778 | 8.139683 | 1.036254 |
val = self._store.get(key)
if val is None:
return value(default)
return val | def get(self, key, default=None) | Retrieve an item from the cache by key.
:param key: The cache key
:type key: str
:param default: The default value to return
:type default: mixed
:rtype: mixed | 6.530927 | 9.419005 | 0.693378 |
minutes = self._get_minutes(minutes)
if minutes is not None:
self._store.put(key, val, minutes) | def put(self, key, val, minutes) | Store an item in the cache.
:param key: The cache key
:type key: str
:param val: The cache value
:type val: mixed
:param minutes: The lifetime in minutes of the cached value
:type minutes: int|datetime | 4.765984 | 6.21587 | 0.766744 |
if hasattr(self._store, 'add'):
return self._store.add(key, val, self._get_minutes(minutes))
if not self.has(key):
self.put(key, val, minutes)
return True
return False | def add(self, key, val, minutes) | Store an item in the cache if it does not exist.
:param key: The cache key
:type key: str
:param val: The cache value
:type val: mixed
:param minutes: The lifetime in minutes of the cached value
:type minutes: int|datetime
:rtype: bool | 3.797147 | 3.706225 | 1.024532 |
if args:
serialized_arguments = (
self._store.serialize(args[1:])
+ self._store.serialize([(k, kwargs[k]) for k in sorted(kwargs.keys())])
)
else:
serialized_arguments = self._store.serialize([(k, kwargs[k]) for k in sorted(kwa... | def _get_key(self, fn, args, kwargs) | Calculate a cache key given a function, args and kwargs.
:param fn: The function
:type fn: callable or str
:param args: The function args
:type args: tuple
:param kwargs: The function kwargs
:type kwargs: dict
:rtype: str | 2.761162 | 2.788716 | 0.99012 |
return self.request("PATCH", path=path, payload=payload,
headers=headers, params_dict=params_dict, **params) | def patch(self, path=None, payload=None, headers=None,
params_dict=None, **params) | HTTP PATCH
- payload: string passed to the body of the request
- path: string additionnal path to the uri
- headers: dict, optionnal headers that will
be added to HTTP request.
- params: Optionnal parameterss added to the request | 2.637948 | 2.574268 | 1.024737 |
return self.request("DELETE", path=path, headers=headers) | def delete(self, path=None, headers=None) | HTTP DELETE
- path: string additionnal path to the uri
- headers: dict, optionnal headers that will
be added to HTTP request.
- params: Optionnal parameterss added to the request | 4.632781 | 6.515465 | 0.711044 |
if self.has_main:
return
self.in_main = True
self.write('task main()')
self.INDENT()
if self.debug:
print 'Flushing main:', self.fv.main
for node in self.fv.main:
self.v(node)
self.NEWLINE()
self.DEDENT... | def flush_main(self) | Flushes the implicit main function if there is no main
function defined. | 7.380868 | 5.947564 | 1.24099 |
self._memcache.set(self._prefix + key, value, minutes * 60) | def put(self, key, value, minutes) | Store an item in the cache for a given number of minutes.
:param key: The cache key
:type key: str
:param value: The cache value
:type value: mixed
:param minutes: The lifetime in minutes of the cached value
:type minutes: int | 4.970534 | 6.095961 | 0.815382 |
return self._memcache.add(self._prefix + key, val, minutes * 60) | def add(self, key, val, minutes) | Store an item in the cache if it does not exist.
:param key: The cache key
:type key: str
:param val: The cache value
:type val: mixed
:param minutes: The lifetime in minutes of the cached value
:type minutes: int
:rtype: bool | 5.552773 | 6.702771 | 0.82843 |
return self._memcache.incr(self._prefix + key, value) | def increment(self, key, value=1) | Increment the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The increment value
:type value: int
:rtype: int or bool | 8.530559 | 10.425406 | 0.818247 |
return self._memcache.decr(self._prefix + key, value) | def decrement(self, key, value=1) | Decrement the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The decrement value
:type value: int
:rtype: int or bool | 8.94173 | 10.961548 | 0.815736 |
data = []
for _ in range(queue.qsize()):
try:
data.append(queue.get_nowait())
except q.Empty:
break
return data | def get_nowait_from_queue(queue) | Collect all immediately available items from a queue | 2.650733 | 2.506219 | 1.057662 |
namespace = self._tags.get_namespace()
self._push_forever_keys(namespace, key)
self._store.forever(
'%s:%s' % (hashlib.sha1(encode(self._tags.get_namespace())).hexdigest(), key),
value
) | def forever(self, key, value) | Store an item in the cache indefinitely.
:param key: The cache key
:type key: str
:param value: The value
:type value: mixed | 7.66091 | 8.495616 | 0.901749 |
full_key = '%s%s:%s' % (self.get_prefix(),
hashlib.sha1(encode(self._tags.get_namespace())).hexdigest(),
key)
for segment in namespace.split('|'):
self._store.connection().lpush(self._forever_key(segment), full_key) | def _push_forever_keys(self, namespace, key) | Store a copy of the full key for each namespace segment.
:type namespace: str
:type key: str | 7.214992 | 6.491815 | 1.111398 |
for segment in self._tags.get_namespace().split('|'):
segment = self._forever_key(segment)
self._delete_forever_values(segment)
self._store.connection().delete(segment) | def _delete_forever_keys(self) | Delete all of the items that were stored forever. | 10.762893 | 9.868809 | 1.090597 |
forever = self._store.connection().lrange(forever_key, 0, -1)
if len(forever) > 0:
self._store.connection().delete(*forever) | def _delete_forever_values(self, forever_key) | Delete all of the keys that have been stored forever.
:type forever_key: str | 3.533317 | 4.742483 | 0.745035 |
logger = logging.getLogger('py.warnings')
# Check for previously installed handlers.
for h in logger.handlers:
if isinstance(h, handler.__class__):
return
logger.addHandler(handler)
logger.setLevel(logging.WARNING) | def capture_pywarnings(handler) | Log python system warnings. | 2.833237 | 2.830283 | 1.001044 |
payload = self._storage.get(key)
# If the key does not exist, we return nothing
if not payload:
return (None, None)
expire = payload[0]
# If the current time is greater than expiration timestamps we will delete
# the entry
if round(time.tim... | def _get_payload(self, key) | Retrieve an item and expiry time from the cache by key.
:param key: The cache key
:type key: str
:rtype: dict | 6.327857 | 6.346501 | 0.997062 |
self._storage[key] = (self._expiration(minutes), value) | def put(self, key, value, minutes) | Store an item in the cache for a given number of minutes.
:param key: The cache key
:type key: str
:param value: The cache value
:type value: mixed
:param minutes: The lifetime in minutes of the cached value
:type minutes: int | 8.40686 | 14.127668 | 0.595064 |
data, time_ = self._get_payload(key)
integer = int(data) + value
self.put(key, integer, int(time_))
return integer | def increment(self, key, value=1) | Increment the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The increment value
:type value: int
:rtype: int or bool | 9.421411 | 11.243751 | 0.837924 |
if key in self._storage:
del self._storage[key]
return True
return False | def forget(self, key) | Remove an item from the cache.
:param key: The cache key
:type key: str
:rtype: bool | 4.836574 | 5.759769 | 0.839717 |
url = '{}{}'.format(
self.base_url, self.endpoint.format(resource=resource))
try:
with async_timeout.timeout(5, loop=self._loop):
response = await self._session.get(url)
_LOGGER.info(
"Response from Netdata: %s", response.sta... | async def get_data(self, resource) | Get detail for a resource from the data endpoint. | 3.257214 | 3.135033 | 1.038973 |
url = '{}{}'.format(self.base_url, self.endpoint)
try:
with async_timeout.timeout(5, loop=self._loop):
response = await self._session.get(url)
_LOGGER.debug(
"Response from Netdata: %s", response.status)
data = await response... | async def get_alarms(self) | Get alarms for a Netdata instance. | 3.198641 | 2.722791 | 1.174765 |
if g and hasattr(g, 'request_id'):
record.request_id = g.request_id
return True | def filter(self, record) | If request_id is set in flask.g, add it to log record. | 5.747565 | 2.508086 | 2.291614 |
# TODO: consider making one verbosity parameter instead of two mutually exclusive
# TODO: default values for parameters
logger = logging.getLogger('')
logger.setLevel(logging.DEBUG)
# add file handler if needed
if log_filename:
file_handler = logging.FileHandler(log_filename)
... | def init_logging(log_filename, verbose, quiet) | Set up logging with default parameters:
* default console logging level is INFO
* ERROR, WARNING and CRITICAL are redirected to stderr
Args:
log_filename (str): if set, will write DEBUG log there
verbose (bool): DEBUG level in console, overrides 'quiet'
quiet (bool): WARNING level i... | 2.197343 | 2.172144 | 1.011601 |
if name is None:
name = self.get_default_driver()
self._stores[name] = self._get(name)
return self._stores[name] | def store(self, name=None) | Get a cache store instance by name.
:param name: The cache store name
:type name: str
:rtype: Repository | 4.62381 | 5.521818 | 0.837371 |
return self._stores.get(name, self._resolve(name)) | def _get(self, name) | Attempt to get the store from the local cache.
:param name: The store name
:type name: str
:rtype: Repository | 12.858827 | 15.156638 | 0.848396 |
config = self._get_config(name)
if not config:
raise RuntimeError('Cache store [%s] is not defined.' % name)
if config['driver'] in self._custom_creators:
repository = self._call_custom_creator(config)
else:
repository = getattr(self, '_crea... | def _resolve(self, name) | Resolve the given store
:param name: The store to resolve
:type name: str
:rtype: Repository | 3.883071 | 3.68169 | 1.054698 |
creator = self._custom_creators[config['driver']](config)
if isinstance(creator, Store):
creator = self.repository(creator)
if not isinstance(creator, Repository):
raise RuntimeError('Custom creator should return a Repository instance.')
return creator | def _call_custom_creator(self, config) | Call a custom driver creator.
:param config: The driver configuration
:type config: dict
:rtype: Repository | 5.94761 | 5.459416 | 1.089422 |
kwargs = {
'directory': config['path']
}
if 'hash_type' in config:
kwargs['hash_type'] = config['hash_type']
return self.repository(FileStore(**kwargs)) | def _create_file_driver(self, config) | Create an instance of the file cache driver.
:param config: The driver configuration
:type config: dict
:rtype: Repository | 5.056325 | 5.052058 | 1.000845 |
if 'default' in self._config:
return self._config['default']
if len(self._config['stores']) == 1:
return list(self._config['stores'].keys())[0]
raise RuntimeError('Missing "default" cache in configuration.') | def get_default_driver(self) | Get the default cache driver name.
:rtype: str
:raises: RuntimeError | 4.638102 | 4.127658 | 1.123664 |
if isinstance(serializer, Serializer):
return serializer
if serializer in self._serializers:
return self._serializers[serializer]
raise RuntimeError('Unsupported serializer') | def _resolve_serializer(self, serializer) | Resolve the given serializer.
:param serializer: The serializer to resolve
:type serializer: str or Serializer
:rtype: Serializer | 4.417184 | 4.403691 | 1.003064 |
if not isinstance(answers, (int, collections.Iterable)):
raise TypeError(
'The `answers` arg is expected to be of type '
'(int | iterable int) but got {} instead.'.format(type(answers))
)
@curry
def check_answer(index, button):
is_correct = (
... | def multiple_choice(question, choices, answers) | Generates a multiple choice question that allows the user to select an
answer choice and shows whether choice was correct.
Args:
question (str): Question text displayed above choices.
choices (list str): Answer choices that user can select.
answers (int | iterable int): Either an inte... | 2.936468 | 2.924221 | 1.004188 |
# Input textbox
textbox = widgets.Text(placeholder='Write your answer here')
# Submit button
submit_button = widgets.Button(description='Submit')
# Space right of the submit button to show checkmark/x-mark
visual_correct = widgets.HTML()
# Space below input line to display error if func... | def short_answer(question, answers, explanation=None) | Generates a short answer question that allows user to input an answer in
a textbox and a submit button to check the answer.
Args:
question (str): The question being asked.
answers (str | list str | func): If a string, only that string will be
marked correct. If a list of string, a... | 3.717101 | 3.588988 | 1.035696 |
if not os.path.isfile(nb_name):
raise ValueError(
"{} isn't a path to a file. Double check your "
"filename and try again.".format(nb_name)
)
if save_first:
_save_nb(nb_name)
print('Converting notebook...')
try:
check_output(
['n... | def publish(spec, nb_name, template='full', save_first=True) | Converts nb_name to an HTML file. Preserves widget functionality.
Outputs a link to download HTML file after conversion if called in a
notebook environment.
Equivalent to running `nbinteract ${spec} ${nb_name}` on the command line.
Args:
spec (str): BinderHub spec for Jupyter image. Must be i... | 3.554099 | 3.192671 | 1.113206 |
display(Javascript('IPython.notebook.save_checkpoint();'))
display(Javascript('IPython.notebook.save_notebook();'))
print('Saving notebook...', end=' ')
if _wait_for_save(nb_name):
print("Saved '{}'.".format(nb_name))
else:
logging.warning(
"Could not save your note... | def _save_nb(nb_name) | Attempts to save notebook. If unsuccessful, shows a warning. | 4.950488 | 4.818048 | 1.027488 |
modification_time = os.path.getmtime(nb_name)
start_time = time.time()
while time.time() < start_time + timeout:
if (
os.path.getmtime(nb_name) > modification_time
and os.path.getsize(nb_name) > 0
):
return True
time.sleep(0.2)
return Fals... | def _wait_for_save(nb_name, timeout=5) | Waits for nb_name to update, waiting up to TIMEOUT seconds.
Returns True if a save was detected, and False otherwise. | 1.941522 | 1.978171 | 0.981474 |
if not callable(maybe_fn):
return maybe_fn
args = get_fn_args(maybe_fn, kwargs, prefix=prefix)
return maybe_fn(**args) | def maybe_call(maybe_fn, kwargs: dict, prefix: str = None) -> 'Any' | If maybe_fn is a function, get its arguments from kwargs and call it, also
searching for prefixed kwargs if prefix is specified. Otherwise, return
maybe_fn.
Used to allow both functions and iterables to be passed into plotting
functions.
>>> def square(x): return x * x
>>> maybe_call(square, {... | 3.31744 | 4.559414 | 0.727602 |
if not callable(maybe_fn):
return maybe_fn
return tz.curry(maybe_fn)(first_arg) | def maybe_curry(maybe_fn, first_arg) -> 'Function | Any' | If maybe_fn is a function, curries it and passes in first_arg. Otherwise
returns maybe_fn. | 3.973501 | 3.881198 | 1.023782 |
all_args = get_all_args(fn)
required_args = get_required_args(fn)
fn_kwargs = pick_kwargs(kwargs, all_args, prefix)
missing_args = [arg for arg in required_args if arg not in fn_kwargs]
if missing_args:
raise ValueError(
'The following args are missing for the function '
... | def get_fn_args(fn, kwargs: dict, prefix: str = None) | Given function and a dict of kwargs return a dict containing only the args
used by the function.
If prefix is specified, also search for args that begin with '{prefix}__'.
Removes prefix in returned dict.
Raises ValueError if a required arg is missing from the kwargs.
Raises ValueError if both pr... | 2.56884 | 2.963969 | 0.866689 |
sig = inspect.signature(fn)
return list(sig.parameters) | def get_all_args(fn) -> list | Returns a list of all arguments for the function fn.
>>> def foo(x, y, z=100): return x + y + z
>>> get_all_args(foo)
['x', 'y', 'z'] | 6.503796 | 10.509393 | 0.618856 |
sig = inspect.signature(fn)
return [
name for name, param in sig.parameters.items()
if param.default == inspect._empty and param.kind not in VAR_ARGS
] | def get_required_args(fn) -> list | Returns a list of required arguments for the function fn.
>>> def foo(x, y, z=100): return x + y + z
>>> get_required_args(foo)
['x', 'y']
>>> def bar(x, y=100, *args, **kwargs): return x
>>> get_required_args(bar)
['x'] | 3.555916 | 5.105418 | 0.696498 |
picked = {k: v for k, v in kwargs.items() if k in required_args}
prefixed = {}
if prefix:
prefix = prefix + '__'
prefixed = {
_remove_prefix(k, prefix): v
for k, v in kwargs.items()
if k.startswith(prefix)
and _remove_prefix(k, prefix) in... | def pick_kwargs(kwargs: dict, required_args: list, prefix: str = None) | Given a dict of kwargs and a list of required_args, return a dict
containing only the args in required_args.
If prefix is specified, also search for args that begin with '{prefix}__'.
Removes prefix in returned dict.
Raises ValueError if both prefixed and unprefixed arg are given in kwargs.
>>> f... | 2.839135 | 2.778705 | 1.021747 |
if not (func.__doc__ and '{options}' in func.__doc__):
return func
descriptions = [option + ': ' + option_doc[option] for option in allowed]
full_desc = ('\n' + indent).join(descriptions)
func.__doc__ = func.__doc__.format(
options=options_docstring.format(desc=full_desc)
)
... | def _update_option_docstring(func, allowed, indent=' ' * 3) | Updates docstring of func, filling in appearance of {options} with a
description of the options.
>>> def f(): '''{options}'''
>>> f = _update_option_docstring(f, ['title', 'xlim'])
>>> print(f.__doc__)
options (dict): Options for the plot. Available options:
<BLANKLINE>
title: T... | 3.550629 | 3.369263 | 1.053829 |
def update_docstring(f):
_update_option_docstring(f, allowed)
@functools.wraps(f)
def check_options(*args, **kwargs):
options = kwargs.get('options', {})
not_allowed = [
option for option in options if option not in allowed
# Don... | def use_options(allowed) | Decorator that logs warnings when unpermitted options are passed into its
wrapped function.
Requires that wrapped function has an keyword-only argument named
`options`. If wrapped function has {options} in its docstring, fills in
with the docs for allowed options.
Args:
allowed (list str):... | 3.097369 | 3.065504 | 1.010395 |
params = {
'marks': [{
'sample': _array_or_placeholder(hist_function),
'bins': _get_option('bins'),
'normalized': _get_option('normalized'),
'scales': (
lambda opts: {'sample': opts['x_sc'], 'count': opts['y_sc']}
),
}]... | def hist(hist_function, *, options={}, **interact_params) | Generates an interactive histogram that allows users to change the
parameters of the input hist_function.
Args:
hist_function (Array | (*args -> Array int | Array float)):
Function that takes in parameters to interact with and returns an
array of numbers. These numbers will be p... | 6.626722 | 7.447894 | 0.889744 |
params = {
'marks': [{
'x': _array_or_placeholder(x_fn, PLACEHOLDER_RANGE),
'y': _array_or_placeholder(y_fn)
}]
}
fig = options.get('_fig', False) or _create_fig(
x_sc=bq.OrdinalScale, options=options
)
[bar] = _create_marks(
fig=fig, mark... | def bar(x_fn, y_fn, *, options={}, **interact_params) | Generates an interactive bar chart that allows users to change the
parameters of the inputs x_fn and y_fn.
Args:
x_fn (Array | (*args -> Array str | Array int | Array float)):
If array, uses array values for categories of bar chart.
If function, must take parameters to interact... | 4.931197 | 5.894064 | 0.836638 |
params = {
'marks': [{
'x': x_points,
'y': y_points,
'enable_move': True,
}, {
'colors': [GOLDENROD],
}]
}
fig = options.get('_fig', False) or _create_fig(options=options)
[scat, lin] = _create_marks(
fig=fig, marks=[bq... | def scatter_drag(
x_points: 'Array',
y_points: 'Array',
*,
fig=None,
show_eqn=True,
options={}
) | Generates an interactive scatter plot with the best fit line plotted over
the points. The points can be dragged by the user and the line will
automatically update.
Args:
x_points (Array Number): x-values of points to plot
y_points (Array Number): y-values of points to plot
Kwargs:
... | 3.329242 | 3.409398 | 0.97649 |
params = {
'marks': [{
'x': _array_or_placeholder(x_fn),
'y': _array_or_placeholder(y_fn),
'marker': _get_option('marker'),
}]
}
fig = options.get('_fig', False) or _create_fig(options=options)
[scat] = _create_marks(
fig=fig, marks=[bq.Sc... | def scatter(x_fn, y_fn, *, options={}, **interact_params) | Generates an interactive scatter chart that allows users to change the
parameters of the inputs x_fn and y_fn.
Args:
x_fn (Array | (*args -> Array str | Array int | Array float)):
If array, uses array values for x-coordinates.
If function, must take parameters to interact with ... | 4.384159 | 4.691171 | 0.934555 |
fig = options.get('_fig', False) or _create_fig(options=options)
[line] = (_create_marks(fig=fig, marks=[bq.Lines], options=options))
_add_marks(fig, [line])
def wrapped(**interact_params):
x_data = util.maybe_call(x_fn, interact_params, prefix='x')
line.x = x_data
y_bound... | def line(x_fn, y_fn, *, options={}, **interact_params) | Generates an interactive line chart that allows users to change the
parameters of the inputs x_fn and y_fn.
Args:
x_fn (Array | (*args -> Array str | Array int | Array float)):
If array, uses array values for x-coordinates.
If function, must take parameters to interact with and... | 5.25988 | 6.463693 | 0.813758 |
marks_params = [
tz.merge(default, param) for default, param in
zip(itertools.repeat(_default_params['marks']), params['marks'])
] if 'marks' in params else [_default_params['marks']]
merged_without_marks = tz.merge_with(
tz.merge, tz.dissoc(_default_params, 'marks'),
t... | def _merge_with_defaults(params) | Performs a 2-level deep merge of params with _default_params with corrent
merging of params for each mark.
This is a bit complicated since params['marks'] is a list and we need to
make sure each mark gets the default params. | 3.884701 | 3.443166 | 1.128235 |
params = _merge_with_defaults(params)
x_sc = x_sc(**_call_params(params['x_sc'], options))
y_sc = y_sc(**_call_params(params['y_sc'], options))
options = tz.merge(options, {'x_sc': x_sc, 'y_sc': y_sc})
x_ax = x_ax(**_call_params(params['x_ax'], options))
y_ax = y_ax(**_call_params(params[... | def _create_fig(
*,
x_sc=bq.LinearScale,
y_sc=bq.LinearScale,
x_ax=bq.Axis,
y_ax=bq.Axis,
fig=bq.Figure,
options={},
params={}
) | Initializes scales and axes for a bqplot figure and returns the resulting
blank figure. Each plot component is passed in as a class. The plot options
should be passed into options.
Any additional parameters to initialize plot components are passed into
params as a dict of { plot_component: { trait: val... | 1.894659 | 1.942012 | 0.975617 |
params = _merge_with_defaults(params)
# Although fig provides scale_x and scale_y properties, the scales on the
# axes are the only ones that are actually used.
x_ax, y_ax = fig.axes
x_sc, y_sc = x_ax.scale, y_ax.scale
options = tz.merge(options, {'x_sc': x_sc, 'y_sc': y_sc})
marks =... | def _create_marks(fig, marks=[bq.Mark], options={}, params={}) | Initializes and returns marks for a figure as a list. Each mark is passed
in as a class. The plot options should be passed into options.
Any additional parameters to initialize plot components are passed into
params as a dict of { 'mark': [{ trait: value, ... }, ...] }
For example, when initializing t... | 4.256007 | 4.28195 | 0.993941 |
if isinstance(maybe_iterable, collections.Iterable):
return np.array([i for i in maybe_iterable])
return placeholder | def _array_or_placeholder(
maybe_iterable, placeholder=PLACEHOLDER_ZEROS
) -> np.array | Return maybe_iterable's contents or a placeholder array.
Used to give bqplot its required initial points to plot even if we're using
a function to generate points. | 3.796967 | 3.693871 | 1.02791 |
tokens = re.split(r'/|:', github_url.replace('.git', ''))
# The username and reponame are the last two tokens
return '{}/{}/master'.format(tokens[-2], tokens[-1]) | def binder_spec_from_github_url(github_url) | Converts GitHub origin into a Binder spec.
For example:
git@github.com:SamLau95/nbinteract.git -> SamLau95/nbinteract/master
https://github.com/Calebs97/riemann_book -> Calebs97/riemann_book/master | 5.436415 | 5.751164 | 0.945272 |
valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False}
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'" % default)
w... | def yes_or_no(question, default="yes") | Ask a yes/no question via input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return val... | 1.666348 | 1.843514 | 0.903897 |
arguments = docopt(__doc__)
if arguments['init']:
return_code = init()
sys.exit(return_code)
run_converter(arguments) | def main() | Parses command line options and runs nbinteract. | 5.369351 | 5.053636 | 1.062473 |
# Get spec from config file
if os.path.isfile(CONFIG_FILE):
with open(CONFIG_FILE, encoding='utf-8') as f:
config = json.load(f)
arguments['--spec'] = arguments['--spec'] or config['spec']
check_arguments(arguments)
notebooks = flatmap(
expand_folder,
... | def run_converter(arguments) | Converts notebooks to HTML files. Returns list of output file paths | 3.391587 | 3.223263 | 1.052222 |
'''
Initializes git repo for nbinteract.
1. Checks for requirements.txt or Dockerfile, offering to create a
requirements.txt if needed.
2. Sets the Binder spec using the `origin` git remote in .nbinteract.json.
3. Prints a Binder URL so the user can debug their image if needed.
'''
l... | def init() | Initializes git repo for nbinteract.
1. Checks for requirements.txt or Dockerfile, offering to create a
requirements.txt if needed.
2. Sets the Binder spec using the `origin` git remote in .nbinteract.json.
3. Prints a Binder URL so the user can debug their image if needed. | 3.99043 | 3.127493 | 1.275919 |
is_file = os.path.isfile(notebook_or_folder)
is_dir = os.path.isdir(notebook_or_folder)
if not (is_file or is_dir):
raise ValueError(
'{} is neither an existing file nor a folder.'
.format(notebook_or_folder)
)
if is_file:
return [notebook_or_folder]... | def expand_folder(notebook_or_folder, recursive=False) | If notebook_or_folder is a folder, returns a list containing all notebooks
in the folder. Otherwise, returns a list containing the notebook name.
If recursive is True, recurses into subdirectories. | 2.200014 | 2.245248 | 0.979854 |
config = Config(InteractExporter=exporter_config)
preprocessors = []
if extract_images:
# Use ExtractOutputPreprocessor to extract the images to separate files
preprocessors.append(
'nbconvert.preprocessors.ExtractOutputPreprocessor'
)
if execute:
# Use ... | def init_exporter(extract_images, execute, **exporter_config) | Returns an initialized exporter. | 5.939482 | 5.992352 | 0.991177 |
resources = defaultdict(str)
resources['metadata'] = defaultdict(str)
resources['metadata']['name'] = nb_name
resources['metadata']['path'] = out_folder
# This results in images like AB_5_1.png for a notebook called AB.ipynb
resources['unique_key'] = nb_name
resources['output_files_dir... | def make_exporter_resources(nb_name, out_folder, images_folder=None) | Creates resources dict for the exporter | 6.072817 | 5.491753 | 1.105807 |
if output_folder:
os.makedirs(output_folder, exist_ok=True)
if images_folder:
os.makedirs(images_folder, exist_ok=True)
# Computes notebooks/ch1 and <name>.ipynb from notebooks/ch1/<name>.ipynb
path, filename = os.path.split(notebook_path)
# Computes <name> from <name>.ipynb
... | def convert(notebook_path, exporter, output_folder=None, images_folder=None) | Converts notebook into an HTML file, outputting notebooks into
output_folder if set and images into images_folder if set.
Returns the path to the resulting HTML file. | 2.782227 | 2.754948 | 1.009902 |
for notebook_path in notebook_paths:
# Computes <name>.ipynb from notebooks/01/<name>.ipynb
path, filename = os.path.split(notebook_path)
# Computes examples from notebooks/examples
chapter = os.path.split(path)[1] if os.sep in path else ''
# Computes <name> from <name>.... | def convert_notebooks_to_html_partial(notebook_paths, url_map) | Converts notebooks in notebook_paths to HTML partials | 3.553705 | 3.550377 | 1.000937 |
code = dedent(
'''
# HIDDEN
# Clear previously defined variables
%reset -f
'''.format(path)
)
return nbformat.v4.new_code_cell(source=code) | def _preamble_cell(path) | This cell is inserted at the start of each notebook to set the working
directory to the correct folder. | 7.709127 | 6.780032 | 1.137034 |
with open(yaml_path) as f:
data = yaml.load(f)
pipeline = [
t.remove(_not_internal_link),
flatmap(_flatten_sections),
t.map(t.get('url')), list, _sliding_three,
t.map(_adj_pages),
t.merge()
]
return t.pipe(data, *pipeline) | def generate_url_map(yaml_path=TOC_PATH) -> dict | Generates mapping from each URL to its previous and next URLs in the
textbook. The dictionary looks like:
{
'ch/10/some_page.html' : {
'prev': 'ch/09/foo.html',
'next': 'ch/10/bar.html',
},
...
} | 12.111832 | 12.601461 | 0.961145 |
for element in self.elements:
if element.element == element_name:
return element
return Element | def find_element_class(self, element_name) | Finds an element class for the given element name contained within the
registry.
Returns Element when there is no matching element subclass.
>>> registry.find_element_class('string')
String
>>> registry.find_element_class('unknown')
Element | 4.791702 | 6.340197 | 0.755766 |
for transformer, target_type in transformer_chain:
# noinspection PyTypeChecker
data = transformer.transform(target_type, data, context)
return data | def _transform(transformer_chain: Sequence[Tuple[DataTransformer, Type]], data: S, context: PipelineContext = None) -> T | Transform data to a new type.
Args:
transformer_chain: A sequence of (transformer, type) pairs to convert the data.
data: The data to be transformed.
context: The context of the transformations (mutable).
Returns:
The transformed data. | 3.26363 | 4.609293 | 0.708054 |
LOGGER.info("Converting item \"{item}\" for sink \"{sink}\"".format(item=item, sink=self._sink))
item = self._transform(data=item, context=context)
LOGGER.info("Puting item \"{item}\" into sink \"{sink}\"".format(item=item, sink=self._sink))
self._sink.put(self._store_type, item... | def put(self, item: T, context: PipelineContext = None) -> None | Puts an objects into the data sink. The objects may be transformed into a new type for insertion if necessary.
Args:
item: The objects to be inserted into the data sink.
context: The context of the insertion (mutable). | 3.666476 | 3.328784 | 1.101446 |
LOGGER.info("Creating transform generator for items \"{items}\" for sink \"{sink}\"".format(items=items, sink=self._sink))
transform_generator = (self._transform(data=item, context=context) for item in items)
LOGGER.info("Putting transform generator for items \"{items}\" into sink \"{si... | def put_many(self, items: Iterable[T], context: PipelineContext = None) -> None | Puts multiple objects of the same type into the data sink. The objects may be transformed into a new type for insertion if necessary.
Args:
items: An iterable (e.g. list) of objects to be inserted into the data sink.
context: The context of the insertions (mutable). | 3.633378 | 3.290802 | 1.104101 |
result = self._source.get(self._source_type, deepcopy(query), context)
LOGGER.info("Got result \"{result}\" from query \"{query}\" of source \"{source}\"".format(result=result, query=query, source=self._source))
LOGGER.info("Sending result \"{result}\" to sinks before converting".forma... | def get(self, query: Mapping[str, Any], context: PipelineContext = None) -> T | Gets a query from the data source.
1) Extracts the query from the data source.
2) Inserts the result into any data sinks.
3) Transforms the result into the requested type if it wasn't already.
4) Inserts the transformed result into any data sinks.
Args:
query: The q... | 2.770089 | 2.633121 | 1.052018 |
result = self._source.get_many(self._source_type, deepcopy(query), context)
LOGGER.info("Got results \"{result}\" from query \"{query}\" of source \"{source}\"".format(result=result, query=query, source=self._source))
if not streaming:
LOGGER.info("Non-streaming get_many re... | def get_many(self, query: Mapping[str, Any], context: PipelineContext = None, streaming: bool = False) -> Iterable[T] | Gets a query from the data source, where the query contains multiple elements to be extracted.
1) Extracts the query from the data source.
2) Inserts the result into any data sinks.
3) Transforms the results into the requested type if it wasn't already.
4) Inserts the transformed result... | 2.870559 | 2.756822 | 1.041257 |
LOGGER.info("Getting SourceHandlers for \"{type}\"".format(type=type.__name__))
try:
handlers = self._get_types[type]
except KeyError:
try:
LOGGER.info("Building new SourceHandlers for \"{type}\"".format(type=type.__name__))
handle... | def get(self, type: Type[T], query: Mapping[str, Any]) -> T | Gets a query from the data pipeline.
1) Extracts the query the sequence of data sources.
2) Inserts the result into the data sinks (if appropriate).
3) Transforms the result into the requested type if it wasn't already.
4) Inserts the transformed result into any data sinks.
Arg... | 3.278371 | 3.164476 | 1.035992 |
LOGGER.info("Getting SourceHandlers for \"{type}\"".format(type=type.__name__))
try:
handlers = self._get_types[type]
except KeyError:
try:
LOGGER.info("Building new SourceHandlers for \"{type}\"".format(type=type.__name__))
handle... | def get_many(self, type: Type[T], query: Mapping[str, Any], streaming: bool = False) -> Iterable[T] | Gets a query from the data pipeline, which contains a request for multiple objects.
1) Extracts the query the sequence of data sources.
2) Inserts the results into the data sinks (if appropriate).
3) Transforms the results into the requested type if it wasn't already.
4) Inserts the tra... | 3.234163 | 3.155231 | 1.025016 |
LOGGER.info("Getting SinkHandlers for \"{type}\"".format(type=type.__name__))
try:
handlers = self._put_types[type]
except KeyError:
try:
LOGGER.info("Building new SinkHandlers for \"{type}\"".format(type=type.__name__))
handlers =... | def put(self, type: Type[T], item: T) -> None | Puts an objects into the data pipeline. The object may be transformed into a new type for insertion if necessary.
Args:
item: The object to be inserted into the data pipeline. | 3.920148 | 3.700535 | 1.059346 |
LOGGER.info("Getting SinkHandlers for \"{type}\"".format(type=type.__name__))
try:
handlers = self._put_types[type]
except KeyError:
try:
LOGGER.info("Building new SinkHandlers for \"{type}\"".format(type=type.__name__))
handlers =... | def put_many(self, type: Type[T], items: Iterable[T]) -> None | Puts multiple objects of the same type into the data sink. The objects may be transformed into a new type for insertion if necessary.
Args:
items: An iterable (e.g. list) of objects to be inserted into the data pipeline. | 4.079433 | 3.895402 | 1.047243 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.