_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 87
6.4k
| title
stringclasses 1
value | language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
d101 | train | def pdf(x, mu, std):
"""Probability density function (normal distribution)"""
return (1.0 / (std * sqrt(2 * pi))) * np.exp(-(x - mu) ** 2 / (2 * std ** 2)) | PYTHON | {
"dummy_field": ""
} |
|
d102 | train | def bytes_to_c_array(data):
"""
Make a C array using the given string.
"""
chars = [
"'{}'".format(encode_escape(i))
for i in decode_escape(data)
]
return ', '.join(chars) + ', 0' | PYTHON | {
"dummy_field": ""
} |
|
d103 | train | def gray2bgr(img):
"""Convert a grayscale image to BGR image.
Args:
img (ndarray or str): The input image.
Returns:
ndarray: The converted BGR image.
"""
img = img[..., None] if img.ndim == 2 else img
out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
return out_img | PYTHON | {
"dummy_field": ""
} |
|
d104 | train | def mean_date(dt_list):
"""Calcuate mean datetime from datetime list
"""
dt_list_sort = sorted(dt_list)
dt_list_sort_rel = [dt - dt_list_sort[0] for dt in dt_list_sort]
avg_timedelta = sum(dt_list_sort_rel, timedelta())/len(dt_list_sort_rel)
return dt_list_sort[0] + avg_timedelta | PYTHON | {
"dummy_field": ""
} |
|
d105 | train | def rotate_img(im, deg, mode=cv2.BORDER_CONSTANT, interpolation=cv2.INTER_AREA):
""" Rotates an image by deg degrees
Arguments:
deg (float): degree to rotate.
"""
r,c,*_ = im.shape
M = cv2.getRotationMatrix2D((c//2,r//2),deg,1)
return cv2.warpAffine(im,M,(c,r), borderMode=mode, flags=cv2.WARP_FILL_OUTLIERS+interpolation) | PYTHON | {
"dummy_field": ""
} |
|
d106 | train | def similarity(self, other):
"""Calculates the cosine similarity between this vector and another
vector."""
if self.magnitude == 0 or other.magnitude == 0:
return 0
return self.dot(other) / self.magnitude | PYTHON | {
"dummy_field": ""
} |
|
d107 | train | def rotate_img(im, deg, mode=cv2.BORDER_CONSTANT, interpolation=cv2.INTER_AREA):
""" Rotates an image by deg degrees
Arguments:
deg (float): degree to rotate.
"""
r,c,*_ = im.shape
M = cv2.getRotationMatrix2D((c//2,r//2),deg,1)
return cv2.warpAffine(im,M,(c,r), borderMode=mode, flags=cv2.WARP_FILL_OUTLIERS+interpolation) | PYTHON | {
"dummy_field": ""
} |
|
d108 | train | def _calculate_distance(latlon1, latlon2):
"""Calculates the distance between two points on earth.
"""
lat1, lon1 = latlon1
lat2, lon2 = latlon2
dlon = lon2 - lon1
dlat = lat2 - lat1
R = 6371 # radius of the earth in kilometers
a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon / 2))**2
c = 2 * np.pi * R * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) / 180
return c | PYTHON | {
"dummy_field": ""
} |
|
d109 | train | def screen_cv2(self):
"""cv2 Image of current window screen"""
pil_image = self.screen.convert('RGB')
cv2_image = np.array(pil_image)
pil_image.close()
# Convert RGB to BGR
cv2_image = cv2_image[:, :, ::-1]
return cv2_image | PYTHON | {
"dummy_field": ""
} |
|
d110 | train | def direct2dDistance(self, point):
"""consider the distance between two mapPoints, ignoring all terrain, pathing issues"""
if not isinstance(point, MapPoint): return 0.0
return ((self.x-point.x)**2 + (self.y-point.y)**2)**(0.5) # simple distance formula | PYTHON | {
"dummy_field": ""
} |
|
d111 | train | def _model_unique(ins):
""" Get unique constraints info
:type ins: sqlalchemy.orm.mapper.Mapper
:rtype: list[tuple[str]]
"""
unique = []
for t in ins.tables:
for c in t.constraints:
if isinstance(c, UniqueConstraint):
unique.append(tuple(col.key for col in c.columns))
return unique | PYTHON | {
"dummy_field": ""
} |
|
d112 | train | def horz_dpi(self):
"""
Integer dots per inch for the width of this image. Defaults to 72
when not present in the file, as is often the case.
"""
pHYs = self._chunks.pHYs
if pHYs is None:
return 72
return self._dpi(pHYs.units_specifier, pHYs.horz_px_per_unit) | PYTHON | {
"dummy_field": ""
} |
|
d113 | train | def parse(self, s):
"""
Parses a date string formatted like ``YYYY-MM-DD``.
"""
return datetime.datetime.strptime(s, self.date_format).date() | PYTHON | {
"dummy_field": ""
} |
|
d114 | train | def estimate_complexity(self, x,y,z,n):
"""
calculates a rough guess of runtime based on product of parameters
"""
num_calculations = x * y * z * n
run_time = num_calculations / 100000 # a 2014 PC does about 100k calcs in a second (guess based on prior logs)
return self.show_time_as_short_string(run_time) | PYTHON | {
"dummy_field": ""
} |
|
d115 | train | def weekly(date=datetime.date.today()):
"""
Weeks start are fixes at Monday for now.
"""
return date - datetime.timedelta(days=date.weekday()) | PYTHON | {
"dummy_field": ""
} |
|
d116 | train | def inh(table):
"""
inverse hyperbolic sine transformation
"""
t = []
for i in table:
t.append(np.ndarray.tolist(np.arcsinh(i)))
return t | PYTHON | {
"dummy_field": ""
} |
|
d117 | train | def daterange(start, end, delta=timedelta(days=1), lower=Interval.CLOSED, upper=Interval.OPEN):
"""Returns a generator which creates the next value in the range on demand"""
date_interval = Interval(lower=lower, lower_value=start, upper_value=end, upper=upper)
current = start if start in date_interval else start + delta
while current in date_interval:
yield current
current = current + delta | PYTHON | {
"dummy_field": ""
} |
|
d118 | train | async def _thread_coro(self, *args):
""" Coroutine called by MapAsync. It's wrapping the call of
run_in_executor to run the synchronous function as thread """
return await self._loop.run_in_executor(
self._executor, self._function, *args) | PYTHON | {
"dummy_field": ""
} |
|
d119 | train | def start_of_month(val):
"""
Return a new datetime.datetime object with values that represent
a start of a month.
:param val: Date to ...
:type val: datetime.datetime | datetime.date
:rtype: datetime.datetime
"""
if type(val) == date:
val = datetime.fromordinal(val.toordinal())
return start_of_day(val).replace(day=1) | PYTHON | {
"dummy_field": ""
} |
|
d120 | train | def check_output(args, env=None, sp=subprocess):
"""Call an external binary and return its stdout."""
log.debug('calling %s with env %s', args, env)
output = sp.check_output(args=args, env=env)
log.debug('output: %r', output)
return output | PYTHON | {
"dummy_field": ""
} |
|
d121 | train | def datetime_to_ms(dt):
"""
Converts a datetime to a millisecond accuracy timestamp
"""
seconds = calendar.timegm(dt.utctimetuple())
return seconds * 1000 + int(dt.microsecond / 1000) | PYTHON | {
"dummy_field": ""
} |
|
d122 | train | def retry_on_signal(function):
"""Retries function until it doesn't raise an EINTR error"""
while True:
try:
return function()
except EnvironmentError, e:
if e.errno != errno.EINTR:
raise | PYTHON | {
"dummy_field": ""
} |
|
d123 | train | def datetime_to_timezone(date, tz="UTC"):
""" convert naive datetime to timezone-aware datetime """
if not date.tzinfo:
date = date.replace(tzinfo=timezone(get_timezone()))
return date.astimezone(timezone(tz)) | PYTHON | {
"dummy_field": ""
} |
|
d124 | train | def test(*args):
"""
Run unit tests.
"""
subprocess.call(["py.test-2.7"] + list(args))
subprocess.call(["py.test-3.4"] + list(args)) | PYTHON | {
"dummy_field": ""
} |
|
d125 | train | def ToDatetime(self):
"""Converts Timestamp to datetime."""
return datetime.utcfromtimestamp(
self.seconds + self.nanos / float(_NANOS_PER_SECOND)) | PYTHON | {
"dummy_field": ""
} |
|
d126 | train | def sortable_title(instance):
"""Uses the default Plone sortable_text index lower-case
"""
title = plone_sortable_title(instance)
if safe_callable(title):
title = title()
return title.lower() | PYTHON | {
"dummy_field": ""
} |
|
d127 | train | def localize(dt):
"""Localize a datetime object to local time."""
if dt.tzinfo is UTC:
return (dt + LOCAL_UTC_OFFSET).replace(tzinfo=None)
# No TZ info so not going to assume anything, return as-is.
return dt | PYTHON | {
"dummy_field": ""
} |
|
d128 | train | def percent_cb(name, complete, total):
""" Callback for updating target progress """
logger.debug(
"{}: {} transferred out of {}".format(
name, sizeof_fmt(complete), sizeof_fmt(total)
)
)
progress.update_target(name, complete, total) | PYTHON | {
"dummy_field": ""
} |
|
d129 | train | def now(self):
"""
Return a :py:class:`datetime.datetime` instance representing the current time.
:rtype: :py:class:`datetime.datetime`
"""
if self.use_utc:
return datetime.datetime.utcnow()
else:
return datetime.datetime.now() | PYTHON | {
"dummy_field": ""
} |
|
d130 | train | def to_pascal_case(s):
"""Transform underscore separated string to pascal case
"""
return re.sub(r'(?!^)_([a-zA-Z])', lambda m: m.group(1).upper(), s.capitalize()) | PYTHON | {
"dummy_field": ""
} |
|
d131 | train | def now(self):
"""
Return a :py:class:`datetime.datetime` instance representing the current time.
:rtype: :py:class:`datetime.datetime`
"""
if self.use_utc:
return datetime.datetime.utcnow()
else:
return datetime.datetime.now() | PYTHON | {
"dummy_field": ""
} |
|
d132 | train | def _convert_date_to_dict(field_date):
"""
Convert native python ``datetime.date`` object to a format supported by the API
"""
return {DAY: field_date.day, MONTH: field_date.month, YEAR: field_date.year} | PYTHON | {
"dummy_field": ""
} |
|
d133 | train | def ToDatetime(self):
"""Converts Timestamp to datetime."""
return datetime.utcfromtimestamp(
self.seconds + self.nanos / float(_NANOS_PER_SECOND)) | PYTHON | {
"dummy_field": ""
} |
|
d134 | train | def convert_array(array):
"""
Converts an ARRAY string stored in the database back into a Numpy array.
Parameters
----------
array: ARRAY
The array object to be converted back into a Numpy array.
Returns
-------
array
The converted Numpy array.
"""
out = io.BytesIO(array)
out.seek(0)
return np.load(out) | PYTHON | {
"dummy_field": ""
} |
|
d135 | train | def parse_timestamp(timestamp):
"""Parse ISO8601 timestamps given by github API."""
dt = dateutil.parser.parse(timestamp)
return dt.astimezone(dateutil.tz.tzutc()) | PYTHON | {
"dummy_field": ""
} |
|
d136 | train | def add_to_js(self, name, var):
"""Add an object to Javascript."""
frame = self.page().mainFrame()
frame.addToJavaScriptWindowObject(name, var) | PYTHON | {
"dummy_field": ""
} |
|
d137 | train | def fromtimestamp(cls, timestamp):
"""Returns a datetime object of a given timestamp (in local tz)."""
d = cls.utcfromtimestamp(timestamp)
return d.astimezone(localtz()) | PYTHON | {
"dummy_field": ""
} |
|
d138 | train | def print_latex(o):
"""A function to generate the latex representation of sympy
expressions."""
if can_print_latex(o):
s = latex(o, mode='plain')
s = s.replace('\\dag','\\dagger')
s = s.strip('$')
return '$$%s$$' % s
# Fallback to the string printer
return None | PYTHON | {
"dummy_field": ""
} |
|
d139 | train | def datetime64_to_datetime(dt):
""" convert numpy's datetime64 to datetime """
dt64 = np.datetime64(dt)
ts = (dt64 - np.datetime64('1970-01-01T00:00:00')) / np.timedelta64(1, 's')
return datetime.datetime.utcfromtimestamp(ts) | PYTHON | {
"dummy_field": ""
} |
|
d140 | train | def batch_tensor(self, name):
""" A buffer of a given value in a 'flat' (minibatch-indexed) format """
if name in self.transition_tensors:
return tensor_util.merge_first_two_dims(self.transition_tensors[name])
else:
return self.rollout_tensors[name] | PYTHON | {
"dummy_field": ""
} |
|
d141 | train | def isInteractive():
"""
A basic check of if the program is running in interactive mode
"""
if sys.stdout.isatty() and os.name != 'nt':
#Hopefully everything but ms supports '\r'
try:
import threading
except ImportError:
return False
else:
return True
else:
return False | PYTHON | {
"dummy_field": ""
} |
|
d142 | train | def create_symlink(source, link_name):
"""
Creates symbolic link for either operating system.
http://stackoverflow.com/questions/6260149/os-symlink-support-in-windows
"""
os_symlink = getattr(os, "symlink", None)
if isinstance(os_symlink, collections.Callable):
os_symlink(source, link_name)
else:
import ctypes
csl = ctypes.windll.kernel32.CreateSymbolicLinkW
csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)
csl.restype = ctypes.c_ubyte
flags = 1 if os.path.isdir(source) else 0
if csl(link_name, source, flags) == 0:
raise ctypes.WinError() | PYTHON | {
"dummy_field": ""
} |
|
d143 | train | def export(defn):
"""Decorator to explicitly mark functions that are exposed in a lib."""
globals()[defn.__name__] = defn
__all__.append(defn.__name__)
return defn | PYTHON | {
"dummy_field": ""
} |
|
d144 | train | def parse(source, remove_comments=True, **kw):
"""Thin wrapper around ElementTree.parse"""
return ElementTree.parse(source, SourceLineParser(), **kw) | PYTHON | {
"dummy_field": ""
} |
|
d145 | train | def decorator(func):
r"""Makes the passed decorators to support optional args.
"""
def wrapper(__decorated__=None, *Args, **KwArgs):
if __decorated__ is None: # the decorator has some optional arguments.
return lambda _func: func(_func, *Args, **KwArgs)
else:
return func(__decorated__, *Args, **KwArgs)
return wrap(wrapper, func) | PYTHON | {
"dummy_field": ""
} |
|
d146 | train | def show_image(self, key):
"""Show image (item is a PIL image)"""
data = self.model.get_data()
data[key].show() | PYTHON | {
"dummy_field": ""
} |
|
d147 | train | def get_default_args(func):
"""
returns a dictionary of arg_name:default_values for the input function
"""
args, varargs, keywords, defaults = getargspec_no_self(func)
return dict(zip(args[-len(defaults):], defaults)) | PYTHON | {
"dummy_field": ""
} |
|
d148 | train | def _interval_to_bound_points(array):
"""
Helper function which returns an array
with the Intervals' boundaries.
"""
array_boundaries = np.array([x.left for x in array])
array_boundaries = np.concatenate(
(array_boundaries, np.array([array[-1].right])))
return array_boundaries | PYTHON | {
"dummy_field": ""
} |
|
d149 | train | def closing_plugin(self, cancelable=False):
"""Perform actions before parent main window is closed"""
self.dialog_manager.close_all()
self.shell.exit_interpreter()
return True | PYTHON | {
"dummy_field": ""
} |
|
d150 | train | def test():
"""Local test."""
from spyder.utils.qthelpers import qapplication
app = qapplication()
dlg = ProjectDialog(None)
dlg.show()
sys.exit(app.exec_()) | PYTHON | {
"dummy_field": ""
} |
|
d151 | train | def del_label(self, name):
"""Delete a label by name."""
labels_tag = self.root[0]
labels_tag.remove(self._find_label(name)) | PYTHON | {
"dummy_field": ""
} |
|
d152 | train | def mixedcase(path):
"""Removes underscores and capitalizes the neighbouring character"""
words = path.split('_')
return words[0] + ''.join(word.title() for word in words[1:]) | PYTHON | {
"dummy_field": ""
} |
|
d153 | train | def delete_all_eggs(self):
""" delete all the eggs in the directory specified """
path_to_delete = os.path.join(self.egg_directory, "lib", "python")
if os.path.exists(path_to_delete):
shutil.rmtree(path_to_delete) | PYTHON | {
"dummy_field": ""
} |
|
d154 | train | def get_system_cpu_times():
"""Return system CPU times as a namedtuple."""
user, nice, system, idle = _psutil_osx.get_system_cpu_times()
return _cputimes_ntuple(user, nice, system, idle) | PYTHON | {
"dummy_field": ""
} |
|
d155 | train | def remove(self, document_id, namespace, timestamp):
"""Removes documents from Solr
The input is a python dictionary that represents a mongo document.
"""
self.solr.delete(id=u(document_id),
commit=(self.auto_commit_interval == 0)) | PYTHON | {
"dummy_field": ""
} |
|
d156 | train | def update_hash_from_str(hsh, str_input):
"""
Convert a str to object supporting buffer API and update a hash with it.
"""
byte_input = str(str_input).encode("UTF-8")
hsh.update(byte_input) | PYTHON | {
"dummy_field": ""
} |
|
d157 | train | def make_regex(separator):
"""Utility function to create regexp for matching escaped separators
in strings.
"""
return re.compile(r'(?:' + re.escape(separator) + r')?((?:[^' +
re.escape(separator) + r'\\]|\\.)+)') | PYTHON | {
"dummy_field": ""
} |
|
d158 | train | def dictify(a_named_tuple):
"""Transform a named tuple into a dictionary"""
return dict((s, getattr(a_named_tuple, s)) for s in a_named_tuple._fields) | PYTHON | {
"dummy_field": ""
} |
|
d159 | train | def _py2_and_3_joiner(sep, joinable):
"""
Allow '\n'.join(...) statements to work in Py2 and Py3.
:param sep:
:param joinable:
:return:
"""
if ISPY3:
sep = bytes(sep, DEFAULT_ENCODING)
joined = sep.join(joinable)
return joined.decode(DEFAULT_ENCODING) if ISPY3 else joined | PYTHON | {
"dummy_field": ""
} |
|
d160 | train | def c_str(string):
""""Convert a python string to C string."""
if not isinstance(string, str):
string = string.decode('ascii')
return ctypes.c_char_p(string.encode('utf-8')) | PYTHON | {
"dummy_field": ""
} |
|
d161 | train | def endline_semicolon_check(self, original, loc, tokens):
"""Check for semicolons at the end of lines."""
return self.check_strict("semicolon at end of line", original, loc, tokens) | PYTHON | {
"dummy_field": ""
} |
|
d162 | train | def _datetime_to_date(arg):
"""
convert datetime/str to date
:param arg:
:return:
"""
_arg = parse(arg)
if isinstance(_arg, datetime.datetime):
_arg = _arg.date()
return _arg | PYTHON | {
"dummy_field": ""
} |
|
d163 | train | def get(self):
"""Get the highest priority Processing Block from the queue."""
with self._mutex:
entry = self._queue.pop()
del self._block_map[entry[2]]
return entry[2] | PYTHON | {
"dummy_field": ""
} |
|
d164 | train | def center_text(text, width=80):
"""Center all lines of the text.
It is assumed that all lines width is smaller then B{width}, because the
line width will not be checked.
Args:
text (str): Text to wrap.
width (int): Maximum number of characters per line.
Returns:
str: Centered text.
"""
centered = []
for line in text.splitlines():
centered.append(line.center(width))
return "\n".join(centered) | PYTHON | {
"dummy_field": ""
} |
|
d165 | train | def from_json(cls, json_str):
"""Deserialize the object from a JSON string."""
d = json.loads(json_str)
return cls.from_dict(d) | PYTHON | {
"dummy_field": ""
} |
|
d166 | train | def update(kernel=False):
"""
Upgrade all packages, skip obsoletes if ``obsoletes=0`` in ``yum.conf``.
Exclude *kernel* upgrades by default.
"""
manager = MANAGER
cmds = {'yum -y --color=never': {False: '--exclude=kernel* update', True: 'update'}}
cmd = cmds[manager][kernel]
run_as_root("%(manager)s %(cmd)s" % locals()) | PYTHON | {
"dummy_field": ""
} |
|
d167 | train | def guess_encoding(text, default=DEFAULT_ENCODING):
"""Guess string encoding.
Given a piece of text, apply character encoding detection to
guess the appropriate encoding of the text.
"""
result = chardet.detect(text)
return normalize_result(result, default=default) | PYTHON | {
"dummy_field": ""
} |
|
d168 | train | def commajoin_as_strings(iterable):
""" Join the given iterable with ',' """
return _(u',').join((six.text_type(i) for i in iterable)) | PYTHON | {
"dummy_field": ""
} |
|
d169 | train | def supports_color():
"""
Returns True if the running system's terminal supports color, and False
otherwise.
"""
unsupported_platform = (sys.platform in ('win32', 'Pocket PC'))
# isatty is not always implemented, #6223.
is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()
if unsupported_platform or not is_a_tty:
return False
return True | PYTHON | {
"dummy_field": ""
} |
|
d170 | train | def seconds_to_hms(seconds):
"""
Converts seconds float to 'hh:mm:ss.ssssss' format.
"""
hours = int(seconds / 3600.0)
minutes = int((seconds / 60.0) % 60.0)
secs = float(seconds % 60.0)
return "{0:02d}:{1:02d}:{2:02.6f}".format(hours, minutes, secs) | PYTHON | {
"dummy_field": ""
} |
|
d171 | train | def __contains__(self, key):
"""
Invoked when determining whether a specific key is in the dictionary
using `key in d`.
The key is looked up case-insensitively.
"""
k = self._real_key(key)
return k in self._data | PYTHON | {
"dummy_field": ""
} |
|
d172 | train | def get_truetype(value):
"""Convert a string to a pythonized parameter."""
if value in ["true", "True", "y", "Y", "yes"]:
return True
if value in ["false", "False", "n", "N", "no"]:
return False
if value.isdigit():
return int(value)
return str(value) | PYTHON | {
"dummy_field": ""
} |
|
d173 | train | def Serializable(o):
"""Make sure an object is JSON-serializable
Use this to return errors and other info that does not need to be
deserialized or does not contain important app data. Best for returning
error info and such"""
if isinstance(o, (str, dict, int)):
return o
else:
try:
json.dumps(o)
return o
except Exception:
LOG.debug("Got a non-serilizeable object: %s" % o)
return o.__repr__() | PYTHON | {
"dummy_field": ""
} |
|
d174 | train | def timed_rotating_file_handler(name, logname, filename, when='h',
interval=1, backupCount=0,
encoding=None, delay=False, utc=False):
"""
A Bark logging handler logging output to a named file. At
intervals specified by the 'when', the file will be rotated, under
control of 'backupCount'.
Similar to logging.handlers.TimedRotatingFileHandler.
"""
return wrap_log_handler(logging.handlers.TimedRotatingFileHandler(
filename, when=when, interval=interval, backupCount=backupCount,
encoding=encoding, delay=delay, utc=utc)) | PYTHON | {
"dummy_field": ""
} |
|
d175 | train | def is_identifier(string):
"""Check if string could be a valid python identifier
:param string: string to be tested
:returns: True if string can be a python identifier, False otherwise
:rtype: bool
"""
matched = PYTHON_IDENTIFIER_RE.match(string)
return bool(matched) and not keyword.iskeyword(string) | PYTHON | {
"dummy_field": ""
} |
|
d176 | train | def uniform_iterator(sequence):
"""Uniform (key, value) iteration on a `dict`,
or (idx, value) on a `list`."""
if isinstance(sequence, abc.Mapping):
return six.iteritems(sequence)
else:
return enumerate(sequence) | PYTHON | {
"dummy_field": ""
} |
|
d177 | train | def _guess_type(val):
"""Guess the input type of the parameter based off the default value, if unknown use text"""
if isinstance(val, bool):
return "choice"
elif isinstance(val, int):
return "number"
elif isinstance(val, float):
return "number"
elif isinstance(val, str):
return "text"
elif hasattr(val, 'read'):
return "file"
else:
return "text" | PYTHON | {
"dummy_field": ""
} |
|
d178 | train | def _to_corrected_pandas_type(dt):
"""
When converting Spark SQL records to Pandas DataFrame, the inferred data type may be wrong.
This method gets the corrected data type for Pandas if that type may be inferred uncorrectly.
"""
import numpy as np
if type(dt) == ByteType:
return np.int8
elif type(dt) == ShortType:
return np.int16
elif type(dt) == IntegerType:
return np.int32
elif type(dt) == FloatType:
return np.float32
else:
return None | PYTHON | {
"dummy_field": ""
} |
|
d179 | train | def _platform_is_windows(platform=sys.platform):
"""Is the current OS a Windows?"""
matched = platform in ('cygwin', 'win32', 'win64')
if matched:
error_msg = "Windows isn't supported yet"
raise OSError(error_msg)
return matched | PYTHON | {
"dummy_field": ""
} |
|
d180 | train | def _xls2col_widths(self, worksheet, tab):
"""Updates col_widths in code_array"""
for col in xrange(worksheet.ncols):
try:
xls_width = worksheet.colinfo_map[col].width
pys_width = self.xls_width2pys_width(xls_width)
self.code_array.col_widths[col, tab] = pys_width
except KeyError:
pass | PYTHON | {
"dummy_field": ""
} |
|
d181 | train | def keys_to_snake_case(camel_case_dict):
"""
Make a copy of a dictionary with all keys converted to snake case. This is just calls to_snake_case on
each of the keys in the dictionary and returns a new dictionary.
:param camel_case_dict: Dictionary with the keys to convert.
:type camel_case_dict: Dictionary.
:return: Dictionary with the keys converted to snake case.
"""
return dict((to_snake_case(key), value) for (key, value) in camel_case_dict.items()) | PYTHON | {
"dummy_field": ""
} |
|
d182 | train | def _bytes_to_json(value):
"""Coerce 'value' to an JSON-compatible representation."""
if isinstance(value, bytes):
value = base64.standard_b64encode(value).decode("ascii")
return value | PYTHON | {
"dummy_field": ""
} |
|
d183 | train | def dict_hash(dct):
"""Return a hash of the contents of a dictionary"""
dct_s = json.dumps(dct, sort_keys=True)
try:
m = md5(dct_s)
except TypeError:
m = md5(dct_s.encode())
return m.hexdigest() | PYTHON | {
"dummy_field": ""
} |
|
d184 | train | def int_to_date(date):
"""
Convert an int of form yyyymmdd to a python date object.
"""
year = date // 10**4
month = date % 10**4 // 10**2
day = date % 10**2
return datetime.date(year, month, day) | PYTHON | {
"dummy_field": ""
} |
|
d185 | train | def filter_dict(d, keys):
"""
Creates a new dict from an existing dict that only has the given keys
"""
return {k: v for k, v in d.items() if k in keys} | PYTHON | {
"dummy_field": ""
} |
|
d186 | train | def hasattrs(object, *names):
"""
Takes in an object and a variable length amount of named attributes,
and checks to see if the object has each property. If any of the
attributes are missing, this returns false.
:param object: an object that may or may not contain the listed attributes
:param names: a variable amount of attribute names to check for
:return: True if the object contains each named attribute, false otherwise
"""
for name in names:
if not hasattr(object, name):
return False
return True | PYTHON | {
"dummy_field": ""
} |
|
d187 | train | def dict_update_newkeys(dict_, dict2):
""" Like dict.update, but does not overwrite items """
for key, val in six.iteritems(dict2):
if key not in dict_:
dict_[key] = val | PYTHON | {
"dummy_field": ""
} |
|
d188 | train | def numpy_aware_eq(a, b):
"""Return whether two objects are equal via recursion, using
:func:`numpy.array_equal` for comparing numpy arays.
"""
if isinstance(a, np.ndarray) or isinstance(b, np.ndarray):
return np.array_equal(a, b)
if ((isinstance(a, Iterable) and isinstance(b, Iterable)) and
not isinstance(a, str) and not isinstance(b, str)):
if len(a) != len(b):
return False
return all(numpy_aware_eq(x, y) for x, y in zip(a, b))
return a == b | PYTHON | {
"dummy_field": ""
} |
|
d189 | train | def update(self, other_dict):
"""update() extends rather than replaces existing key lists."""
for key, value in iter_multi_items(other_dict):
MultiDict.add(self, key, value) | PYTHON | {
"dummy_field": ""
} |
|
d190 | train | def _internet_on(address):
"""
Check to see if the internet is on by pinging a set address.
:param address: the IP or address to hit
:return: a boolean - true if can be reached, false if not.
"""
try:
urllib2.urlopen(address, timeout=1)
return True
except urllib2.URLError as err:
return False | PYTHON | {
"dummy_field": ""
} |
|
d191 | train | def _defaultdict(dct, fallback=_illegal_character):
"""Wraps the given dictionary such that the given fallback function will be called when a nonexistent key is
accessed.
"""
out = defaultdict(lambda: fallback)
for k, v in six.iteritems(dct):
out[k] = v
return out | PYTHON | {
"dummy_field": ""
} |
|
d192 | train | def is_json_file(filename, show_warnings = False):
"""Check configuration file type is JSON
Return a boolean indicating wheather the file is JSON format or not
"""
try:
config_dict = load_config(filename, file_type = "json")
is_json = True
except:
is_json = False
return(is_json) | PYTHON | {
"dummy_field": ""
} |
|
d193 | train | def _remove_dict_keys_with_value(dict_, val):
"""Removes `dict` keys which have have `self` as value."""
return {k: v for k, v in dict_.items() if v is not val} | PYTHON | {
"dummy_field": ""
} |
|
d194 | train | def post_commit_hook(argv):
"""Hook: for checking commit message."""
_, stdout, _ = run("git log -1 --format=%B HEAD")
message = "\n".join(stdout)
options = {"allow_empty": True}
if not _check_message(message, options):
click.echo(
"Commit message errors (fix with 'git commit --amend').",
file=sys.stderr)
return 1 # it should not fail with exit
return 0 | PYTHON | {
"dummy_field": ""
} |
|
d195 | train | def setdefaults(dct, defaults):
"""Given a target dct and a dict of {key:default value} pairs,
calls setdefault for all of those pairs."""
for key in defaults:
dct.setdefault(key, defaults[key])
return dct | PYTHON | {
"dummy_field": ""
} |
|
d196 | train | def is_image_file_valid(file_path_name):
"""
Indicate whether the specified image file is valid or not.
@param file_path_name: absolute path and file name of an image.
@return: ``True`` if the image file is valid, ``False`` if the file is
truncated or does not correspond to a supported image.
"""
# Image.verify is only implemented for PNG images, and it only verifies
# the CRC checksum in the image. The only way to check from within
# Pillow is to load the image in a try/except and check the error. If
# as much info as possible is from the image is needed,
# ``ImageFile.LOAD_TRUNCATED_IMAGES=True`` needs to bet set and it
# will attempt to parse as much as possible.
try:
with Image.open(file_path_name) as image:
image.load()
except IOError:
return False
return True | PYTHON | {
"dummy_field": ""
} |
|
d197 | train | def dict_to_html_attrs(dict_):
"""
Banana banana
"""
res = ' '.join('%s="%s"' % (k, v) for k, v in dict_.items())
return res | PYTHON | {
"dummy_field": ""
} |
|
d198 | train | def is_binary(filename):
""" Returns True if the file is binary
"""
with open(filename, 'rb') as fp:
data = fp.read(1024)
if not data:
return False
if b'\0' in data:
return True
return False | PYTHON | {
"dummy_field": ""
} |
|
d199 | 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": ""
} |
|
d200 | 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": ""
} |