function stringlengths 11 56k | repo_name stringlengths 5 60 | features list |
|---|---|---|
def testMakeBatchedFeaturesDataset(self):
files = 2
records_per_file = 5
def make_record(file_index):
example = example_pb2.Example(
features=feature_pb2.Features(
feature={
"file":
feature_pb2.Feature(
int64_li... | tensorflow/tensorflow | [
171949,
87931,
171949,
2300,
1446859160
] |
def testHintShardingValidPattern(self):
options = options_lib.Options()
options.experimental_distribute.auto_shard_policy = (
options_lib.AutoShardPolicy.HINT)
dataset = dataset_ops.Dataset.range(100).shard(distribute.SHARD_HINT, 0)
dataset = dataset.with_options(options)
dataset = distribu... | tensorflow/tensorflow | [
171949,
87931,
171949,
2300,
1446859160
] |
def testHintShardingInvalidPattern(self):
options = options_lib.Options()
options.experimental_distribute.auto_shard_policy = (
options_lib.AutoShardPolicy.HINT)
dataset = dataset_ops.Dataset.range(100).shard(1, 0)
dataset = dataset.with_options(options)
dataset = distribute._AutoShardDatas... | tensorflow/tensorflow | [
171949,
87931,
171949,
2300,
1446859160
] |
def testEnumerateAutoShardPolicies(self, auto_shard_policy):
"""Verifies tf.data handles every auto-shard policy with no errors."""
dataset = dataset_ops.Dataset.list_files(self._filenames, shuffle=False)
dataset = dataset.flat_map(core_readers.TFRecordDataset)
dataset = dataset.batch(5)
options = o... | tensorflow/tensorflow | [
171949,
87931,
171949,
2300,
1446859160
] |
def _setUpFiles(self, num_files, num_records_per_file):
self._num_files = num_files
self._num_records = num_records_per_file
self._filenames = self._createFiles() | tensorflow/tensorflow | [
171949,
87931,
171949,
2300,
1446859160
] |
def testFileShardingWithLegacyRebatch(self):
# Tests that RebatchDatasetV1 is a passthrough op.
self._setUpFiles(num_files=5, num_records_per_file=10)
dataset = dataset_ops.Dataset.list_files(self._filenames, shuffle=False)
dataset = dataset.apply(
testing.assert_next(["Shard", "FlatMap", "Batch... | tensorflow/tensorflow | [
171949,
87931,
171949,
2300,
1446859160
] |
def testFileShardingWithRebatch(self):
# Tests that RebatchDatasetV2 is a passthrough op.
self._setUpFiles(num_files=3, num_records_per_file=5)
dataset = dataset_ops.Dataset.list_files(self._filenames, shuffle=False)
dataset = dataset.apply(
testing.assert_next(["Shard", "FlatMap", "Batch", "Reb... | tensorflow/tensorflow | [
171949,
87931,
171949,
2300,
1446859160
] |
def testUseLegacyRebatchWithDataSharding(self, sharding_policy,
with_prefetch):
# This test simulates a distributed environment with 3 workers, each with
# 1 replica.
dataset = dataset_ops.Dataset.range(8)
dataset = dataset.batch(4)
options = options_lib.Op... | tensorflow/tensorflow | [
171949,
87931,
171949,
2300,
1446859160
] |
def setUp(self):
super(AutoShardDatasetCheckpointTest, self).setUp()
self._num_files = 10
self._num_records = 10
self._filenames = self._createFiles() | tensorflow/tensorflow | [
171949,
87931,
171949,
2300,
1446859160
] |
def test(self, verify_fn):
def build_dataset():
dataset = dataset_ops.Dataset.list_files(self._filenames, shuffle=False)
dataset = dataset.apply(
interleave_ops.parallel_interleave(core_readers.TFRecordDataset, 10))
dataset = distribute._AutoShardDataset(dataset, 5, 3)
return data... | tensorflow/tensorflow | [
171949,
87931,
171949,
2300,
1446859160
] |
def setUp(self):
"""Create a user and log in. """
super(SupportViewTestCase, self).setUp()
self.user = UserFactory(username=self.USERNAME, email=self.EMAIL, password=self.PASSWORD)
self.course = CourseFactory.create()
success = self.client.login(username=self.USERNAME, password=s... | Stanford-Online/edx-platform | [
41,
19,
41,
1,
1374606346
] |
def setUp(self):
"""Make the user support staff"""
super(SupportViewManageUserTests, self).setUp()
SupportStaffRole().add_users(self.user) | Stanford-Online/edx-platform | [
41,
19,
41,
1,
1374606346
] |
def test_get_form_with_user_info(self):
"""
Tests Support View to return Manage User Form
with user info
"""
url = reverse('support:manage_user_detail') + self.user.username
response = self.client.get(url)
data = json.loads(response.content)
self.assertEqu... | Stanford-Online/edx-platform | [
41,
19,
41,
1,
1374606346
] |
def test_access(self, url_name, role, has_access):
if role is not None:
role().add_users(self.user)
url = reverse(url_name)
response = self.client.get(url)
if has_access:
self.assertEqual(response.status_code, 200)
else:
self.assertEqual(resp... | Stanford-Online/edx-platform | [
41,
19,
41,
1,
1374606346
] |
def test_require_login(self, url_name):
url = reverse(url_name)
# Log out then try to retrieve the page
self.client.logout()
response = self.client.get(url)
# Expect a redirect to the login page
redirect_url = "{login_url}?next={original_url}".format(
login_... | Stanford-Online/edx-platform | [
41,
19,
41,
1,
1374606346
] |
def setUp(self):
"""Make the user support staff. """
super(SupportViewIndexTests, self).setUp()
SupportStaffRole().add_users(self.user) | Stanford-Online/edx-platform | [
41,
19,
41,
1,
1374606346
] |
def setUp(self):
"""Make the user support staff. """
super(SupportViewCertificatesTests, self).setUp()
SupportStaffRole().add_users(self.user) | Stanford-Online/edx-platform | [
41,
19,
41,
1,
1374606346
] |
def test_certificates_with_user_filter(self):
# Check that an initial filter is passed to the JavaScript client.
url = reverse("support:certificates") + "?user=student@example.com"
response = self.client.get(url)
self.assertContains(response, "userFilter: 'student@example.com'") | Stanford-Online/edx-platform | [
41,
19,
41,
1,
1374606346
] |
def setUp(self):
super(SupportViewEnrollmentsTests, self).setUp()
SupportStaffRole().add_users(self.user)
self.course = CourseFactory(display_name=u'teꜱᴛ')
self.student = UserFactory.create(username='student', email='test@example.com', password='test')
for mode in (
... | Stanford-Online/edx-platform | [
41,
19,
41,
1,
1374606346
] |
def test_get_enrollments(self, search_string_type):
url = reverse(
'support:enrollment_list',
kwargs={'username_or_email': getattr(self.student, search_string_type)}
)
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
data = json.... | Stanford-Online/edx-platform | [
41,
19,
41,
1,
1374606346
] |
def test_change_enrollment(self, search_string_type):
self.assertIsNone(ManualEnrollmentAudit.get_manual_enrollment_by_email(self.student.email))
url = reverse(
'support:enrollment_list',
kwargs={'username_or_email': getattr(self.student, search_string_type)}
)
re... | Stanford-Online/edx-platform | [
41,
19,
41,
1,
1374606346
] |
def test_change_enrollment_bad_data(self, data, error_message):
# `self` isn't available from within the DDT declaration, so
# assign the course ID here
if 'course_id' in data and data['course_id'] is None:
data['course_id'] = unicode(self.course.id) # pylint: disable=no-member
... | Stanford-Online/edx-platform | [
41,
19,
41,
1,
1374606346
] |
def test_update_enrollment_for_all_modes(self, new_mode):
""" Verify support can changed the enrollment to all available modes
except credit. """
self.assert_update_enrollment('username', new_mode) | Stanford-Online/edx-platform | [
41,
19,
41,
1,
1374606346
] |
def test_update_enrollment_for_ended_course(self, new_mode):
""" Verify support can changed the enrollment of archived course. """
self.set_course_end_date_and_expiry()
self.assert_update_enrollment('username', new_mode) | Stanford-Online/edx-platform | [
41,
19,
41,
1,
1374606346
] |
def test_get_enrollments_with_expired_mode(self, search_string_type):
""" Verify that page can get the all modes with archived course. """
self.set_course_end_date_and_expiry()
url = reverse(
'support:enrollment_list',
kwargs={'username_or_email': getattr(self.student, se... | Stanford-Online/edx-platform | [
41,
19,
41,
1,
1374606346
] |
def test_update_enrollments_with_expired_mode(self, search_string_type):
""" Verify that enrollment can be updated to verified mode. """
self.set_course_end_date_and_expiry()
self.assertIsNone(ManualEnrollmentAudit.get_manual_enrollment_by_email(self.student.email))
self.assert_update_en... | Stanford-Online/edx-platform | [
41,
19,
41,
1,
1374606346
] |
def assert_update_enrollment(self, search_string_type, new_mode):
""" Dry method to update the enrollment and assert response."""
self.assertIsNone(ManualEnrollmentAudit.get_manual_enrollment_by_email(self.student.email))
url = reverse(
'support:enrollment_list',
kwargs={... | Stanford-Online/edx-platform | [
41,
19,
41,
1,
1374606346
] |
def __init__(self, values, index, level=-1, value_columns=None):
self.is_categorical = None
if values.ndim == 1:
if isinstance(values, Categorical):
self.is_categorical = values
values = np.array(values)
values = values[:, np.newaxis]
self... | Vvucinic/Wander | [
1,
1,
1,
11,
1449375044
] |
def _make_selectors(self):
new_levels = self.new_index_levels
# make the mask
remaining_labels = self.sorted_labels[:-1]
level_sizes = [len(x) for x in new_levels]
comp_index, obs_ids = get_compressed_ids(remaining_labels, level_sizes)
ngroups = len(obs_ids)
co... | Vvucinic/Wander | [
1,
1,
1,
11,
1449375044
] |
def get_new_values(self):
values = self.values
# place the values
length, width = self.full_shape
stride = values.shape[1]
result_width = width * stride
result_shape = (length, result_width)
# if our mask is all True, then we can use our existing dtype
i... | Vvucinic/Wander | [
1,
1,
1,
11,
1449375044
] |
def get_new_index(self):
result_labels = [lab.take(self.compressor)
for lab in self.sorted_labels[:-1]]
# construct the new index
if len(self.new_index_levels) == 1:
lev, lab = self.new_index_levels[0], result_labels[0]
if (lab == -1).any():
... | Vvucinic/Wander | [
1,
1,
1,
11,
1449375044
] |
def pivot(self, index=None, columns=None, values=None):
"""
See DataFrame.pivot
"""
if values is None:
cols = [columns] if index is None else [index, columns]
append = index is None
indexed = self.set_index(cols, append=append)
return indexed.unstack(columns)
else:
... | Vvucinic/Wander | [
1,
1,
1,
11,
1449375044
] |
def _slow_pivot(index, columns, values):
"""
Produce 'pivot' table based on 3 columns of this DataFrame.
Uses unique values from index / columns and fills with values.
Parameters
----------
index : string or object
Column name to use to make new frame's index
columns : string or obj... | Vvucinic/Wander | [
1,
1,
1,
11,
1449375044
] |
def _unstack_frame(obj, level):
from pandas.core.internals import BlockManager, make_block
if obj._is_mixed_type:
unstacker = _Unstacker(np.empty(obj.shape, dtype=bool), # dummy
obj.index, level=level,
value_columns=obj.columns)
new... | Vvucinic/Wander | [
1,
1,
1,
11,
1449375044
] |
def stack(frame, level=-1, dropna=True):
"""
Convert DataFrame to Series with multi-level Index. Columns become the
second level of the resulting hierarchical index
Returns
-------
stacked : Series
"""
def factorize(index):
if index.is_unique:
return index, np.arange... | Vvucinic/Wander | [
1,
1,
1,
11,
1449375044
] |
def _stack_multi_columns(frame, level_num=-1, dropna=True):
def _convert_level_number(level_num, columns):
"""
Logic for converting the level number to something
we can safely pass to swaplevel:
We generally want to convert the level number into
a level name, except when col... | Vvucinic/Wander | [
1,
1,
1,
11,
1449375044
] |
def lreshape(data, groups, dropna=True, label=None):
"""
Reshape long-format data to wide. Generalized inverse of DataFrame.pivot
Parameters
----------
data : DataFrame
groups : dict
{new_name : list_of_columns}
dropna : boolean, default True
Examples
--------
>>> impor... | Vvucinic/Wander | [
1,
1,
1,
11,
1449375044
] |
def get_var_names(df, regex):
return df.filter(regex=regex).columns.tolist() | Vvucinic/Wander | [
1,
1,
1,
11,
1449375044
] |
def get_dummies(data, prefix=None, prefix_sep='_', dummy_na=False,
columns=None, sparse=False):
"""
Convert categorical variable into dummy/indicator variables
Parameters
----------
data : array-like, Series, or DataFrame
prefix : string, list of strings, or dict of strings, def... | Vvucinic/Wander | [
1,
1,
1,
11,
1449375044
] |
def pack(width, data):
return b''.join(v.to_bytes(width, sys.byteorder, signed=True) for v in data) | Microvellum/Fluid-Designer | [
69,
30,
69,
37,
1461884765
] |
def test_max(self):
for w in 1, 2, 3, 4:
self.assertEqual(audioop.max(b'', w), 0)
self.assertEqual(audioop.max(bytearray(), w), 0)
self.assertEqual(audioop.max(memoryview(b''), w), 0)
p = packs[w]
self.assertEqual(audioop.max(p(5), w), 5)
s... | Microvellum/Fluid-Designer | [
69,
30,
69,
37,
1461884765
] |
def test_maxpp(self):
for w in 1, 2, 3, 4:
self.assertEqual(audioop.maxpp(b'', w), 0)
self.assertEqual(audioop.maxpp(bytearray(), w), 0)
self.assertEqual(audioop.maxpp(memoryview(b''), w), 0)
self.assertEqual(audioop.maxpp(packs[w](*range(100)), w), 0)
... | Microvellum/Fluid-Designer | [
69,
30,
69,
37,
1461884765
] |
def test_avgpp(self):
for w in 1, 2, 3, 4:
self.assertEqual(audioop.avgpp(b'', w), 0)
self.assertEqual(audioop.avgpp(bytearray(), w), 0)
self.assertEqual(audioop.avgpp(memoryview(b''), w), 0)
self.assertEqual(audioop.avgpp(packs[w](*range(100)), w), 0)
... | Microvellum/Fluid-Designer | [
69,
30,
69,
37,
1461884765
] |
def test_cross(self):
for w in 1, 2, 3, 4:
self.assertEqual(audioop.cross(b'', w), -1)
self.assertEqual(audioop.cross(bytearray(), w), -1)
self.assertEqual(audioop.cross(memoryview(b''), w), -1)
p = packs[w]
self.assertEqual(audioop.cross(p(0, 1, 2), w... | Microvellum/Fluid-Designer | [
69,
30,
69,
37,
1461884765
] |
def test_bias(self):
for w in 1, 2, 3, 4:
for bias in 0, 1, -1, 127, -128, 0x7fffffff, -0x80000000:
self.assertEqual(audioop.bias(b'', w, bias), b'')
self.assertEqual(audioop.bias(bytearray(), w, bias), b'')
self.assertEqual(audioop.bias(memoryview(b''... | Microvellum/Fluid-Designer | [
69,
30,
69,
37,
1461884765
] |
def test_adpcm2lin(self):
self.assertEqual(audioop.adpcm2lin(b'\x07\x7f\x7f', 1, None),
(b'\x00\x00\x00\xff\x00\xff', (-179, 40)))
self.assertEqual(audioop.adpcm2lin(bytearray(b'\x07\x7f\x7f'), 1, None),
(b'\x00\x00\x00\xff\x00\xff', (-179, 40)))
... | Microvellum/Fluid-Designer | [
69,
30,
69,
37,
1461884765
] |
def test_invalid_adpcm_state(self):
# state must be a tuple or None, not an integer
self.assertRaises(TypeError, audioop.adpcm2lin, b'\0', 1, 555)
self.assertRaises(TypeError, audioop.lin2adpcm, b'\0', 1, 555)
# Issues #24456, #24457: index out of range
self.assertRaises(ValueErr... | Microvellum/Fluid-Designer | [
69,
30,
69,
37,
1461884765
] |
def test_alaw2lin(self):
encoded = b'\x00\x03\x24\x2a\x51\x54\x55\x58\x6b\x71\x7f'\
b'\x80\x83\xa4\xaa\xd1\xd4\xd5\xd8\xeb\xf1\xff'
src = [-688, -720, -2240, -4032, -9, -3, -1, -27, -244, -82, -106,
688, 720, 2240, 4032, 9, 3, 1, 27, 244, 82, 106]
for w in 1, 2, ... | Microvellum/Fluid-Designer | [
69,
30,
69,
37,
1461884765
] |
def test_ulaw2lin(self):
encoded = b'\x00\x0e\x28\x3f\x57\x6a\x76\x7c\x7e\x7f'\
b'\x80\x8e\xa8\xbf\xd7\xea\xf6\xfc\xfe\xff'
src = [-8031, -4447, -1471, -495, -163, -53, -18, -6, -2, 0,
8031, 4447, 1471, 495, 163, 53, 18, 6, 2, 0]
for w in 1, 2, 3, 4:
... | Microvellum/Fluid-Designer | [
69,
30,
69,
37,
1461884765
] |
def test_ratecv(self):
for w in 1, 2, 3, 4:
self.assertEqual(audioop.ratecv(b'', w, 1, 8000, 8000, None),
(b'', (-1, ((0, 0),))))
self.assertEqual(audioop.ratecv(bytearray(), w, 1, 8000, 8000, None),
(b'', (-1, ((0, 0),))))
... | Microvellum/Fluid-Designer | [
69,
30,
69,
37,
1461884765
] |
def test_tomono(self):
for w in 1, 2, 3, 4:
data1 = datas[w]
data2 = bytearray(2 * len(data1))
for k in range(w):
data2[k::2*w] = data1[k::w]
self.assertEqual(audioop.tomono(data2, w, 1, 0), data1)
self.assertEqual(audioop.tomono(data2,... | Microvellum/Fluid-Designer | [
69,
30,
69,
37,
1461884765
] |
def test_findfactor(self):
self.assertEqual(audioop.findfactor(datas[2], datas[2]), 1.0)
self.assertEqual(audioop.findfactor(bytearray(datas[2]),
bytearray(datas[2])), 1.0)
self.assertEqual(audioop.findfactor(memoryview(datas[2]),
... | Microvellum/Fluid-Designer | [
69,
30,
69,
37,
1461884765
] |
def test_findmax(self):
self.assertEqual(audioop.findmax(datas[2], 1), 5)
self.assertEqual(audioop.findmax(bytearray(datas[2]), 1), 5)
self.assertEqual(audioop.findmax(memoryview(datas[2]), 1), 5) | Microvellum/Fluid-Designer | [
69,
30,
69,
37,
1461884765
] |
def test_byteswap(self):
swapped_datas = {
1: datas[1],
2: packs[2](0, 0x3412, 0x6745, -0x6646, -0x81, 0x80, -1),
3: packs[3](0, 0x563412, -0x7698bb, 0x7798ba, -0x81, 0x80, -1),
4: packs[4](0, 0x78563412, -0x547698bb, 0x557698ba,
-0x81, 0x8... | Microvellum/Fluid-Designer | [
69,
30,
69,
37,
1461884765
] |
def test_issue7673(self):
state = None
for data, size in INVALID_DATA:
size2 = size
self.assertRaises(audioop.error, audioop.getsample, data, size, 0)
self.assertRaises(audioop.error, audioop.max, data, size)
self.assertRaises(audioop.error, audioop.minmax... | Microvellum/Fluid-Designer | [
69,
30,
69,
37,
1461884765
] |
def test_wrongsize(self):
data = b'abcdefgh'
state = None
for size in (-1, 0, 5, 1024):
self.assertRaises(audioop.error, audioop.ulaw2lin, data, size)
self.assertRaises(audioop.error, audioop.alaw2lin, data, size)
self.assertRaises(audioop.error, audioop.adpcm... | Microvellum/Fluid-Designer | [
69,
30,
69,
37,
1461884765
] |
def new_module(name):
"""**DEPRECATED**
Create a new module.
The module is not entered into sys.modules.
"""
return types.ModuleType(name) | Microvellum/Fluid-Designer | [
69,
30,
69,
37,
1461884765
] |
def get_tag():
"""Return the magic tag for .pyc files."""
return sys.implementation.cache_tag | Microvellum/Fluid-Designer | [
69,
30,
69,
37,
1461884765
] |
def source_from_cache(path):
"""**DEPRECATED**
Given the path to a .pyc. file, return the path to its .py file.
The .pyc file does not need to exist; this simply returns the path to
the .py file calculated to correspond to the .pyc file. If path does
not conform to PEP 3147 format, ValueError wil... | Microvellum/Fluid-Designer | [
69,
30,
69,
37,
1461884765
] |
def __init__(self, path):
if path == '':
raise ImportError('empty pathname', path='')
elif os.path.isdir(path):
raise ImportError('existing directory', path=path) | Microvellum/Fluid-Designer | [
69,
30,
69,
37,
1461884765
] |
def __init__(self, fullname, path, file=None):
super().__init__(fullname, path)
self.file = file | Microvellum/Fluid-Designer | [
69,
30,
69,
37,
1461884765
] |
def load_source(name, pathname, file=None):
loader = _LoadSourceCompatibility(name, pathname, file)
spec = util.spec_from_file_location(name, pathname, loader=loader)
if name in sys.modules:
module = _exec(spec, sys.modules[name])
else:
module = _load(spec)
# To allow reloading to po... | Microvellum/Fluid-Designer | [
69,
30,
69,
37,
1461884765
] |
def load_compiled(name, pathname, file=None):
"""**DEPRECATED**"""
loader = _LoadCompiledCompatibility(name, pathname, file)
spec = util.spec_from_file_location(name, pathname, loader=loader)
if name in sys.modules:
module = _exec(spec, sys.modules[name])
else:
module = _load(spec)
... | Microvellum/Fluid-Designer | [
69,
30,
69,
37,
1461884765
] |
def load_module(name, file, filename, details):
"""**DEPRECATED**
Load a module, given information returned by find_module().
The module name must include the full package name, if any.
"""
suffix, mode, type_ = details
if mode and (not mode.startswith(('r', 'U')) or '+' in mode):
rai... | Microvellum/Fluid-Designer | [
69,
30,
69,
37,
1461884765
] |
def reload(module):
"""**DEPRECATED**
Reload the module and return it.
The module must have been successfully imported before.
"""
return importlib.reload(module) | Microvellum/Fluid-Designer | [
69,
30,
69,
37,
1461884765
] |
def load_dynamic(name, path, file=None):
"""**DEPRECATED**
Load an extension module.
"""
import importlib.machinery
loader = importlib.machinery.ExtensionFileLoader(name, path)
# Issue #24748: Skip the sys.modules check in _load_module_shim;
# always load new ex... | Microvellum/Fluid-Designer | [
69,
30,
69,
37,
1461884765
] |
def setUp(self):
# requires local installation of ICON sample files!
self.gridfile ='../..//example_data/icon/r2b4_amip.nc'
self.datafile = '../../example_data/icon/rms0006_atm_phy_DOM01_ML_0001.nc' | pygeo/pycmbs | [
15,
10,
15,
9,
1391865830
] |
def test_IconInit(self):
x = Icon(None, None, 'None') | pygeo/pycmbs | [
15,
10,
15,
9,
1391865830
] |
def test_IconInitMissingGridFile(self):
x = Icon(self.datafile, 'nothing.nc', 'novar')
with self.assertRaises(ValueError):
x.read() | pygeo/pycmbs | [
15,
10,
15,
9,
1391865830
] |
def handle_bad_input(e: Exception) -> Response:
return make_response(profiled_jsonify({"Error": f"{e}"}), 400) | the-blue-alliance/the-blue-alliance | [
334,
153,
334,
422,
1283632451
] |
def __init__(
self, plotly_name="showticklabels", parent_name="heatmap.colorbar", **kwargs | plotly/plotly.py | [
13052,
2308,
13052,
1319,
1385013188
] |
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24]) | ActiveState/code | [
1884,
686,
1884,
41,
1500923597
] |
def __init__(self, reason, verb, tb=None):
self.reason = reason
self.verb = verb
self.tb = tb
super().__init__(self.get_message()) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def _reasonstr(self):
"""Get the reason as a string."""
if isinstance(self.reason, str):
return self.reason
elif isinstance(self.reason, bytes):
return self.reason.decode('utf-8', 'ignore')
elif hasattr(self.reason, 'strerror'): # i.e., EnvironmentError
... | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def log(self, logger):
"""Log to the provided `logger` a human-readable message as an
error and a verbose traceback as a debug message.
"""
if self.tb:
logger.debug(self.tb)
logger.error('{0}: {1}', self.error_kind, self.args[0]) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def __init__(self, reason, verb, paths, tb=None):
self.paths = paths
super().__init__(reason, verb, tb) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def normpath(path):
"""Provide the canonical form of the path suitable for storing in
the database.
"""
path = syspath(path, prefix=False)
path = os.path.normpath(os.path.abspath(os.path.expanduser(path)))
return bytestring_path(path) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def sorted_walk(path, ignore=(), ignore_hidden=False, logger=None):
"""Like `os.walk`, but yields things in case-insensitive sorted,
breadth-first order. Directory and file names matching any glob
pattern in `ignore` are skipped. If `logger` is provided, then
warning messages are logged there when a di... | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def mkdirall(path):
"""Make all the enclosing directories of path (like mkdir -p on the
parent).
"""
for ancestor in ancestry(path):
if not os.path.isdir(syspath(ancestor)):
try:
os.mkdir(syspath(ancestor))
except OSError as exc:
raise File... | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def prune_dirs(path, root=None, clutter=('.DS_Store', 'Thumbs.db')):
"""If path is an empty directory, then remove it. Recursively remove
path's ancestry up to root (which is never removed) where there are
empty directories. If path is not contained in root, then nothing is
removed. Glob patterns in clu... | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def arg_encoding():
"""Get the encoding for command-line arguments (and other OS
locale-sensitive strings).
"""
try:
return locale.getdefaultlocale()[1] or 'utf-8'
except ValueError:
# Invalid locale environment variable setting. To avoid
# failing entirely for no good reason... | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def bytestring_path(path):
"""Given a path, which is either a bytes or a unicode, returns a str
path (ensuring that we never deal with Unicode pathnames).
"""
# Pass through bytestrings.
if isinstance(path, bytes):
return path
# On Windows, remove the magic prefix added by `syspath`. Th... | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def displayable_path(path, separator='; '):
"""Attempts to decode a bytestring path to a unicode object for the
purpose of displaying it to the user. If the `path` argument is a
list or a tuple, the elements are joined with `separator`.
"""
if isinstance(path, (list, tuple)):
return separato... | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def samefile(p1, p2):
"""Safer equality for paths."""
if p1 == p2:
return True
return shutil._samefile(syspath(p1), syspath(p2)) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def copy(path, dest, replace=False):
"""Copy a plain file. Permissions are not copied. If `dest` already
exists, raises a FilesystemError unless `replace` is True. Has no
effect if `path` is the same as `dest`. Paths are translated to
system paths before the syscall.
"""
if samefile(path, dest):... | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def link(path, dest, replace=False):
"""Create a symbolic link from path to `dest`. Raises an OSError if
`dest` already exists, unless `replace` is True. Does nothing if
`path` == `dest`.
"""
if samefile(path, dest):
return
if os.path.exists(syspath(dest)) and not replace:
raise... | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def reflink(path, dest, replace=False, fallback=False):
"""Create a reflink from `dest` to `path`.
Raise an `OSError` if `dest` already exists, unless `replace` is
True. If `path` == `dest`, then do nothing.
If reflinking fails and `fallback` is enabled, try copying the file
instead. Otherwise, ra... | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def sanitize_path(path, replacements=None):
"""Takes a path (as a Unicode string) and makes sure that it is
legal. Returns a new path. Only works with fragments; won't work
reliably on Windows when a path begins with a drive letter. Path
separators (including altsep!) should already be cleaned from the
... | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def _legalize_stage(path, replacements, length, extension, fragment):
"""Perform a single round of path legalization steps
(sanitation/replacement, encoding from Unicode to bytes,
extension-appending, and truncation). Return the path (Unicode if
`fragment` is set, `bytes` otherwise) and whether truncati... | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def py3_path(path):
"""Convert a bytestring path to Unicode on Python 3 only. On Python
2, return the bytestring path unchanged.
This helps deal with APIs on Python 3 that *only* accept Unicode
(i.e., `str` objects). I philosophically disagree with this
decision, because paths are sadly bytes on Un... | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def as_string(value):
"""Convert a value to a Unicode object for matching with a query.
None becomes the empty string. Bytestrings are silently decoded.
"""
if value is None:
return ''
elif isinstance(value, memoryview):
return bytes(value).decode('utf-8', 'ignore')
elif isinstan... | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def plurality(objs):
"""Given a sequence of hashble objects, returns the object that
is most common in the set and the its number of appearance. The
sequence must contain at least one object.
"""
c = Counter(objs)
if not c:
raise ValueError('sequence must be non-empty')
return c.most... | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def convert_command_args(args):
"""Convert command arguments to bytestrings on Python 2 and
surrogate-escaped strings on Python 3."""
assert isinstance(args, list)
def convert(arg):
if isinstance(arg, bytes):
arg = arg.decode(arg_encoding(), 'surrogateescape')
return arg
... | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def command_output(cmd, shell=False):
"""Runs the command and returns its output after it has exited.
Returns a CommandOutput. The attributes ``stdout`` and ``stderr`` contain
byte strings of the respective output streams.
``cmd`` is a list of arguments starting with the command names. The
argumen... | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def open_anything():
"""Return the system command that dispatches execution to the correct
program.
"""
sys_name = platform.system()
if sys_name == 'Darwin':
base_cmd = 'open'
elif sys_name == 'Windows':
base_cmd = 'start'
else: # Assume Unix
base_cmd = 'xdg-open'
... | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def interactive_open(targets, command):
"""Open the files in `targets` by `exec`ing a new `command`, given
as a Unicode string. (The new program takes over, and Python
execution ends: this does not fork a subprocess.)
Can raise `OSError`.
"""
assert command
# Split the command string into ... | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def case_sensitive(path):
"""Check whether the filesystem at the given path is case sensitive.
To work best, the path should point to a file or a directory. If the path
does not exist, assume a case sensitive file system on every platform
except Windows.
"""
# A fallback in case the path does n... | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def asciify_path(path, sep_replace):
"""Decodes all unicode characters in a path into ASCII equivalents.
Substitutions are provided by the unidecode module. Path separators in the
input are preserved.
Keyword arguments:
path -- The path to be asciified.
sep_replace -- the string to be used to ... | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def lazy_property(func):
"""A decorator that creates a lazily evaluated property. On first access,
the property is assigned the return value of `func`. This first value is
stored, so that future accesses do not have to evaluate `func` again.
This behaviour is useful when `func` is expensive to evaluate... | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def __init__(
self, plotly_name="familysrc", parent_name="barpolar.hoverlabel.font", **kwargs | plotly/python-api | [
13052,
2308,
13052,
1319,
1385013188
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.