_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 87
6.4k
| title
stringclasses 1
value | language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
d201 | train | def dict_to_querystring(dictionary):
"""Converts a dict to a querystring suitable to be appended to a URL."""
s = u""
for d in dictionary.keys():
s = unicode.format(u"{0}{1}={2}&", s, d, dictionary[d])
return s[:-1] | PYTHON | {
"dummy_field": ""
} |
|
d202 | train | def _check_elements_equal(lst):
"""
Returns true if all of the elements in the list are equal.
"""
assert isinstance(lst, list), "Input value must be a list."
return not lst or lst.count(lst[0]) == len(lst) | PYTHON | {
"dummy_field": ""
} |
|
d203 | train | def nonull_dict(self):
"""Like dict, but does not hold any null values.
:return:
"""
return {k: v for k, v in six.iteritems(self.dict) if v and k != '_codes'} | PYTHON | {
"dummy_field": ""
} |
|
d204 | train | def is_element_present(driver, selector, by=By.CSS_SELECTOR):
"""
Returns whether the specified element selector is present on the page.
@Params
driver - the webdriver object (required)
selector - the locator that is used (required)
by - the method to search for the locator (Default: By.CSS_SELECTOR)
@Returns
Boolean (is element present)
"""
try:
driver.find_element(by=by, value=selector)
return True
except Exception:
return False | PYTHON | {
"dummy_field": ""
} |
|
d205 | train | def updateFromKwargs(self, properties, kwargs, collector, **unused):
"""Primary entry point to turn 'kwargs' into 'properties'"""
properties[self.name] = self.getFromKwargs(kwargs) | PYTHON | {
"dummy_field": ""
} |
|
d206 | train | def is_callable(*p):
""" True if all the args are functions and / or subroutines
"""
import symbols
return all(isinstance(x, symbols.FUNCTION) for x in p) | PYTHON | {
"dummy_field": ""
} |
|
d207 | train | async def disconnect(self):
""" Disconnect from target. """
if not self.connected:
return
self.writer.close()
self.reader = None
self.writer = None | PYTHON | {
"dummy_field": ""
} |
|
d208 | train | def is_dataframe(obj):
"""
Returns True if the given object is a Pandas Data Frame.
Parameters
----------
obj: instance
The object to test whether or not is a Pandas DataFrame.
"""
try:
# This is the best method of type checking
from pandas import DataFrame
return isinstance(obj, DataFrame)
except ImportError:
# Pandas is not a dependency, so this is scary
return obj.__class__.__name__ == "DataFrame" | PYTHON | {
"dummy_field": ""
} |
|
d209 | train | def test():
"""Run the unit tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests) | PYTHON | {
"dummy_field": ""
} |
|
d210 | train | def is_datetime_like(dtype):
"""Check if a dtype is a subclass of the numpy datetime types
"""
return (np.issubdtype(dtype, np.datetime64) or
np.issubdtype(dtype, np.timedelta64)) | PYTHON | {
"dummy_field": ""
} |
|
d211 | train | def serialize_json_string(self, value):
"""
Tries to load an encoded json string back into an object
:param json_string:
:return:
"""
# Check if the value might be a json string
if not isinstance(value, six.string_types):
return value
# Make sure it starts with a brace
if not value.startswith('{') or value.startswith('['):
return value
# Try to load the string
try:
return json.loads(value)
except:
return value | PYTHON | {
"dummy_field": ""
} |
|
d212 | train | def is_defined(self, objtxt, force_import=False):
"""Return True if object is defined"""
return self.interpreter.is_defined(objtxt, force_import) | PYTHON | {
"dummy_field": ""
} |
|
d213 | train | def get_hline():
""" gets a horiztonal line """
return Window(
width=LayoutDimension.exact(1),
height=LayoutDimension.exact(1),
content=FillControl('-', token=Token.Line)) | PYTHON | {
"dummy_field": ""
} |
|
d214 | train | def group_exists(groupname):
"""Check if a group exists"""
try:
grp.getgrnam(groupname)
group_exists = True
except KeyError:
group_exists = False
return group_exists | PYTHON | {
"dummy_field": ""
} |
|
d215 | train | def sync(self, recursive=False):
"""
Syncs the information from this item to the tree and view.
"""
self.syncTree(recursive=recursive)
self.syncView(recursive=recursive) | PYTHON | {
"dummy_field": ""
} |
|
d216 | train | def is_same_shape(self, other_im, check_channels=False):
""" Checks if two images have the same height and width (and optionally channels).
Parameters
----------
other_im : :obj:`Image`
image to compare
check_channels : bool
whether or not to check equality of the channels
Returns
-------
bool
True if the images are the same shape, False otherwise
"""
if self.height == other_im.height and self.width == other_im.width:
if check_channels and self.channels != other_im.channels:
return False
return True
return False | PYTHON | {
"dummy_field": ""
} |
|
d217 | train | def get_distance_between_two_points(self, one, two):
"""Returns the distance between two XYPoints."""
dx = one.x - two.x
dy = one.y - two.y
return math.sqrt(dx * dx + dy * dy) | PYTHON | {
"dummy_field": ""
} |
|
d218 | train | def is_same_shape(self, other_im, check_channels=False):
""" Checks if two images have the same height and width (and optionally channels).
Parameters
----------
other_im : :obj:`Image`
image to compare
check_channels : bool
whether or not to check equality of the channels
Returns
-------
bool
True if the images are the same shape, False otherwise
"""
if self.height == other_im.height and self.width == other_im.width:
if check_channels and self.channels != other_im.channels:
return False
return True
return False | PYTHON | {
"dummy_field": ""
} |
|
d219 | train | def post_process(self):
""" Apply last 2D transforms"""
self.image.putdata(self.pixels)
self.image = self.image.transpose(Image.ROTATE_90) | PYTHON | {
"dummy_field": ""
} |
|
d220 | train | def _not_none(items):
"""Whether the item is a placeholder or contains a placeholder."""
if not isinstance(items, (tuple, list)):
items = (items,)
return all(item is not _none for item in items) | PYTHON | {
"dummy_field": ""
} |
|
d221 | train | def delete_all_from_db():
"""Clear the database.
Used for testing and debugging.
"""
# The models.CASCADE property is set on all ForeignKey fields, so tables can
# be deleted in any order without breaking constraints.
for model in django.apps.apps.get_models():
model.objects.all().delete() | PYTHON | {
"dummy_field": ""
} |
|
d222 | train | def is_complex(dtype):
"""Returns whether this is a complex floating point type."""
dtype = tf.as_dtype(dtype)
if hasattr(dtype, 'is_complex'):
return dtype.is_complex
return np.issubdtype(np.dtype(dtype), np.complex) | PYTHON | {
"dummy_field": ""
} |
|
d223 | train | def delete(build_folder):
"""Delete build directory and all its contents.
"""
if _meta_.del_build in ["on", "ON"] and os.path.exists(build_folder):
shutil.rmtree(build_folder) | PYTHON | {
"dummy_field": ""
} |
|
d224 | train | def _stdin_ready_posix():
"""Return True if there's something to read on stdin (posix version)."""
infds, outfds, erfds = select.select([sys.stdin],[],[],0)
return bool(infds) | PYTHON | {
"dummy_field": ""
} |
|
d225 | train | def json_response(data, status=200):
"""Return a JsonResponse. Make sure you have django installed first."""
from django.http import JsonResponse
return JsonResponse(data=data, status=status, safe=isinstance(data, dict)) | PYTHON | {
"dummy_field": ""
} |
|
d226 | train | def _is_path(s):
"""Return whether an object is a path."""
if isinstance(s, string_types):
try:
return op.exists(s)
except (OSError, ValueError):
return False
else:
return False | PYTHON | {
"dummy_field": ""
} |
|
d227 | train | def see_doc(obj_with_doc):
"""Copy docstring from existing object to the decorated callable."""
def decorator(fn):
fn.__doc__ = obj_with_doc.__doc__
return fn
return decorator | PYTHON | {
"dummy_field": ""
} |
|
d228 | train | def isToneCal(self):
"""Whether the currently selected calibration stimulus type is the calibration curve
:returns: boolean -- if the current combo box selection is calibration curve
"""
return self.ui.calTypeCmbbx.currentIndex() == self.ui.calTypeCmbbx.count() -1 | PYTHON | {
"dummy_field": ""
} |
|
d229 | train | def hmsToDeg(h, m, s):
"""Convert RA hours, minutes, seconds into an angle in degrees."""
return h * degPerHMSHour + m * degPerHMSMin + s * degPerHMSSec | PYTHON | {
"dummy_field": ""
} |
|
d230 | train | def is_date(thing):
"""Checks if the given thing represents a date
:param thing: The object to check if it is a date
:type thing: arbitrary object
:returns: True if we have a date object
:rtype: bool
"""
# known date types
date_types = (datetime.datetime,
datetime.date,
DateTime)
return isinstance(thing, date_types) | PYTHON | {
"dummy_field": ""
} |
|
d231 | train | def prepare(doc):
"""Sets the caption_found and plot_found variables to False."""
doc.caption_found = False
doc.plot_found = False
doc.listings_counter = 0 | PYTHON | {
"dummy_field": ""
} |
|
d232 | train | def validate(key):
"""Check that the key is a string or bytestring.
That's the only valid type of key.
"""
if not isinstance(key, (str, bytes)):
raise KeyError('Key must be of type str or bytes, found type {}'.format(type(key))) | PYTHON | {
"dummy_field": ""
} |
|
d233 | train | def _normal_prompt(self):
"""
Flushes the prompt before requesting the input
:return: The command line
"""
sys.stdout.write(self.__get_ps1())
sys.stdout.flush()
return safe_input() | PYTHON | {
"dummy_field": ""
} |
|
d234 | train | def maxDepth(self, currentDepth=0):
"""Compute the depth of the longest branch of the tree"""
if not any((self.left, self.right)):
return currentDepth
result = 0
for child in (self.left, self.right):
if child:
result = max(result, child.maxDepth(currentDepth + 1))
return result | PYTHON | {
"dummy_field": ""
} |
|
d235 | train | def from_rectangle(box):
""" Create a vector randomly within the given rectangle. """
x = box.left + box.width * random.uniform(0, 1)
y = box.bottom + box.height * random.uniform(0, 1)
return Vector(x, y) | PYTHON | {
"dummy_field": ""
} |
|
d236 | train | def launched():
"""Test whether the current python environment is the correct lore env.
:return: :any:`True` if the environment is launched
:rtype: bool
"""
if not PREFIX:
return False
return os.path.realpath(sys.prefix) == os.path.realpath(PREFIX) | PYTHON | {
"dummy_field": ""
} |
|
d237 | train | def hline(self, x, y, width, color):
"""Draw a horizontal line up to a given length."""
self.rect(x, y, width, 1, color, fill=True) | PYTHON | {
"dummy_field": ""
} |
|
d238 | train | def is_sequence(obj):
"""Check if `obj` is a sequence, but not a string or bytes."""
return isinstance(obj, Sequence) and not (
isinstance(obj, str) or BinaryClass.is_valid_type(obj)) | PYTHON | {
"dummy_field": ""
} |
|
d239 | train | def isnamedtuple(obj):
"""Heuristic check if an object is a namedtuple."""
return isinstance(obj, tuple) \
and hasattr(obj, "_fields") \
and hasattr(obj, "_asdict") \
and callable(obj._asdict) | PYTHON | {
"dummy_field": ""
} |
|
d240 | train | def starts_with_prefix_in_list(text, prefixes):
"""
Return True if the given string starts with one of the prefixes in the given list, otherwise
return False.
Arguments:
text (str): Text to check for prefixes.
prefixes (list): List of prefixes to check for.
Returns:
bool: True if the given text starts with any of the given prefixes, otherwise False.
"""
for prefix in prefixes:
if text.startswith(prefix):
return True
return False | PYTHON | {
"dummy_field": ""
} |
|
d241 | train | def print_yaml(o):
"""Pretty print an object as YAML."""
print(yaml.dump(o, default_flow_style=False, indent=4, encoding='utf-8')) | PYTHON | {
"dummy_field": ""
} |
|
d242 | train | def issuperset(self, other):
"""Report whether this RangeSet contains another set."""
self._binary_sanity_check(other)
return set.issuperset(self, other) | PYTHON | {
"dummy_field": ""
} |
|
d243 | train | def deserialize_ndarray_npy(d):
"""
Deserializes a JSONified :obj:`numpy.ndarray` that was created using numpy's
:obj:`save` function.
Args:
d (:obj:`dict`): A dictionary representation of an :obj:`ndarray` object, created
using :obj:`numpy.save`.
Returns:
An :obj:`ndarray` object.
"""
with io.BytesIO() as f:
f.write(json.loads(d['npy']).encode('latin-1'))
f.seek(0)
return np.load(f) | PYTHON | {
"dummy_field": ""
} |
|
d244 | train | def check(text):
"""Check the text."""
err = "misc.currency"
msg = u"Incorrect use of symbols in {}."
symbols = [
"\$[\d]* ?(?:dollars|usd|us dollars)"
]
return existence_check(text, symbols, err, msg) | PYTHON | {
"dummy_field": ""
} |
|
d245 | train | def listlike(obj):
"""Is an object iterable like a list (and not a string)?"""
return hasattr(obj, "__iter__") \
and not issubclass(type(obj), str)\
and not issubclass(type(obj), unicode) | PYTHON | {
"dummy_field": ""
} |
|
d246 | train | def _map_table_name(self, model_names):
"""
Pre foregin_keys potrbejeme pre z nazvu tabulky zistit class,
tak si to namapujme
"""
for model in model_names:
if isinstance(model, tuple):
model = model[0]
try:
model_cls = getattr(self.models, model)
self.table_to_class[class_mapper(model_cls).tables[0].name] = model
except AttributeError:
pass | PYTHON | {
"dummy_field": ""
} |
|
d247 | train | def service_available(service_name):
"""Determine whether a system service is available"""
try:
subprocess.check_output(
['service', service_name, 'status'],
stderr=subprocess.STDOUT).decode('UTF-8')
except subprocess.CalledProcessError as e:
return b'unrecognized service' not in e.output
else:
return True | PYTHON | {
"dummy_field": ""
} |
|
d248 | train | def keys(self):
"""Return a list of all keys in the dictionary.
Returns:
list of str: [key1,key2,...,keyN]
"""
all_keys = [k.decode('utf-8') for k,v in self.rdb.hgetall(self.session_hash).items()]
return all_keys | PYTHON | {
"dummy_field": ""
} |
|
d249 | train | def _valid_other_type(x, types):
"""
Do all elements of x have a type from types?
"""
return all(any(isinstance(el, t) for t in types) for el in np.ravel(x)) | PYTHON | {
"dummy_field": ""
} |
|
d250 | train | def escape_tex(value):
"""
Make text tex safe
"""
newval = value
for pattern, replacement in LATEX_SUBS:
newval = pattern.sub(replacement, newval)
return newval | PYTHON | {
"dummy_field": ""
} |
|
d251 | train | def _pip_exists(self):
"""Returns True if pip exists inside the virtual environment. Can be
used as a naive way to verify that the environment is installed."""
return os.path.isfile(os.path.join(self.path, 'bin', 'pip')) | PYTHON | {
"dummy_field": ""
} |
|
d252 | train | def update_index(index):
"""Re-index every document in a named index."""
logger.info("Updating search index: '%s'", index)
client = get_client()
responses = []
for model in get_index_models(index):
logger.info("Updating search index model: '%s'", model.search_doc_type)
objects = model.objects.get_search_queryset(index).iterator()
actions = bulk_actions(objects, index=index, action="index")
response = helpers.bulk(client, actions, chunk_size=get_setting("chunk_size"))
responses.append(response)
return responses | PYTHON | {
"dummy_field": ""
} |
|
d253 | train | def is_datetime_like(dtype):
"""Check if a dtype is a subclass of the numpy datetime types
"""
return (np.issubdtype(dtype, np.datetime64) or
np.issubdtype(dtype, np.timedelta64)) | PYTHON | {
"dummy_field": ""
} |
|
d254 | train | def hidden_cursor(self):
"""Return a context manager that hides the cursor while inside it and
makes it visible on leaving."""
self.stream.write(self.hide_cursor)
try:
yield
finally:
self.stream.write(self.normal_cursor) | PYTHON | {
"dummy_field": ""
} |
|
d255 | train | def service_available(service_name):
"""Determine whether a system service is available"""
try:
subprocess.check_output(
['service', service_name, 'status'],
stderr=subprocess.STDOUT).decode('UTF-8')
except subprocess.CalledProcessError as e:
return b'unrecognized service' not in e.output
else:
return True | PYTHON | {
"dummy_field": ""
} |
|
d256 | train | def copy(doc, dest, src):
"""Copy element from sequence, member from mapping.
:param doc: the document base
:param dest: the destination
:type dest: Pointer
:param src: the source
:type src: Pointer
:return: the new object
"""
return Target(doc).copy(dest, src).document | PYTHON | {
"dummy_field": ""
} |
|
d257 | train | def is_string(val):
"""Determines whether the passed value is a string, safe for 2/3."""
try:
basestring
except NameError:
return isinstance(val, str)
return isinstance(val, basestring) | PYTHON | {
"dummy_field": ""
} |
|
d258 | train | def read_from_file(file_path, encoding="utf-8"):
"""
Read helper method
:type file_path: str|unicode
:type encoding: str|unicode
:rtype: str|unicode
"""
with codecs.open(file_path, "r", encoding) as f:
return f.read() | PYTHON | {
"dummy_field": ""
} |
|
d259 | train | def _stdin_ready_posix():
"""Return True if there's something to read on stdin (posix version)."""
infds, outfds, erfds = select.select([sys.stdin],[],[],0)
return bool(infds) | PYTHON | {
"dummy_field": ""
} |
|
d260 | train | def _is_root():
"""Checks if the user is rooted."""
import os
import ctypes
try:
return os.geteuid() == 0
except AttributeError:
return ctypes.windll.shell32.IsUserAnAdmin() != 0
return False | PYTHON | {
"dummy_field": ""
} |
|
d261 | train | def _valid_other_type(x, types):
"""
Do all elements of x have a type from types?
"""
return all(any(isinstance(el, t) for t in types) for el in np.ravel(x)) | PYTHON | {
"dummy_field": ""
} |
|
d262 | train | def describe_enum_value(enum_value):
"""Build descriptor for Enum instance.
Args:
enum_value: Enum value to provide descriptor for.
Returns:
Initialized EnumValueDescriptor instance describing the Enum instance.
"""
enum_value_descriptor = EnumValueDescriptor()
enum_value_descriptor.name = six.text_type(enum_value.name)
enum_value_descriptor.number = enum_value.number
return enum_value_descriptor | PYTHON | {
"dummy_field": ""
} |
|
d263 | train | def user_in_all_groups(user, groups):
"""Returns True if the given user is in all given groups"""
return user_is_superuser(user) or all(user_in_group(user, group) for group in groups) | PYTHON | {
"dummy_field": ""
} |
|
d264 | train | def items(self):
"""Return a list of the (name, value) pairs of the enum.
These are returned in the order they were defined in the .proto file.
"""
return [(value_descriptor.name, value_descriptor.number)
for value_descriptor in self._enum_type.values] | PYTHON | {
"dummy_field": ""
} |
|
d265 | train | def n_choose_k(n, k):
""" get the number of quartets as n-choose-k. This is used
in equal splits to decide whether a split should be exhaustively sampled
or randomly sampled. Edges near tips can be exhaustive while highly nested
edges probably have too many quartets
"""
return int(reduce(MUL, (Fraction(n-i, i+1) for i in range(k)), 1)) | PYTHON | {
"dummy_field": ""
} |
|
d266 | train | def items(cls):
"""
All values for this enum
:return: list of tuples
"""
return [
cls.PRECIPITATION,
cls.WIND,
cls.TEMPERATURE,
cls.PRESSURE
] | PYTHON | {
"dummy_field": ""
} |
|
d267 | train | def revnet_164_cifar():
"""Tiny hparams suitable for CIFAR/etc."""
hparams = revnet_cifar_base()
hparams.bottleneck = True
hparams.num_channels = [16, 32, 64]
hparams.num_layers_per_block = [8, 8, 8]
return hparams | PYTHON | {
"dummy_field": ""
} |
|
d268 | train | def items(cls):
"""
All values for this enum
:return: list of tuples
"""
return [
cls.PRECIPITATION,
cls.WIND,
cls.TEMPERATURE,
cls.PRESSURE
] | PYTHON | {
"dummy_field": ""
} |
|
d269 | train | def mtf_image_transformer_cifar_mp_4x():
"""Data parallel CIFAR parameters."""
hparams = mtf_image_transformer_base_cifar()
hparams.mesh_shape = "model:4;batch:8"
hparams.layout = "batch:batch;d_ff:model;heads:model"
hparams.batch_size = 32
hparams.num_heads = 8
hparams.d_ff = 8192
return hparams | PYTHON | {
"dummy_field": ""
} |
|
d270 | train | def image_set_aspect(aspect=1.0, axes="gca"):
"""
sets the aspect ratio of the current zoom level of the imshow image
"""
if axes is "gca": axes = _pylab.gca()
e = axes.get_images()[0].get_extent()
axes.set_aspect(abs((e[1]-e[0])/(e[3]-e[2]))/aspect) | PYTHON | {
"dummy_field": ""
} |
|
d271 | train | def Flush(self):
"""Flush all items from cache."""
while self._age:
node = self._age.PopLeft()
self.KillObject(node.data)
self._hash = dict() | PYTHON | {
"dummy_field": ""
} |
|
d272 | train | def _propagate_mean(mean, linop, dist):
"""Propagate a mean through linear Gaussian transformation."""
return linop.matmul(mean) + dist.mean()[..., tf.newaxis] | PYTHON | {
"dummy_field": ""
} |
|
d273 | train | def invalidate_cache(cpu, address, size):
""" remove decoded instruction from instruction cache """
cache = cpu.instruction_cache
for offset in range(size):
if address + offset in cache:
del cache[address + offset] | PYTHON | {
"dummy_field": ""
} |
|
d274 | train | def convertToBool():
""" Convert a byte value to boolean (0 or 1) if
the global flag strictBool is True
"""
if not OPTIONS.strictBool.value:
return []
REQUIRES.add('strictbool.asm')
result = []
result.append('pop af')
result.append('call __NORMALIZE_BOOLEAN')
result.append('push af')
return result | PYTHON | {
"dummy_field": ""
} |
|
d275 | train | def normalize(x, min_value, max_value):
"""Normalize value between min and max values.
It also clips the values, so that you cannot have values higher or lower
than 0 - 1."""
x = (x - min_value) / (max_value - min_value)
return clip(x, 0, 1) | PYTHON | {
"dummy_field": ""
} |
|
d276 | train | def prepare_for_reraise(error, exc_info=None):
"""Prepares the exception for re-raising with reraise method.
This method attaches type and traceback info to the error object
so that reraise can properly reraise it using this info.
"""
if not hasattr(error, "_type_"):
if exc_info is None:
exc_info = sys.exc_info()
error._type_ = exc_info[0]
error._traceback = exc_info[2]
return error | PYTHON | {
"dummy_field": ""
} |
|
d277 | train | def close_all_but_this(self):
"""Close all files but the current one"""
self.close_all_right()
for i in range(0, self.get_stack_count()-1 ):
self.close_file(0) | PYTHON | {
"dummy_field": ""
} |
|
d278 | train | def eval_in_system_namespace(self, exec_str):
"""
Get Callable for specified string (for GUI-based editing)
"""
ns = self.cmd_namespace
try:
return eval(exec_str, ns)
except Exception as e:
self.logger.warning('Could not execute %s, gave error %s', exec_str, e)
return None | PYTHON | {
"dummy_field": ""
} |
|
d279 | train | def _close_socket(self):
"""Shutdown and close the Socket.
:return:
"""
try:
self.socket.shutdown(socket.SHUT_RDWR)
except (OSError, socket.error):
pass
self.socket.close() | PYTHON | {
"dummy_field": ""
} |
|
d280 | train | def exec_function(ast, globals_map):
"""Execute a python code object in the given environment.
Args:
globals_map: Dictionary to use as the globals context.
Returns:
locals_map: Dictionary of locals from the environment after execution.
"""
locals_map = globals_map
exec ast in globals_map, locals_map
return locals_map | PYTHON | {
"dummy_field": ""
} |
|
d281 | train | def cleanup(self, app):
"""Close all connections."""
if hasattr(self.database.obj, 'close_all'):
self.database.close_all() | PYTHON | {
"dummy_field": ""
} |
|
d282 | train | def get_unicode_str(obj):
"""Makes sure obj is a unicode string."""
if isinstance(obj, six.text_type):
return obj
if isinstance(obj, six.binary_type):
return obj.decode("utf-8", errors="ignore")
return six.text_type(obj) | PYTHON | {
"dummy_field": ""
} |
|
d283 | train | def close_all_but_this(self):
"""Close all files but the current one"""
self.close_all_right()
for i in range(0, self.get_stack_count()-1 ):
self.close_file(0) | PYTHON | {
"dummy_field": ""
} |
|
d284 | train | def exp_fit_fun(x, a, tau, c):
"""Function used to fit the exponential decay."""
# pylint: disable=invalid-name
return a * np.exp(-x / tau) + c | PYTHON | {
"dummy_field": ""
} |
|
d285 | train | def _findNearest(arr, value):
""" Finds the value in arr that value is closest to
"""
arr = np.array(arr)
# find nearest value in array
idx = (abs(arr-value)).argmin()
return arr[idx] | PYTHON | {
"dummy_field": ""
} |
|
d286 | train | def gauss_pdf(x, mu, sigma):
"""Normalized Gaussian"""
return 1 / np.sqrt(2 * np.pi) / sigma * np.exp(-(x - mu) ** 2 / 2. / sigma ** 2) | PYTHON | {
"dummy_field": ""
} |
|
d287 | train | def remove_examples_all():
"""remove arduino/examples/all directory.
:rtype: None
"""
d = examples_all_dir()
if d.exists():
log.debug('remove %s', d)
d.rmtree()
else:
log.debug('nothing to remove: %s', d) | PYTHON | {
"dummy_field": ""
} |
|
d288 | train | def resources(self):
"""Retrieve contents of each page of PDF"""
return [self.pdf.getPage(i) for i in range(self.pdf.getNumPages())] | PYTHON | {
"dummy_field": ""
} |
|
d289 | train | def cli_command_quit(self, msg):
"""\
kills the child and exits
"""
if self.state == State.RUNNING and self.sprocess and self.sprocess.proc:
self.sprocess.proc.kill()
else:
sys.exit(0) | PYTHON | {
"dummy_field": ""
} |
|
d290 | train | def dot(self, w):
"""Return the dotproduct between self and another vector."""
return sum([x * y for x, y in zip(self, w)]) | PYTHON | {
"dummy_field": ""
} |
|
d291 | train | def printc(cls, txt, color=colors.red):
"""Print in color."""
print(cls.color_txt(txt, color)) | PYTHON | {
"dummy_field": ""
} |
|
d292 | train | def need_update(a, b):
"""
Check if file a is newer than file b and decide whether or not to update
file b. Can generalize to two lists.
"""
a = listify(a)
b = listify(b)
return any((not op.exists(x)) for x in b) or \
all((os.stat(x).st_size == 0 for x in b)) or \
any(is_newer_file(x, y) for x in a for y in b) | PYTHON | {
"dummy_field": ""
} |
|
d293 | train | def lengths( self ):
"""
The cell lengths.
Args:
None
Returns:
(np.array(a,b,c)): The cell lengths.
"""
return( np.array( [ math.sqrt( sum( row**2 ) ) for row in self.matrix ] ) ) | PYTHON | {
"dummy_field": ""
} |
|
d294 | train | def random_str(size=10):
"""
create random string of selected size
:param size: int, length of the string
:return: the string
"""
return ''.join(random.choice(string.ascii_lowercase) for _ in range(size)) | PYTHON | {
"dummy_field": ""
} |
|
d295 | train | def get_table_columns(dbconn, tablename):
"""
Return a list of tuples specifying the column name and type
"""
cur = dbconn.cursor()
cur.execute("PRAGMA table_info('%s');" % tablename)
info = cur.fetchall()
cols = [(i[1], i[2]) for i in info]
return cols | PYTHON | {
"dummy_field": ""
} |
|
d296 | train | def remove_duplicates(lst):
"""
Emulate what a Python ``set()`` does, but keeping the element's order.
"""
dset = set()
return [l for l in lst if l not in dset and not dset.add(l)] | PYTHON | {
"dummy_field": ""
} |
|
d297 | train | def _on_select(self, *args):
"""
Function bound to event of selection in the Combobox, calls callback if callable
:param args: Tkinter event
"""
if callable(self.__callback):
self.__callback(self.selection) | PYTHON | {
"dummy_field": ""
} |
|
d298 | train | def fft_spectrum(frames, fft_points=512):
"""This function computes the one-dimensional n-point discrete Fourier
Transform (DFT) of a real-valued array by means of an efficient algorithm
called the Fast Fourier Transform (FFT). Please refer to
https://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.rfft.html
for further details.
Args:
frames (array): The frame array in which each row is a frame.
fft_points (int): The length of FFT. If fft_length is greater than frame_len, the frames will be zero-padded.
Returns:
array: The fft spectrum.
If frames is an num_frames x sample_per_frame matrix, output
will be num_frames x FFT_LENGTH.
"""
SPECTRUM_VECTOR = np.fft.rfft(frames, n=fft_points, axis=-1, norm=None)
return np.absolute(SPECTRUM_VECTOR) | PYTHON | {
"dummy_field": ""
} |
|
d299 | train | def isetdiff_flags(list1, list2):
"""
move to util_iter
"""
set2 = set(list2)
return (item not in set2 for item in list1) | PYTHON | {
"dummy_field": ""
} |
|
d300 | train | def guess_file_type(kind, filepath=None, youtube_id=None, web_url=None, encoding=None):
""" guess_file_class: determines what file the content is
Args:
filepath (str): filepath of file to check
Returns: string indicating file's class
"""
if youtube_id:
return FileTypes.YOUTUBE_VIDEO_FILE
elif web_url:
return FileTypes.WEB_VIDEO_FILE
elif encoding:
return FileTypes.BASE64_FILE
else:
ext = os.path.splitext(filepath)[1][1:].lower()
if kind in FILE_TYPE_MAPPING and ext in FILE_TYPE_MAPPING[kind]:
return FILE_TYPE_MAPPING[kind][ext]
return None | PYTHON | {
"dummy_field": ""
} |