func_name
stringlengths
2
57
code
stringlengths
206
31.2k
prompt
stringlengths
12
1.86k
task_id
stringlengths
1
5
tests
listlengths
5
5
cyclomatic_complexity
int64
10
82
toTextType
class AvroNull: pass class AvroBoolean: pass class AvroInt: pass class AvroLong: pass class AvroFloat: pass class AvroDouble: pass class AvroBytes: pass class AvroString: pass class AvroArray: def __init__(self, items): self.items = items class AvroMap: def __in...
Render a type as humanreadable text. Note that this function is incomplete, but it covers all the cases seen in any PFA functions.
1
[ "def test_toTextType_0():\n assert toTextType(AvroNull()) == 'null'", "def test_toTextType_1():\n assert toTextType(AvroNull()) == 'null'", "def test_toTextType_2():\n assert toTextType(AvroNull()) == 'null'", "def test_toTextType_3():\n assert toTextType(AvroNull()) == 'null'", "def test_toText...
11
protest
def protest(text,hashtag): if (len(re.findall(r'\bmarch', text)) != 0) | (len(re.findall(r'\bprotest', text)) != 0) | (len(re.findall(r'\brally', text)) != 0) | (len(re.findall(r'\bgather', text)) != 0) | (len(re.findall(r'\bsit-in', text)) != 0) | (len(re.findall(r'\bcrowd', text)) != 0) | (len(re.findall(r'\briot...
boolean filter to be used in our classifier
4
[ "def test_protest_0():\n test_input = 'The protest march was peaceful and well-organized.'\n expected_output = 1\n assert protest(test_input, 'protest') == expected_output", "def test_protest_1():\n test_input = 'A large crowd gathered for the rally, but no march was seen.'\n expected_output = 1\n ...
21
paintTheFence
def paintTheFence(ranges, n, q): section = [0] * (n + 2) # Constant range addition for i in range(q): section[ranges[i][0]] += 1 # adding -1 to next idx to nullify the effect of addition section[ranges[i][1]+1] -= 1 # prefix sum for i in range(1, n + 1): section[i]...
We first calculate all the sections that are painted by all the painters given and store them in sections array. This time we use the method of constant range addtion using prefix sums.
7
[ "def test_paintTheFence_0():\n assert paintTheFence([(1, 3), (2, 5)], 5, 2) == 2", "def test_paintTheFence_1():\n assert paintTheFence([(1, 2), (2, 3), (3, 4)], 4, 3) == 1", "def test_paintTheFence_2():\n assert paintTheFence([(1, 2), (2, 3), (3, 4), (1, 4)], 4, 4) == 0", "def test_paintTheFence_3():...
10
is_degree_in_degree_range
def is_degree_in_degree_range(degree_a, degree_b, degree_c): degrees_omni = [degree_a, degree_b, degree_c] for x in range(len(degrees_omni)): if degrees_omni[x] > 180 or degrees_omni[x] <= -180: degrees_omni[x] = -180 * (((degrees_omni[x] // 180) % 2) * degrees_omni[x]/abs(degrees_omni[x]))...
Checkes whether a given degreevalue lies between two bounding degreevalues, where degree_a and degree_b are the bounding degreelimits, with degree_a representing the clockwise oriented degreevalue and degree_b representing the counterclockwise degreevalue. Degree_c is the value being checked.
10
[ "def test_is_degree_in_degree_range_0():\n assert is_degree_in_degree_range(30, 150, 100) == True", "def test_is_degree_in_degree_range_1():\n assert is_degree_in_degree_range(-190, 170, -180) == True", "def test_is_degree_in_degree_range_2():\n assert is_degree_in_degree_range(359, 1, 180) == True", ...
12
starve_nests
terrain_nest_bc = 1 terrain_nest_sc = 2 terrain_nest_starved_bc = 3 bc_starve_range = 1 sc_feed_multiplier = 2 def starve_nests(terrain_map): height = len(terrain_map) width = len(terrain_map[0]) for y in range(height): for x in range(width): if terrain_map[y][x] == terrain_nest_bc: ...
For each BC, check other SC and BC tiles in a given range, and starve the nest if it then exceeds a limit set by sc_feed_multiplier
13
[ "def test_starve_nests_0():\n terrain_map = [[1, 1, 1, 1, 1], [1, 2, 2, 2, 1], [1, 2, 1, 2, 1], [1, 2, 2, 2, 1], [1, 1, 1, 1, 1]]\n expected_map = [[1, 1, 1, 1, 1], [1, 3, 2, 2, 1], [1, 2, 1, 2, 1], [1, 2, 2, 2, 1], [1, 1, 1, 1, 1]]\n result = starve_nests(terrain_map)\n assert result == expected_map, f...
18
compute_comment_stats
def compute_comment_stats(file_name, comment_char): isComment = False x = 0 try: with open(file_name) as input: idx = 0 for line in input: isComment = False while idx < (len(line) - 1): if(comment_char == "#"): ...
Collect data on number of comments in the current file
15
[ "def test_compute_comment_stats_0():\n assert compute_comment_stats('test_comments.txt', '#') == 3", "def test_compute_comment_stats_1():\n assert compute_comment_stats('test_no_comments.txt', '#') == 0", "def test_compute_comment_stats_2():\n assert compute_comment_stats('test_multiple_comments.txt', ...
14
question4c
def question4c(T, r, n1, n2): # if three has less than three nodes, return None if len(T)<=2: return # order search nodes if n1<n2: ln, rn = n1, n2 else: ln, rn = n2, n1 while True: # if either node matches with root, return root if r==ln or r==ln: ...
Find the least common ancestor between two nodes on a binary search tree
20
[ "def test_question4c_0():\n test_input = [[], [1, 2, 3, 4, 5, 6, 7], 3, 5, 2, 4]\n assert question4c(*test_input) == 3", "def test_question4c_1():\n test_input = [[], [1, 2, 3, 4, 5, 6, 7], 1, 5, 1, 5]\n assert question4c(*test_input) == 1", "def test_question4c_2():\n test_input = [[], [1, 2, 3,...
16
for_FIVE
def for_FIVE(): for row in range(5): for col in range(4): if col==0 and row!=3 or col==3 and row!=1 or row==0 or row==2 or row==4: print("*",end=" ") else: print(" ",end=" ") print()
printing numbr 'FIVE' using for loop
21
[ "def test_for_FIVE_0():\n for_FIVE()\n expected_output = ' * * * *\\n * * * *\\n * * * *\\n * * * *\\n * * * *'\n assert print('\\n'.join([''.join(line) for line in for_FIVE()]), f\"Expected output:\\n{expected_output}\\nBut got:\\n{''.join([''.join(line) for line in for_FIVE()])}\")", "def test_for_FIVE...
10
while_FIVE
def while_FIVE(): i=0 while i<5: j=0 while j<4: if i==0 or i==2 or i==4 or j==3 and i in(0,2,3,4)or j==0 and i==1: print("*",end=" ") else: print(" ",end=" ") j+=1 i+=1 prin...
printing number 'FIVE' using while loop
22
[ "def test_while_FIVE_0():", "def test_while_FIVE_1():", "def test_while_FIVE_2():", "def test_while_FIVE_3():\n expected_output = ' ' * 25\n with self.assertRaises(SystemExit):\n while_FIVE()", "def test_while_FIVE_4():" ]
10
are_inputs_valid
def are_inputs_valid(mainParams, trgRoiNames): mod = mainParams['roicolMod'] srcRoiName = mainParams['srcRoiName'] srcSlcNum = mainParams['srcSlcNum'] trgRoiName = mainParams['trgRoiName'] trgSlcNum = mainParams['trgSlcNum'] """ Useful variables: RorS = 'ROI' or 'segment', ...
Check if the combination of input parameters are valid.
28
[ "def test_are_inputs_valid_0():\n test_input = {'roicolMod': 'RTSTRUCT', 'srcRoiName': 'TestROI', 'srcSlcNum': None, 'trgRoiName': 'TestROI', 'trgSlcNum': None, 'trgRoiNames': None}\n assert are_inputs_valid(test_input) == (True, '')", "def test_are_inputs_valid_1():\n test_input = {'roicolMod': 'NIFTI',...
14
get_edge_point_delta
def get_edge_point_delta(wd, ht, angle): # logging.info(['angle: ', angle]) if angle >= 0 and angle <= math.pi/2: sector = 1 elif angle > math.pi/2: sector = 2 elif angle < -math.pi/2: sector = 3 elif angle <= 0 and angle >= -math.pi/2: sector = 4 # jfc have to define every single case separa...
get attach point of edge for node
29
[ "def test_get_edge_point_delta_0():\n assert get_edge_point_delta(10, 5, math.pi / 4) == (5, 5 * math.sqrt(2))", "def test_get_edge_point_delta_1():\n assert get_edge_point_delta(10, 5, -math.pi / 4) == (5, -5 * math.sqrt(2))", "def test_get_edge_point_delta_2():\n assert get_edge_point_delta(5, 10, ma...
16
DetPiece
def DetPiece(x): wpawn = ['P'+str(i) for i in range(1, 9)] bpawn = ['p'+str(i) for i in range(1, 9)] wpromote = [None, 'Q', 'R', 'B', 'N'] bpromote = [None, 'q', 'r', 'b', 'n'] wother = ['R'+str(i) for i in range(1, 9)] + ['N'+str(i) for i in range(1, 9)] + ['B'+str(i) for i in range(1, 9)] + ['Q',...
Takes the starting location of the piece to be moved and returns a tuple that contains the name of the piece at that location and the boolean value of the color. Returns 'None' if there is nothing located at the given position
30
[ "def test_DetPiece_0():\n assert DetPiece('e4') == ('Pawn', True)", "def test_DetPiece_1():\n assert DetPiece('e5') == ('Pawn', False)", "def test_DetPiece_2():\n assert DetPiece('Nf3') == ('Knight', True)", "def test_DetPiece_3():\n assert DetPiece('Qd1') == ('King', True)", "def test_DetPiece_...
18
get_adjacent_buckets
def get_adjacent_buckets(cx, cy, buckets): c_bucket = [] b_length = len(buckets[0]) if cx - 1 >= 0: c_bucket += buckets[cy ][cx - 1] if cx - 1 >= 0 and cy - 1 >= 0: c_bucket += buckets[cy - 1][cx - 1] if cy - 1 >= 0: c_bucket += buckets[cy - 1][cx] if cx + 1 < b_leng...
Return a list of the points in the buckets adjacent to the given bucket.
31
[ "def test_get_adjacent_buckets_0():\n buckets = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n (cx, cy) = (1, 1)\n expected = [2, 4, 5, 6, 8, 9, 1, 3]\n assert get_adjacent_buckets(cx, cy, buckets) == expected", "def test_get_adjacent_buckets_1():\n buckets = [[1, 2], [3, 4]]\n (cx, cy) = (0, 0)\n expec...
13
for_three
def for_three(): for row in range(7): for col in range(4): if row%3==0 and col>0 and col<3 or col==3 and row%3!=0 or col==0 and row in (1,5): print('*', end = ' ') else: print(' ...
Number pattern '3' using Python for loop
35
[ "def test_for_three_0():\n expected_output = ' * * *\\n * * *\\n * * *\\n * * *\\n * * *\\n * * *\\n * * *\\n'\n print(for_three())\n assert print(for_three()) == expected_output, 'Test failed: Output does not match expected pattern.'", "def test_for_three_1():\n expected_output = ' * * *\\n * * *\\n ...
10
while_three
def while_three(): row = 0 while row<7: col = 0 while col<4: if row%3==0 and col>0 and col<3 or col==3 and row%3!=0 or col==0 and row in (1,5): print('*', end = ' ') else: ...
Number pattern '3' using Python while loop
36
[ "def test_while_three_0():\n expected_output = ' * * *\\n * * *\\n * * *\\n * * *\\n * * *\\n * * *\\n * * *\\n'\n assert while_three() == expected_output", "def test_while_three_1():\n expected_output = ' * * *\\n * * *\\n * * *\\n * * *\\n * * *\\n * * *\\n * * *\\n'\n assert while_three() == expect...
10
do_filesizeformat
def do_filesizeformat(value, binary=False): bytes = float(value) base = binary and 1024 or 1000 prefixes = [ (binary and "KiB" or "kB"), (binary and "MiB" or "MB"), (binary and "GiB" or "GB"), (binary and "TiB" or "TB"), (binary and "PiB" or "PB"), (b...
Format the value like a 'humanreadable' file size (i.e. 13 kB, 4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega, Giga, etc.), if the second parameter is set to `True` the binary prefixes are used (Mebi, Gibi).
38
[ "def test_do_filesizeformat_0():\n assert do_filesizeformat(13) == '13 Bytes'", "def test_do_filesizeformat_1():\n assert do_filesizeformat(0.5) == '0.5 Bytes'", "def test_do_filesizeformat_2():\n assert do_filesizeformat(999999, False) == '999.999 kB'", "def test_do_filesizeformat_3():\n assert d...
23
region_initial_allocated_loss
def region_initial_allocated_loss(m, r): region_interconnector_loss = 0 for i in m['S_INTERCONNECTORS']: from_region = m['P_INTERCONNECTOR_FROM_REGION'][i] to_region = m['P_INTERCONNECTOR_TO_REGION'][i] mnsp_status = m['P_INTERCONNECTOR_MNSP_STATUS'][i] if r not in [from_regio...
Losses allocated to region due to interconnector flow
39
[ "def test_region_initial_allocated_loss_0():\n m = {'S_INTERCONNECTORS': [0], 'P_INTERCONNECTOR_FROM_REGION': ['A', 'B'], 'P_INTERCONNECTOR_TO_REGION': ['B', 'A'], 'P_INTERCONNECTOR_MNSP_STATUS': ['1', '0'], 'P_INTERCONNECTOR_INITIAL_LOSS_ESTIMATE': [100], 'P_INTERCONNECTOR_LOSS_SHARE': [0.1], 'P_INTERCONNECTOR_...
19
region_allocated_loss_rule
def region_allocated_loss_rule(m, r): region_interconnector_loss = 0 for i in m['S_INTERCONNECTORS']: from_region = m['P_INTERCONNECTOR_FROM_REGION'][i] to_region = m['P_INTERCONNECTOR_TO_REGION'][i] mnsp_status = m['P_INTERCONNECTOR_MNSP_STATUS'][i] if r not in [from_region, t...
Interconnector loss allocated to given region
40
[ "def test_region_allocated_loss_rule_0():\n m = {'S_INTERCONNECTORS': [0], 'P_INTERCONNECTOR_FROM_REGION': ['A', 'B'], 'P_INTERCONNECTOR_TO_REGION': ['B', 'A'], 'P_INTERCONNECTOR_MNSP_STATUS': ['1', '0'], 'V_LOSS': [100], 'P_INTERCONNECTOR_LOSS_SHARE': [0.1], 'P_INTERCONNECTOR_EFFECTIVE_INITIAL_MW': [50, -10]}\n...
19
max_size_for_tile
def max_size_for_tile(tile, grid, tile_by_loc, rclk_rows): tile_type = grid[tile]['type'] if tile_type == 'NULL': return (1, 1) # Pos X, Neg Y base_grid_x = grid[tile]['grid_x'] base_grid_y = grid[tile]['grid_y'] # Walk up X grid_x = base_grid_x grid_y = base_grid_y while T...
Guess maximum size for a tile.
41
[ "def test_max_size_for_tile_0():\n test_input = {\n 'tile': 'A',\n 'grid': {\n 'A': {'type': 'NULL', 'grid_x': 0, 'grid_y': 0},\n 'B': {'type': 'NULL', 'grid_x': 1, 'grid_y': 0},\n 'C': {'type': 'NULL', 'grid_x': 2, 'grid_y': 0},\n 'D': {'type': 'NULL', '...
10
create_process_env
def create_process_env(options): penv = {} ## by default, a worker/guest process inherits ## complete environment inherit_all = True ## check/inherit parent process environment if 'env' in options and 'inherit' in options['env']: inherit = options['env']['inherit'] if type(inhe...
Create worker process environment dictionary.
42
[ "def test_create_process_env_0():\n options = {'env': {'inherit': True, 'vars': {'PATH': '/usr/bin'}}}\n expected_env = os.environ.copy()\n expected_env['PATH'] = '/usr/bin'\n env = create_process_env(options)\n assert env == expected_env", "def test_create_process_env_1():\n options = {'env': {...
12
check_convert
def check_convert(original_string, target_string, n_operations): len_original = len(original_string) len_target = len(target_string) similar_index = 0 #import pdb;pdb.set_trace() flag = True while flag: #special cases if n_operations > (len_original + len_target): ret...
check if the original_string can be converted to target_string in n_operations
43
[ "def test_check_convert_0():\n assert check_convert('abc', 'ac', 1) == True", "def test_check_convert_1():\n assert check_convert('abc', 'ac', 1) == True", "def test_check_convert_2():\n assert check_convert('abc', 'ac', 1) == True", "def test_check_convert_3():\n assert check_convert('abc', 'ac',...
15
truncate_object
def truncate_object(obj, n_bytes, is_header=False): if n_bytes > 0: critical_headers = ["authorization", "content-type", "x-fuzzerest-state"] for key in obj if isinstance(obj, dict) else range(len(obj)): if isinstance(obj[key], (dict, list)): truncate_object(obj[key], n_b...
Reduce the number of character bytes in obj by n_bytes. This is necessary to avoid rejected oversized requests.
45
[ "def test_truncate_object_0():\n test_input = {'authorization': 'Bearer valid_token', 'content-type': 'application/json', 'x-fuzzerest-state': 'some_state', 'data': 'This is some data that should be truncated because it exceeds the limit.'}\n expected_output = {'authorization': 'Bearer valid_token', 'content-...
10
filterLocations
def filterLocations(locs, model): # Possible to do list: # - Is there a need to check if water level data matches MWL? # - Should we combine multiple stations at same grid location? for site in locs: for site2 in locs: if (locs[site]['enabled'] and locs[site2]['enabled'] and locs...
Leaves only one measurement station enabled per grid location in the model configuration. Chooses the one with original coordinates closest to the grid location.
46
[ "def test_filterLocations_0():\n locs = {\n 'site1': {'enabled': True, 'if_indices': [1, 2], 'moved_distance': 0.5, 'if_orientation': 'U'},\n 'site2': {'enabled': True, 'if_indices': [1, 2], 'moved_distance': 0.3, 'if_orientation': 'V'},\n 'site3': {'enabled': True, 'if_indices': [1, 2], 'mo...
10
choose_stat
def choose_stat(favored_stats, unfavored_stats=None, exclude=None): favored = [f for f in favored_stats if not exclude or f not in exclude] unfavored = None if unfavored_stats: unfavored = [u for u in unfavored_stats if not exclude or u not in exclude] if not...
Select stats based on preference
55
[ "def test_choose_stat_0():\n assert choose_stat(['strength', 'agility'], exclude=['agility']) == 'strength' or 'agility'", "def test_choose_stat_1():\n assert choose_stat(['strength', 'agility'], unfavored_stats=['intelligence'], exclude=['agility']) in ['strength', 'intelligence']", "def test_choose_stat...
12
primes_list_mem
def primes_list_mem(num, isprime=[3]): if num < 2: return [] if num > 2 * len(isprime) + 2: def mapping(x): return (x - 3)//2 first_new = 2 * len(isprime) + 3 isprime += [num for num in range(first_new, num + 1, 2)] temp2 = int(math.sqrt(num)) + 1 f...
Returns list of Prime numbers
56
[ "def test_primes_list_mem_0():\n assert primes_list_mem(10) == [2, 3, 5, 7]", "def test_primes_list_mem_1():\n assert primes_list_mem(1) == []", "def test_primes_list_mem_2():\n assert primes_list_mem(29) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]", "def test_primes_list_mem_3():\n assert primes_list...
14
edits1
def edits1(word): letters = 'abcdefghijklmnopqrstuvwxyz' splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [L + R[1:] for L, R in splits if R] transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1] replaces = [L + c + R[1:] for L, R in splits ...
All edits that are one edit away from `word`.
65
[ "def test_edits1_0():\n assert 'a' in edits1('a')\n assert 'abc' in edits1('abc')\n assert 'acb' in edits1('abc')\n assert 'abb' in edits1('abc')\n assert 'abc' in edits1('ab')\n assert 'ab' in edits1('a')\n assert 'ac' in edits1('a')\n assert 'ab' in edits1('b')\n assert 'ba' in edits1('...
11
test_init
class CoreWorkflow: def __init__(self): self.message = {"first_name": "John", "last_name": "Doe"} self.data_format = "custom" self.origin_url = "http://localhost:5000/data" self.start_time = None self.use_response = False self.verify_certs = False self.lfh_ex...
Tests CoreWorkflow.__init__ and the state transition.
67
[ "def test_test_init_0():\n workflow = CoreWorkflow()\n assert workflow.message == {'first_name': 'John', 'last_name': 'Doe'}\n assert workflow.data_format == 'custom'\n assert workflow.origin_url == 'http://localhost:5000/data'\n assert workflow.start_time is None\n assert workflow.use_response is...
10
choose_fun_cov
def choose_fun_cov(str_cov, is_grad=False): def grad_cov_se(): pass def cov_se(): pass def grad_cov_matern32(): pass def cov_matern32(): pass def grad_cov_matern52(): pass def cov_matern52(): pass assert isinstance(str_cov, str) asse...
It is for choosing a covariance function or a function for computing gradients of covariance function.
69
[ "def test_choose_fun_cov_0():\n fun_cov = choose_fun_cov('matern32', True)\n assert fun_cov == grad_cov_matern32", "def test_choose_fun_cov_1():\n fun_cov = choose_fun_cov('se', False)\n assert fun_cov == cov_se", "def test_choose_fun_cov_2():\n fun_cov = choose_fun_cov('matern52', True)\n ass...
10
list_to_tran
def list_to_tran(list): transcription = "" for tran in list: if tran[-3:] == "(0)": transcription += tran[:-3] elif tran[-4:] == "(0)-" or tran[-4:] == "(0).": transcription += tran[:-4] + tran[-1] elif tran[-1] == ")" or tran[-2:] == ")-" or tran[-2:] == ").": ...
Transform the list of predicted tags to a printable way
76
[ "def test_list_to_tran_0():\n assert list_to_tran(['(0)Hello', '(0)-World', 'Test', '(0).Done']) == 'Hello World Test Done'", "def test_list_to_tran_1():\n assert list_to_tran(['(0)Python', '(0)-Programming', 'is', '(0).fun', 'and', '(0)-cool']) == 'Python Programming is fun and cool'", "def test_list_to_...
10
on_box_edge
class Position: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def on_box_edge(position, xmin, xmax, ymin, ymax, zmin, zmax): return ((((position.x == xmin or position.x == xmax) and position.y >= ymin and position.y <= ymax) or (...
Detect whether a point is on the perimeter of a given rectangular prism
87
[ "def test_on_box_edge_0():\n test_input = Position(0, 0, 0)\n assert on_box_edge(test_input, -1, 1, -1, 1, -1, 1) == True", "def test_on_box_edge_1():\n test_input = Position(1, 1, 1)\n assert on_box_edge(test_input, 0, 2, 0, 2, 0, 2) == True", "def test_on_box_edge_2():\n test_input = Position(2...
10
get_task_frame
class State: def __init__(self, drawer_position, drawer_opening, lid_position, box_position): self.drawer_position = drawer_position self.drawer_opening = drawer_opening self.lid_position = lid_position self.box_position = box_position class Position: def __init__(self, x, y, t...
Get a taskrelated frame (e.g. drawer, lid, table, etc.) for actions such as place
88
[ "def test_get_task_frame_0():\n state = State(Position(0, 0, 0), 5, Position(0, 0, 0), Position(0, 0, 0))\n position = Position(1, 1, 0)\n assert get_task_frame(state, position) == 'stack'", "def test_get_task_frame_1():\n state = State(Position(0, 0, 0), 5, Position(0, 0, 0), Position(0, 0, 0))\n ...
45
get_nearest_open_cell
TRACK = 1 START = 2 GOAL = 3 def get_nearest_open_cell(environment, x_crash, y_crash, vx=0, vy=0, acceptable_cells=(TRACK, START, GOAL)): # Record number of rows (lines) and columns in the environment rows = len(environment) cols = len(environment[0]) # Add expanded coverage for searching for nearest...
Locate the nearest open cell in order to handle crash scenario. Distance is calculated as the Manhattan distance. Start from the crash grid square and expand outward from there with a radius of 1, 2, 3, etc.
90
[ "def test_get_nearest_open_cell_0():\n environment = [[1, 1, 1, 1, 1], [1, 0, 0, 0, 1], [1, 0, 3, 0, 1], [1, 0, 0, 0, 1], [1, 1, 1, 1, 1]]\n (x_crash, y_crash) = (2, 2)\n expected = (1, 1)\n assert get_nearest_open_cell(environment, x_crash, y_crash) == expected", "def test_get_nearest_open_cell_1():\...
13
get_one_move
from enum import Enum class Move(Enum): ROCK = 1 PAPER = 2 SCISSORS = 3 class Result(Enum): WIN = 1 LOSE = 2 DRAW = 3 def get_one_move(move2: Move, result: Result) -> Move: if result == Result.DRAW: return move2 if result == Result.LOSE: if move2 == Move.ROCK: ...
Get Player 1's move given Player 2's move and the outcome.
95
[ "def test_get_one_move_0():\n assert get_one_move(Move.ROCK, Result.LOSE) == Move.SCISSORS", "def test_get_one_move_1():\n assert get_one_move(Move.SCISSORS, Result.WIN) == Move.ROCK", "def test_get_one_move_2():\n assert get_one_move(Move.PAPER, Result.LOSE) == Move.ROCK", "def test_get_one_move_3()...
10
merge_date_ranges
def merge_date_ranges(dates): if not dates: return saved = list(dates[0]) for st, en in sorted([sorted(t) for t in dates]): if st < MIN_PERIOD_DATE or st > MAX_PERIOD_DATE: raise ValueError("start date %s is out of bounds" % str(st)) if en < MIN_PERIOD_DATE or en > MAX_...
Merge date ranges. Generator that merges ovelaped data ranges. Default init and end dates (19000101 and 21000101) are considered range
103
[ "def test_merge_date_ranges_0():\n dates = [[(19000101, 19000201), (19000201, 19000301)], [(19000201, 19000401)]]\n expected = [(19000101, 19000401)]\n result = list(merge_date_ranges(dates))\n assert result == expected, f'Expected {expected}, got {result}'", "def test_merge_date_ranges_1():\n date...
11
island_perimeter
def island_perimeter(grid): perimeter = 0 if len(grid) < 100: for list_num in range(len(grid) - 1): if len(grid[list_num]) < 100: for uno in range(len(grid[list_num]) - 1): if grid[list_num][uno] != 0: if list_num < len(grid) - 1: ...
returns the perimeter of the island described in grid
113
[ "def test_island_perimeter_0():", "def test_island_perimeter_1():", "def test_island_perimeter_2():", "def test_island_perimeter_3():", "def test_island_perimeter_4():" ]
24
check_table_format
def check_table_format(table): if not isinstance(table, dict): sys.stderr.write("Backpointer table is not a dict.\n") return False for split in table: if not isinstance(split, tuple) and len(split) ==2 and \ isinstance(split[0], int) and isinstance(split[1], int): ...
Return true if the backpointer table object is formatted correctly. Otherwise return False and print an error.
121
[ "def test_check_table_format_0():\n test_input = {(0, 1): {'S': ((0, 1, 2), (1, 2, 3))}, (1, 2): {'A': 'leaf'}}\n assert check_table_format(test_input) == True", "def test_check_table_format_1():\n test_input = {(0, 1): {'S': ((0, 1, 2), (1, 2, 3))}, (1, 2): {'A': 'leaf'}}\n assert check_table_format(...
19
check_probs_format
def check_probs_format(table): if not isinstance(table, dict): sys.stderr.write("Probability table is not a dict.\n") return False for split in table: if not isinstance(split, tuple) and len(split) ==2 and isinstance(split[0], int) and isinstance(split[1], int): sys.stderr....
Return true if the probability table object is formatted correctly. Otherwise return False and print an error.
122
[ "def test_check_probs_format_0():\n test_input = {(0, 1): {'A': 0.5, 'B': 0.5}, (1, 2): {'A': 0.7, 'B': 0.3}}\n assert check_probs_format(test_input) == True", "def test_check_probs_format_1():\n test_input = {(0, 1): {'A': 0.5, 'B': 0.5}, (1, 2): {'A': 0.7, 'B': 0.3}}\n assert check_probs_format(test...
12
date_to_jd
def date_to_jd(year,month,day): if month == 1 or month == 2: yearp = year - 1 monthp = month + 12 else: yearp = year monthp = month # this checks where we are in relation to October 15, 1582, the beginning # of the Gregorian calendar. if ((year < 1582) or ...
Convert a date to Julian Day. Algorithm from 'Practical Astronomy with your Calculator or Spreadsheet', 4th ed., DuffetSmith and Zwart, 2011.
123
[ "def test_date_to_jd_0():\n assert date_to_jd(2021, 3, 14) == 2459580.5", "def test_date_to_jd_1():\n assert date_to_jd(1582, 10, 4) == 2299160.5", "def test_date_to_jd_2():\n assert date_to_jd(2000, 1, 1) == 2451544.5", "def test_date_to_jd_3():\n assert date_to_jd(2000, 12, 31) == 2451544.5", ...
10
generate_suite_name
class RunProperties: def __init__(self, enterprise, encryption_at_rest=False, ssl=False): self.enterprise = enterprise self.encryption_at_rest = encryption_at_rest self.ssl = ssl def generate_suite_name(properties: RunProperties, versions: list, runner_type, installer_type): ZIP_PACKAG...
generate test suite name for allure report
124
[ "def test_generate_suite_name_0():\n properties = RunProperties(enterprise=True, encryption_at_rest=True, ssl=True)\n versions = [1, 2, 3]\n runner_type = 'JUnit'\n installer_type = 'universal binary archive'\n assert generate_suite_name(properties, versions, runner_type, installer_type) == 'ArangoDB...
10
_translate_binary_operator
class Tree: def __init__(self, token): self.children = [token] class Token: def __init__(self, value): self.value = value def _translate_binary_operator(tree: Tree) -> str: # Binary op will have only one child and it will be a Token operator = tree.children[0] if operator.value =...
Translates nonpython binary operators to python equivalents.
125
[ "def test__translate_binary_operator_0():\n tree = Tree(Token('gt'))\n assert _translate_binary_operator(tree) == ' > '", "def test__translate_binary_operator_1():\n tree = Tree(Token('eq'))\n assert _translate_binary_operator(tree) == ' == '", "def test__translate_binary_operator_2():\n tree = T...
11
calculate_read_trim_position_linear
def calculate_read_trim_position_linear(read, m, alpha, beta, gamma, offset, bal...
This implements the linear version of the read trimmer. Read is a tuple. It has the id string, the read string, and the phred string. alpha controls the influence of the length beta controls the influence of the correctness probability gamma controls the influence of entropy balanced uses the geometric mean entropyOnly...
126
[ "def test\n ", "def", "", "", "" ]
14
for_j
def for_j(): for row in range(8): for col in range(3): if col==2 and row!=1 or row==7 and col in(1,2) or row in(6,5) and col!=1 or row==2 and col!=0: print("*",end=" ") else: print(" ",end=" ") print()
printing small 'j' using for loop
128
[ "def test_for_j_0():\n def test_for_j_0():\n test_for_j_0()", "def test_for_j_1():\n def test_for_j_1():\n test_for_j_1()", "", "", "" ]
11
quick_select
def quick_select(S, k): if len(S) == 1: return S[0] pivot = random.choice(S) # pick random pivot element from S L = [x for x in S if x < pivot] # elements less than pivot E = [x for x in S if x == pivot] # elements equal to pivot G = [x for x in S if x > pivot] # elements greater than p...
return the kth smallest element of list S, for k from 1 to len(S)
130
[ "def test_quick_select_0(S, k:", "def test_quick_select_1():\n assert quick_select([3, 1, 2, 4, 5], 1) == 1", "def test = 1\n assert 1\n [1\n assert\n assert\n assert\n # 1\n assert\n # 1\n # 1\n # 1\n # 1\n # 1\n # 1\n # 1\n # 1\n # 1\n # 1\n # 1\n # ...
10
Lgain
def Lgain(spacecraft_id, sensor_id, band_id): if(spacecraft_id == "Terra"): if (sensor_id == "Aster"): if(band_id == "band1"): Lgain = 0.676 if(band_id == "band2"): Lgain = 0.862 if(band_id == "band3"): Lgain = 0.217 if(band_id == "band4"): Lgain = 0.0696 if(band_id == "band5"): Lg...
Gain for Dn to Rad conversion This is used for processing radiance of Terra Aster images.
135
[ "def test_Lgain:\n def test_Lgain:\n def test_Lgain:\n\tspacecraft = 0.0.0:\n test_Lgain:\n\tdef test_Lgain:\n test_L:\n\t0.0:\n\t0.0:\n\t0.0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:...
11
Loffset
def Loffset(spacecraft_id, sensor_id, band_id): if(spacecraft_id == "Terra"): if (sensor_id == "Aster"): if(band_id == "band1"): Loffset = -0.676 if(band_id == "band2"): Loffset = -0.862 if(band_id == "band3"): Loffset = -0.217 if(band_id == "band4"): Loffset = -0.0696 if(band_id == "b...
Offset for Dn to Rad conversion This is used for processing radiance of Terra Aster images.
136
[ "def test_Loffset_0:\n def test_Loffset_0:\n def test_Loffset_0:\n\tspacecraft_id = 0.0.0:\n def test_Loffset_0(spacecraft = 0:\n test_Loffset_0 = 0:\n if 0:\n if 0:\n if 0:\n if 0:\n if 0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t0:\n\t...
11
log_quadrature_rule
def log_quadrature_rule(N_poly, N_poly_log): lvls = (N_poly, N_poly_log) if lvls == (0, 0): return ((0.36787944117144232159552377016146086744581, ), ((1.00000000000000000000000000000000000000000, ))) elif lvls == (1, 1): return (( 0.0882968651376530117595951385184...
Returns quadrature rule that is exact on 0^1 for p(x) + q(x)log(x) for deg(p) <= N_poly and deg(q) <= N_log.
140
[ "def test_log_quadrature_rule_0():\n # Test cases for the log_quadrature_rule function\n # Each test case is a tuple of (N_poly, N_log, expected_rule)\n test_cases = [\n (0, 0, (0.0, 0.0)), # No polynomial or logarithm, trivial case\n (1, 0, (0.0, 0.0)), # Linear polynomial, no logarithm\n ...
32
log_log_quadrature_rule
def log_log_quadrature_rule(N_poly, N_log): lvls = (N_poly, N_log) if lvls == (0, 0): return (( 0.061151359021200679621983711149640788306168520381328374043636166, 0.500000000000000000000000000000000000000000000000000000000000000, 0.938848640978799320378016288850359211...
Returns quadrature rule that is exact on 0^1 for p(x) + q(x)log(x) + k(x)log(1x) for deg(p) <= N_poly, deg(k) <= deg(q) <= N_log.
141
[ "def test_log_log_quadrature_rule_0():", "def test_log_log_quadrature_rule_1():", "def test_log_log_quadrature_rule_2():", "def test_log_log_quadrature_rule_3():", "def test_log_log_quadrature_rule_4():" ]
18
sqrtinv_quadrature_rule
def sqrtinv_quadrature_rule(N_poly, N_poly_sqrt): lvls = (N_poly, N_poly_sqrt) if lvls == (0, 0): return ((0.25, ), (1., )) elif lvls == (1, 1): return (( 0.0446581987385204510787589430823546055095, 0.6220084679281462155879077235843120611571, ), ( ...
Returns quadrature rule that is exact on 0^1 for p(x) + q(x)1/sqrt(x) for deg(p) <= N_poly and deg(q) <= N_poly_sqrt.
143
[ "def test_sqrtinv_quadrature_rule_0():\n assert sqrtinv_quadrature_rule(0, 0) == ((0.25,), (1.0,))", "def test_sqrtinv_quadrature_rule_1():", "def test_sqrtinv_quadrature_rule_2():", "def test_sqrtinv_quadrature_rule_3():", "def test_sqrtinv_quadrature_rule_4():" ]
16
gauss_sqrtinv_quadrature_rule
def gauss_sqrtinv_quadrature_rule(N): if N == 1: return ((0.3333333333333333333333333333333333333333333, ), (2.0000000000000000000000000000000000000000000, )) elif N == 2: return (( 0.1155871099970479351674458383995416377412887, 0.7415557471458092076896970...
Gauss rule of N pts that is exact on 0^1 with weight sqrt(x)^1
144
[ "def test_gauss_sqrtinv_quadrature_rule_0():", "def test_gauss_sqrtinv_quadrature_rule_1():\n assert gauss_sqrtinv_quadrature_rule(4) == ((0.022163568807217638, 0.18783156765244552, 0.46159736149626673, 0.7483346283872805, 0.9484939262883686), (0.5910484494295057, 0.5385334386199927, 0.4381727250319641, 0.2989...
14
gauss_log_quadrature_rule
def gauss_log_quadrature_rule(N): if N == 0: return ((0.25, ), (-1, )) elif N == 1: return (( 0.11200880616697618295720548894767738145955234705971531137512, 0.60227690811873810275708022533803690425473336722599897433915, ), ( -0.718539319030384440665510...
Gauss rule of N pts that is exact on 0^1 with weight log(x).
146
[ "def test_gauss_log_quadrature_rule_0():\n assert gauss_log_quadrature_rule(0) == ((0.25,), (-1,))", "def test_gauss_log_quadrature_rule_1():", "def test_gauss_log_quadrature_rule_2():", "def test_gauss_log_quadrature_rule_3():", "def test_gauss_log_quadrature_rule_4():" ]
12
BinaryFromFraction
def BinaryFromFraction(num, den): Precision = 52 MinExponent = -1022 assert num != 0 assert den != 0 f = 0 e = 0 p = Precision isExact = True # g = fractions.gcd(num, den) # num //= g # den //= g # Scale into [2^(p-1), 2^p) while num >= 2**p * den: den *=...
Converts x = num / den to IEEE binary floatingpoint x' = f 2^e
147
[ "def test_BinaryFromFraction_0():\n assert BinaryFromFraction(1, 2) == (0, 0, 52, True)", "def test_BinaryFromFraction_1():\n assert BinaryFromFraction(1, 16) == (1, 0, 52, True)", "def test_BinaryFromFraction_2():\n assert BinaryFromFraction(1, 1) == (1, 0, 52, True)", "def test_BinaryFromFraction_3...
16
get_relative_time
import datetime DAY = 86400 HOUR = 3600 MINUTE = 60 MONTH = 30 * DAY def get_relative_time(dt): now = datetime.datetime.now() delta_time = now - dt delta = delta_time.days * DAY + delta_time.seconds minutes = delta / MINUTE hours = delta / HOUR days = delta / DAY if delta <= 0: ...
Returns relative time compared to now from timestamp
159
[ "def test_get_relative_time_0():\n test_input = datetime.datetime(2020, 1, 1, 0, 0, 0)\n expected_output = '11 years ago'\n assert get_relative_time(test_input) == expected_output", "def test_get_relative_time_1():\n test_input = datetime.datetime(2021, 5, 1, 12, 0, 0)\n expected_output = '1 day ag...
13
_pco_fixPlateMatix
def _pco_fixPlateMatix(mat, row, col): matSize = len(mat) # Return if there are useful no values maxVal = -10 for curr in range(0, matSize): maxVal = max(maxVal, mat[row][curr]) maxVal = max(maxVal, mat[curr][col]) if maxVal <= 0.0: return # Calc the missing values ...
A function which calculates the missing values for the given position.
162
[ "def test__pco_fixPlateMatix_0():\n test_input = [[0, 0, 1, 2], [0, 3, 0, 4], [5, 0, 6, 0], [7, 8, 9, 0]]\n expected_output = [[0, 0, 1, 2], [0, 3, 0, 4], [5, 0, 6, 0], [7, 8, 9, 0.012345679012345678]]\n _pco_fixPlateMatix(*test_input, 3, 3)\n assert test_input[3][3] == expected_output[3][3], 'Test fail...
13
graph_ifield
class Node: def __init__(self, is_output, children, right=None, left=None): self.is_output = is_output self.children = children self.right = right self.left = left self.index = 0 def graph_ifield(in_layer, in_b, in_e): if in_b == in_e: return 0, 0 n = in_la...
Search up through the graph for field of influence of the input range [in_b, in_e)
175
[ "def test_graph_ifield_0():\n in_layer = [Node(False, [Node(False, [Node(True, [])])]), Node(False, [Node(False, [Node(True, [])])])]\n in_b = 0\n in_e = 2\n expected_output = (0, 1)\n assert graph_ifield(in_layer, in_b, in_e) == expected_output", "def test_graph_ifield_1():\n in_layer = [Node(F...
10
general_correct_percent
def general_correct_percent(bases_dict_raw): base_dict = {} raw_base_dict = bases_dict_raw for base_location in raw_base_dict: total_base = 0 a_count = 0 t_count = 0 c_count = 0 g_count = 0 correct_base = '' correct_count = 0 for base in raw_b...
creates the dictionary with error chances to use in error seeding
180
[ "def test_general_correct_percent_0():\n test_input = {'location1': ['A', 'T', 'C', 'G', 'a', 't', 'c', 'g']}\n expected_output = {'location1': 0.5}\n assert general_correct_percent(test_input) == expected_output", "def test_general_correct_percent_1():\n test_input = {'location2': ['A', 'A', 'A', 'A'...
23
majority_element
def majority_element(nums): if len(nums) == 0: return -1 k1, k2, c1, c2 = math.inf, math.inf, 0, 0 for n in nums: if c1 == 0 and k1 != n and k2 != n: k1 = n elif c2 == 0 and k2 != n and k1 != n: k2 = n if k1 == n: c1 += 1 elif k2 ...
Find the majority elements in given array
182
[ "def test_majority_element_0():\n assert majority_element([3, 2, 3]) == 3", "def test_majority_element_1():\n assert majority_element([1, 1, 1, 2, 2, 3, 3, 3]) == 1", "def test_majority_element_2():\n assert majority_element([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == -1", "def test_majority_element_3():", ...
15
partition_round
def partition_round(elms, percent, exact=-1, total=100, *args, **kwargs): if elms < 100: factor = 10 x = elms / 10.0 else: factor = 1 x = elms / 100.0 if exact == -1: exact = 0 if percent > 50 else 1 if elms % 2 == 0: if percent == 50: logging....
Partitions dataset in a predictable way.
184
[ "def test_partition_round_0():\n assert partition_round(10, 50) == 5", "def test_partition_round_1():\n assert partition_round(100, 50) == 50", "def test_partition_round_2():\n assert partition_round(50, 25, exact=1) == 12", "def test_partition_round_3():\n assert partition_round(25, 75, exact=1) ...
10
fix_labels
def fix_labels(header): for i, label in enumerate(header): if re.search("Unix", label): header[i] = "Timestamp" if (re.search("Accel", label) and re.search("X", label)): header[i] = "Accel_X" if (re.search("Accel", label) and re.search("Y", label)): heade...
Fix the labels from the Shimmer data by removing unnecessary text.
186
[ "def test_fix_labels_0():\n assert fix_labels(['Unix Time', 'Accel_X', 'Accel_Y', 'Gyro_Z', 'Pressure', 'Temp', 'GSR']) == ['Timestamp', 'Accel_X', 'Accel_Y', 'Gyro_Z', 'Pressure', 'Temperature', 'GSR']", "def test_fix_labels_1():\n assert fix_labels(['Accel_X', 'Accel_Y', 'Gyro_X', 'Gyro_Y', 'Gyro_Z', 'Pre...
18
iterate_pagerank
def iterate_pagerank(corpus, damping_factor): n = len(corpus) num = 1 / n if n > 0 else 0 answer = {key: num for key in corpus} changed = True while changed: changed = False for p in corpus: summation = 0 for i in corpus: if p != i: ...
Return PageRank values for each page by iteratively updating PageRank values until convergence. Return a dictionary where keys are page names, and values are their estimated PageRank value (a value between 0 and 1). All PageRank values should sum to 1.
187
[ "def test_iterate_pagerank_0():\n corpus = {'A': ['B'], 'B': ['C'], 'C': ['A'], 'D': ['C']}\n damping_factor = 0.85\n expected = {'A': 0.3333333333333333, 'B': 0.26666666666666666, 'C': 0.4000000000000001, 'D': 1e-16}\n assert iterate_pagerank(corpus, damping_factor) == expected", "def test_iterate_pa...
11
precision_recall
def precision_recall(y_true, y_pred): TP = FP = FN = TN = 0 epsilon = 1e-4 for i in range(len(y_pred)): if y_true[i] == 1 and y_pred[i] == 1: TP += 1 elif y_true[i] == 0 and y_pred[i] == 1: FP += 1 elif y_true[i] == 1 and y_pred[i] == 0: FN += 1 ...
Computes the precision and recall values for the positive class
191
[ "def test_precision_recall_0():\n y_true = [1, 0, 1, 1, 0, 1, 0, 0]\n y_pred = [1, 0, 1, 0, 0, 1, 1, 0]\n (precision, recall) = precision_recall(y_true, y_pred)\n assert precision == 66.66666666666666\n assert recall == 66.66666666666666", "def test_precision_recall_1():\n y_true = [0, 0, 0, 0, ...
10
movie_tags
import requests import re def movie_tags(id): html = requests.get("https://www.imdb.com/title/" + id).text genre = re.findall('"genre": ([\s\S]+),\\n[\s\S]+"contentRating":', html) certificate = re.findall('"contentRating": "(.*)",\\n[\s\S]+<strong', html) rate = re.findall('<strong title="(.*) based...
Scrapes data of movie tags/details/variables from IMDB based on the movie IDs
193
[ "def test_movie_tags_0():\n test_id = 'tt0111161'\n expected_output = ['PG', '2h 5min', 'Action, Adventure, Drama', 7.9, 91, 'The Shawshank Redemption', 123456, 123456, 123456, 123456, 123456, 123456, 123456, 123456, 123456]\n assert movie_tags(test_id) == expected_output", "def test_movie_tags_1():\n ...
13
iterate_directory
def iterate_directory(root_path, extensions=None, recursive=False): if not recursive: for file in os.listdir(root_path): file_name, extension_name = os.path.splitext(file) if extensions is None\ or ((isinstance(extensions, list) or isinstance(extensions, tuple)) ...
iterate file in directory
195
[ "def test_iterate_directory_0():\n test_input = ('test_dir', ['txt', 'md'], True)\n expected_output = [('test_dir/file1.txt', 'file1.txt'), ('test_dir/subdir/file2.md', 'file2.md')]\n assert list(iterate_directory(*test_input)) == expected_output", "def test_iterate_directory_1():\n test_input = ('tes...
17
__get_jour_mois
def __get_jour_mois(index): # En commençant au 11/04 if index <= 20: return index + 10, 4 if index <= 51: return index - 20, 5 mois = 6 tmp = 51 while True: if mois < 8: if mois % 2 == 0: if index <= ...
determine le jour et le mois pour un index donne
196
[ "def test___get_jour_mois_0():\n assert __get_jour_mois(15) == (25, 5)", "def test___get_jour_mois_1():\n assert __get_jour_mois(60) == (40, 6)", "def test___get_jour_mois_2():\n assert __get_jour_mois(0) == (10, 4)", "def test___get_jour_mois_3():\n assert __get_jour_mois(100) == (80, 7)", "def...
12
x0x1_after_extraction
def x0x1_after_extraction(x0o: int, x1o: int, x0e: int, x1e: int): if x0e >= x0o and x0e <= x1o: x0 = 0 elif x0e <= x0o: x0 = x0o - x0e elif x0e >= x0o: x0 = 0 if x1e >= x0o and x1e <= x1o: x1 = x1e - x0e elif x1e > x1o: x1 = x1o - x0e try...
When we extract an array, we also update the extracted array's regions by mapping each region from their coordinates on the original array (which has a shape_native) to the extracted array (which is a 2D section on this array). This function compares the 1D coordinates of a regions original coordinates on a array to th...
199
[ "def test_x0x1_after_extraction_0():\n assert x0x1_after_extraction(2, 6, 1, 5) == (1, 4)", "def test_x0x1_after_extraction_1():\n assert x0x1_after_extraction(0, 5, 0, 5) == (0, 0)", "def test_x0x1_after_extraction_2():\n assert x0x1_after_extraction(3, 5, 4, 5) == (0, 1)", "def test_x0x1_after_extr...
12
build_random_function
def build_random_function(min_depth, max_depth): rand = random.randint(1,9) f = [] if max_depth >= 1: if min_depth >= 1: if rand == 1: f = ["prod", build_random_function(min_depth - 1, max_depth - 1), build_random_function(min_depth - 1, max_depth - 1)] elif r...
Build a random function. Builds a random function of depth at least min_depth and depth at most max_depth.
200
[ "def test_build_random_function_0():\n test_input = (2, 3)\n expected_output = ['prod', ['x'], ['y']]\n assert build_random_function(*test_input) == expected_output", "def test_build_random_function_1():\n test_input = (1, 2)\n expected_output = ['x', ['y']]\n assert build_random_function(*test_...
13
next_line_of_traps
def next_line_of_traps(traps): traps_safe_sides = '.' + traps + '.' # add 'safe' pseudosquares on either side next_traps = '' # next line starts empty for l, c, r in zip(traps_safe_sides[0:], traps_safe_sides[1:], traps_safe_sides[2:]): # Its left and center tiles are trap...
Given a line of traps, follow the rules to determine the next line of traps.
202
[ "def test_next_line_of_traps_0():\n assert next_line_of_traps('^^^') == '^^.'", "def test_next_line_of_traps_1():\n assert next_line_of_traps('^.^') == '^^.'", "def test_next_line_of_traps_2():\n assert next_line_of_traps('^^^^') == '^^^^'", "def test_next_line_of_traps_3():\n assert next_line_of_...
14
bf_wheel
def bf_wheel (n): if n <= 3: return n > 1 while math.sqrt(n) == int(math.sqrt(n)): yield math.sqrt(n) n //= math.sqrt(n) if not n % 2 or not n % 3: while not n % 2: yield 2 n //= 2 while not n % 3: yield 3 n //= 3 # starting value for candidate # and improved upper bound d = 5 upper = m...
Bruteforce trial factorization with successive integers as candidate factors. uses a wheel mod 6 to speed things up a lot. can be expanded to wheel mod 30 by adding to the prime basis, but takes extra steps in the trial phase. this seems to be the most optimized version I could put together.
206
[ "def test_bf_wheel_0():\n assert list(bf_wheel(28)) == [2, 2, 7]", "def test_bf_wheel_1():\n assert list(bf_wheel(1)) == []\n assert list(bf_wheel(2)) == [2]\n assert list(bf_wheel(3)) == [3]\n assert list(bf_wheel(4)) == [2, 2]\n assert list(bf_wheel(5)) == [5]\n assert list(bf_wheel(6)) == ...
12
format_time_ago
import datetime def format_time_ago(t): now = datetime.datetime.now() if type(t) is int: diff = now - datetime.datetime.fromtimestamp(t) elif isinstance(t, datetime.datetime): diff = now - t elif not t: diff = now - now second_diff = diff.seconds day_diff = diff.days ...
Get a datetime object or a int() Epoch timestamp and return a pretty string like 'an hour ago', 'Yesterday', '3 months ago', 'just now', etc
207
[ "def test_format_time_ago_0():\n test_input = datetime.datetime(2023, 3, 1)\n expected_output = '2 days ago'\n assert format_time_ago(test_input) == expected_output", "def test_format_time_ago_1():\n test_input = datetime.datetime(2023, 1, 1, 12, 0, 0)\n expected_output = '2 months ago'\n assert...
16
fast_guass
def fast_guass(mat): m_row = len(mat) n_col = len(mat[0]) if m_row < n_col: print("More Data needed, Enter more rows.") pivot = [False] * m_row pivot_found = False pivot_col_to_row = {} for j in range(n_col): pivot_found = False # Look for pivot for i in r...
Used in conjunction with find_dependent_rows to find rows in the matrix that sum to the zero vector in modulo 2.
210
[ "def test_fast_guass_0():\n test_input = [[1, 0, 1], [0, 1, 1], [1, 1, 0]]\n expected_output = ([[1, 1, 0], [0, 1, 1], [1, 0, 1]], [True, False, True], {0: 0, 1: 1, 2: 2})\n assert fast_guass(test_input) == expected_output", "def test_fast_guass_1():\n test_input = []\n expected_output = ([], [], {...
10
_is_unit
def _is_unit(node): # Looking for a .units attribute, a units.myunit, or a call to units() is_units_attr = isinstance(node, ast.Attribute) and node.attr == 'units' is_reg_attr = (isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id == 'uni...
Check whether a node should be considered to represent "units".
222
[ "def test__is_unit_0():\n test_node = ast.Name(id='unit', ctx=ast.Load())\n assert _is_unit(test_node) == True", "def test__is_unit_1():\n test_node = ast.Attribute(value=ast.Name(id='units', ctx=ast.Load()), attr='myunit')\n assert _is_unit(test_node) == True", "def test__is_unit_2():\n test_nod...
10
delete_duplicated_node
class Node: def __init__(self, val=0, next=None): self.val = val self.next = next def delete_duplicated_node(root: Node) -> Node: if not root or not root.next: return root pprev = None pnode = root while pnode: pnext = pnode.next need_delete = False ...
Given a link, delete a node in O(1).
224
[ "def test_delete_duplicated_node_0():\n root = Node(1, Node(1, Node(2, Node(3, Node(3)))))\n delete_duplicated_node(root)\n assert root.next.next.next == Node(2, Node(3, Node(3)))", "def test_delete_duplicated_node_1():\n root = Node(1)\n delete_duplicated_node(root)\n assert root == Node(1)\n\n...
10
forward_check
def forward_check(remaining_values, row, col, value): # check column for i in range(9): if i == row: continue x = remaining_values[row][i] if len(x) == 1 and list(x)[0] == value: return False # check row for i in range(9): if i == col: ...
Checks if a value inserted at a specific position violates rules of the sudoku board
226
[ "def test_forward_check_0():\n remaining_values = [\n [[1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, ...
14
check_win_diagonal
def check_win_diagonal(board): # TODO: write docstring # TODO: implement function for i in range(21,25): n = 0 while n < 4: if (board[i] != 0 and board[i] == board[i-6] and board[i] == board[i-6-6] and board[i] == board[i...
check either diagonal line has same elements
231
[ "def test_check_win_diagonal_0():", "def test_check_win_diagonal_1():", "def test_check_win_diagonal_2():", "def test_check_win_diagonal_3():", "def test_check_win_diagonal_4():" ]
13
get_per_pollutant_index
def get_per_pollutant_index(breakpoints, monitors, m, c): i_min = -1 i_max = -1 con_min = -1 con_max = -1 x = -1 for i in range(len(monitors)): if monitors[i] == m: x = i break for j in range(len(breakpoints)): c = float(c) if len(breakpoint...
Generates the perpollutant index using the AQI formula for the concentration 'c' associated with pollutant monitor 'm'. The calculation makes use of the EPA breakpoint table. If the concentration is out of range or should be ignored, returns 1; otherwise, returns the index that was calculated.
234
[ "def test_get_per_pollutant_index_0():\n test_input = ([", "def test_get_per_pollutant_index_1():\n test_input = ([", "def test_get_per_pollutant_index_2():\n test_input = ([", "def test_get_per_pollutant_index_3():\n test_input = ([", "def test_get_per_pollutant_index_4():\n test_input = (["...
12
simpler_inverse
from sympy import Symbol def simpler_inverse(ex): if ex.is_Pow: if (1/ex.exp).is_integer and ex.exp < 0: if ex.base.is_Add: return True if ex.is_Mul: hit = True a = [] for p in ex.args: if p.is_Add: return False ...
Returns True if it is more likely that the minimal polynomial algorithm works better with the inverse
237
[ "def test_simpler_inverse_0():\n test_input = Symbol('x') ** (-2)\n assert simpler_inverse(test_input) == True", "def test_simpler_inverse_1():\n test_input = Symbol('x') ** 3\n assert simpler_inverse(test_input) == False", "def test_simpler_inverse_2():\n test_input = Symbol('x') ** (-3)\n as...
12
scrub_meta
def scrub_meta(xform): property_map = {'TimeStart': 'timeStart', 'TimeEnd': 'timeEnd', 'chw_id': 'userID', 'DeviceID': 'deviceID', 'uid': 'instanceID'} if not hasattr(xform, 'form'): return # hack to make sure uppercas...
Cleans up old format metadata to our current standard. Does NOT save the doc, but returns whether the doc needs to be saved.
238
[ "def test_scrub_meta_0():\n xform = type('XForm', (object,), {'form': {'Meta': {'TimeStart': '2021-01-01', 'TimeEnd': '2021-01-02', 'chw_id': '123', 'DeviceID': '456', 'uid': '789'}}})()\n assert scrub_meta(xform) is True", "def test_scrub_meta_1():\n xform = type('XForm', (object,), {'form': {'Meta': [{...
10
byClients
def byClients(path): numa = 0 write = 0 if 'numa_one/' in path: numa = 1 if 'cwrite/' in path: write = 1 if 'clients_one/' in path: return 1 * 3 + numa + write if 'clients_two/' in path: return 2 * 3 + numa + write if 'clients_three/' in path: return 3...
Sorts based on the number of clients used in the closed loop run
240
[ "def test_byClients_0():\n assert byClients('clients_one/') == 4", "def test_byClients_1():\n assert byClients('clients_one/') == 4", "def test_byClients_2():\n assert byClients('clients_one/') == 4", "def test_byClients_3():\n assert byClients('clients_one/') == 4", "def test_byClients_4():\n ...
14
move_to_mem
class Brainfuck: def __init__(self): self.piv = 0 def move_to_mem(bf, input_dec, copy_to_dec): output = "" if bf.piv < copy_to_dec: for i in range(copy_to_dec - bf.piv): output += '>' elif copy_to_dec < bf.piv: for i in range(bf.piv - copy_to_dec): outpu...
reset the copy_to_dec and move input_dec to copy_to_dec YOU SHOULD DOUBLED NUMBER
241
[ "def test_move_to_mem_0():\n bf = Brainfuck()\n bf.piv = 5\n result = move_to_mem(bf, 3, 7)\n assert result == '>>[-]>+<->-]>>[>+<-]>+<->-]'", "def test_move_to_mem_1():\n bf = Brainfuck()\n bf.piv = 10\n result = move_to_mem(bf, 15, 5)\n assert result == '<<[-]>+<->-]>[>+<-]>+<->-]'", "...
15
_remove_strings
def _remove_strings(code): removed_string = "" is_string_now = None for i in range(0, len(code)-1): append_this_turn = False if code[i] == "'" and (i == 0 or code[i-1] != '\\'): if is_string_now == "'": is_string_now = None ...
Remove strings in code
251
[ "def test__remove_strings_0():\n assert _remove_strings(\"print('Hello, World!')\") == 'print(Hello, World!)'", "def test__remove_strings_1():\n assert _remove_strings(\"x = 'Hello, World!'\") == 'x = '", "def test__remove_strings_2():\n assert _remove_strings(\"y = 'Hello, World!'\") == 'y = '", "de...
14
filter_by_value
def filter_by_value(sequence, value): for element in sequence: # for index, att in enumerate(["asdf", "event_number", "ix_num"]): # if hasattr(element, att): # if element.asdf == value \ # or element.event_number == value \ # or element.ix_num % va...
A generator than yields all elements of a sequence whose attrName matches value. More readable than a list comprehension, though accomplishes the same thing.
270
[ "def test_filter_by_value_0():\n sequence = [MockElement(1, 'asdf', 10), MockElement(2, 'event_number', 20), MockElement(3, 'ix_num', 30)]\n value = 10\n result = list(filter_by_value(sequence, value))\n assert result == [MockElement(1, 'asdf', 10), MockElement(3, 'ix_num', 30)]", "def test_filter_by_...
10
does_complete
def does_complete(BoardArray): size = len(BoardArray) subsquare = int(math.sqrt(size)) # check each cell on the board for a 0, or if the value of the cell #is present elsewhere within the same row, column, or square for row in range(size): for col in range(size): if isinstance(BoardArray[row][col], list): ...
Test whether the given board is complete
273
[ "def test_does_complete_0():\n test_input = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]\n assert does_complete(test_input) == True", "def test_does_complete_1():\n test_input = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 0]]\n assert does_complete(test_input) == True", "def test_does_complete_2...
14
can_blas
def can_blas(inputs, result, idx_removed): # Gotta remove indices if len(idx_removed) == 0: return False # Can only do two if len(inputs) != 2: return False # Make sure there is overlap if len(set(inputs[0]) & set(inputs[1])) == 0: return False # Build a few tempo...
Checks if we can use a BLAS call.
287
[ "def test_can_blas_0():\n assert can_blas([[1, 2, 3], [3, 4, 5]], 'GEMM', [2]) == 'GEMM'", "def test_can_blas_1():\n assert can_blas([[1, 2], [3, 4]], 'TDOT', []) == 'TDOT'", "def test_can_blas_2():\n assert can_blas([[1, 2, 3], [4, 5, 6]], 'TDOT', [0, 1, 2]) == 'TDOT'", "def test_can_blas_3():\n ...
16
dollars_to_ticks
def dollars_to_ticks(price: float) -> int: if price < 2.: ticks = (price - 1) / 0.01 elif price < 3: ticks = 100 + price % 2 / 0.02 elif price < 4: ticks = 150 + price % 3 / 0.05 elif price < 6: ticks = 170 + price % 4 / 0.1 elif price < 10: ticks = 190 + pric...
Converts a price in dollars to the level of betfair ticks
300
[ "def test_dollars_to_ticks_0():\n assert dollars_to_ticks(2.5) == 100", "def test_dollars_to_ticks_1():\n assert dollars_to_ticks(1.99) == 100", "def test_dollars_to_ticks_2():\n assert dollars_to_ticks(0.99) == 100", "def test_dollars_to_ticks_3():\n assert dollars_to_ticks(0.01) == 100", "def ...
10
deg2HMS
def deg2HMS(ra=None, dec=None, round=False): RA, DEC, rs, ds = '', '', '', '' if dec is not None: if str(dec)[0] == '-': ds, dec = '-', abs(dec) deg = int(dec) decM = abs(int((dec-deg)*60)) if round: decS = int((abs((dec-deg)*60)-decM)*60) else: ...
quick and dirty coord conversion. googled to find bdnyc.org.
301
[ "def test_deg2HMS_0():\n assert deg2HMS(ra=30, dec=45, round=True) == ('E 2 0 0', 'N 45 0 0')", "def test_deg2HMS_1():\n assert deg2HMS(ra=180, dec=-45, round=False) == ('E 12 0', 'S 45 0')", "def test_deg2HMS_2():\n assert deg2HMS(ra=-90, dec=0, round=True) == ('W 0 0 0', 'N 0 0 0')", "def test_deg2...
10
safe_rm
def safe_rm(path_to_rm): # handle directory if os.path.isdir(path_to_rm): files_to_rm = [f'{path_to_rm}/{fname}' for fname in os.listdir(path_to_rm)] dir_to_rm = path_to_rm else: files_to_rm = [path_to_rm] dir_to_rm = None # clear out files for file_to_rm in files_to_...
Safely remove a directory of files or a file 1.) check path exists, files are files, dirs are dirs 2.) only remove things on approved list REMOVABLE_PATHS 3.) assert no longer exists
305
[ "def test_safe_rm_0():\n safe_rm('test_dir')", "def test_safe_rm_1():\n safe_rm('test_file.txt')", "def test_safe_rm_2():\n safe_rm('nonexistent_path')", "def test_safe_rm_3():\n safe_rm('nonremovable_file.txt')", "def test_safe_rm_4():\n safe_rm('empty_directory')" ]
10
generateHeader
class Setting: PAPER_SIZE = "a4paper" DOCUMENT_CLASS = "article" PACKAGES = ["graphicx", "xcolor"] MULTICOL = 0 PAGE_HEADER = False SECTION_BREAK = True CODE_FONT = "Courier New" CJK_FONT = "SimSun" LANGUAGE_SETTINGS = {} GEOMENTRY_SETTINGS = ["margin=1in"] TITLE = "My Docum...
Generate tex file header
313
[ "def test_generateHeader_0():\n expected_output = (\n r\"\\documentclass[a4paper]{article}\\n\"\n r\"\\usepackage{graphicx}\\n\"\n r\"\\usepackage{xcolor}\\n\"\n r\"\\usepackage{multicol}\\n\"\n r\"\\usepackage{fancyhdr}\\n\"\n r\"\\headwidth=28cm\\n\"\n r\"\\newc...
15
moveFunction
def moveFunction(scoreMatrix, x, y): diag = scoreMatrix[x-1][y-1] #all of the possible moves based on up = scoreMatrix[x-1][y] #coordinates in the scoring matrix left = scoreMatrix[x][y-1] if diag >= up and diag >= left: #in this function, a score "tie" is a diagonal move return 1 if diag != 0 else 0 #0 in this...
this will be the function that allows us to move throughout the scoring matrix
315
[ "def test_moveFunction_0():\n test_input = ([[0, 0, 0], [0, 0, 0], [0, 0, 0]], 1, 1)\n expected_output = 1\n assert moveFunction(*test_input) == expected_output", "def test_moveFunction_1():\n test_input = ([[0, 0, 0], [0, 0, 0], [0, 0, 0]], 1, 2)\n expected_output = 3\n assert moveFunction(*tes...
10
transition_definition
def transition_definition(in_dict): out_str= "" for key in iter(in_dict): # Get value of current transition value= in_dict[key] # Pre-places pre= value[0] # Pre-places condition pre_str= "(" for idx,item in enumerate(pre): # Not last element...
Define transition firing conditions in NuSMV
327
[ "def test_transition_definition_0():\n input_dict = {'t1': (['p1', 'p2'], [['i1', 'i2'], ['i3']], ['q1', 'q2'])}\n expected_output = 't1:= (p1 & p2) & (i1 & i2 & i3) & (q1 & q2);'\n assert transition_definition(input_dict) == expected_output", "def test_transition_definition_1():\n input_dict = {'t2':...
14
get_cv_description
from enum import Enum class CV_Type(Enum): ACTIVITY_ID = 1 CF_STANDARD_NAME = 2 DATA_NODE = 3 EXPERIMENT_ID = 4 FREQUENCY = 5 GRID_LABEL = 6 INSTITUTION_ID = 7 MIP_ERA = 8 MODEL_COHORT = 9 NOMINAL_RESOLUTION = 10 PRODUCT = 11 REALM = 12 SOURCE_ID = 13 SOURCE_TYP...
Get the description of a CV.
328
[ "def test_get_cv_description_0():\n assert get_cv_description(CV_Type.ACTIVITY_ID) == 'Activity ID Description'", "def test_get_cv_description_1():\n assert get_cv_description(CV_Type.ACTIVITY_ID) == 'Activity ID Description'", "def test_get_cv_description_2():\n assert get_cv_description(CV_Type.ACTIV...
19
miller_rabin_test
def miller_rabin_test(n, rounds): if n < 3 or rounds < 1: raise ValueError('n < 3 or rounds < 1') r = n - 1 s = 0 while not r & 1: # r % 2 == 0 r = r >> 1 # r = r / 2 s = s + 1 for _ in range(rounds): a = random.randint(2, n - 1) y = pow(a, r, n)...
RabinMiller primality test. Return True if n is probably prime.
329
[ "def test_miller_rabin_test_0():\n assert miller_rabin_test(7, 5) == True", "def test_miller_rabin_test_1():\n assert miller_rabin_test(2, 1) == True", "def test_miller_rabin_test_2():\n assert miller_rabin_test(1, 1) == False", "def test_miller_rabin_test_3():\n assert miller_rabin_test(561, 5) =...
11
patgen
def patgen(buf_len, size=4): pat = "" symbols = "`~!@#$%^&*()-=_+[]\{}|;':,./<>?" if size == 4: for u in string.ascii_uppercase: for l in string.ascii_lowercase: for i in string.digits: for s in symbols: ...
The pattern generator is used to populate structures which are passed into functions as arguments. By monitoring outputs at certain points in the function, the subpattern can be searched for within the original pattern, helping us derive the offset from which it originated.
334
[ "def test_patgen_0():", "def test_patgen_1():\n assert patgen(0, 4) == ''", "def test_patgen_2():\n assert patgen(0, 3) == ''", "def test_patgen_3():\n assert patgen(0, 2) == ''", "def test_patgen_4():\n assert patgen(0, 5) == ''" ]
16
fix_camel_case
def fix_camel_case(s): if " " in s: s_out = s else: s_out = s[0] for i in range(1, len(s)): # Iterate over the letters, starting with the second one. if s[i - 1].isupper() and s[i].isupper(): # A pattern like 'PAPublic' --> PA Public ...
Sometimes courts provide nasty camelcased content instead of real words. This code attempts to fix that.
336
[ "def test_fix_camel_case_0():\n assert fix_camel_case('McDonald') == 'Mc Donald'", "def test_fix_camel_case_1():\n assert fix_camel_case('FederalReserveBank') == 'Federal Reserve Bank'", "def test_fix_camel_case_2():\n assert fix_camel_case('FederalReserveBank') == 'Federal Reserve Bank'", "def test_...
22
calculate_frame_ier
def calculate_frame_ier(y_human, y_lena, speech_tiers, skip_overlap=True): false_alarms = 0 misses = 0 confusions = 0 total = 0 # total frames of speech in ground truth correct = 0 overlap_count = 0 for i in range(len(y_human)): if skip_overlap and y_human[i] == 'Overlap': # skip o...
Given framelevel annotations, calculates the components of the identification error rate.
337
[ "def test_calculate_frame_ier_0():\n y_human = ['Speech', 'Silence', 'Overlap', 'Speech', 'Silence']\n y_lena = ['Speech', 'Silence', 'Speech', 'Silence', 'Silence']\n speech_tiers = ['Speech', 'Silence']\n result = calculate_frame_ier(y_human, y_lena, speech_tiers)\n assert result == (0, 0, 0, 3)", ...
15
single_defcom_extract
def single_defcom_extract(start_from, srcls, is_class_begin=False): i = start_from fcombody = "" # def comment body comstart = -1 # the starting line index of comment mark "'''" or """""" # if it is not -1, it indicates the loop is in the comment body comstyle = 0 # comment mark style ,comments ...
to extract a def function/class/method comments body
341
[ "def test_single_defcom_extract_0():\n assert single_defcom_extract(0, ['def my_function():', \" '''\", ' This is a comment', \" '''\", ' pass']) == ' This is a comment'", "def test_single_defcom_extract_1():\n assert single_defcom_extract(0, ['class MyClass:', \" '''\", ' Class docstri...
17
fwscan_wins
def fwscan_wins(limit, rlen, numdocs): docratio = rlen / float(numdocs) if limit: limitratio = limit / float(numdocs) else: limitratio = 1 div = 65536.0 if docratio >= 16384/div: # forward scan tends to beat nbest or timsort reliably when # the rlen is greater than...
Primitive curvefitting to see if forward scan will beat both nbest and timsort for a particular limit/rlen/numdocs tuple. In sortbench tests up to 'numdocs' sizes of 65536, this curve fit had a 95%+ accuracy rate, except when 'numdocs' is < 64, then its lowest accuracy percentage was 83%. Thus, it could still use some ...
342
[ "def test_fwscan_wins_0():\n assert fwscan_wins(100, 200, 64) == True", "def test_fwscan_wins_1():\n assert fwscan_wins(0, 100, 64) == False", "def test_fwscan_wins_2():\n assert fwscan_wins(100, 8192, 64) == True", "def test_fwscan_wins_3():\n assert fwscan_wins(100, 4096, 64) == False", "def t...
14
get_allen_relation
def get_allen_relation(duration1, duration2): is1, ie1 = duration1 is2, ie2 = duration2 if is2-1 == ie1: return 'meets' elif is1-1 == ie2: return 'metby' elif is1 == is2 and ie1 == ie2: return 'equal' elif is2 > ie1: return 'before' elif is1 > ie2: ...
Generates an Allen interval algebra relation between two discrete durations of time
349
[ "def test_get_allen_relation_0():\n assert get_allen_relation((1, 5), (2, 3)) == 'meets'", "def test_get_allen_relation_1():\n assert get_allen_relation((1, 5), (6, 8)) == 'before'", "def test_get_allen_relation_2():\n assert get_allen_relation((1, 5), (3, 4)) == 'overlaps'", "def test_get_allen_rela...
25
drawWalls
class Cell: def __init__(self, walls): self.walls = walls def drawWalls(grid: list, binGrid: list) -> list: for yindex, y in enumerate(grid): for xindex, x in enumerate(y): for i, w in enumerate(x.walls): if i == 0 and w: binGrid[yindex*2+1][xind...
Draw existing walls around Cells
351
[ "def test_drawWalls_0():\n grid = [[Cell([True, False, True, False]), Cell([False, True, False, True])]]\n binGrid = [[' ' for _ in range(4)] for _ in range(2)]\n expected = [['⬛ ', '⬛ ', ' ', ' '], [' ', '⬛ ', ' ', '⬛']]\n result = drawWalls(grid, binGrid)\n assert result == expected, f'Expected {ex...
12
adjust_predicts
def adjust_predicts(score, label, threshold, pred=None, calc_latency=False): if label is None: predict = [s > threshold for s in score] return predict, None if pred is None: if len(score) != len(label): raise ValueError("score and label must have the same length") p...
Calculate adjusted predict labels using given `score`, `threshold` (or given `pred`) and `label`.
356
[ "def test_adjust_predicts_0():\n score = [0.2, 0.5, 0.3, 0.7]\n label = [0, 1, 0, 1]\n threshold = 0.4\n pred = None\n calc_latency = False\n expected = ([True, True, True, True], None)\n (predict, _) = adjust_predicts(score, label, threshold, pred, calc_latency)\n assert predict == expected...
17
split_condition
def split_condition(w,h): if w != 0: tosplit_w = random.uniform(120, w*1.5) if h != 0: tosplit_h = random.uniform(120, h*1.5) if w != 0 and h != 0:#if we want to split vertically and horizontally if tosplit_w < w and tosplit_h < h: return "Both" elif w !...
This function decides if the rectangle of width w and height h will be split or not, and if it will be done vertically, horizontally or both.
363
[ "def test_split_condition_0():\n assert split_condition(100, 200) == 'h_split'", "def test_split_condition_1():\n assert split_condition(0, 200) == 'h_split'", "def test_split_condition_2():\n assert split_condition(150, 0) == 'w_split'", "def test_split_condition_3():\n assert split_condition(0, ...
11
get_elo_today_from_v1_api
def get_elo_today_from_v1_api(data_v1): logging.info("start get_elo_today_from_v1_api") EloDiff = 0 EloStart = 0 found_data = 0 today = datetime.date.today() for x in data_v1: date: str = str(x["date"]) dateint: int = date[0:10] datetime_time = datetime.datetime....
Calculate the + Elo in a Day
366
[ "def test_get_elo_today_from_v1_api_0():\n test_data = [\n {\"date\": \"2023-04-01T00:00:00\", \"elo\": 1500},\n {\"date\": \"2023-04-02T00:00:00\", \"elo\": 1505},\n {\"date\": \"2023-04-03T00:00:00\", \"elo\": 1510},\n {\"date\": \"2023-04-04T00:00:00\", \"elo\": 1500},\n {\"...
12