project_name stringlengths 6 104 | file_name stringlengths 4 89 | full_name stringlengths 1 102 | func_name stringlengths 1 85 | docstring stringlengths 13 836 | docstring_tokens listlengths 4 122 | code stringlengths 23 39.7k | code_tokens stringlengths 29 44.6k | url int64 3 986k |
|---|---|---|---|---|---|---|---|---|
ipazc/vrpwrp | test_boundingbox.py | TestBoundingBox.test_get_box | test_get_box | Tests that bounding box successfully returns the array of the box dimensions. | [
"Tests",
"that",
"bounding",
"box",
"successfully",
"returns",
"the",
"array",
"of",
"the",
"box",
"dimensions."
] | def test_get_box(self):
box = BoundingBox(15, 16, 17, 18)
self.assertEqual(box.get_box(), [15, 16, 17, 18]) | ['def', 'test_get_box(self):', 'box', '=', 'BoundingBox(15,', '16,', '17,', '18)', 'self.assertEqual(box.get_box(),', '[15,', '16,', '17,', '18])'] | 940,010 |
ipazc/vrpwrp | test_boundingbox.py | TestBoundingBox.test_get_components | test_get_components | Tests that bounding box isolated components are accessible. | [
"Tests",
"that",
"bounding",
"box",
"isolated",
"components",
"are",
"accessible."
] | def test_get_components(self):
box = BoundingBox(15, 16, 17, 18)
self.assertEqual(box.get_x(), 15)
self.assertEqual(box.get_y(), 16)
self.assertEqual(box.get_width(), 17)
self.assertEqual(box.get_height(), 18) | ['def', 'test_get_components(self):', 'box', '=', 'BoundingBox(15,', '16,', '17,', '18)', 'self.assertEqual(box.get_x(),', '15)', 'self.assertEqual(box.get_y(),', '16)', 'self.assertEqual(box.get_width(),', '17)', 'self.assertEqual(box.get_height(),', '18)'] | 940,012 |
ipazc/vrpwrp | test_boundingbox.py | TestBoundingBox.test_get_numpy_format | test_get_numpy_format | Tests that bounding box numpy format is correct. | [
"Tests",
"that",
"bounding",
"box",
"numpy",
"format",
"is",
"correct."
] | def test_get_numpy_format(self):
box = BoundingBox(15, 16, 17, 18)
self.assertEqual(box.get_numpy_format(), [16, 34, 15, 32]) | ['def', 'test_get_numpy_format(self):', 'box', '=', 'BoundingBox(15,', '16,', '17,', '18)', 'self.assertEqual(box.get_numpy_format(),', '[16,', '34,', '15,', '32])'] | 940,013 |
ipazc/vrpwrp | test_boundingbox.py | TestBoundingBox.test_intersection_with_other_boundingbox | test_intersection_with_other_boundingbox | Tests that bounding box intersects itself with other bounding boxes. | [
"Tests",
"that",
"bounding",
"box",
"intersects",
"itself",
"with",
"other",
"bounding",
"boxes."
] | def test_intersection_with_other_boundingbox(self):
for rect_set in self.rect_sets:
rect1 = rect_set[0]
rect2 = rect_set[1]
expectedArea = rect_set[2]
expectedPercentage = rect_set[3]
box1 = BoundingBox(*rect1)
box2 = BoundingBox(*rect2)
intersection = box1.in... | ['def', 'test_intersection_with_other_boundingbox(self):', 'for', 'rect_set', 'in', 'self.rect_sets:', 'rect1', '=', 'rect_set[0]', 'rect2', '=', 'rect_set[1]', 'expectedArea', '=', 'rect_set[2]', 'expectedPercentage', '=', 'rect_set[3]', 'box1', '=', 'BoundingBox(*rect1)', 'box2', '=', 'BoundingBox(*rect2)', 'intersec... | 940,015 |
ipazc/vrpwrp | test_boundingbox.py | TestBoundingBox.test_center | test_center | Tests that bounding box knows its center point. | [
"Tests",
"that",
"bounding",
"box",
"knows",
"its",
"center",
"point."
] | def test_center(self):
box = BoundingBox(10, 10, 20, 20)
self.assertEqual(box.get_center(), [20, 20]) | ['def', 'test_center(self):', 'box', '=', 'BoundingBox(10,', '10,', '20,', '20)', 'self.assertEqual(box.get_center(),', '[20,', '20])'] | 940,016 |
ipazc/vrpwrp | test_boundingbox.py | TestBoundingBox.test_area | test_area | Tests that bounding box knows its area. | [
"Tests",
"that",
"bounding",
"box",
"knows",
"its",
"area."
] | def test_area(self):
box = BoundingBox(10, 10, 20, 20)
self.assertEqual(box.get_area(), 400) | ['def', 'test_area(self):', 'box', '=', 'BoundingBox(10,', '10,', '20,', '20)', 'self.assertEqual(box.get_area(),', '400)'] | 940,017 |
ipazc/vrpwrp | test_embedding.py | TestEmbedding.test_creation_from_list_with_numpy_available | test_creation_from_list_with_numpy_available | Tests the creation of an embedding from a list of numbers with numpy available. | [
"Tests",
"the",
"creation",
"of",
"an",
"embedding",
"from",
"a",
"list",
"of",
"numbers",
"with",
"numpy",
"available."
] | def test_creation_from_list_with_numpy_available(self):
if NUMPY_AVAILABLE:
EMB.NUMPY_LOADED = True
list = [2, 3, 4]
emb = EMB.Embedding(list)
self.assertTrue(np.array_equal(emb.get_embedding_np(), np.asarray(list)))
else:
self.assertTrue(True) | ['def', 'test_creation_from_list_with_numpy_available(self):', 'if', 'NUMPY_AVAILABLE:', 'EMB.NUMPY_LOADED', '=', 'True', 'list', '=', '[2,', '3,', '4]', 'emb', '=', 'EMB.Embedding(list)', 'self.assertTrue(np.array_equal(emb.get_embedding_np(),', 'np.asarray(list)))', 'else:', 'self.assertTrue(True)'] | 940,018 |
ipazc/vrpwrp | test_embedding.py | TestEmbedding.test_creation_from_list_without_numpy_available | test_creation_from_list_without_numpy_available | Tests the creation of an embedding from a list of numbers without numpy available. | [
"Tests",
"the",
"creation",
"of",
"an",
"embedding",
"from",
"a",
"list",
"of",
"numbers",
"without",
"numpy",
"available."
] | def test_creation_from_list_without_numpy_available(self):
EMB.NUMPY_LOADED = False
list = [2, 3, 4]
emb = EMB.Embedding(list)
self.assertEqual(emb.get_embedding_np(), str(list).replace(',', ' ')) | ['def', 'test_creation_from_list_without_numpy_available(self):', 'EMB.NUMPY_LOADED', '=', 'False', 'list', '=', '[2,', '3,', '4]', 'emb', '=', 'EMB.Embedding(list)', 'self.assertEqual(emb.get_embedding_np(),', "str(list).replace(',',", "'", "'))"] | 940,019 |
ipazc/vrpwrp | test_embedding.py | TestEmbedding.test_creation_from_numpy | test_creation_from_numpy | Tests the creation of an embedding from a numpy array with numpy available. | [
"Tests",
"the",
"creation",
"of",
"an",
"embedding",
"from",
"a",
"numpy",
"array",
"with",
"numpy",
"available."
] | def test_creation_from_numpy(self):
if NUMPY_AVAILABLE:
EMB.NUMPY_LOADED = True
np_array = np.asarray([2, 3, 4])
emb = EMB.Embedding(np_array)
self.assertTrue(np.array_equal(emb.get_embedding_np(), np_array))
else:
self.assertTrue(True) | ['def', 'test_creation_from_numpy(self):', 'if', 'NUMPY_AVAILABLE:', 'EMB.NUMPY_LOADED', '=', 'True', 'np_array', '=', 'np.asarray([2,', '3,', '4])', 'emb', '=', 'EMB.Embedding(np_array)', 'self.assertTrue(np.array_equal(emb.get_embedding_np(),', 'np_array))', 'else:', 'self.assertTrue(True)'] | 940,020 |
ipazc/vrpwrp | test_embedding.py | TestEmbedding.test_creation_from_str_with_numpy_available | test_creation_from_str_with_numpy_available | Tests the creation of an embedding from a string with numpy available. | [
"Tests",
"the",
"creation",
"of",
"an",
"embedding",
"from",
"a",
"string",
"with",
"numpy",
"available."
] | def test_creation_from_str_with_numpy_available(self):
if NUMPY_AVAILABLE:
EMB.NUMPY_LOADED = True
np_str = '[2 3 4]'
emb = EMB.Embedding(np_str)
np_array = emb.get_embedding_np()
self.assertTrue(type(np_array) is np.ndarray)
else:
self.assertTrue(True) | ['def', 'test_creation_from_str_with_numpy_available(self):', 'if', 'NUMPY_AVAILABLE:', 'EMB.NUMPY_LOADED', '=', 'True', 'np_str', '=', "'[2", '3', "4]'", 'emb', '=', 'EMB.Embedding(np_str)', 'np_array', '=', 'emb.get_embedding_np()', 'self.assertTrue(type(np_array)', 'is', 'np.ndarray)', 'else:', 'self.assertTrue(True... | 940,021 |
ipazc/vrpwrp | test_embedding.py | TestEmbedding.test_substract_with_numpy | test_substract_with_numpy | Tests the substraction of two embeddings to calculate the distance with numpy. | [
"Tests",
"the",
"substraction",
"of",
"two",
"embeddings",
"to",
"calculate",
"the",
"distance",
"with",
"numpy."
] | def test_substract_with_numpy(self):
if NUMPY_AVAILABLE:
EMB.NUMPY_LOADED = True
class FakeFaceRecognition(object):
def get_embeddings_distance(self, emb1, array_embs):
return [0 for a in array_embs]
emb1 = EMB.Embedding('[ 0.0158451 -0.10712819 0.03863023 -0.... | ['def', 'test_substract_with_numpy(self):', 'if', 'NUMPY_AVAILABLE:', 'EMB.NUMPY_LOADED', '=', 'True', 'class', 'FakeFaceRecognition(object):', 'def', 'get_embeddings_distance(self,', 'emb1,', 'array_embs):', 'return', '[0', 'for', 'a', 'in', 'array_embs]', 'emb1', '=', "EMB.Embedding('[", '0.0158451', '-0.10712819', '... | 940,023 |
ipazc/vrpwrp | test_embedding.py | TestEmbedding.test_substract_without_numpy | test_substract_without_numpy | Tests the substraction of two embeddings to calculate the distance without numpy. | [
"Tests",
"the",
"substraction",
"of",
"two",
"embeddings",
"to",
"calculate",
"the",
"distance",
"without",
"numpy."
] | def test_substract_without_numpy(self):
EMB.NUMPY_LOADED = False
FACEREC.NUMPY_AVAILABLE = False
emb1 = EMB.Embedding('[ 0.0158451 -0.10712819 0.03863023 -0.03482883 -0.0824572 0.14168985 -0.09636037 0.19106716 -0.02492222 0.14210707 -0.01116645 -0.02843223 0.11468598 0.05238573 -0.07595719 0.02790... | ['def', 'test_substract_without_numpy(self):', 'EMB.NUMPY_LOADED', '=', 'False', 'FACEREC.NUMPY_AVAILABLE', '=', 'False', 'emb1', '=', "EMB.Embedding('[", '0.0158451', '-0.10712819', '0.03863023', '-0.03482883', '-0.0824572', '0.14168985', '-0.09636037', '0.19106716', '-0.02492222', '0.14210707', '-0.01116645', '-0.028... | 940,024 |
ipazc/vrpwrp | test_embedding.py | TestEmbedding.test_embedding_str | test_embedding_str | Tests that the embedding is convertible into string. | [
"Tests",
"that",
"the",
"embedding",
"is",
"convertible",
"into",
"string."
] | def test_embedding_str(self):
emb1 = EMB.Embedding('[ 0.0158451 -0.10712819 0.03863023 -0.03482883 -0.0824572 0.14168985 -0.09636037 0.19106716 -0.02492222 0.14210707 -0.01116645 -0.02843223 0.11468598 0.05238573 -0.07595719 0.02790567 0.08421595 -0.02046278 0.11567297 -0.04182892 0.04587755 0.06748006... | ['def', 'test_embedding_str(self):', 'emb1', '=', "EMB.Embedding('[", '0.0158451', '-0.10712819', '0.03863023', '-0.03482883', '-0.0824572', '0.14168985', '-0.09636037', '0.19106716', '-0.02492222', '0.14210707', '-0.01116645', '-0.02843223', '0.11468598', '0.05238573', '-0.07595719', '0.02790567', '0.08421595', '-0.02... | 940,025 |
ipazc/vrpwrp | test_image_helper.py | TestImageHelper.test_get_file_binary_content | test_get_file_binary_content | Tests that the image helper can retrieve content from a file. | [
"Tests",
"that",
"the",
"image",
"helper",
"can",
"retrieve",
"content",
"from",
"a",
"file."
] | def test_get_file_binary_content(self):
content = image_helper.get_file_binary_content(self.subject)
self.assertGreater(len(content), 0)
with open(self.subject, 'rb') as f:
original_content = f.read()
self.assertEqual(content, original_content) | ['def', 'test_get_file_binary_content(self):', 'content', '=', 'image_helper.get_file_binary_content(self.subject)', 'self.assertGreater(len(content),', '0)', 'with', 'open(self.subject,', "'rb')", 'as', 'f:', 'original_content', '=', 'f.read()', 'self.assertEqual(content,', 'original_content)'] | 940,032 |
ipazc/vrpwrp | test_image_helper.py | TestImageHelper.test_get_file_image | test_get_file_image | Tests that the image helper can retrieve the PIL image from the file. | [
"Tests",
"that",
"the",
"image",
"helper",
"can",
"retrieve",
"the",
"PIL",
"image",
"from",
"the",
"file."
] | def test_get_file_image(self):
image = image_helper.get_file_image(self.subject)
self.assertEqual(image.size, (800, 450)) | ['def', 'test_get_file_image(self):', 'image', '=', 'image_helper.get_file_image(self.subject)', 'self.assertEqual(image.size,', '(800,', '450))'] | 940,033 |
ipazc/vrpwrp | test_image_helper.py | TestImageHelper.test_get_cropped_faces | test_get_cropped_faces | Tests that the image helper can crop an image successfully by multiple bounding boxes. | [
"Tests",
"that",
"the",
"image",
"helper",
"can",
"crop",
"an",
"image",
"successfully",
"by",
"multiple",
"bounding",
"boxes."
] | def test_get_cropped_faces(self):
with Image.open(self.subject) as im:
image = im.convert('RGB')
cropped_list = image_helper.get_cropped_faces(image, [BoundingBox(0, 0, 15, 15), BoundingBox(20, 20, 45, 45)])
self.assertEqual(cropped_list[0].size, (15, 15))
self.assertEqual(cropped_list[1].size, ... | ['def', 'test_get_cropped_faces(self):', 'with', 'Image.open(self.subject)', 'as', 'im:', 'image', '=', "im.convert('RGB')", 'cropped_list', '=', 'image_helper.get_cropped_faces(image,', '[BoundingBox(0,', '0,', '15,', '15),', 'BoundingBox(20,', '20,', '45,', '45)])', 'self.assertEqual(cropped_list[0].size,', '(15,', '... | 940,038 |
ipazc/vrpwrp | boundingbox.py | BoundingBox.get_center | get_center | Computes the center of the bounding box :return: array (point 2D) of the center. | [
"Computes",
"the",
"center",
"of",
"the",
"bounding",
"box",
":return:",
"array",
"(point",
"2D)",
"of",
"the",
"center."
] | def get_center(self):
return [int(self.x + self.width / 2), int(self.y + self.height / 2)] | ['def', 'get_center(self):', 'return', '[int(self.x', '+', 'self.width', '/', '2),', 'int(self.y', '+', 'self.height', '/', '2)]'] | 940,049 |
bpx-energy/VRP_reinforcement_learning | tsp_utils.py | Env.step | step | Mask the nodes that can be visited in next steps. | [
"Mask",
"the",
"nodes",
"that",
"can",
"be",
"visited",
"in",
"next",
"steps."
] | def step(self, idx, beam_parent=None):
if beam_parent is not None:
batchBeamSeq = tf.expand_dims(tf.tile(tf.cast(tf.range(self.batch_size), tf.int64), [self.beam_width]), 1)
batchedBeamIdx = batchBeamSeq + tf.cast(self.batch_size, tf.int64) * beam_parent
self.mask = tf.gather_nd(self.mask, b... | ['def', 'step(self,', 'idx,', 'beam_parent=None):', 'if', 'beam_parent', 'is', 'not', 'None:', 'batchBeamSeq', '=', 'tf.expand_dims(tf.tile(tf.cast(tf.range(self.batch_size),', 'tf.int64),', '[self.beam_width]),', '1)', 'batchedBeamIdx', '=', 'batchBeamSeq', '+', 'tf.cast(self.batch_size,', 'tf.int64)', '*', 'beam_pare... | 940,085 |
IBM/vsrl-framework | models.py | intersperse | intersperse | Put `interspersed_item` between each of the elements of `items`. | [
"Put",
"`interspersed_item`",
"between",
"each",
"of",
"the",
"elements",
"of",
"`items`."
] | def intersperse(interspersed_item, items) -> list:
if not items:
return []
ret = [items[0]]
for item in items[1:]:
ret.append(interspersed_item)
ret.append(item)
return ret | ['def', 'intersperse(interspersed_item,', 'items)', '->', 'list:', 'if', 'not', 'items:', 'return', '[]', 'ret', '=', '[items[0]]', 'for', 'item', 'in', 'items[1:]:', 'ret.append(interspersed_item)', 'ret.append(item)', 'return', 'ret'] | 940,124 |
IBM/vsrl-framework | space_helpers.py | union_states | union_states | Returns the union of 2 disjoint states. | [
"Returns",
"the",
"union",
"of",
"2",
"disjoint",
"states."
] | def union_states(s1: Dict[expr.Variable, expr.Expression], s2: Dict[expr.Variable, expr.Expression]) -> Dict[expr.Variable, expr.Expression]:
assert s1.keys().isdisjoint(s2.keys()), 'States should be disjoint.'
return_value = copy.deepcopy(s1)
return_value.update(s2)
return return_value | ['def', 'union_states(s1:', 'Dict[expr.Variable,', 'expr.Expression],', 's2:', 'Dict[expr.Variable,', 'expr.Expression])', '->', 'Dict[expr.Variable,', 'expr.Expression]:', 'assert', 's1.keys().isdisjoint(s2.keys()),', "'States", 'should', 'be', "disjoint.'", 'return_value', '=', 'copy.deepcopy(s1)', 'return_value.upda... | 940,140 |
IBM/vsrl-framework | data.py | ImgDataset.gen_img | gen_img | Returns raw_img, img, label; useful for debugging. | [
"Returns",
"raw_img,",
"img,",
"label;",
"useful",
"for",
"debugging."
] | def gen_img(self):
(raw_img, label) = gen_img(self.bg_imgs, self.obj_imgs, self.img_shape, output_scale=self.label_scale)
img = self.transform(raw_img)
return (raw_img, img, label) | ['def', 'gen_img(self):', '(raw_img,', 'label)', '=', 'gen_img(self.bg_imgs,', 'self.obj_imgs,', 'self.img_shape,', 'output_scale=self.label_scale)', 'img', '=', 'self.transform(raw_img)', 'return', '(raw_img,', 'img,', 'label)'] | 940,146 |
IBM/vsrl-framework | expr_helpers.py | numbers | numbers | Returns all of the numbers in `e`. | [
"Returns",
"all",
"of",
"the",
"numbers",
"in",
"`e`."
] | def numbers(e: Expression) -> Set[Number]:
return_value = set()
def f(e: Expression):
if isinstance(e, Number):
return_value.add(e)
traversal.on_every_node(f, e)
return return_value | ['def', 'numbers(e:', 'Expression)', '->', 'Set[Number]:', 'return_value', '=', 'set()', 'def', 'f(e:', 'Expression):', 'if', 'isinstance(e,', 'Number):', 'return_value.add(e)', 'traversal.on_every_node(f,', 'e)', 'return', 'return_value'] | 940,176 |
IBM/vsrl-framework | expr_helpers.py | get_atomic_odes | get_atomic_odes | Returns all of the AtomicODEs in the `ode_system`. | [
"Returns",
"all",
"of",
"the",
"AtomicODEs",
"in",
"the",
"`ode_system`."
] | def get_atomic_odes(ode_system: ODESystem) -> List[AtomicODE]:
atomic_odes = []
def append_atomic_odes(expr):
if isinstance(expr, AtomicODE):
atomic_odes.append(expr)
traversal.on_every_node(append_atomic_odes, ode_system.dp)
return atomic_odes | ['def', 'get_atomic_odes(ode_system:', 'ODESystem)', '->', 'List[AtomicODE]:', 'atomic_odes', '=', '[]', 'def', 'append_atomic_odes(expr):', 'if', 'isinstance(expr,', 'AtomicODE):', 'atomic_odes.append(expr)', 'traversal.on_every_node(append_atomic_odes,', 'ode_system.dp)', 'return', 'atomic_odes'] | 940,177 |
IBM/vsrl-framework | expr_helpers.py | is_comparison_operator | is_comparison_operator | Returns true if f is a comparison formula (<, >, >=, <=, and =). | [
"Returns",
"true",
"if",
"f",
"is",
"a",
"comparison",
"formula",
"(<,",
">,",
">=,",
"<=,",
"and",
"=)."
] | def is_comparison_operator(f: Formula):
assert isinstance(f, Formula)
return isinstance(f, Greater) or isinstance(f, GreaterEq) or isinstance(f, Less) or isinstance(f, LessEq) or isinstance(f, Eq) | ['def', 'is_comparison_operator(f:', 'Formula):', 'assert', 'isinstance(f,', 'Formula)', 'return', 'isinstance(f,', 'Greater)', 'or', 'isinstance(f,', 'GreaterEq)', 'or', 'isinstance(f,', 'Less)', 'or', 'isinstance(f,', 'LessEq)', 'or', 'isinstance(f,', 'Eq)'] | 940,180 |
IBM/vsrl-framework | expr_helpers.py | variable_dots | variable_dots | Returns the list of all DotTerms that must be filled by a variable. | [
"Returns",
"the",
"list",
"of",
"all",
"DotTerms",
"that",
"must",
"be",
"filled",
"by",
"a",
"variable."
] | def variable_dots(e: Expression) -> List[DotTerm]:
return list(filter(lambda dot: isinstance(dot, DotTerm) and dot.is_variable, all_dots(e))) | ['def', 'variable_dots(e:', 'Expression)', '->', 'List[DotTerm]:', 'return', 'list(filter(lambda', 'dot:', 'isinstance(dot,', 'DotTerm)', 'and', 'dot.is_variable,', 'all_dots(e)))'] | 940,185 |
IBM/vsrl-framework | expr_helpers.py | true_term_dots | true_term_dots | Returns all of the term dots that are not variables or numbers. | [
"Returns",
"all",
"of",
"the",
"term",
"dots",
"that",
"are",
"not",
"variables",
"or",
"numbers."
] | def true_term_dots(e: Expression) -> List[DotTerm]:
return list(filter(lambda dot: isinstance(dot, DotTerm) and (not dot.is_variable) and (not dot.is_numeric), all_dots(e))) | ['def', 'true_term_dots(e:', 'Expression)', '->', 'List[DotTerm]:', 'return', 'list(filter(lambda', 'dot:', 'isinstance(dot,', 'DotTerm)', 'and', '(not', 'dot.is_variable)', 'and', '(not', 'dot.is_numeric),', 'all_dots(e)))'] | 940,186 |
IBM/vsrl-framework | expr_helpers.py | formula_dots | formula_dots | Returns the set of all DotFormulas in `e`. | [
"Returns",
"the",
"set",
"of",
"all",
"DotFormulas",
"in",
"`e`."
] | def formula_dots(e: Expression) -> List[DotTerm]:
return list(filter(lambda dot: isinstance(dot, DotFormula), all_dots(e))) | ['def', 'formula_dots(e:', 'Expression)', '->', 'List[DotTerm]:', 'return', 'list(filter(lambda', 'dot:', 'isinstance(dot,', 'DotFormula),', 'all_dots(e)))'] | 940,187 |
Erotemic/vtool_ibeis | clustering2.py | groupedzip | groupedzip | Function for grouping multiple lists of data (stored in ``datas_list``) using ``id_list``. | [
"Function",
"for",
"grouping",
"multiple",
"lists",
"of",
"data",
"(stored",
"in",
"``datas_list``)",
"using",
"``id_list``."
] | def groupedzip(id_list, datas_list):
(unique_ids, groupxs) = group_indices(id_list)
grouped_datas_list = [apply_grouping_(data, groupxs) for data in datas_list]
grouped_iter = zip(*grouped_datas_list)
return (unique_ids, grouped_iter) | ['def', 'groupedzip(id_list,', 'datas_list):', '(unique_ids,', 'groupxs)', '=', 'group_indices(id_list)', 'grouped_datas_list', '=', '[apply_grouping_(data,', 'groupxs)', 'for', 'data', 'in', 'datas_list]', 'grouped_iter', '=', 'zip(*grouped_datas_list)', 'return', '(unique_ids,', 'grouped_iter)'] | 940,470 |
Erotemic/vtool_ibeis | fontdemo.py | Font.text_dimensions | text_dimensions | Return (width, height, baseline) of `text` rendered in the current font. | [
"Return",
"(width,",
"height,",
"baseline)",
"of",
"`text`",
"rendered",
"in",
"the",
"current",
"font."
] | def text_dimensions(self, text):
width = 0
max_ascent = 0
max_descent = 0
previous_char = None
for char in text:
glyph = self.glyph_for_character(char)
max_ascent = max(max_ascent, glyph.ascent)
max_descent = max(max_descent, glyph.descent)
kerning_x = self.kerning_of... | ['def', 'text_dimensions(self,', 'text):', 'width', '=', '0', 'max_ascent', '=', '0', 'max_descent', '=', '0', 'previous_char', '=', 'None', 'for', 'char', 'in', 'text:', 'glyph', '=', 'self.glyph_for_character(char)', 'max_ascent', '=', 'max(max_ascent,', 'glyph.ascent)', 'max_descent', '=', 'max(max_descent,', 'glyph... | 940,540 |
Erotemic/vtool_ibeis | histogram.py | wrap_histogram | wrap_histogram | Simulates the first and last histogram bin being being adjacent to one another by replicating those bins at the last and first positions respectively. | [
"Simulates",
"the",
"first",
"and",
"last",
"histogram",
"bin",
"being",
"being",
"adjacent",
"to",
"one",
"another",
"by",
"replicating",
"those",
"bins",
"at",
"the",
"last",
"and",
"first",
"positions",
"respectively."
] | def wrap_histogram(hist_, edges_, _debug=False):
(left_step, right_step) = np.diff(edges_)[[0, -1]]
hist_wrap = np.hstack((hist_[-1:], hist_, hist_[0:1]))
edge_wrap = np.hstack((edges_[0:1] - left_step, edges_, edges_[-1:] + right_step))
if _debug:
import vtool_ibeis as vt
print(vt.kpts_... | ['def', 'wrap_histogram(hist_,', 'edges_,', '_debug=False):', '(left_step,', 'right_step)', '=', 'np.diff(edges_)[[0,', '-1]]', 'hist_wrap', '=', 'np.hstack((hist_[-1:],', 'hist_,', 'hist_[0:1]))', 'edge_wrap', '=', 'np.hstack((edges_[0:1]', '-', 'left_step,', 'edges_,', 'edges_[-1:]', '+', 'right_step))', 'if', '_debu... | 940,561 |
Erotemic/vtool_ibeis | keypoint.py | augment_2x2_with_translation | augment_2x2_with_translation | helper function to augment shape matrix with a translation component. | [
"helper",
"function",
"to",
"augment",
"shape",
"matrix",
"with",
"a",
"translation",
"component."
] | def augment_2x2_with_translation(kpts, _mat2x2):
nKpts = len(kpts)
_11s = _mat2x2.T[0, 0]
_12s = _mat2x2.T[1, 0]
_21s = _mat2x2.T[0, 1]
_22s = _mat2x2.T[1, 1]
(_13s, _23s) = get_xys(kpts)
_zeros = np.zeros(nKpts)
_ones = np.ones(nKpts)
_arrs3x3 = np.array([[_11s, _12s, _13s], [_21s, ... | ['def', 'augment_2x2_with_translation(kpts,', '_mat2x2):', 'nKpts', '=', 'len(kpts)', '_11s', '=', '_mat2x2.T[0,', '0]', '_12s', '=', '_mat2x2.T[1,', '0]', '_21s', '=', '_mat2x2.T[0,', '1]', '_22s', '=', '_mat2x2.T[1,', '1]', '(_13s,', '_23s)', '=', 'get_xys(kpts)', '_zeros', '=', 'np.zeros(nKpts)', '_ones', '=', 'np.o... | 940,615 |
Erotemic/vtool_ibeis | keypoint.py | get_kpts_wh | get_kpts_wh | Gets the width / height diameter of a keypoint ie the diameter of the xaxis and yaxis of the keypoint. | [
"Gets",
"the",
"width",
"/",
"height",
"diameter",
"of",
"a",
"keypoint",
"ie",
"the",
"diameter",
"of",
"the",
"xaxis",
"and",
"yaxis",
"of",
"the",
"keypoint."
] | def get_kpts_wh(kpts, outer=True):
if outer:
invV_mats2x2 = get_invVR_mats2x2(kpts)
corners = np.array([[-1, 1, 1, -1], [-1, -1, 1, 1]])
warped_corners = np.array([invV.dot(corners) for invV in invV_mats2x2])
maxx = warped_corners[:, 0, :].max(axis=1)
minx = warped_corners[:,... | ['def', 'get_kpts_wh(kpts,', 'outer=True):', 'if', 'outer:', 'invV_mats2x2', '=', 'get_invVR_mats2x2(kpts)', 'corners', '=', 'np.array([[-1,', '1,', '1,', '-1],', '[-1,', '-1,', '1,', '1]])', 'warped_corners', '=', 'np.array([invV.dot(corners)', 'for', 'invV', 'in', 'invV_mats2x2])', 'maxx', '=', 'warped_corners[:,', '... | 940,632 |
Erotemic/vtool_ibeis | matching.py | AnnotPairFeatInfo.get_infostr | get_infostr | Summarizes the types (global, local, summary) of features in X based on standardized dimension names. | [
"Summarizes",
"the",
"types",
"(global,",
"local,",
"summary)",
"of",
"features",
"in",
"X",
"based",
"on",
"standardized",
"dimension",
"names."
] | def get_infostr(featinfo):
grouped_keys = ub.ddict(list)
for key in featinfo.columns:
type_ = featinfo.measure_type(key)
grouped_keys[type_].append(key)
info_items = ub.odict([('global_measures', ut.lmap(featinfo.global_measure, grouped_keys['global'])), ('local_sorters', set(map(featinfo.lo... | ['def', 'get_infostr(featinfo):', 'grouped_keys', '=', 'ub.ddict(list)', 'for', 'key', 'in', 'featinfo.columns:', 'type_', '=', 'featinfo.measure_type(key)', 'grouped_keys[type_].append(key)', 'info_items', '=', "ub.odict([('global_measures',", 'ut.lmap(featinfo.global_measure,', "grouped_keys['global'])),", "('local_s... | 940,665 |
Erotemic/vtool_ibeis | other.py | ensure_rng | ensure_rng | Returns a numpy random number generator given a seed. | [
"Returns",
"a",
"numpy",
"random",
"number",
"generator",
"given",
"a",
"seed."
] | def ensure_rng(seed=None):
if seed is None:
rng = np.random
elif isinstance(seed, np.random.RandomState):
rng = seed
else:
rng = np.random.RandomState(seed)
return rng | ['def', 'ensure_rng(seed=None):', 'if', 'seed', 'is', 'None:', 'rng', '=', 'np.random', 'elif', 'isinstance(seed,', 'np.random.RandomState):', 'rng', '=', 'seed', 'else:', 'rng', '=', 'np.random.RandomState(seed)', 'return', 'rng'] | 940,713 |
Erotemic/vtool_ibeis | other.py | asserteq | asserteq | recursive equality checks asserts that output1 and output2 are close to equal. | [
"recursive",
"equality",
"checks",
"asserts",
"that",
"output1",
"and",
"output2",
"are",
"close",
"to",
"equal."
] | def asserteq(output1, output2, thresh=1e-08, nestpath=None, level=0, lbl1=None, lbl2=None, output_lbl=None, verbose=True, iswarning=False):
failed = False
if lbl1 is None:
lbl1 = ut.get_varname_from_stack(output1, N=1)
if lbl2 is None:
lbl2 = ut.get_varname_from_stack(output2, N=1)
if ne... | ['def', 'asserteq(output1,', 'output2,', 'thresh=1e-08,', 'nestpath=None,', 'level=0,', 'lbl1=None,', 'lbl2=None,', 'output_lbl=None,', 'verbose=True,', 'iswarning=False):', 'failed', '=', 'False', 'if', 'lbl1', 'is', 'None:', 'lbl1', '=', 'ut.get_varname_from_stack(output1,', 'N=1)', 'if', 'lbl2', 'is', 'None:', 'lbl2... | 940,719 |
Erotemic/vtool_ibeis | other.py | find_elbow_point | find_elbow_point | Finds the on the curve point furthest from the line defined by the endpoints of the curve. | [
"Finds",
"the",
"on",
"the",
"curve",
"point",
"furthest",
"from",
"the",
"line",
"defined",
"by",
"the",
"endpoints",
"of",
"the",
"curve."
] | def find_elbow_point(curve):
num_points = len(curve)
all_coords = np.vstack((np.arange(num_points), curve)).T
np.array([np.arange(num_points), curve])
first_point = all_coords[0]
line_vec = all_coords[-1] - all_coords[0]
line_vec_norm = line_vec / np.sqrt(np.sum(line_vec ** 2))
vec_from_firs... | ['def', 'find_elbow_point(curve):', 'num_points', '=', 'len(curve)', 'all_coords', '=', 'np.vstack((np.arange(num_points),', 'curve)).T', 'np.array([np.arange(num_points),', 'curve])', 'first_point', '=', 'all_coords[0]', 'line_vec', '=', 'all_coords[-1]', '-', 'all_coords[0]', 'line_vec_norm', '=', 'line_vec', '/', 'n... | 940,722 |
Erotemic/vtool_ibeis | score_normalization.py | ScoreNormalizer.predict | predict | Predict true or false of ``X``. | [
"Predict",
"true",
"or",
"false",
"of",
"``X``."
] | def predict(encoder, X):
prob = encoder.normalize_scores(X)
pred = prob > encoder.learned_thresh
return pred | ['def', 'predict(encoder,', 'X):', 'prob', '=', 'encoder.normalize_scores(X)', 'pred', '=', 'prob', '>', 'encoder.learned_thresh', 'return', 'pred'] | 940,757 |
mvondracek/VUT-FIT-POVa-2018-Pedestrian-Tracking | utils.py | calculate_flat_histogram | calculate_flat_histogram | Calculate flattened normalized histogram (1-D array) of the image. | [
"Calculate",
"flattened",
"normalized",
"histogram",
"(1-D",
"array)",
"of",
"the",
"image."
] | def calculate_flat_histogram(image):
hist = cv2.calcHist([image], channels=[0, 1, 2], mask=None, histSize=[16, 16, 16], ranges=[0, 256, 0, 256, 0, 256])
cv2.normalize(hist, hist)
return hist.flatten() | ['def', 'calculate_flat_histogram(image):', 'hist', '=', 'cv2.calcHist([image],', 'channels=[0,', '1,', '2],', 'mask=None,', 'histSize=[16,', '16,', '16],', 'ranges=[0,', '256,', '0,', '256,', '0,', '256])', 'cv2.normalize(hist,', 'hist)', 'return', 'hist.flatten()'] | 940,964 |
mvondracek/VUT-FIT-POVa-2018-Pedestrian-Tracking | utils.py | get_frame_from_video | get_frame_from_video | From the given video pick 1 frame (image/photo) that is closest to the given time [seconds] since video start. | [
"From",
"the",
"given",
"video",
"pick",
"1",
"frame",
"(image/photo)",
"that",
"is",
"closest",
"to",
"the",
"given",
"time",
"[seconds]",
"since",
"video",
"start."
] | def get_frame_from_video(video_path, frame_time=0.0):
cap = cv2.VideoCapture(video_path)
fps = cap.get(cv2.CAP_PROP_FPS)
time_tolerance_ms = 1 / fps / 2 * 1000
frame_time_ms = frame_time * 1000
current_time_ms = 0.0
frame = None
found = False
while not found:
(ret, frame) = cap.r... | ['def', 'get_frame_from_video(video_path,', 'frame_time=0.0):', 'cap', '=', 'cv2.VideoCapture(video_path)', 'fps', '=', 'cap.get(cv2.CAP_PROP_FPS)', 'time_tolerance_ms', '=', '1', '/', 'fps', '/', '2', '*', '1000', 'frame_time_ms', '=', 'frame_time', '*', '1000', 'current_time_ms', '=', '0.0', 'frame', '=', 'None', 'fo... | 940,966 |
mvondracek/VUT-FIT-POVa-2018-Pedestrian-Tracking | timer.py | povapose_single_image_single_person | povapose_single_image_single_person | Measure pedestrian detection using PovaPose for single image with single person. | [
"Measure",
"pedestrian",
"detection",
"using",
"PovaPose",
"for",
"single",
"image",
"with",
"single",
"person."
] | def povapose_single_image_single_person():
person_detector = PovaPose(prototxt_path='../openpose/pose/coco/pose_deploy_linevec.prototxt', caffemodel_path='../openpose/pose/coco/pose_iter_440000.caffemodel')
image = cv2.imread('../testing_data/s2_f_x0y300.png')
detection = 'person_detector.set_image_for_dete... | ['def', 'povapose_single_image_single_person():', 'person_detector', '=', "PovaPose(prototxt_path='../openpose/pose/coco/pose_deploy_linevec.prototxt',", "caffemodel_path='../openpose/pose/coco/pose_iter_440000.caffemodel')", 'image', '=', "cv2.imread('../testing_data/s2_f_x0y300.png')", 'detection', '=', "'person_dete... | 940,975 |
mvondracek/VUT-FIT-POVa-2018-Pedestrian-Tracking | timer.py | openpose_cpu_binary | openpose_cpu_binary | Measure pedestrian detection using OpenPose binary for GPU. | [
"Measure",
"pedestrian",
"detection",
"using",
"OpenPose",
"binary",
"for",
"GPU."
] | def openpose_cpu_binary(openpose_binary_path=None, repeat=3):
assert openpose_binary_path, 'Provide path to OpenPose binary!'
image = cv2.imread('../testing_data/s2_f_x0y300.png')
person_detector = OpenPoseBinaryDetector(openpose_binary_path, using_gpu=False)
detection = 'people = person_detector.detect... | ['def', 'openpose_cpu_binary(openpose_binary_path=None,', 'repeat=3):', 'assert', 'openpose_binary_path,', "'Provide", 'path', 'to', 'OpenPose', "binary!'", 'image', '=', "cv2.imread('../testing_data/s2_f_x0y300.png')", 'person_detector', '=', 'OpenPoseBinaryDetector(openpose_binary_path,', 'using_gpu=False)', 'detecti... | 940,977 |
kingofspace0wzz/wae-rnf-lm | main.py | weight_schedule | weight_schedule | Scheduling of the KLD annealing weight. | [
"Scheduling",
"of",
"the",
"KLD",
"annealing",
"weight."
] | def weight_schedule(t):
return interpolate(t, 6000, 40000) | ['def', 'weight_schedule(t):', 'return', 'interpolate(t,', '6000,', '40000)'] | 941,010 |
snuailab/waffle_utils | search.py | get_files | get_files | Retrieves a list of files in a directory, optionally filtered by extension. | [
"Retrieves",
"a",
"list",
"of",
"files",
"in",
"a",
"directory,",
"optionally",
"filtered",
"by",
"extension."
] | def get_files(directory: Union[str, Path], extension: Union[list[str], str, None]=None) -> list:
directory = Path(directory)
if isinstance(extension, str):
extension = [extension]
elif extension is None:
extension = []
files = directory.glob(f'**/*')
files = list(filter(lambda x: x.i... | ['def', 'get_files(directory:', 'Union[str,', 'Path],', 'extension:', 'Union[list[str],', 'str,', 'None]=None)', '->', 'list:', 'directory', '=', 'Path(directory)', 'if', 'isinstance(extension,', 'str):', 'extension', '=', '[extension]', 'elif', 'extension', 'is', 'None:', 'extension', '=', '[]', 'files', '=', "directo... | 941,013 |
snuailab/waffle_utils | search.py | get_image_files | get_image_files | Retrieves a list of all image files in a directory. | [
"Retrieves",
"a",
"list",
"of",
"all",
"image",
"files",
"in",
"a",
"directory."
] | def get_image_files(directory: Union[str, Path]) -> list:
return get_files(directory, SUPPORTED_IMAGE_EXTENSIONS) | ['def', 'get_image_files(directory:', 'Union[str,', 'Path])', '->', 'list:', 'return', 'get_files(directory,', 'SUPPORTED_IMAGE_EXTENSIONS)'] | 941,014 |
snuailab/waffle_utils | search.py | get_video_files | get_video_files | Retrieves a list of all video files in a directory. | [
"Retrieves",
"a",
"list",
"of",
"all",
"video",
"files",
"in",
"a",
"directory."
] | def get_video_files(directory: Union[str, Path]) -> list:
return get_files(directory, SUPPORTED_VIDEO_EXTENSION) | ['def', 'get_video_files(directory:', 'Union[str,', 'Path])', '->', 'list:', 'return', 'get_files(directory,', 'SUPPORTED_VIDEO_EXTENSION)'] | 941,015 |
snuailab/waffle_utils | __init__.py | get_fourcc | get_fourcc | Get OpenCV fourcc by extension name. | [
"Get",
"OpenCV",
"fourcc",
"by",
"extension",
"name."
] | def get_fourcc(extension: str) -> cv2.VideoWriter_fourcc:
if extension not in FOURCC_MAP:
raise KeyError(f'{extension} is not supported. Choose one of {list(FOURCC_MAP.keys())}')
return FOURCC_MAP[extension] | ['def', 'get_fourcc(extension:', 'str)', '->', 'cv2.VideoWriter_fourcc:', 'if', 'extension', 'not', 'in', 'FOURCC_MAP:', 'raise', "KeyError(f'{extension}", 'is', 'not', 'supported.', 'Choose', 'one', 'of', "{list(FOURCC_MAP.keys())}')", 'return', 'FOURCC_MAP[extension]'] | 941,019 |
soanagno/wakenet | neuralWake.py | wakeNet.forward | forward | Performs a forward step during training. | [
"Performs",
"a",
"forward",
"step",
"during",
"training."
] | def forward(self, X):
X = X.to(device)
if train_net == 0:
X = X.view(1, -1)
X = self.fc1(X)
X = self.act(X)
X = self.fcb1(X)
if train_net == 0:
X = X.view(1, -1)
X = self.fc2(X)
X = self.act(X)
X = self.fcb2(X)
out = self.act2(self.fc3(X))
return out | ['def', 'forward(self,', 'X):', 'X', '=', 'X.to(device)', 'if', 'train_net', '==', '0:', 'X', '=', 'X.view(1,', '-1)', 'X', '=', 'self.fc1(X)', 'X', '=', 'self.act(X)', 'X', '=', 'self.fcb1(X)', 'if', 'train_net', '==', '0:', 'X', '=', 'X.view(1,', '-1)', 'X', '=', 'self.fc2(X)', 'X', '=', 'self.act(X)', 'X', '=', 'sel... | 941,025 |
soanagno/wakenet | optimisation.py | neuralOptimiser | neuralOptimiser | Calls the Floris optimiser to calculate the optimal yaws of a turbine farm. | [
"Calls",
"the",
"Floris",
"optimiser",
"to",
"calculate",
"the",
"optimal",
"yaws",
"of",
"a",
"turbine",
"farm."
] | def neuralOptimiser(ws, ti, xs, ys, min_yaw=-30, max_yaw=30, plots=False, plots_ini=False, floris_gain=False, mode='yaw', results=True):
print()
print()
print('In NEURAL Optimiser...')
layout = np.concatenate((xs, ys), axis=0)
if mode == 'yaw':
power_ini = -superposition(np.zeros(xs.size), l... | ['def', 'neuralOptimiser(ws,', 'ti,', 'xs,', 'ys,', 'min_yaw=-30,', 'max_yaw=30,', 'plots=False,', 'plots_ini=False,', 'floris_gain=False,', "mode='yaw',", 'results=True):', 'print()', 'print()', "print('In", 'NEURAL', "Optimiser...')", 'layout', '=', 'np.concatenate((xs,', 'ys),', 'axis=0)', 'if', 'mode', '==', "'yaw'... | 941,028 |
soanagno/wakenet | optimisation.py | compare | compare | Performs a comparison between a wind farm produced by the Neural Network vs Floris. | [
"Performs",
"a",
"comparison",
"between",
"a",
"wind",
"farm",
"produced",
"by",
"the",
"Neural",
"Network",
"vs",
"Floris."
] | def compare(yws, ws, ti, xs, ys, plots=False, print_times=True, timings=False, power_opt=True, single=False, saveas=None):
f = open(file_path)
data = json.load(f)
f.close()
layout = np.concatenate((xs, ys), axis=0)
cp = np.array(data['turbine']['properties']['power_thrust_table']['power'])
wind_... | ['def', 'compare(yws,', 'ws,', 'ti,', 'xs,', 'ys,', 'plots=False,', 'print_times=True,', 'timings=False,', 'power_opt=True,', 'single=False,', 'saveas=None):', 'f', '=', 'open(file_path)', 'data', '=', 'json.load(f)', 'f.close()', 'layout', '=', 'np.concatenate((xs,', 'ys),', 'axis=0)', 'cp', '=', "np.array(data['turbi... | 941,029 |
soanagno/wakenet | synth_and_train.py | training | training | Trains the neural model. | [
"Trains",
"the",
"neural",
"model."
] | def training(X_train, X_val, X_test, y_train, y_val, y_test, model, plot_curves=0, multiplots=False, data_size=data_size, batch_size=batch_size, saveas=None):
if batch_size > X_train.shape[0]:
print('Error: batch_size must be <', X_train.shape[0])
exit()
val_batch_size = y_val.size()[0]
trai... | ['def', 'training(X_train,', 'X_val,', 'X_test,', 'y_train,', 'y_val,', 'y_test,', 'model,', 'plot_curves=0,', 'multiplots=False,', 'data_size=data_size,', 'batch_size=batch_size,', 'saveas=None):', 'if', 'batch_size', '>', 'X_train.shape[0]:', "print('Error:", 'batch_size', 'must', 'be', "<',", 'X_train.shape[0])', 'e... | 941,036 |
soanagno/wakenet | visualise.py | visualize_farm | visualize_farm | Function to plot flow-field around a wind farm. | [
"Function",
"to",
"plot",
"flow-field",
"around",
"a",
"wind",
"farm."
] | def visualize_farm(plane, nr_points, size_x, size_y, title='', ax=None, vmax=False):
x = np.linspace(0, size_x, nr_points[0])
y = np.linspace(0, size_y, nr_points[1])
(x_mesh, y_mesh) = np.meshgrid(x, y)
if vmax is False:
vmax = np.max(plane)
im = ax.pcolormesh(x_mesh, y_mesh, plane, shading... | ['def', 'visualize_farm(plane,', 'nr_points,', 'size_x,', 'size_y,', "title='',", 'ax=None,', 'vmax=False):', 'x', '=', 'np.linspace(0,', 'size_x,', 'nr_points[0])', 'y', '=', 'np.linspace(0,', 'size_y,', 'nr_points[1])', '(x_mesh,', 'y_mesh)', '=', 'np.meshgrid(x,', 'y)', 'if', 'vmax', 'is', 'False:', 'vmax', '=', 'np... | 941,062 |
wandb/wandb | noxfile.py | build_nexus | build_nexus | Builds the nexus binary for the current platform. | [
"Builds",
"the",
"nexus",
"binary",
"for",
"the",
"current",
"platform."
] | def build_nexus(session):
session.run('python', '-m', 'build', '-w', '-n', '-x', './nexus', external=True) | ['def', 'build_nexus(session):', "session.run('python',", "'-m',", "'build',", "'-w',", "'-n',", "'-x',", "'./nexus',", 'external=True)'] | 941,155 |
wandb/wandb | noxfile.py | install_nexus | install_nexus | Installs the nexus wheel into the current environment. | [
"Installs",
"the",
"nexus",
"wheel",
"into",
"the",
"current",
"environment."
] | def install_nexus(session):
wheel_file = [f for f in os.listdir('./nexus/dist/') if f.startswith(f'wandb_core-{NEXUS_VERSION}') and f.endswith('.whl')][0]
session.run('pip', 'install', '--force-reinstall', f'./nexus/dist/{wheel_file}', external=True) | ['def', 'install_nexus(session):', 'wheel_file', '=', '[f', 'for', 'f', 'in', "os.listdir('./nexus/dist/')", 'if', "f.startswith(f'wandb_core-{NEXUS_VERSION}')", 'and', "f.endswith('.whl')][0]", "session.run('pip',", "'install',", "'--force-reinstall',", "f'./nexus/dist/{wheel_file}',", 'external=True)'] | 941,156 |
wandb/wandb | save-dir.py | test_save_dir | test_save_dir | NOTE: this is demonstrating broken functionality. | [
"NOTE:",
"this",
"is",
"demonstrating",
"broken",
"functionality."
] | def test_save_dir():
with tempfile.TemporaryDirectory() as tmpdir:
dirname = os.path.join(tmpdir, 'newdir')
fname = os.path.join(tmpdir, 'newdir', 'newfile.txt')
os.mkdir(dirname)
write_file(fname)
with wandb.init() as run:
run.config.id = 'save_dir'
r... | ['def', 'test_save_dir():', 'with', 'tempfile.TemporaryDirectory()', 'as', 'tmpdir:', 'dirname', '=', 'os.path.join(tmpdir,', "'newdir')", 'fname', '=', 'os.path.join(tmpdir,', "'newdir',", "'newfile.txt')", 'os.mkdir(dirname)', 'write_file(fname)', 'with', 'wandb.init()', 'as', 'run:', 'run.config.id', '=', "'save_dir... | 941,162 |
wandb/wandb | conftest.py | local_settings | local_settings | Place global settings in an isolated dir. | [
"Place",
"global",
"settings",
"in",
"an",
"isolated",
"dir."
] | def local_settings(filesystem_isolate):
config_path = os.path.join(os.getcwd(), '.config', 'wandb', 'settings')
filesystem.mkdir_exists_ok(os.path.join('.config', 'wandb'))
with unittest.mock.patch.object(wandb.old.settings.Settings, '_global_path', return_value=config_path):
yield | ['def', 'local_settings(filesystem_isolate):', 'config_path', '=', 'os.path.join(os.getcwd(),', "'.config',", "'wandb',", "'settings')", "filesystem.mkdir_exists_ok(os.path.join('.config',", "'wandb'))", 'with', 'unittest.mock.patch.object(wandb.old.settings.Settings,', "'_global_path',", 'return_value=config_path):', ... | 941,164 |
wandb/wandb | conftest.py | local_netrc | local_netrc | Never use our real credentials, put them in their own isolated dir. | [
"Never",
"use",
"our",
"real",
"credentials,",
"put",
"them",
"in",
"their",
"own",
"isolated",
"dir."
] | def local_netrc(filesystem_isolate):
original_expanduser = os.path.expanduser
open('.netrc', 'wb').close()
def expand(path):
if 'netrc' in path:
try:
full_path = os.path.realpath('netrc')
except OSError:
full_path = original_expanduser(path)
... | ['def', 'local_netrc(filesystem_isolate):', 'original_expanduser', '=', 'os.path.expanduser', "open('.netrc',", "'wb').close()", 'def', 'expand(path):', 'if', "'netrc'", 'in', 'path:', 'try:', 'full_path', '=', "os.path.realpath('netrc')", 'except', 'OSError:', 'full_path', '=', 'original_expanduser(path)', 'else:', 'f... | 941,165 |
wandb/wandb | conftest.py | relay_server | relay_server | Create a new relay server. | [
"Create",
"a",
"new",
"relay",
"server."
] | def relay_server(base_url, wandb_verbose):
@contextmanager
def relay_server_context(inject: Optional[List[InjectedResponse]]=None):
_relay_server = RelayServer(base_url=base_url, inject=inject, verbose=wandb_verbose)
try:
_relay_server.start()
print(f'Relay server starte... | ['def', 'relay_server(base_url,', 'wandb_verbose):', '@contextmanager', 'def', 'relay_server_context(inject:', 'Optional[List[InjectedResponse]]=None):', '_relay_server', '=', 'RelayServer(base_url=base_url,', 'inject=inject,', 'verbose=wandb_verbose)', 'try:', '_relay_server.start()', "print(f'Relay", 'server', 'start... | 941,169 |
wandb/wandb | test_wandb_artifacts_full.py | test_check_existing_artifact_before_download | test_check_existing_artifact_before_download | Don't re-download an artifact if it's already in the desired location. | [
"Don't",
"re-download",
"an",
"artifact",
"if",
"it's",
"already",
"in",
"the",
"desired",
"location."
] | def test_check_existing_artifact_before_download(wandb_init, tmp_path, monkeypatch):
cache_dir = tmp_path / 'cache'
monkeypatch.setenv('WANDB_CACHE_DIR', str(cache_dir))
original_file = tmp_path / 'test.txt'
original_file.write_text('hello')
with wandb_init() as run:
artifact = wandb.Artifac... | ['def', 'test_check_existing_artifact_before_download(wandb_init,', 'tmp_path,', 'monkeypatch):', 'cache_dir', '=', 'tmp_path', '/', "'cache'", "monkeypatch.setenv('WANDB_CACHE_DIR',", 'str(cache_dir))', 'original_file', '=', 'tmp_path', '/', "'test.txt'", "original_file.write_text('hello')", 'with', 'wandb_init()', 'a... | 941,170 |
wandb/wandb | test_metric_full.py | test_metric_dotted | test_metric_dotted | Escape dots in metric definitions. | [
"Escape",
"dots",
"in",
"metric",
"definitions."
] | def test_metric_dotted(relay_server, wandb_init):
with relay_server() as relay:
run = wandb_init()
run_id = run.id
run.define_metric('this\\.that', summary='min')
run.log({'this.that': 3})
run.log({'this.that': 2})
run.log({'this.that': 4})
run.finish()
su... | ['def', 'test_metric_dotted(relay_server,', 'wandb_init):', 'with', 'relay_server()', 'as', 'relay:', 'run', '=', 'wandb_init()', 'run_id', '=', 'run.id', "run.define_metric('this\\\\.that',", "summary='min')", "run.log({'this.that':", '3})', "run.log({'this.that':", '2})', "run.log({'this.that':", '4})', 'run.finish()... | 941,173 |
wandb/wandb | test_metric_internal.py | test_metric_dot_flat_escaped | test_metric_dot_flat_escaped | Match works when metric is escaped. | [
"Match",
"works",
"when",
"metric",
"is",
"escaped."
] | def test_metric_dot_flat_escaped(relay_server, user, publish_util, mock_run):
history = []
history.append(dict(step=0, data={'this.has.dots': 2}))
history.append(dict(step=1, data={'this.also': 2}))
history.append(dict(step=2, data={'nodots': 2}))
history.append(dict(step=3, data={'this.also': 1}))
... | ['def', 'test_metric_dot_flat_escaped(relay_server,', 'user,', 'publish_util,', 'mock_run):', 'history', '=', '[]', 'history.append(dict(step=0,', "data={'this.has.dots':", '2}))', 'history.append(dict(step=1,', "data={'this.also':", '2}))', 'history.append(dict(step=2,', "data={'nodots':", '2}))', 'history.append(dict... | 941,174 |
wandb/wandb | test_time_resolution.py | test_log | test_log | Make sure log is generating history with subsecond resolution. | [
"Make",
"sure",
"log",
"is",
"generating",
"history",
"with",
"subsecond",
"resolution."
] | def test_log(relay_server, wandb_init):
with relay_server() as relay:
before = time.time()
run = wandb_init()
run_id = run.id
for i in range(10):
run.log(dict(k=i))
time.sleep(1e-05)
run.finish()
after = time.time()
history = relay.context.... | ['def', 'test_log(relay_server,', 'wandb_init):', 'with', 'relay_server()', 'as', 'relay:', 'before', '=', 'time.time()', 'run', '=', 'wandb_init()', 'run_id', '=', 'run.id', 'for', 'i', 'in', 'range(10):', 'run.log(dict(k=i))', 'time.sleep(1e-05)', 'run.finish()', 'after', '=', 'time.time()', 'history', '=', 'relay.co... | 941,178 |
wandb/wandb | test_torch_full.py | init_conv_weights | init_conv_weights | Initialize weights for subnet convolution. | [
"Initialize",
"weights",
"for",
"subnet",
"convolution."
] | def init_conv_weights(layer, weights_std=0.01, bias=0):
nn.init.normal_(layer.weight.data, std=weights_std)
nn.init.constant_(layer.bias.data, val=bias)
return layer | ['def', 'init_conv_weights(layer,', 'weights_std=0.01,', 'bias=0):', 'nn.init.normal_(layer.weight.data,', 'std=weights_std)', 'nn.init.constant_(layer.bias.data,', 'val=bias)', 'return', 'layer'] | 941,179 |
wandb/wandb | test_torch_full.py | conv3x3 | conv3x3 | Return a 3x3 convolutional layer for SubNet. | [
"Return",
"a",
"3x3",
"convolutional",
"layer",
"for",
"SubNet."
] | def conv3x3(in_channels, out_channels, **kwargs):
layer = nn.Conv2d(in_channels, out_channels, kernel_size=3, **kwargs)
layer = init_conv_weights(layer)
return layer | ['def', 'conv3x3(in_channels,', 'out_channels,', '**kwargs):', 'layer', '=', 'nn.Conv2d(in_channels,', 'out_channels,', 'kernel_size=3,', '**kwargs)', 'layer', '=', 'init_conv_weights(layer)', 'return', 'layer'] | 941,180 |
wandb/wandb | test_wandb_init.py | test_upsert_bucket_409 | test_upsert_bucket_409 | Test that we retry upsert bucket mutations on 409s. | [
"Test",
"that",
"we",
"retry",
"upsert",
"bucket",
"mutations",
"on",
"409s."
] | def test_upsert_bucket_409(wandb_init, relay_server, inject_graphql_response):
def custom_match_fn(self, other):
request_body = other.__dict__.get('body') or b'{}'
return b'mutation UpsertBucket' in request_body
inject_response = inject_graphql_response(body='GOT ME A 409', status=409, custom_m... | ['def', 'test_upsert_bucket_409(wandb_init,', 'relay_server,', 'inject_graphql_response):', 'def', 'custom_match_fn(self,', 'other):', 'request_body', '=', "other.__dict__.get('body')", 'or', "b'{}'", 'return', "b'mutation", "UpsertBucket'", 'in', 'request_body', 'inject_response', '=', "inject_graphql_response(body='G... | 941,182 |
wandb/wandb | test_wandb_init.py | test_upsert_bucket_410 | test_upsert_bucket_410 | Test that we do not retry upsert bucket mutations on 410s. | [
"Test",
"that",
"we",
"do",
"not",
"retry",
"upsert",
"bucket",
"mutations",
"on",
"410s."
] | def test_upsert_bucket_410(wandb_init, relay_server, inject_graphql_response):
def custom_match_fn(self, other):
request_body = other.__dict__.get('body') or b'{}'
return b'mutation UpsertBucket' in request_body
inject_response = inject_graphql_response(body='GOT ME A 410', status=410, custom_m... | ['def', 'test_upsert_bucket_410(wandb_init,', 'relay_server,', 'inject_graphql_response):', 'def', 'custom_match_fn(self,', 'other):', 'request_body', '=', "other.__dict__.get('body')", 'or', "b'{}'", 'return', "b'mutation", "UpsertBucket'", 'in', 'request_body', 'inject_response', '=', "inject_graphql_response(body='G... | 941,183 |
wandb/wandb | test_github_reference.py | test_parse_bad | test_parse_bad | Expected parse failures, None result. | [
"Expected",
"parse",
"failures,",
"None",
"result."
] | def test_parse_bad() -> None:
ref = GitHubReference.parse('not a url')
assert ref is None
ref = GitHubReference.parse('http://github.com')
assert ref is None | ['def', 'test_parse_bad()', '->', 'None:', 'ref', '=', "GitHubReference.parse('not", 'a', "url')", 'assert', 'ref', 'is', 'None', 'ref', '=', "GitHubReference.parse('http://github.com')", 'assert', 'ref', 'is', 'None'] | 941,190 |
wandb/wandb | test_github_reference.py | test_parse_ssh | test_parse_ssh | We should be able to parse and reconstruct an SSH reference. | [
"We",
"should",
"be",
"able",
"to",
"parse",
"and",
"reconstruct",
"an",
"SSH",
"reference."
] | def test_parse_ssh() -> None:
case = 'git@github.com:wandb/examples.git'
ref = GitHubReference.parse(case)
assert ref.host == 'github.com'
assert ref.organization == 'wandb'
assert ref.repo == 'examples'
assert ref.path is None
assert ref.repo_ssh == case | ['def', 'test_parse_ssh()', '->', 'None:', 'case', '=', "'git@github.com:wandb/examples.git'", 'ref', '=', 'GitHubReference.parse(case)', 'assert', 'ref.host', '==', "'github.com'", 'assert', 'ref.organization', '==', "'wandb'", 'assert', 'ref.repo', '==', "'examples'", 'assert', 'ref.path', 'is', 'None', 'assert', 're... | 941,191 |
wandb/wandb | test_github_reference.py | test_parse_organization | test_parse_organization | Should parse URLs that only have an organization. | [
"Should",
"parse",
"URLs",
"that",
"only",
"have",
"an",
"organization."
] | def test_parse_organization() -> None:
cases = ['https://github.com/wandb', 'https://github.com/orgs/wandb/people']
for case in cases:
ref = GitHubReference.parse(case)
assert ref.host == 'github.com'
assert ref.organization == 'wandb' | ['def', 'test_parse_organization()', '->', 'None:', 'cases', '=', "['https://github.com/wandb',", "'https://github.com/orgs/wandb/people']", 'for', 'case', 'in', 'cases:', 'ref', '=', 'GitHubReference.parse(case)', 'assert', 'ref.host', '==', "'github.com'", 'assert', 'ref.organization', '==', "'wandb'"] | 941,192 |
wandb/wandb | test_github_reference.py | test_parse_repo | test_parse_repo | Should parse URLs that have an organization and a repo. | [
"Should",
"parse",
"URLs",
"that",
"have",
"an",
"organization",
"and",
"a",
"repo."
] | def test_parse_repo() -> None:
case = 'https://github.com/wandb/examples.git'
ref = GitHubReference.parse(case)
assert ref.host == 'github.com'
assert ref.organization == 'wandb'
assert ref.repo == 'examples'
cases = ['https://github.com/wandb/examples', 'https://github.com/wandb/examples/pulls'... | ['def', 'test_parse_repo()', '->', 'None:', 'case', '=', "'https://github.com/wandb/examples.git'", 'ref', '=', 'GitHubReference.parse(case)', 'assert', 'ref.host', '==', "'github.com'", 'assert', 'ref.organization', '==', "'wandb'", 'assert', 'ref.repo', '==', "'examples'", 'cases', '=', "['https://github.com/wandb/ex... | 941,194 |
wandb/wandb | test_github_reference.py | test_parse_auth | test_parse_auth | Should parse a URL that includes a username/password. | [
"Should",
"parse",
"a",
"URL",
"that",
"includes",
"a",
"username/password."
] | def test_parse_auth() -> None:
case = 'https://username@github.com/wandb/examples/blob/commit/path/entry.py'
ref = GitHubReference.parse(case)
assert ref.username == 'username'
assert ref.password is None
assert ref.host == 'github.com'
assert ref.organization == 'wandb'
assert ref.repo == '... | ['def', 'test_parse_auth()', '->', 'None:', 'case', '=', "'https://username@github.com/wandb/examples/blob/commit/path/entry.py'", 'ref', '=', 'GitHubReference.parse(case)', 'assert', 'ref.username', '==', "'username'", 'assert', 'ref.password', 'is', 'None', 'assert', 'ref.host', '==', "'github.com'", 'assert', 'ref.o... | 941,197 |
wandb/wandb | test_github_reference.py | test_get_commit | test_get_commit | Test getting commit from reference. | [
"Test",
"getting",
"commit",
"from",
"reference."
] | def test_get_commit(monkeypatch) -> None:
def mock_fetch_repo(self, dst_dir):
os.makedirs(os.path.join(dst_dir, 'commit/path/'), exist_ok=True)
with open(os.path.join(dst_dir, 'commit/path/requirements.txt'), 'w') as f:
f.write('wandb\n')
self.commit_hash = '1234567890'
... | ['def', 'test_get_commit(monkeypatch)', '->', 'None:', 'def', 'mock_fetch_repo(self,', 'dst_dir):', 'os.makedirs(os.path.join(dst_dir,', "'commit/path/'),", 'exist_ok=True)', 'with', 'open(os.path.join(dst_dir,', "'commit/path/requirements.txt'),", "'w')", 'as', 'f:', "f.write('wandb\\n')", 'self.commit_hash', '=', "'1... | 941,198 |
wandb/wandb | test_launch_sagemaker.py | mock_sagemaker_environment | mock_sagemaker_environment | Mock an instance of the AwsEnvironment class. | [
"Mock",
"an",
"instance",
"of",
"the",
"AwsEnvironment",
"class."
] | def mock_sagemaker_environment():
environment = MagicMock()
client = MagicMock()
session = MagicMock()
session.client.return_value = client
environment.get_session.return_value = session
environment.get_region.return_value = 'us-east-1' | ['def', 'mock_sagemaker_environment():', 'environment', '=', 'MagicMock()', 'client', '=', 'MagicMock()', 'session', '=', 'MagicMock()', 'session.client.return_value', '=', 'client', 'environment.get_session.return_value', '=', 'session', 'environment.get_region.return_value', '=', "'us-east-1'"] | 941,199 |
wandb/wandb | conftest.py | run_id | run_id | Fixture to return a fixed run id for testing. | [
"Fixture",
"to",
"return",
"a",
"fixed",
"run",
"id",
"for",
"testing."
] | def run_id() -> str:
return 'lovely-dawn-32' | ['def', 'run_id()', '->', 'str:', 'return', "'lovely-dawn-32'"] | 941,202 |
wandb/wandb | conftest.py | WandbNotebookClient.cell_output | cell_output | Return a cell's outputs. | [
"Return",
"a",
"cell's",
"outputs."
] | def cell_output(self, cell_index: int) -> List[Dict[str, Any]]:
idx = cell_index + 1
outputs = self.nb.cells[idx]['outputs']
return outputs | ['def', 'cell_output(self,', 'cell_index:', 'int)', '->', 'List[Dict[str,', 'Any]]:', 'idx', '=', 'cell_index', '+', '1', 'outputs', '=', "self.nb.cells[idx]['outputs']", 'return', 'outputs'] | 941,204 |
wandb/wandb | conftest.py | WandbNotebookClient.cell_output_html | cell_output_html | Return a cell's HTML outputs concatenated into a string. | [
"Return",
"a",
"cell's",
"HTML",
"outputs",
"concatenated",
"into",
"a",
"string."
] | def cell_output_html(self, cell_index: int) -> str:
idx = cell_index + 1
html = io.StringIO()
for output in self.nb.cells[idx]['outputs']:
if output['output_type'] == 'display_data':
html.write(output['data']['text/html'])
return html.getvalue() | ['def', 'cell_output_html(self,', 'cell_index:', 'int)', '->', 'str:', 'idx', '=', 'cell_index', '+', '1', 'html', '=', 'io.StringIO()', 'for', 'output', 'in', "self.nb.cells[idx]['outputs']:", 'if', "output['output_type']", '==', "'display_data':", "html.write(output['data']['text/html'])", 'return', 'html.getvalue()'... | 941,205 |
wandb/wandb | conftest.py | WandbNotebookClient.cell_output_text | cell_output_text | Return a cell's text outputs concatenated into a string. | [
"Return",
"a",
"cell's",
"text",
"outputs",
"concatenated",
"into",
"a",
"string."
] | def cell_output_text(self, cell_index: int) -> str:
idx = cell_index + 1
text = io.StringIO()
for output in self.nb.cells[idx]['outputs']:
if output['output_type'] == 'stream':
text.write(output['text'])
return text.getvalue() | ['def', 'cell_output_text(self,', 'cell_index:', 'int)', '->', 'str:', 'idx', '=', 'cell_index', '+', '1', 'text', '=', 'io.StringIO()', 'for', 'output', 'in', "self.nb.cells[idx]['outputs']:", 'if', "output['output_type']", '==', "'stream':", "text.write(output['text'])", 'return', 'text.getvalue()'] | 941,206 |
wandb/wandb | test_datastore.py | check | check | Check datastore size after multiple items written. | [
"Check",
"datastore",
"size",
"after",
"multiple",
"items",
"written."
] | def check(ds, chunk_sizes=tuple(), expected_records=0, expected_pad=0, expected_record_sizes=None):
record_sizes = []
for (_, chunk_size) in enumerate(chunk_sizes):
size = ds._write_data(b'\x01' * chunk_size)
record_sizes.append(size)
num = 7 + sum(chunk_sizes) + expected_records * 7 + expec... | ['def', 'check(ds,', 'chunk_sizes=tuple(),', 'expected_records=0,', 'expected_pad=0,', 'expected_record_sizes=None):', 'record_sizes', '=', '[]', 'for', '(_,', 'chunk_size)', 'in', 'enumerate(chunk_sizes):', 'size', '=', "ds._write_data(b'\\x01'", '*', 'chunk_size)', 'record_sizes.append(size)', 'num', '=', '7', '+', '... | 941,207 |
wandb/wandb | test_datastore.py | test_proto_write_partial | test_proto_write_partial | Serialize a proto into a partial block. | [
"Serialize",
"a",
"proto",
"into",
"a",
"partial",
"block."
] | def test_proto_write_partial():
data = dict(this=2, that=4)
history = wandb_internal_pb2.HistoryRecord()
for (k, v) in data.items():
json_data = json.dumps(v)
item = history.item.add()
item.key = k
item.value_json = json_data
rec = wandb_internal_pb2.Record()
rec.hist... | ['def', 'test_proto_write_partial():', 'data', '=', 'dict(this=2,', 'that=4)', 'history', '=', 'wandb_internal_pb2.HistoryRecord()', 'for', '(k,', 'v)', 'in', 'data.items():', 'json_data', '=', 'json.dumps(v)', 'item', '=', 'history.item.add()', 'item.key', '=', 'k', 'item.value_json', '=', 'json_data', 'rec', '=', 'wa... | 941,209 |
wandb/wandb | test_datastore.py | test_data_write_full | test_data_write_full | Write a full block. | [
"Write",
"a",
"full",
"block."
] | def test_data_write_full(with_datastore):
(sizes, records) = (tuple([32768 - 7 - 7]), 1)
check(with_datastore, chunk_sizes=sizes, expected_records=records) | ['def', 'test_data_write_full(with_datastore):', '(sizes,', 'records)', '=', '(tuple([32768', '-', '7', '-', '7]),', '1)', 'check(with_datastore,', 'chunk_sizes=sizes,', 'expected_records=records)'] | 941,210 |
wandb/wandb | test_datastore.py | test_data_write_overflow | test_data_write_overflow | Write one more than we can fit in a block. | [
"Write",
"one",
"more",
"than",
"we",
"can",
"fit",
"in",
"a",
"block."
] | def test_data_write_overflow(with_datastore):
ds = with_datastore
ds._write_data(b'\x01' * (32768 - 7 - 7 + 1))
ds.close()
s = os.stat(FNAME)
assert s.st_size == 32768 + 7 + 1 | ['def', 'test_data_write_overflow(with_datastore):', 'ds', '=', 'with_datastore', "ds._write_data(b'\\x01'", '*', '(32768', '-', '7', '-', '7', '+', '1))', 'ds.close()', 's', '=', 'os.stat(FNAME)', 'assert', 's.st_size', '==', '32768', '+', '7', '+', '1'] | 941,211 |
wandb/wandb | test_datastore.py | test_data_write_split | test_data_write_split | Leave just room for 1 more byte, then try to write 2. | [
"Leave",
"just",
"room",
"for",
"1",
"more",
"byte,",
"then",
"try",
"to",
"write",
"2."
] | def test_data_write_split(with_datastore):
ds = with_datastore
ds._write_data(b'\x01' * (32768 - 7 - 7 - 8))
ds._write_data(b'\x02' * 2)
ds.close()
s = os.stat(FNAME)
assert s.st_size == 32768 + 7 + 1 | ['def', 'test_data_write_split(with_datastore):', 'ds', '=', 'with_datastore', "ds._write_data(b'\\x01'", '*', '(32768', '-', '7', '-', '7', '-', '8))', "ds._write_data(b'\\x02'", '*', '2)', 'ds.close()', 's', '=', 'os.stat(FNAME)', 'assert', 's.st_size', '==', '32768', '+', '7', '+', '1'] | 941,214 |
wandb/wandb | test_data_types.py | subdict | subdict | Return a new dict with only the items from `d` whose keys occur in `expected_dict`. | [
"Return",
"a",
"new",
"dict",
"with",
"only",
"the",
"items",
"from",
"`d`",
"whose",
"keys",
"occur",
"in",
"`expected_dict`."
] | def subdict(d, expected_dict):
return {k: v for (k, v) in d.items() if k in expected_dict} | ['def', 'subdict(d,', 'expected_dict):', 'return', '{k:', 'v', 'for', '(k,', 'v)', 'in', 'd.items()', 'if', 'k', 'in', 'expected_dict}'] | 941,217 |
wandb/wandb | test_data_types.py | matplotlib_without_image | matplotlib_without_image | Create a matplotlib figure without an image. | [
"Create",
"a",
"matplotlib",
"figure",
"without",
"an",
"image."
] | def matplotlib_without_image():
(fig, ax) = plt.subplots(2)
ax[0].plot([1, 2, 3])
ax[1].plot([1, 2, 3])
return fig | ['def', 'matplotlib_without_image():', '(fig,', 'ax)', '=', 'plt.subplots(2)', 'ax[0].plot([1,', '2,', '3])', 'ax[1].plot([1,', '2,', '3])', 'return', 'fig'] | 941,220 |
wandb/wandb | test_dir_watcher.py | test_dirwatcher_update_policy_live_calls_file_changed_iff_file_nonempty | test_dirwatcher_update_policy_live_calls_file_changed_iff_file_nonempty | Test that if a file exists, the update policy is called. | [
"Test",
"that",
"if",
"a",
"file",
"exists,",
"the",
"update",
"policy",
"is",
"called."
] | def test_dirwatcher_update_policy_live_calls_file_changed_iff_file_nonempty(tempdir: Path, file_pusher: FilePusher, dir_watcher: DirWatcher, write_file: Callable[[Path], None], expect_called: bool):
f = tempdir / 'my-file.txt'
write_file(f)
dir_watcher.update_policy(str(f), 'live')
assert file_pusher.fi... | ['def', 'test_dirwatcher_update_policy_live_calls_file_changed_iff_file_nonempty(tempdir:', 'Path,', 'file_pusher:', 'FilePusher,', 'dir_watcher:', 'DirWatcher,', 'write_file:', 'Callable[[Path],', 'None],', 'expect_called:', 'bool):', 'f', '=', 'tempdir', '/', "'my-file.txt'", 'write_file(f)', 'dir_watcher.update_poli... | 941,233 |
wandb/wandb | test_util.py | test_matplotlib_contains_images | test_matplotlib_contains_images | Test detecting images in a matplotlib figure. | [
"Test",
"detecting",
"images",
"in",
"a",
"matplotlib",
"figure."
] | def test_matplotlib_contains_images():
fig = matplotlib_with_image()
assert util.matplotlib_contains_images(fig)
plt.close()
fig = matplotlib_with_image()
assert util.matplotlib_contains_images(plt)
plt.close()
fig = matplotlib_without_image()
assert not util.matplotlib_contains_images(f... | ['def', 'test_matplotlib_contains_images():', 'fig', '=', 'matplotlib_with_image()', 'assert', 'util.matplotlib_contains_images(fig)', 'plt.close()', 'fig', '=', 'matplotlib_with_image()', 'assert', 'util.matplotlib_contains_images(plt)', 'plt.close()', 'fig', '=', 'matplotlib_without_image()', 'assert', 'not', 'util.m... | 941,244 |
wandb/wandb | test_util.py | test_make_check_reply_fn_timeout | test_make_check_reply_fn_timeout | Verify case where secondary check returns a new timeout. | [
"Verify",
"case",
"where",
"secondary",
"check",
"returns",
"a",
"new",
"timeout."
] | def test_make_check_reply_fn_timeout():
e = mock.MagicMock(spec=requests.HTTPError)
e.response = mock.MagicMock(spec=requests.Response)
check_retry_fn = util.make_check_retry_fn(check_fn=util.check_retry_conflict_or_gone, check_timedelta=datetime.timedelta(minutes=3), fallback_retry_fn=util.no_retry_auth)
... | ['def', 'test_make_check_reply_fn_timeout():', 'e', '=', 'mock.MagicMock(spec=requests.HTTPError)', 'e.response', '=', 'mock.MagicMock(spec=requests.Response)', 'check_retry_fn', '=', 'util.make_check_retry_fn(check_fn=util.check_retry_conflict_or_gone,', 'check_timedelta=datetime.timedelta(minutes=3),', 'fallback_retr... | 941,246 |
wandb/wandb | test_util.py | test_make_check_reply_fn_false | test_make_check_reply_fn_false | Verify case where secondary check forces no retry. | [
"Verify",
"case",
"where",
"secondary",
"check",
"forces",
"no",
"retry."
] | def test_make_check_reply_fn_false():
e = mock.MagicMock(spec=requests.HTTPError)
e.response = mock.MagicMock(spec=requests.Response)
def is_special(e):
if e.response.status_code == 500:
return False
return None
check_retry_fn = util.make_check_retry_fn(check_fn=is_special, ... | ['def', 'test_make_check_reply_fn_false():', 'e', '=', 'mock.MagicMock(spec=requests.HTTPError)', 'e.response', '=', 'mock.MagicMock(spec=requests.Response)', 'def', 'is_special(e):', 'if', 'e.response.status_code', '==', '500:', 'return', 'False', 'return', 'None', 'check_retry_fn', '=', 'util.make_check_retry_fn(chec... | 941,247 |
wandb/wandb | test_agent.py | test_thread_failed_no_run | test_thread_failed_no_run | Test that we fail RQI when the job exits non-zero but there is no run. | [
"Test",
"that",
"we",
"fail",
"RQI",
"when",
"the",
"job",
"exits",
"non-zero",
"but",
"there",
"is",
"no",
"run."
] | def test_thread_failed_no_run(mocker):
_setup_thread_finish(mocker)
mock_config = {'entity': 'test-entity', 'project': 'test-project'}
mocker.api.get_run_info.return_value = None
agent = LaunchAgent(api=mocker.api, config=mock_config)
mock_saver = MagicMock()
job = JobAndRunStatusTracker('run_qu... | ['def', 'test_thread_failed_no_run(mocker):', '_setup_thread_finish(mocker)', 'mock_config', '=', "{'entity':", "'test-entity',", "'project':", "'test-project'}", 'mocker.api.get_run_info.return_value', '=', 'None', 'agent', '=', 'LaunchAgent(api=mocker.api,', 'config=mock_config)', 'mock_saver', '=', 'MagicMock()', 'j... | 941,255 |
wandb/wandb | test_kaniko.py | azure_environment | azure_environment | Fixture for AzureEnvironment class. | [
"Fixture",
"for",
"AzureEnvironment",
"class."
] | def azure_environment(mocker):
mocker.patch('wandb.sdk.launch.environment.azure_environment.DefaultAzureCredential', MagicMock())
config = {'environment': {'type': 'azure'}}
return AzureEnvironment.from_config(config) | ['def', 'azure_environment(mocker):', "mocker.patch('wandb.sdk.launch.environment.azure_environment.DefaultAzureCredential',", 'MagicMock())', 'config', '=', "{'environment':", "{'type':", "'azure'}}", 'return', 'AzureEnvironment.from_config(config)'] | 941,257 |
wandb/wandb | test_kaniko.py | test_kaniko_azure | test_kaniko_azure | Test that the kaniko builder correctly constructs the job spec for Azure. | [
"Test",
"that",
"the",
"kaniko",
"builder",
"correctly",
"constructs",
"the",
"job",
"spec",
"for",
"Azure."
] | def test_kaniko_azure(azure_container_registry):
builder = KanikoBuilder(environment=azure_container_registry.environment, registry=azure_container_registry, build_job_name='test', build_context_store='https://account.blob.core.windows.net/container/blob')
core_client = MagicMock()
job = builder._create_kan... | ['def', 'test_kaniko_azure(azure_container_registry):', 'builder', '=', 'KanikoBuilder(environment=azure_container_registry.environment,', 'registry=azure_container_registry,', "build_job_name='test',", "build_context_store='https://account.blob.core.windows.net/container/blob')", 'core_client', '=', 'MagicMock()', 'jo... | 941,259 |
wandb/wandb | test_aws.py | test_from_default | test_from_default | Test creating an AWS environment from the default credentials. | [
"Test",
"creating",
"an",
"AWS",
"environment",
"from",
"the",
"default",
"credentials."
] | def test_from_default(mocker) -> None:
boto3 = MagicMock()
session = MagicMock()
credentials = MagicMock()
credentials.access_key = 'access_key'
credentials.secret_key = 'secret_key'
credentials.token = 'token'
session.get_credentials.return_value = credentials
boto3.Session.return_value... | ['def', 'test_from_default(mocker)', '->', 'None:', 'boto3', '=', 'MagicMock()', 'session', '=', 'MagicMock()', 'credentials', '=', 'MagicMock()', 'credentials.access_key', '=', "'access_key'", 'credentials.secret_key', '=', "'secret_key'", 'credentials.token', '=', "'token'", 'session.get_credentials.return_value', '=... | 941,260 |
wandb/wandb | test_aws.py | test_verify_storage | test_verify_storage | Test that the AwsEnvironment correctly verifies storage. | [
"Test",
"that",
"the",
"AwsEnvironment",
"correctly",
"verifies",
"storage."
] | def test_verify_storage(mocker):
session = MagicMock()
client = MagicMock()
client.head_bucket.return_value = 'Success!'
session.client.return_value = client
mocker.patch('wandb.sdk.launch.environment.aws_environment.AwsEnvironment.get_session', return_value=session)
environment = _get_environme... | ['def', 'test_verify_storage(mocker):', 'session', '=', 'MagicMock()', 'client', '=', 'MagicMock()', 'client.head_bucket.return_value', '=', "'Success!'", 'session.client.return_value', '=', 'client', "mocker.patch('wandb.sdk.launch.environment.aws_environment.AwsEnvironment.get_session',", 'return_value=session)', 'en... | 941,261 |
wandb/wandb | test_aws.py | test_upload_directory | test_upload_directory | Test that we issue the correct api calls to upload files to s3. | [
"Test",
"that",
"we",
"issue",
"the",
"correct",
"api",
"calls",
"to",
"upload",
"files",
"to",
"s3."
] | def test_upload_directory(mocker):
source_dir = 'source_dir'
walk_output = [(f'{source_dir}', None, ['Dockerfile', 'main.py', 'requirements.txt']), (os.path.join(source_dir, 'module'), '', ['dataset.py', 'eval.py', 'model.py']), (os.path.join(source_dir, 'module', 'submodule'), '', ['that.py', 'this.py'])]
... | ['def', 'test_upload_directory(mocker):', 'source_dir', '=', "'source_dir'", 'walk_output', '=', "[(f'{source_dir}',", 'None,', "['Dockerfile',", "'main.py',", "'requirements.txt']),", '(os.path.join(source_dir,', "'module'),", "'',", "['dataset.py',", "'eval.py',", "'model.py']),", '(os.path.join(source_dir,', "'modul... | 941,263 |
wandb/wandb | test_gcp.py | test_environment_no_default_creds | test_environment_no_default_creds | Test that the environment raises an error if there are no default credentials. | [
"Test",
"that",
"the",
"environment",
"raises",
"an",
"error",
"if",
"there",
"are",
"no",
"default",
"credentials."
] | def test_environment_no_default_creds(mocker):
mocker.patch('wandb.sdk.launch.environment.gcp_environment.google.auth.default', side_effect=DefaultCredentialsError)
with pytest.raises(LaunchError):
GcpEnvironment('region') | ['def', 'test_environment_no_default_creds(mocker):', "mocker.patch('wandb.sdk.launch.environment.gcp_environment.google.auth.default',", 'side_effect=DefaultCredentialsError)', 'with', 'pytest.raises(LaunchError):', "GcpEnvironment('region')"] | 941,267 |
wandb/wandb | test_gcp.py | test_environment_verify_invalid_creds | test_environment_verify_invalid_creds | Test that the environment raises an error if the credentials are invalid. | [
"Test",
"that",
"the",
"environment",
"raises",
"an",
"error",
"if",
"the",
"credentials",
"are",
"invalid."
] | def test_environment_verify_invalid_creds(mocker):
credentials = MagicMock()
credentials.refresh = MagicMock()
credentials.valid = False
mocker.patch('wandb.sdk.launch.environment.gcp_environment.google.auth.default', return_value=(credentials, 'project'))
with pytest.raises(LaunchError):
Gc... | ['def', 'test_environment_verify_invalid_creds(mocker):', 'credentials', '=', 'MagicMock()', 'credentials.refresh', '=', 'MagicMock()', 'credentials.valid', '=', 'False', "mocker.patch('wandb.sdk.launch.environment.gcp_environment.google.auth.default',", 'return_value=(credentials,', "'project'))", 'with', 'pytest.rais... | 941,268 |
wandb/wandb | test_gcp.py | test_get_gcloud_config_value | test_get_gcloud_config_value | Test that we correctly handle gcloud outputs. | [
"Test",
"that",
"we",
"correctly",
"handle",
"gcloud",
"outputs."
] | def test_get_gcloud_config_value(mocker, region, value):
mocker.patch('wandb.sdk.launch.environment.gcp_environment.subprocess.check_output', return_value=region)
assert get_gcloud_config_value('region') == value | ['def', 'test_get_gcloud_config_value(mocker,', 'region,', 'value):', "mocker.patch('wandb.sdk.launch.environment.gcp_environment.subprocess.check_output',", 'return_value=region)', 'assert', "get_gcloud_config_value('region')", '==', 'value'] | 941,270 |
wandb/wandb | test_acr.py | test_acr_registry_name | test_acr_registry_name | Test if repository name is parsed correctly. | [
"Test",
"if",
"repository",
"name",
"is",
"parsed",
"correctly."
] | def test_acr_registry_name(mocker):
mocker.patch('wandb.sdk.launch.environment.azure_environment.DefaultAzureCredential', MagicMock())
config = {'uri': 'https://test.azurecr.io/repository'}
registry = AzureContainerRegistry.from_config(config, AzureEnvironment.from_config({}))
assert registry.registry_n... | ['def', 'test_acr_registry_name(mocker):', "mocker.patch('wandb.sdk.launch.environment.azure_environment.DefaultAzureCredential',", 'MagicMock())', 'config', '=', "{'uri':", "'https://test.azurecr.io/repository'}", 'registry', '=', 'AzureContainerRegistry.from_config(config,', 'AzureEnvironment.from_config({}))', 'asse... | 941,274 |
wandb/wandb | test_ecr.py | test_ecr_verify | test_ecr_verify | Test that the ECR registry is verified correctly. | [
"Test",
"that",
"the",
"ECR",
"registry",
"is",
"verified",
"correctly."
] | def test_ecr_verify():
client = MagicMock()
client.describe_registry.return_value = {'registryId': '123456789012'}
client.describe_repositories.return_value = {'repositories': [{'repositoryUri': '123456789012.dkr.ecr.us-east-1.amazonaws.com/my-repo'}]}
session = MagicMock()
session.client.return_val... | ['def', 'test_ecr_verify():', 'client', '=', 'MagicMock()', 'client.describe_registry.return_value', '=', "{'registryId':", "'123456789012'}", 'client.describe_repositories.return_value', '=', "{'repositories':", "[{'repositoryUri':", "'123456789012.dkr.ecr.us-east-1.amazonaws.com/my-repo'}]}", 'session', '=', 'MagicMo... | 941,275 |
wandb/wandb | test_ecr.py | test_ecr_image_exists | test_ecr_image_exists | Test that the ECR registry checks if an image exists correctly. | [
"Test",
"that",
"the",
"ECR",
"registry",
"checks",
"if",
"an",
"image",
"exists",
"correctly."
] | def test_ecr_image_exists():
client = MagicMock()
client.describe_images.return_value = {'imageDetails': [{'imageDigest': 'sha256:1234567890123456789012345678901234567890123456789012345678901234'}]}
client.describe_registry.return_value = {'registryId': '123456789012'}
client.describe_repositories.retur... | ['def', 'test_ecr_image_exists():', 'client', '=', 'MagicMock()', 'client.describe_images.return_value', '=', "{'imageDetails':", "[{'imageDigest':", "'sha256:1234567890123456789012345678901234567890123456789012345678901234'}]}", 'client.describe_registry.return_value', '=', "{'registryId':", "'123456789012'}", 'client... | 941,277 |
wandb/wandb | test_gcp_artifact_registry.py | test_bad_image_name | test_bad_image_name | Test that a bad image name raises an error. | [
"Test",
"that",
"a",
"bad",
"image",
"name",
"raises",
"an",
"error."
] | def test_bad_image_name():
bad_names = ['-bad-image-name', 'bad-image-name!', 'bad image name']
for bad_name in bad_names:
with pytest.raises(LaunchError) as e:
GoogleArtifactRegistry(repository='test-repository', image_name=bad_name, environment=MagicMock(), verify=False)
assert f'T... | ['def', 'test_bad_image_name():', 'bad_names', '=', "['-bad-image-name',", "'bad-image-name!',", "'bad", 'image', "name']", 'for', 'bad_name', 'in', 'bad_names:', 'with', 'pytest.raises(LaunchError)', 'as', 'e:', "GoogleArtifactRegistry(repository='test-repository',", 'image_name=bad_name,', 'environment=MagicMock(),',... | 941,279 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.