Dataset Viewer
_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 87
6.4k
| title
stringclasses 1
value | language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
d1
|
train
|
def writeBoolean(self, n):
"""
Writes a Boolean to the stream.
"""
t = TYPE_BOOL_TRUE
if n is False:
t = TYPE_BOOL_FALSE
self.stream.write(t)
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d2
|
train
|
def paste(xsel=False):
"""Returns system clipboard contents."""
selection = "primary" if xsel else "clipboard"
try:
return subprocess.Popen(["xclip", "-selection", selection, "-o"], stdout=subprocess.PIPE).communicate()[0].decode("utf-8")
except OSError as why:
raise XclipNotFound
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d4
|
train
|
def create_path(path):
"""Creates a absolute path in the file system.
:param path: The path to be created
"""
import os
if not os.path.exists(path):
os.makedirs(path)
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d5
|
train
|
def _vector_or_scalar(x, type='row'):
"""Convert an object to either a scalar or a row or column vector."""
if isinstance(x, (list, tuple)):
x = np.array(x)
if isinstance(x, np.ndarray):
assert x.ndim == 1
if type == 'column':
x = x[:, None]
return x
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d6
|
train
|
def experiment_property(prop):
"""Get a property of the experiment by name."""
exp = experiment(session)
p = getattr(exp, prop)
return success_response(field=prop, data=p, request_type=prop)
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d10
|
train
|
def _convert_to_array(array_like, dtype):
"""
Convert Matrix attributes which are array-like or buffer to array.
"""
if isinstance(array_like, bytes):
return np.frombuffer(array_like, dtype=dtype)
return np.asarray(array_like, dtype=dtype)
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d13
|
train
|
def _array2cstr(arr):
""" Serializes a numpy array to a compressed base64 string """
out = StringIO()
np.save(out, arr)
return b64encode(out.getvalue())
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d15
|
train
|
def _string_hash(s):
"""String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`)."""
h = 5381
for c in s:
h = h * 33 + ord(c)
return h
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d16
|
train
|
def transform_from_rot_trans(R, t):
"""Transforation matrix from rotation matrix and translation vector."""
R = R.reshape(3, 3)
t = t.reshape(3, 1)
return np.vstack((np.hstack([R, t]), [0, 0, 0, 1]))
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d18
|
train
|
def transform_to_3d(points,normal,z=0):
"""Project points into 3d from 2d points."""
d = np.cross(normal, (0, 0, 1))
M = rotation_matrix(d)
transformed_points = M.dot(points.T).T + z
return transformed_points
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d22
|
train
|
def mag(z):
"""Get the magnitude of a vector."""
if isinstance(z[0], np.ndarray):
return np.array(list(map(np.linalg.norm, z)))
else:
return np.linalg.norm(z)
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d23
|
train
|
def config_parser_to_dict(config_parser):
"""
Convert a ConfigParser to a dictionary.
"""
response = {}
for section in config_parser.sections():
for option in config_parser.options(section):
response.setdefault(section, {})[option] = config_parser.get(section, option)
return response
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d24
|
train
|
def __add__(self, other):
"""Handle the `+` operator."""
return self._handle_type(other)(self.value + other.value)
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d25
|
train
|
def connect_mysql(host, port, user, password, database):
"""Connect to MySQL with retries."""
return pymysql.connect(
host=host, port=port,
user=user, passwd=password,
db=database
)
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d26
|
train
|
def get_column(self, X, column):
"""Return a column of the given matrix.
Args:
X: `numpy.ndarray` or `pandas.DataFrame`.
column: `int` or `str`.
Returns:
np.ndarray: Selected column.
"""
if isinstance(X, pd.DataFrame):
return X[column].values
return X[:, column]
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d27
|
train
|
def connect(url, username, password):
"""
Return a connected Bitbucket session
"""
bb_session = stashy.connect(url, username, password)
logger.info('Connected to: %s as %s', url, username)
return bb_session
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d28
|
train
|
def add_blank_row(self, label):
"""
Add a blank row with only an index value to self.df.
This is done inplace.
"""
col_labels = self.df.columns
blank_item = pd.Series({}, index=col_labels, name=label)
# use .loc to add in place (append won't do that)
self.df.loc[blank_item.name] = blank_item
return self.df
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d29
|
train
|
def teardown(self):
"""
Stop and remove the container if it exists.
"""
while self._http_clients:
self._http_clients.pop().close()
if self.created:
self.halt()
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d34
|
train
|
def serialize(obj):
"""Takes a object and produces a dict-like representation
:param obj: the object to serialize
"""
if isinstance(obj, list):
return [serialize(o) for o in obj]
return GenericSerializer(ModelProviderImpl()).serialize(obj)
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d35
|
train
|
def advance_one_line(self):
"""Advances to next line."""
current_line = self._current_token.line_number
while current_line == self._current_token.line_number:
self._current_token = ConfigParser.Token(*next(self._token_generator))
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d37
|
train
|
def do_next(self, args):
"""Step over the next statement
"""
self._do_print_from_last_cmd = True
self._interp.step_over()
return True
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d39
|
train
|
def get_line_flux(line_wave, wave, flux, **kwargs):
"""Interpolated flux at a given wavelength (calls np.interp)."""
return np.interp(line_wave, wave, flux, **kwargs)
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d41
|
train
|
def get_number(s, cast=int):
"""
Try to get a number out of a string, and cast it.
"""
import string
d = "".join(x for x in str(s) if x in string.digits)
return cast(d)
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d45
|
train
|
def populate_obj(obj, attrs):
"""Populates an object's attributes using the provided dict
"""
for k, v in attrs.iteritems():
setattr(obj, k, v)
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d46
|
train
|
def wordfreq(text, is_filename=False):
"""Return a dictionary of words and word counts in a string."""
if is_filename:
with open(text) as f:
text = f.read()
freqs = {}
for word in text.split():
lword = word.lower()
freqs[lword] = freqs.get(lword, 0) + 1
return freqs
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d47
|
train
|
def copyFile(input, output, replace=None):
"""Copy a file whole from input to output."""
_found = findFile(output)
if not _found or (_found and replace):
shutil.copy2(input, output)
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d48
|
train
|
def push(h, x):
"""Push a new value into heap."""
h.push(x)
up(h, h.size()-1)
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d50
|
train
|
def filter_contour(imageFile, opFile):
""" convert an image by applying a contour """
im = Image.open(imageFile)
im1 = im.filter(ImageFilter.CONTOUR)
im1.save(opFile)
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d51
|
train
|
def count(lines):
""" Counts the word frequences in a list of sentences.
Note:
This is a helper function for parallel execution of `Vocabulary.from_text`
method.
"""
words = [w for l in lines for w in l.strip().split()]
return Counter(words)
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d54
|
train
|
def visit_Name(self, node):
""" Get range for parameters for examples or false branching. """
return self.add(node, self.result[node.id])
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d55
|
train
|
def mkdir(dir, enter):
"""Create directory with template for topic of the current environment
"""
if not os.path.exists(dir):
os.makedirs(dir)
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d56
|
train
|
def qrot(vector, quaternion):
"""Rotate a 3D vector using quaternion algebra.
Implemented by Vladimir Kulikovskiy.
Parameters
----------
vector: np.array
quaternion: np.array
Returns
-------
np.array
"""
t = 2 * np.cross(quaternion[1:], vector)
v_rot = vector + quaternion[0] * t + np.cross(quaternion[1:], t)
return v_rot
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d57
|
train
|
def _numpy_char_to_bytes(arr):
"""Like netCDF4.chartostring, but faster and more flexible.
"""
# based on: http://stackoverflow.com/a/10984878/809705
arr = np.array(arr, copy=False, order='C')
dtype = 'S' + str(arr.shape[-1])
return arr.view(dtype).reshape(arr.shape[:-1])
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d60
|
train
|
def get_tri_area(pts):
"""
Given a list of coords for 3 points,
Compute the area of this triangle.
Args:
pts: [a, b, c] three points
"""
a, b, c = pts[0], pts[1], pts[2]
v1 = np.array(b) - np.array(a)
v2 = np.array(c) - np.array(a)
area_tri = abs(sp.linalg.norm(sp.cross(v1, v2)) / 2)
return area_tri
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d62
|
train
|
def round_to_int(number, precision):
"""Round a number to a precision"""
precision = int(precision)
rounded = (int(number) + precision / 2) // precision * precision
return rounded
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d66
|
train
|
def string_input(prompt=''):
"""Python 3 input()/Python 2 raw_input()"""
v = sys.version[0]
if v == '3':
return input(prompt)
else:
return raw_input(prompt)
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d69
|
train
|
def _display(self, layout):
"""launch layouts display"""
print(file=self.out)
TextWriter().format(layout, self.out)
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d70
|
train
|
def assert_list(self, putative_list, expected_type=string_types, key_arg=None):
"""
:API: public
"""
return assert_list(putative_list, expected_type, key_arg=key_arg,
raise_type=lambda msg: TargetDefinitionException(self, msg))
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d72
|
train
|
def assert_exactly_one_true(bool_list):
"""This method asserts that only one value of the provided list is True.
:param bool_list: List of booleans to check
:return: True if only one value is True, False otherwise
"""
assert isinstance(bool_list, list)
counter = 0
for item in bool_list:
if item:
counter += 1
return counter == 1
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d78
|
train
|
def exit(exit_code=0):
r"""A function to support exiting from exit hooks.
Could also be used to exit from the calling scripts in a thread safe manner.
"""
core.processExitHooks()
if state.isExitHooked and not hasattr(sys, 'exitfunc'): # The function is called from the exit hook
sys.stderr.flush()
sys.stdout.flush()
os._exit(exit_code) #pylint: disable=W0212
sys.exit(exit_code)
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d80
|
train
|
def reloader_thread(softexit=False):
"""If ``soft_exit`` is True, we use sys.exit(); otherwise ``os_exit``
will be used to end the process.
"""
while RUN_RELOADER:
if code_changed():
# force reload
if softexit:
sys.exit(3)
else:
os._exit(3)
time.sleep(1)
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d86
|
train
|
def loganalytics_data_plane_client(cli_ctx, _):
"""Initialize Log Analytics data client for use with CLI."""
from .vendored_sdks.loganalytics import LogAnalyticsDataClient
from azure.cli.core._profile import Profile
profile = Profile(cli_ctx=cli_ctx)
cred, _, _ = profile.get_login_credentials(
resource="https://api.loganalytics.io")
return LogAnalyticsDataClient(cred)
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d90
|
train
|
def get_stoplist(language):
"""Returns an built-in stop-list for the language as a set of words."""
file_path = os.path.join("stoplists", "%s.txt" % language)
try:
stopwords = pkgutil.get_data("justext", file_path)
except IOError:
raise ValueError(
"Stoplist for language '%s' is missing. "
"Please use function 'get_stoplists' for complete list of stoplists "
"and feel free to contribute by your own stoplist." % language
)
return frozenset(w.decode("utf8").lower() for w in stopwords.splitlines())
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d91
|
train
|
def add_str(window, line_num, str):
""" attempt to draw str on screen and ignore errors if they occur """
try:
window.addstr(line_num, 0, str)
except curses.error:
pass
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d93
|
train
|
def dictfetchall(cursor):
"""Returns all rows from a cursor as a dict (rather than a headerless table)
From Django Documentation: https://docs.djangoproject.com/en/dev/topics/db/sql/
"""
desc = cursor.description
return [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()]
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d94
|
train
|
def xmltreefromfile(filename):
"""Internal function to read an XML file"""
try:
return ElementTree.parse(filename, ElementTree.XMLParser(collect_ids=False))
except TypeError:
return ElementTree.parse(filename, ElementTree.XMLParser())
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d96
|
train
|
def beta_pdf(x, a, b):
"""Beta distirbution probability density function."""
bc = 1 / beta(a, b)
fc = x ** (a - 1)
sc = (1 - x) ** (b - 1)
return bc * fc * sc
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d97
|
train
|
def filter_out(queryset, setting_name):
"""
Remove unwanted results from queryset
"""
kwargs = helpers.get_settings().get(setting_name, {}).get('FILTER_OUT', {})
queryset = queryset.exclude(**kwargs)
return queryset
|
PYTHON
|
{
"dummy_field": ""
}
|
|
d99
|
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": ""
}
|
|
d100
|
train
|
def table_top_abs(self):
"""Returns the absolute position of table top"""
table_height = np.array([0, 0, self.table_full_size[2]])
return string_to_array(self.floor.get("pos")) + table_height
|
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": ""
}
|
|
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": ""
}
|
|
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": ""
}
|
|
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": ""
}
|
|
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": ""
}
|
|
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": ""
}
|
|
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": ""
}
|
|
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": ""
}
|
|
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": ""
}
|
|
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": ""
}
|
|
d133
|
train
|
def ToDatetime(self):
"""Converts Timestamp to datetime."""
return datetime.utcfromtimestamp(
self.seconds + self.nanos / float(_NANOS_PER_SECOND))
|
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": ""
}
|
|
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": ""
}
|
|
d144
|
train
|
def parse(source, remove_comments=True, **kw):
"""Thin wrapper around ElementTree.parse"""
return ElementTree.parse(source, SourceLineParser(), **kw)
|
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": ""
}
|
|
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": ""
}
|
|
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": ""
}
|
|
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": ""
}
|
|
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": ""
}
|
|
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": ""
}
|
|
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": ""
}
|
|
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": ""
}
|
|
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": ""
}
|
|
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": ""
}
|
|
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": ""
}
|
|
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": ""
}
|
|
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": ""
}
|
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 17