uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
f8748ac0bc202d105e89fae8
train
class
class Upsample2xBlock(torch.nn.Module): def __init__(self, input_size, output_size, bias=True, upsample='rnc', activation='relu', norm='batch'): super(Upsample2xBlock, self).__init__() scale_factor = 2 self.upsample = torch.nn.Sequential( torch.nn.Upsample(scale_factor=s...
class Upsample2xBlock(torch.nn.Module):
def __init__(self, input_size, output_size, bias=True, upsample='rnc', activation='relu', norm='batch'): super(Upsample2xBlock, self).__init__() scale_factor = 2 self.upsample = torch.nn.Sequential( torch.nn.Upsample(scale_factor=scale_factor, mode='nearest'), ...
def forward(self, x): if self.norm is not None: out = self.bn(self.conv(x)) else: out = self.conv(x) if self.activation is not None: return self.act(out) else: return out class Upsample2xBlock(torch.nn.Module):
64
64
144
10
53
Siyeong-Lee/Deep_Recursive_HDRI
block.py
Python
Upsample2xBlock
Upsample2xBlock
94
108
94
94
951f02117d8303d5ebb268938b40962ad4875ed4
bigcode/the-stack
train
849a597838d110196e5cc0de
train
function
def geometry(left_fitx, right_fitx, ploty, leftx, rightx): # Radius # Define y-value where we want radius of curvature # We'll choose the maximum y-value, corresponding to the bottom of the image y_eval = np.max(ploty) ##### TO-DO: Implement the calculation of R_curve (radius of curvature) ##### ...
def geometry(left_fitx, right_fitx, ploty, leftx, rightx): # Radius # Define y-value where we want radius of curvature # We'll choose the maximum y-value, corresponding to the bottom of the image
y_eval = np.max(ploty) ##### TO-DO: Implement the calculation of R_curve (radius of curvature) ##### left_curverad = (1+(2*left_fit[0]*y_eval+left_fit[1])**2)**(3.0/2)/abs(2*left_fit[0]) right_curverad = (1+(2*right_fit[0]*y_eval+right_fit[1])**2)**(3.0/2)/abs(2*right_fit[0]) # Meters # Defi...
= cv2.warpPerspective(color_warp, Minv, (binary_warped.shape[1], binary_warped.shape[0])) # Combine the result with the original image result = cv2.addWeighted(undist, 1, newwarp, 0.3, 0) return result def geometry(left_fitx, right_fitx, ploty, leftx, rightx): # Radius # Define y-value where we wa...
122
122
409
52
69
lianghu83/CarND-Advanced-Lane-Lines-master
pipeline.py
Python
geometry
geometry
313
330
313
316
41878f12ed77d44c91220569a2c5a3bbb7875082
bigcode/the-stack
train
4f4a45309a26ab743caaab50
train
function
def search_around_poly_refit(binary_warped): # HYPERPARAMETER # Choose the width of the margin around the previous polynomial to search margin = 100 # Grab activated pixels nonzero = binary_warped.nonzero() nonzeroy = np.array(nonzero[0]) nonzerox = np.array(nonzero[1]) ### Set the area ...
def search_around_poly_refit(binary_warped): # HYPERPARAMETER # Choose the width of the margin around the previous polynomial to search
margin = 100 # Grab activated pixels nonzero = binary_warped.nonzero() nonzeroy = np.array(nonzero[0]) nonzerox = np.array(nonzero[1]) ### Set the area of search based on activated x-values ### ### within the +/- margin of our polynomial function ### ### consider the window areas for the...
255, 0)) cv2.fillPoly(window_img, np.int_([right_line_pts]), (0,255, 0)) result = cv2.addWeighted(out_img, 1, window_img, 0.3, 0) # Plot the polynomial lines onto the image plt.plot(left_fitx, ploty, color='yellow') plt.plot(right_fitx, ploty, color='yellow') ## End visualization steps ## # ...
153
153
512
35
118
lianghu83/CarND-Advanced-Lane-Lines-master
pipeline.py
Python
search_around_poly_refit
search_around_poly_refit
263
294
263
265
9399e9d32816df52d558fd05c97ce73d6eb2d1e7
bigcode/the-stack
train
7e3a11643df72c4cc4dac43f
train
function
def undistort_image(img, mtx, dist): undist = cv2.undistort(img, mtx, dist, None, mtx) return undist
def undistort_image(img, mtx, dist):
undist = cv2.undistort(img, mtx, dist, None, mtx) return undist
# Read in the saved camera matrix and distortion coefficients dist_pickle = pickle.load( open( "wide_dist_pickle.p", "rb" ) ) mtx = dist_pickle["mtx"] dist = dist_pickle["dist"] # Undistort image def undistort_image(img, mtx, dist):
64
64
39
12
51
lianghu83/CarND-Advanced-Lane-Lines-master
pipeline.py
Python
undistort_image
undistort_image
19
21
19
19
6cb2592a916ff0d27fa6ea70465338b72e11da22
bigcode/the-stack
train
5bc60a9d1e21282958aa0396
train
function
def color_lane_region(undist, binary_warped, left_fitx, right_fitx, ploty, Minv): # Create an image to draw the lines on warp_zero = np.zeros_like(binary_warped).astype(np.uint8) color_warp = np.dstack((warp_zero, warp_zero, warp_zero)) # Recast the x and y points into usable format for cv2.fillPoly() ...
def color_lane_region(undist, binary_warped, left_fitx, right_fitx, ploty, Minv): # Create an image to draw the lines on
warp_zero = np.zeros_like(binary_warped).astype(np.uint8) color_warp = np.dstack((warp_zero, warp_zero, warp_zero)) # Recast the x and y points into usable format for cv2.fillPoly() pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))]) pts_right = np.array([np.flipud(np.transpose(np.vst...
_fitx = right_fit[0]*ploty**2 + right_fit[1]*ploty + right_fit[2] #return return left_fitx, right_fitx, ploty def color_lane_region(undist, binary_warped, left_fitx, right_fitx, ploty, Minv): # Create an image to draw the lines on
81
81
272
38
42
lianghu83/CarND-Advanced-Lane-Lines-master
pipeline.py
Python
color_lane_region
color_lane_region
296
310
296
297
661203f3aa29a45f4cc1145b9b66782ce00626b1
bigcode/the-stack
train
a92be9647508b30f4af7fba1
train
function
def warper(img, src, dst): # Compute and apply perpective transform # The img should be an undistorted image img_size = (img.shape[1], img.shape[0]) M = cv2.getPerspectiveTransform(src, dst) warped = cv2.warpPerspective(img, M, img_size, flags=cv2.INTER_NEAREST) # keep same size as input image ...
def warper(img, src, dst): # Compute and apply perpective transform # The img should be an undistorted image
img_size = (img.shape[1], img.shape[0]) M = cv2.getPerspectiveTransform(src, dst) warped = cv2.warpPerspective(img, M, img_size, flags=cv2.INTER_NEAREST) # keep same size as input image return warped, M
], [320, 720], [960, 720], [960, 0]]) Minv = cv2.getPerspectiveTransform(dst, src) def warper(img, src, dst): # Compute and apply perpective transform # The img should be an undistorted image
64
64
94
30
34
lianghu83/CarND-Advanced-Lane-Lines-master
pipeline.py
Python
warper
warper
58
64
58
60
efd53047e43767f79f7d300bcedc62b7d5cceae9
bigcode/the-stack
train
084bf87056ec4c6fb7eabd8c
train
class
class Line(): def __init__(self): # was the line detected in the last iteration? self.detected = False # x values of the last n fits of the line self.recent_xfitted = [] #average x values of the fitted line over the last n iterations self.bestx = None ...
class Line():
def __init__(self): # was the line detected in the last iteration? self.detected = False # x values of the last n fits of the line self.recent_xfitted = [] #average x values of the fitted line over the last n iterations self.bestx = None #polynomial co...
and right polynomials on the lane lines plt.plot(left_fitx, ploty, color='yellow') plt.plot(right_fitx, ploty, color='yellow') # Return output image return out_img """ # Define a class to receive the characteristics of each line detection class Line():
65
65
219
3
61
lianghu83/CarND-Advanced-Lane-Lines-master
pipeline.py
Python
Line
Line
170
191
170
170
0fa7c65bfacf9578dfb56a06cc25230e94bca471
bigcode/the-stack
train
870502a5d56bbebb54a5c305
train
function
def create_binary(img, s_thresh=(170, 255), sx_thresh=(20, 100)): img = np.copy(img) # Convert to HLS color space and separate the V channel hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS) l_channel = hls[:,:,1] s_channel = hls[:,:,2] # Sobel x sobelx = cv2.Sobel(l_channel, cv2.CV_64F, 1, 0) # Ta...
def create_binary(img, s_thresh=(170, 255), sx_thresh=(20, 100)):
img = np.copy(img) # Convert to HLS color space and separate the V channel hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS) l_channel = hls[:,:,1] s_channel = hls[:,:,2] # Sobel x sobelx = cv2.Sobel(l_channel, cv2.CV_64F, 1, 0) # Take the derivative in x abs_sobelx = np.absolute(sobelx) # Abso...
) ) mtx = dist_pickle["mtx"] dist = dist_pickle["dist"] # Undistort image def undistort_image(img, mtx, dist): undist = cv2.undistort(img, mtx, dist, None, mtx) return undist # Get binary image def create_binary(img, s_thresh=(170, 255), sx_thresh=(20, 100)):
89
89
299
21
67
lianghu83/CarND-Advanced-Lane-Lines-master
pipeline.py
Python
create_binary
create_binary
24
44
24
24
c692c029b532928018f65c41c9b9ba7b2483aaeb
bigcode/the-stack
train
35bb57288adc49f46e675215
train
function
def command( iArgs, iFiles, iConfig, iDirs, iKeys ): ProjectDependencies.utils.notify_ignore_args( iArgs ) ProjectDependencies.utils.smart_gather_wtree_resolve_all_hash_inconsistencies( iDirs, iFiles ) # Bake utility strings from gathered information src = iConfig["remote"] + iConfig["file"] dst =...
def command( iArgs, iFiles, iConfig, iDirs, iKeys ):
ProjectDependencies.utils.notify_ignore_args( iArgs ) ProjectDependencies.utils.smart_gather_wtree_resolve_all_hash_inconsistencies( iDirs, iFiles ) # Bake utility strings from gathered information src = iConfig["remote"] + iConfig["file"] dst = iDirs["tmp"] + iConfig["file"] # Create tm...
#:: furnished to do so, subject to the following conditions: #:: #:: The above copyright notice and this permission notice shall be included in all #:: copies or substantial portions of the Software. #:: #:: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #:: IMPLIED, INCLUDING BUT NOT LIMIT...
225
225
751
18
207
Robot-Fromage/ProjectDependencies
ProjectDependencies/download.py
Python
command
command
40
126
40
40
04803086c42f61d62c6737ce3ee36653f3c7e7a8
bigcode/the-stack
train
01a6e81dc2c5a99a1de6b20f
train
function
def validate_collection_change(obj): """Validates collection change. Args: obj: dict. Data that needs to be validated. """ # No explicit call to validate_dict method is necessary, because # CollectionChange calls validate method while initialization. collection_domain.CollectionChange(o...
def validate_collection_change(obj):
"""Validates collection change. Args: obj: dict. Data that needs to be validated. """ # No explicit call to validate_dict method is necessary, because # CollectionChange calls validate method while initialization. collection_domain.CollectionChange(obj) # type: ignore[no-untyped-call]
# type: ignore[no-untyped-call] 'list_of_default_tags_for_blog_post').value if not all(tag in list_of_default_tags for tag in change_dict['tags']): raise Exception( 'Invalid tags provided. Tags not in default tags list.') def validate_collection_change(obj):
63
64
71
6
57
nbaddam/oppia
core/controllers/domain_objects_validator.py
Python
validate_collection_change
validate_collection_change
87
95
87
87
9a97209cb98c3fe13556ec7d059e1a13ae909226
bigcode/the-stack
train
deee3617c9178f66bc068376
train
function
def validate_change_dict_for_blog_post(change_dict): """Validates change_dict required for updating values of blog post. Args: change_dict: dict. Data that needs to be validated. """ if 'title' in change_dict: blog_domain.BlogPost.require_valid_title( # type: ignore[no-untyped-call] ...
def validate_change_dict_for_blog_post(change_dict):
"""Validates change_dict required for updating values of blog post. Args: change_dict: dict. Data that needs to be validated. """ if 'title' in change_dict: blog_domain.BlogPost.require_valid_title( # type: ignore[no-untyped-call] change_dict['title'], True) if 'thumbnai...
should be a string, received' ': %s' % name) config_property = config_domain.Registry.get_config_property(name) # type: ignore[no-untyped-call] if config_property is None: raise Exception('%s do not have any schema.' % name) config_property.normalize(value) def vali...
74
74
249
10
64
nbaddam/oppia
core/controllers/domain_objects_validator.py
Python
validate_change_dict_for_blog_post
validate_change_dict_for_blog_post
63
84
63
63
75e5ec3a20df8c569b4ca4ffb9fba8a8133e6cc2
bigcode/the-stack
train
e9469af4fa3f7c0c438d0d62
train
function
def validate_aggregated_stats(aggregated_stats): """Validates the attribute stats dict. Args: aggregated_stats: dict. Data that needs to be validated. Raises: InvalidInputException. Property not in aggregated stats dict. """ exploration_stats_properties = [ 'num_starts', ...
def validate_aggregated_stats(aggregated_stats):
"""Validates the attribute stats dict. Args: aggregated_stats: dict. Data that needs to be validated. Raises: InvalidInputException. Property not in aggregated stats dict. """ exploration_stats_properties = [ 'num_starts', 'num_actual_starts', 'num_completio...
') target_id = task_entries.get('target_id', None) if target_id is None: raise base.BaseHandler.InvalidInputException('No target_id provided') status = task_entries.get('status', None) if status is None: raise base.BaseHandler.InvalidInputException('No status provided') def validate_aggr...
76
76
254
11
65
nbaddam/oppia
core/controllers/domain_objects_validator.py
Python
validate_aggregated_stats
validate_aggregated_stats
148
180
148
148
38846edbc4c2c62fbbe04289304ae7d6db3d40ac
bigcode/the-stack
train
30684d4548f135e1c4745554
train
function
def validate_task_entries(task_entries): """Validates the task entry dict. Args: task_entries: dict. Data that needs to be validated. """ entity_version = task_entries.get('entity_version', None) if entity_version is None: raise base.BaseHandler.InvalidInputException( 'N...
def validate_task_entries(task_entries):
"""Validates the task entry dict. Args: task_entries: dict. Data that needs to be validated. """ entity_version = task_entries.get('entity_version', None) if entity_version is None: raise base.BaseHandler.InvalidInputException( 'No entity_version provided') task_type...
'] for predicate in predicates] for key, value in data.items(): if value is None: continue if key not in possible_keys: # Raise exception if key is not one of the allowed keys. raise Exception('400 Invalid input for query.') def validate_task_entries(task_entries...
63
64
168
7
56
nbaddam/oppia
core/controllers/domain_objects_validator.py
Python
validate_task_entries
validate_task_entries
127
145
127
127
2ab73a68b8173ce001951a37936683813cf6961d
bigcode/the-stack
train
0fadeba24011a6c876b42c7d
train
function
def validate_exploration_change(obj): """Validates exploration change. Args: obj: dict. Data that needs to be validated. """ # No explicit call to validate_dict method is necessary, because # ExplorationChange calls validate method while initialization. exp_domain.ExplorationChange(obj)...
def validate_exploration_change(obj):
"""Validates exploration change. Args: obj: dict. Data that needs to be validated. """ # No explicit call to validate_dict method is necessary, because # ExplorationChange calls validate method while initialization. exp_domain.ExplorationChange(obj) # type: ignore[no-untyped-call]
from core.constants import constants from core.controllers import base from core.domain import blog_domain from core.domain import collection_domain from core.domain import config_domain from core.domain import exp_domain from core.domain import state_domain from typing import Dict, Optional, Union def validate_explor...
64
64
75
8
55
nbaddam/oppia
core/controllers/domain_objects_validator.py
Python
validate_exploration_change
validate_exploration_change
34
42
34
34
e17e87c9f33cd22597a838b24a2a7eb98026ae87
bigcode/the-stack
train
dbef847586c5b1358795e3ae
train
function
def validate_state_dict(state_dict): """Validates state dict. Args: state_dict: dict. Data that needs to be validated. """ validation_class = state_domain.State.from_dict(state_dict) # type: ignore[no-untyped-call] validation_class.validate(None, True)
def validate_state_dict(state_dict):
"""Validates state dict. Args: state_dict: dict. Data that needs to be validated. """ validation_class = state_domain.State.from_dict(state_dict) # type: ignore[no-untyped-call] validation_class.validate(None, True)
Args: obj: dict. Data that needs to be validated. """ # No explicit call to validate_dict method is necessary, because # CollectionChange calls validate method while initialization. collection_domain.CollectionChange(obj) # type: ignore[no-untyped-call] def validate_state_dict(state_dict):
64
64
62
7
57
nbaddam/oppia
core/controllers/domain_objects_validator.py
Python
validate_state_dict
validate_state_dict
98
105
98
98
f62d46493c40ff086c592e06d44f170688880204
bigcode/the-stack
train
0cf019410e4e076328b17dce
train
function
def validate_email_dashboard_data( data: Dict[str, Optional[Union[bool, int]]] ) -> None: """Validates email dashboard data. Args: data: dict. Data that needs to be validated. """ predicates = constants.EMAIL_DASHBOARD_PREDICATE_DEFINITION possible_keys = [predicate['backend_attr'] ...
def validate_email_dashboard_data( data: Dict[str, Optional[Union[bool, int]]] ) -> None:
"""Validates email dashboard data. Args: data: dict. Data that needs to be validated. """ predicates = constants.EMAIL_DASHBOARD_PREDICATE_DEFINITION possible_keys = [predicate['backend_attr'] for predicate in predicates] for key, value in data.items(): if value is None: ...
Data that needs to be validated. """ validation_class = state_domain.State.from_dict(state_dict) # type: ignore[no-untyped-call] validation_class.validate(None, True) def validate_email_dashboard_data( data: Dict[str, Optional[Union[bool, int]]] ) -> None:
64
64
130
25
39
nbaddam/oppia
core/controllers/domain_objects_validator.py
Python
validate_email_dashboard_data
validate_email_dashboard_data
108
124
108
110
0a31ab9b06d6ec2d47eb56ec4162297a06e0b297
bigcode/the-stack
train
b49ba335e0f7325392a5eb91
train
function
def validate_new_config_property_values(obj): """Validates new config property values. Args: obj: dict. Data that needs to be validated. """ for (name, value) in obj.items(): if not isinstance(name, str): raise Exception( 'config property name should be a str...
def validate_new_config_property_values(obj):
"""Validates new config property values. Args: obj: dict. Data that needs to be validated. """ for (name, value) in obj.items(): if not isinstance(name, str): raise Exception( 'config property name should be a string, received' ': %s' % name) ...
obj: dict. Data that needs to be validated. """ # No explicit call to validate_dict method is necessary, because # ExplorationChange calls validate method while initialization. exp_domain.ExplorationChange(obj) # type: ignore[no-untyped-call] def validate_new_config_property_values(obj):
64
64
126
8
56
nbaddam/oppia
core/controllers/domain_objects_validator.py
Python
validate_new_config_property_values
validate_new_config_property_values
45
60
45
45
56417191cf73efa162053bb3af964dbc3e72b0dd
bigcode/the-stack
train
cbfc94ec0d7bb12f7bb2efa5
train
function
def print_help(): """ Print the manual of the program """ print("merge_files.py allow you to easily merge .ins files\nTo use it:>\n\npython merge_files.py <directory_to_save_output> <fileA> <fileB> <fileC> ... \n\nFor all the files:\n\npython merge_files.py <directory_to_save_output> <directory/*.ins>"...
def print_help():
""" Print the manual of the program """ print("merge_files.py allow you to easily merge .ins files\nTo use it:>\n\npython merge_files.py <directory_to_save_output> <fileA> <fileB> <fileC> ... \n\nFor all the files:\n\npython merge_files.py <directory_to_save_output> <directory/*.ins>")
#!/usr/bin/env python import os import sys import collections def print_help():
19
64
86
4
14
SMV818VMS/pyutils
merge_ins_files.py
Python
print_help
print_help
8
13
8
8
863938a55e198fec40ada76506a4e9f668df25e1
bigcode/the-stack
train
a23559f0930a049e7775fc75
train
function
def main(): """ Main function to run the merge_files function """ # Evaluate arguments and if help required: if len(sys.argv) <= 2: print_help() else: merge_files()
def main():
""" Main function to run the merge_files function """ # Evaluate arguments and if help required: if len(sys.argv) <= 2: print_help() else: merge_files()
(line[1]) # Export to a file: fo = open(outFile, 'w') od = collections.OrderedDict(sorted(results_dic.items())) for k, v in od.iteritems(): fo.write(str(k)+'\t'+str(v)+'\n') fo.close() def main():
64
64
44
3
61
SMV818VMS/pyutils
merge_ins_files.py
Python
main
main
49
56
49
49
ff815ce18a19d1885ffb4f0ea452f4e32ad64110
bigcode/the-stack
train
64c6dd9d313e95f06e8c0890
train
function
def merge_files(): """ Given a list of files where position\treads\nposition\treads...\n Returns a merged file containing the position and the reads, if the position between two files is the same, sums the reads. """ # Ste the variables outFile = sys.argv[1] inFile = sys.argv[2:] # Ta...
def merge_files():
""" Given a list of files where position\treads\nposition\treads...\n Returns a merged file containing the position and the reads, if the position between two files is the same, sums the reads. """ # Ste the variables outFile = sys.argv[1] inFile = sys.argv[2:] # Takes the second argu...
""" print("merge_files.py allow you to easily merge .ins files\nTo use it:>\n\npython merge_files.py <directory_to_save_output> <fileA> <fileB> <fileC> ... \n\nFor all the files:\n\npython merge_files.py <directory_to_save_output> <directory/*.ins>") def merge_files():
77
78
260
4
74
SMV818VMS/pyutils
merge_ins_files.py
Python
merge_files
merge_files
16
46
16
16
8033d4a173771a1cd710fc3caef68fa867b14867
bigcode/the-stack
train
182bcee11b6ae5f1fac3a748
train
function
def x_length_words(sentence, x): sentence_split = sentence.split() for word in sentence_split: if len(word) < x: return False else: return True
def x_length_words(sentence, x):
sentence_split = sentence.split() for word in sentence_split: if len(word) < x: return False else: return True
# Write your x_length_words function here: def x_length_words(sentence, x):
17
64
41
8
9
orby2002/learn-python
6-strings/code-challenge/x-length.py
Python
x_length_words
x_length_words
2
8
2
2
30e4b6e239b41aec4bce7057bd930db11151758a
bigcode/the-stack
train
5121082516ab3d7632dc8f1f
train
class
class TestNAT44EDMW(TestNAT44ED): """ NAT44ED MW Test Case """ vpp_worker_count = 4 max_sessions = 5000 def test_dynamic(self): """ NAT44ED dynamic translation test """ pkt_count = 1500 tcp_port_offset = 20 udp_port_offset = 20 icmp_id_offset = 20 self.n...
class TestNAT44EDMW(TestNAT44ED):
""" NAT44ED MW Test Case """ vpp_worker_count = 4 max_sessions = 5000 def test_dynamic(self): """ NAT44ED dynamic translation test """ pkt_count = 1500 tcp_port_offset = 20 udp_port_offset = 20 icmp_id_offset = 20 self.nat_add_address(self.nat_addr) ...
port=7000+i, dport=8000+i) / Raw(payload)) info.data = p pkts.append(p) self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() recvd = self.pg1.get_capture(len(pkts)) for p_recvd in recvd: payload...
256
256
16,710
13
243
caijie2020/vpp
test/test_nat44_ed.py
Python
TestNAT44EDMW
TestNAT44EDMW
2,155
3,838
2,155
2,155
3fbdc1750e4366fc2a952f7f710ad978a737f47d
bigcode/the-stack
train
a50c9585f2606cf4ef2c60fd
train
class
class TestNAT44ED(VppTestCase): """ NAT44ED Test Case """ nat_addr = '10.0.0.3' tcp_port_in = 6303 tcp_port_out = 6303 udp_port_in = 6304 udp_port_out = 6304 icmp_id_in = 6305 icmp_id_out = 6305 tcp_external_port = 80 max_sessions = 100 def setUp(self): super()...
class TestNAT44ED(VppTestCase):
""" NAT44ED Test Case """ nat_addr = '10.0.0.3' tcp_port_in = 6303 tcp_port_out = 6303 udp_port_in = 6304 udp_port_out = 6304 icmp_id_in = 6305 icmp_id_out = 6305 tcp_external_port = 80 max_sessions = 100 def setUp(self): super().setUp() self.plugin_ena...
#!/usr/bin/env python3 import unittest from io import BytesIO from random import randint, shuffle, choice import scapy.compat from framework import VppTestCase, VppTestRunner from scapy.data import IP_PROTOS from scapy.layers.inet import IP, TCP, UDP, ICMP, GRE from scapy.layers.inet import IPerror, TCPerror from sca...
195
256
19,311
11
183
caijie2020/vpp
test/test_nat44_ed.py
Python
TestNAT44ED
TestNAT44ED
22
2,152
22
22
cda64c30f3696cbaaca0521c3df0b8f235e630f5
bigcode/the-stack
train
129b5a9fdd9ffdb96a9ce528
train
class
class gdrive(object): def __init__(self): self.initialize = ee.Initialize() self.credentials = ee.Credentials() self.service = discovery.build( serviceName="drive", version="v3", cache_discovery=False, credentials=self.credentials, ) ...
class gdrive(object):
def __init__(self): self.initialize = ee.Initialize() self.credentials = ee.Credentials() self.service = discovery.build( serviceName="drive", version="v3", cache_discovery=False, credentials=self.credentials, ) def tasks_list(sel...
from pathlib import Path import ee import io from googleapiclient.http import MediaIoBaseDownload from apiclient import discovery from component.message import ms from .gee import search_task import logging logging.getLogger("googleapiclient.discovery_cache").setLevel(logging.ERROR) class gdrive(object):
67
256
987
5
62
12rambau/coverage_analysis
component/scripts/gdrive.py
Python
gdrive
gdrive
16
163
16
16
282b1f1f40b111b25334d2b68d321a0f59762f7a
bigcode/the-stack
train
9cea67ab5a48ba5c52cc16d5
train
function
@exception_handler(SLACK_HOOK=SLACK_HOOK, NETWORK_ID=NETWORK_ID, logger=logger, EXCEPTIONS=EXCEPTIONS) def callback(event, context): logger.info(f"received event from verification for callback {event}") payload = event["body"] path_parameters = event["queryStringParameters"] if "verification_id" not in ...
@exception_handler(SLACK_HOOK=SLACK_HOOK, NETWORK_ID=NETWORK_ID, logger=logger, EXCEPTIONS=EXCEPTIONS) def callback(event, context):
logger.info(f"received event from verification for callback {event}") payload = event["body"] path_parameters = event["queryStringParameters"] if "verification_id" not in path_parameters and "entity_id" not in path_parameters: raise BadRequestException() entity_id = path_parameters.get("enti...
Code.CREATED, {"status": ResponseStatus.SUCCESS, "data": response, "error": {}}, cors_enabled=True) @exception_handler(SLACK_HOOK=SLACK_HOOK, NETWORK_ID=NETWORK_ID, logger=logger, EXCEPTIONS=EXCEPTIONS) def callback(event, context):
64
64
170
38
26
DhivakharVenkatachalam/snet-marketplace-service
verification/application/handlers/verification_handlers.py
Python
callback
callback
31
43
31
32
858f64690a6f4da9f8933c33672a2a96cad30bd5
bigcode/the-stack
train
81478ad6c06f293d455f6635
train
function
@exception_handler(SLACK_HOOK=SLACK_HOOK, NETWORK_ID=NETWORK_ID, logger=logger, EXCEPTIONS=EXCEPTIONS) def get_status(event, context): query_parameters = event["queryStringParameters"] if "type" not in query_parameters: raise BadRequestException() verification_type = query_parameters["type"] if ...
@exception_handler(SLACK_HOOK=SLACK_HOOK, NETWORK_ID=NETWORK_ID, logger=logger, EXCEPTIONS=EXCEPTIONS) def get_status(event, context):
query_parameters = event["queryStringParameters"] if "type" not in query_parameters: raise BadRequestException() verification_type = query_parameters["type"] if verification_type == VerificationType.INDIVIDUAL.value: entity_id = event["requestContext"]["authorizer"]["claims"]["email"] ...
.CREATED, {"status": ResponseStatus.SUCCESS, "data": response, "error": {}}, cors_enabled=True) @exception_handler(SLACK_HOOK=SLACK_HOOK, NETWORK_ID=NETWORK_ID, logger=logger, EXCEPTIONS=EXCEPTIONS) def get_status(event, context):
64
64
181
39
25
DhivakharVenkatachalam/snet-marketplace-service
verification/application/handlers/verification_handlers.py
Python
get_status
get_status
46
60
46
47
3fe33583316a644a483ea49c4281d064bffcc9dd
bigcode/the-stack
train
fb7a9a479c23eb4e181759df
train
function
@exception_handler(SLACK_HOOK=SLACK_HOOK, NETWORK_ID=NETWORK_ID, logger=logger, EXCEPTIONS=EXCEPTIONS) def initiate(event, context): payload = json.loads(event["body"]) username = event["requestContext"]["authorizer"]["claims"]["email"] required_keys = ["type"] if not validate_dict(payload, required_key...
@exception_handler(SLACK_HOOK=SLACK_HOOK, NETWORK_ID=NETWORK_ID, logger=logger, EXCEPTIONS=EXCEPTIONS) def initiate(event, context):
payload = json.loads(event["body"]) username = event["requestContext"]["authorizer"]["claims"]["email"] required_keys = ["type"] if not validate_dict(payload, required_keys): raise BadRequestException() response = VerificationManager().initiate_verification(payload, username) return gene...
import VerificationType from verification.exceptions import EXCEPTIONS, BadRequestException patch_all() logger = get_logger(__name__) @exception_handler(SLACK_HOOK=SLACK_HOOK, NETWORK_ID=NETWORK_ID, logger=logger, EXCEPTIONS=EXCEPTIONS) def initiate(event, context):
64
64
131
38
26
DhivakharVenkatachalam/snet-marketplace-service
verification/application/handlers/verification_handlers.py
Python
initiate
initiate
18
28
18
19
994b87b47b3a1fa0354c76cb8fefea14afdbf214
bigcode/the-stack
train
0ea62687aac2779f0d8e437b
train
function
@exception_handler(SLACK_HOOK=SLACK_HOOK, NETWORK_ID=NETWORK_ID, logger=logger, EXCEPTIONS=EXCEPTIONS) def get_verifications(event, context): query_parameters = event["queryStringParameters"] if "type" not in query_parameters: raise BadRequestException() response = VerificationManager().get_verifica...
@exception_handler(SLACK_HOOK=SLACK_HOOK, NETWORK_ID=NETWORK_ID, logger=logger, EXCEPTIONS=EXCEPTIONS) def get_verifications(event, context):
query_parameters = event["queryStringParameters"] if "type" not in query_parameters: raise BadRequestException() response = VerificationManager().get_verifications(query_parameters) return generate_lambda_response(StatusCode.OK, {"status": ResponseStatus.SUCCESS, "data": response, "error": {}}, ...
.OK, {"status": ResponseStatus.SUCCESS, "data": response, "error": {}}, cors_enabled=True) @exception_handler(SLACK_HOOK=SLACK_HOOK, NETWORK_ID=NETWORK_ID, logger=logger, EXCEPTIONS=EXCEPTIONS) def get_verifications(event, context):
64
64
109
40
24
DhivakharVenkatachalam/snet-marketplace-service
verification/application/handlers/verification_handlers.py
Python
get_verifications
get_verifications
63
70
63
64
a75a30e205b77e91b08afa39e7036123a521bd68
bigcode/the-stack
train
eee6b7347f6e9f2244f20abf
train
function
def setup_path() -> None: if os.path.basename(sys.prefix) != "zulip-py3-venv": BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) venv = os.path.join(BASE_DIR, "zulip-py3-venv") activate_this = os.path.join(venv, "bin", "activate_this.py") activat...
def setup_path() -> None:
if os.path.basename(sys.prefix) != "zulip-py3-venv": BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) venv = os.path.join(BASE_DIR, "zulip-py3-venv") activate_this = os.path.join(venv, "bin", "activate_this.py") activate_locals = dict(__file__=a...
""" Use libraries from a virtualenv (by modifying sys.path) in production. """ import os import sys def setup_path() -> None:
30
64
194
7
22
cozyrohan/zulip
scripts/lib/setup_path.py
Python
setup_path
setup_path
8
20
8
8
b597f631f392f63434fe01ca9af9e714d43f6551
bigcode/the-stack
train
1e8af6f955e3c7d0893f9a18
train
class
class Migration(migrations.Migration): dependencies = [ ('timewebapp', '0021_auto_20210418_1303'), ] operations = [ migrations.AlterField( model_name='settingsmodel', name='show_info_buttons', field=models.BooleanField(default=True, verbose_name='Show In...
class Migration(migrations.Migration):
dependencies = [ ('timewebapp', '0021_auto_20210418_1303'), ] operations = [ migrations.AlterField( model_name='settingsmodel', name='show_info_buttons', field=models.BooleanField(default=True, verbose_name='Show Info Buttons'), ), ]
# Generated by Django 3.1.8 on 2021-04-18 20:23 from django.db import migrations, models class Migration(migrations.Migration):
38
64
73
7
30
snapsnap123/TimeWeb
timeweb/timewebapp/migrations/0022_auto_20210418_1323.py
Python
Migration
Migration
6
18
6
7
dbd9582811b4211d9ab8a250a17fc58cfa3251ec
bigcode/the-stack
train
0fd18aa40e678fab5025be97
train
function
def assert_xyz_img_dir(xyz_dir, ids): """ Asserts XYZ images in the xyz_dir directory. Args: xyz_dir: directory of the XYZ images for data augmentation. ids: a list of scene IDs. """ for i in range(len(ids)): if not os.path.exists(os.path.join(xyz_dir, '%04d.png' % (ids[i] + 1))): print('Imag...
def assert_xyz_img_dir(xyz_dir, ids):
""" Asserts XYZ images in the xyz_dir directory. Args: xyz_dir: directory of the XYZ images for data augmentation. ids: a list of scene IDs. """ for i in range(len(ids)): if not os.path.exists(os.path.join(xyz_dir, '%04d.png' % (ids[i] + 1))): print('Image %s not found!' % os.path.join(xyz_di...
name. Args: camera_models: a list of camera model names. """ for c in range(len(camera_models)): target_cam = camera_models[c] assert (target_cam.lower() in cameras or target_cam.lower() == 'all') def assert_xyz_img_dir(xyz_dir, ids):
64
64
124
11
53
manipopopo/C5
src/aug_ops.py
Python
assert_xyz_img_dir
assert_xyz_img_dir
543
554
543
543
dc6c9dfbcc44ec7539462c8e3df8d41a0862b58b
bigcode/the-stack
train
dad50421b9196d72089560f0
train
function
def assert_target_camera(camera_models): """ Asserts target camera model name. Args: camera_models: a list of camera model names. """ for c in range(len(camera_models)): target_cam = camera_models[c] assert (target_cam.lower() in cameras or target_cam.lower() == 'all')
def assert_target_camera(camera_models):
""" Asserts target camera model name. Args: camera_models: a list of camera model names. """ for c in range(len(camera_models)): target_cam = camera_models[c] assert (target_cam.lower() in cameras or target_cam.lower() == 'all')
result[:, :, c] = (cst[c, 0] * im[:, :, 0] + cst[c, 1] * im[:, :, 1] + cst[c, 2] * im[:, :, 2]) return result def assert_target_camera(camera_models):
64
64
67
7
56
manipopopo/C5
src/aug_ops.py
Python
assert_target_camera
assert_target_camera
532
540
532
532
89a960b8c0959bff6abb72d8396463c97a0c5172
bigcode/the-stack
train
d3c51e2347840dd6149fbe40
train
function
def sampling(im, t_camera_data, output_dir, filename, c_temp, baseline_exposure, baseline_noise, ISO, aperture, aperture_norm, exposure_time, transfer_intensity, remove_saturated_pixels, save_as_16_bits, output_image_size, saturation_level, cropping, rotated, ...
def sampling(im, t_camera_data, output_dir, filename, c_temp, baseline_exposure, baseline_noise, ISO, aperture, aperture_norm, exposure_time, transfer_intensity, remove_saturated_pixels, save_as_16_bits, output_image_size, saturation_level, cropping, rotated, ...
""" Samples from target camera set's settings and maps input image (im) to the sampled setting. Args: im: source image. t_camera_data: metadata of the target camera model. output_dir: output directory to save mapped images and metadata. filename: filename of output image. c_temp: color temper...
(%d/%d)...', camera_i, len(target_cameras)) for image_i in range(images_per_scene): filename = 'image_%07d_sensorname_%s.png' % ( counter, target_cameras[camera_i].lower().replace(' ', '_')) status = sampling(copy.deepcopy(image), target_cameras_data[camera...
256
256
2,001
76
179
manipopopo/C5
src/aug_ops.py
Python
sampling
sampling
266
446
266
271
ce2335963b73dea0efea0f3207ef6ea736886f19
bigcode/the-stack
train
f661ef73ebb107e61a933d11
train
function
def softmax(x): """ Applies softmax function: softmax(x) = np.exp(x)/sum(np.exp(x)). """ return np.exp(x) / sum(np.exp(x))
def softmax(x):
""" Applies softmax function: softmax(x) = np.exp(x)/sum(np.exp(x)). """ return np.exp(x) / sum(np.exp(x))
0) > 0.4 * num_pixels or np.sum(im[:, :, 2] < 0) > 0.4 * num_pixels or np.sum(np.isnan(ill)) >= 1): return False else: return True def softmax(x):
64
64
40
5
58
manipopopo/C5
src/aug_ops.py
Python
softmax
softmax
468
471
468
468
cd2e78d5bb4ce771a8bdc3a9e97b00bcf457f8ea
bigcode/the-stack
train
7605909d1585a1200218e1d8
train
function
def knnsearch(query, data, k): """ Finds the nearest K data points. Args: query: input vector (1 x d). data: training vectors (n x d). k: number of nearest data points. Returns: indices: indices of the k nearest data points. d: distances between the query data point and the k n...
def knnsearch(query, data, k):
""" Finds the nearest K data points. Args: query: input vector (1 x d). data: training vectors (n x d). k: number of nearest data points. Returns: indices: indices of the k nearest data points. d: distances between the query data point and the k nearest data points. """ d ...
1): return False else: return True def softmax(x): """ Applies softmax function: softmax(x) = np.exp(x)/sum(np.exp(x)). """ return np.exp(x) / sum(np.exp(x)) def knnsearch(query, data, k):
64
64
139
10
54
manipopopo/C5
src/aug_ops.py
Python
knnsearch
knnsearch
474
492
474
474
8e00623045e6e64500f8867f8b5e699e0c5f557b
bigcode/the-stack
train
826bd70913e1f9be05fa53a3
train
function
def set_sampling_params(im_per_scene_per_camera=1, intensity_transfer=False, target_aug_im_num=5000, excluded_camera_models=None, excluded_datasets=None, save_as_16_bits=True, remove_saturated_pixels=False, saturation_level=0.97, ...
def set_sampling_params(im_per_scene_per_camera=1, intensity_transfer=False, target_aug_im_num=5000, excluded_camera_models=None, excluded_datasets=None, save_as_16_bits=True, remove_saturated_pixels=False, saturation_level=0.97, ...
""" Sets sampling parameters. Args: im_per_scene_per_camera: number of sampled images per scene per camera model; the default is 1. intensity_transfer: transfer the intensity of target image into the source image. This is useful for methods that are not relying on the log-chroma space as ...
import random import cv2 import ops import copy logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s') rand = np.random.rand cameras = ['canon eos 550d', 'canon eos 5d', 'canon eos-1ds', 'canon eos-1ds mark iii', 'fujifilm x-m1', 'nikon d40', 'nikon d5200', 'olympus e-pl6',...
218
218
727
91
127
manipopopo/C5
src/aug_ops.py
Python
set_sampling_params
set_sampling_params
34
98
34
40
4cef8ec62f6c9bcadf67a9c9f695dcb80c5d04f5
bigcode/the-stack
train
59d75a9df338f5b640626105
train
function
def map_raw_images(xyz_img_dir, target_cameras, output_dir, params): """ Maps raw images to target camera models. Args: xyz_img_dir: directory of XYZ images. target_cameras: target camera model name is a list of one or more of the following models: 'Canon EOS 550D', 'Canon EOS 5D', 'Canon EOS...
def map_raw_images(xyz_img_dir, target_cameras, output_dir, params):
""" Maps raw images to target camera models. Args: xyz_img_dir: directory of XYZ images. target_cameras: target camera model name is a list of one or more of the following models: 'Canon EOS 550D', 'Canon EOS 5D', 'Canon EOS-1DS', 'Canon EOS-1Ds Mark III', 'Fujifilm X-M1', 'Nikon D40'...
channel in sampling (see the paper for more info.); default is 1.2. k: number of nearest neighbors; default is 15. Returns: params: a dict of sampling parameters. """ if excluded_camera_models is None: excluded_camera_models = [] if excluded_datasets is None: excluded_datasets = [] if o...
256
256
1,398
18
237
manipopopo/C5
src/aug_ops.py
Python
map_raw_images
map_raw_images
101
263
101
101
1c1e7c7f080149f6b0a5f1b5de88e5e3600744d6
bigcode/the-stack
train
2dde68236448b0f64a74bdaf
train
function
def check_sampled_data(im, ill, cst): """ Checks the mapped image, illuminant value, and the inverse of CST matrix. """ h, w, c = im.shape num_pixels = h * w if (np.sum(np.isnan(cst)) >= 1 or np.sum(np.isnan(im)) >= 1 or np.sum(np.isinf(im)) >= 1 or np.mean(im) < 0.009 or np.sum(im[:, :, 0] > 1) >...
def check_sampled_data(im, ill, cst):
""" Checks the mapped image, illuminant value, and the inverse of CST matrix. """ h, w, c = im.shape num_pixels = h * w if (np.sum(np.isnan(cst)) >= 1 or np.sum(np.isnan(im)) >= 1 or np.sum(np.isinf(im)) >= 1 or np.mean(im) < 0.009 or np.sum(im[:, :, 0] > 1) > 0.4 * num_pixels or np.sum(im[:...
ops.from_rgb2bgr(im) cv2.imwrite(os.path.join(output_dir, filename), im) with open(os.path.join( output_dir, filename.lower().replace('.png', '') + '_metadata.json'), 'w') as outfile: json.dump(output_metadata, outfile) return True def check_sampled_data(im, ill, cst):
77
77
259
12
64
manipopopo/C5
src/aug_ops.py
Python
check_sampled_data
check_sampled_data
449
465
449
449
221a6797829441a89b6e2249d9ddd18dd56d4f28
bigcode/the-stack
train
62e8ecb99aad6e09c7487865
train
function
def predict(x, w): """ Predicts a response y given a value x in a linear regression model with polynomial basis function. Args: x: input data point w: (d x 1) vector contains the weights of the basis functions. Returns: y: predicted value. """ d = len(w) phi = np.zeros((1, d)) for i in ...
def predict(x, w):
""" Predicts a response y given a value x in a linear regression model with polynomial basis function. Args: x: input data point w: (d x 1) vector contains the weights of the basis functions. Returns: y: predicted value. """ d = len(w) phi = np.zeros((1, d)) for i in range(d): phi[0...
""" d = np.sqrt(np.sum((query - data) ** 2, axis=1)) indices = np.argsort(d) d.sort() indices = indices[0: k] d = d[0: k] return indices, d def predict(x, w):
64
64
114
6
57
manipopopo/C5
src/aug_ops.py
Python
predict
predict
495
511
495
495
102bc40839ebe24e651f68dd079af9d07b2c9c39
bigcode/the-stack
train
1e086f3b57d599a854e08cf8
train
function
def apply_cst(im, cst): """ Applies CST matrix to image. Args: im: input ndarray image ((height * width) x channel). cst: a 3x3 CST matrix. Returns: transformed image. """ result = im for c in range(3): result[:, :, c] = (cst[c, 0] * im[:, :, 0] + cst[c, 1] * im[:, :, 1] + ...
def apply_cst(im, cst):
""" Applies CST matrix to image. Args: im: input ndarray image ((height * width) x channel). cst: a 3x3 CST matrix. Returns: transformed image. """ result = im for c in range(3): result[:, :, c] = (cst[c, 0] * im[:, :, 0] + cst[c, 1] * im[:, :, 1] + cst[c, 2] * im[:...
: y: predicted value. """ d = len(w) phi = np.zeros((1, d)) for i in range(d): phi[0, i] = x ** (i) return np.matmul(phi, w)[0] def apply_cst(im, cst):
64
64
125
9
55
manipopopo/C5
src/aug_ops.py
Python
apply_cst
apply_cst
514
529
514
514
2e1b137088122ace3a3d4f7b2bd64ee9321aa16c
bigcode/the-stack
train
b82f2a0cc95be584847eeef5
train
class
class PCNN_Loss(nn.Module): def __init__(self, one_d): super(PCNN_Loss, self).__init__() self.size_average = True self.log2 = np.log(2.0) if one_d: self.loss_func = discretized_mix_logistic_loss_1d else: self.loss_func = discretized_mix_logisti...
class PCNN_Loss(nn.Module):
def __init__(self, one_d): super(PCNN_Loss, self).__init__() self.size_average = True self.log2 = np.log(2.0) if one_d: self.loss_func = discretized_mix_logistic_loss_1d else: self.loss_func = discretized_mix_logistic_loss def forward(sel...
torch.sum(log_sum_exp(log_probs)) else: lse_val = log_sum_exp(log_probs) lse_val = lse_val.view(lse_val.size(0), -1).mean(dim=1, keepdim=True) return -lse_val class PCNN_Loss(nn.Module):
64
64
195
8
55
BartlomiejOlber/od-test
models/pixelcnn/utils.py
Python
PCNN_Loss
PCNN_Loss
154
173
154
154
1ceffc1a627abd77b745c1e5e3e875b6bda5bcf4
bigcode/the-stack
train
1573e098f5ee1f4fcfe29a9c
train
function
def to_one_hot(tensor, n, fill_with=1.): # we perform one hot encore with respect to the last axis one_hot = torch.FloatTensor(tensor.size() + (n,)).zero_() if tensor.is_cuda : one_hot = one_hot.cuda() one_hot.scatter_(len(tensor.size()), tensor.unsqueeze(-1), fill_with) return one_hot
def to_one_hot(tensor, n, fill_with=1.): # we perform one hot encore with respect to the last axis
one_hot = torch.FloatTensor(tensor.size() + (n,)).zero_() if tensor.is_cuda : one_hot = one_hot.cuda() one_hot.scatter_(len(tensor.size()), tensor.unsqueeze(-1), fill_with) return one_hot
deno = self.log2 if do_reduce: obs = Y.numel() deno = deno * obs return loss / deno def to_one_hot(tensor, n, fill_with=1.): # we perform one hot encore with respect to the last axis
64
64
84
29
34
BartlomiejOlber/od-test
models/pixelcnn/utils.py
Python
to_one_hot
to_one_hot
175
180
175
176
9e1a7fcc2be762e014f337dcf4ee7ad2abf67b24
bigcode/the-stack
train
a9aedcf0e2053fe4a8bd759f
train
function
def down_shift(x, pad=None): # Pytorch ordering xs = [int(y) for y in x.size()] # when downshifting, the last row is removed x = x[:, :, :xs[2] - 1, :] # padding left, padding right, padding top, padding bottom pad = nn.ZeroPad2d((0, 0, 1, 0)) if pad is None else pad return pad(x)
def down_shift(x, pad=None): # Pytorch ordering
xs = [int(y) for y in x.size()] # when downshifting, the last row is removed x = x[:, :, :xs[2] - 1, :] # padding left, padding right, padding top, padding bottom pad = nn.ZeroPad2d((0, 0, 1, 0)) if pad is None else pad return pad(x)
dim=3) # put back in Pytorch ordering out = out.permute(0, 3, 1, 2) return out ''' utilities for shifting the image around, efficient alternative to masking convolutions ''' def down_shift(x, pad=None): # Pytorch ordering
64
64
104
14
50
BartlomiejOlber/od-test
models/pixelcnn/utils.py
Python
down_shift
down_shift
259
266
259
260
57275e6889cf147a5d9a7f648414682f8ec9dd7d
bigcode/the-stack
train
a06d1a2c07545c9abb74f2eb
train
function
def log_prob_from_logits(x): """ numerically stable log_softmax implementation that prevents overflow """ # TF ordering axis = len(x.size()) - 1 m, _ = torch.max(x, dim=axis, keepdim=True) return x - m - torch.log(torch.sum(torch.exp(x - m), dim=axis, keepdim=True))
def log_prob_from_logits(x):
""" numerically stable log_softmax implementation that prevents overflow """ # TF ordering axis = len(x.size()) - 1 m, _ = torch.max(x, dim=axis, keepdim=True) return x - m - torch.log(torch.sum(torch.exp(x - m), dim=axis, keepdim=True))
()) - 1 m, _ = torch.max(x, dim=axis) m2, _ = torch.max(x, dim=axis, keepdim=True) return m + torch.log(torch.sum(torch.exp(x - m2), dim=axis)) def log_prob_from_logits(x):
63
64
77
7
56
BartlomiejOlber/od-test
models/pixelcnn/utils.py
Python
log_prob_from_logits
log_prob_from_logits
24
29
24
24
ec7b6550f11740e98e378b1b25c355ad278c85d0
bigcode/the-stack
train
05693010ef2de261a573d3c0
train
function
def sample_from_discretized_mix_logistic(l, nr_mix): # Pytorch ordering l = l.permute(0, 2, 3, 1) ls = [int(y) for y in l.size()] xs = ls[:-1] + [3] # unpack parameters logit_probs = l[:, :, :, :nr_mix] l = l[:, :, :, nr_mix:].contiguous().view(xs + [nr_mix * 3]) # sample mixtu...
def sample_from_discretized_mix_logistic(l, nr_mix): # Pytorch ordering
l = l.permute(0, 2, 3, 1) ls = [int(y) for y in l.size()] xs = ls[:-1] + [3] # unpack parameters logit_probs = l[:, :, :, :nr_mix] l = l[:, :, :, nr_mix:].contiguous().view(xs + [nr_mix * 3]) # sample mixture indicator from softmax temp = torch.FloatTensor(logit_probs.size()) ...
(l[:, :, :, :, :nr_mix] * sel, dim=4) log_scales = torch.clamp(torch.sum( l[:, :, :, :, nr_mix:2 * nr_mix] * sel, dim=4), min=-7.) u = torch.FloatTensor(means.size()) if l.is_cuda : u = u.cuda() u.uniform_(1e-5, 1. - 1e-5) x = means + torch.exp(log_scales) * (torch.log(u) - torch.log(...
179
179
597
20
158
BartlomiejOlber/od-test
models/pixelcnn/utils.py
Python
sample_from_discretized_mix_logistic
sample_from_discretized_mix_logistic
215
254
215
216
8b15b6eff75c3163f87ef7df1709ffd4e4de3867
bigcode/the-stack
train
5d87ef6af929eeee7b4cbb20
train
function
def concat_elu(x): """ like concatenated ReLU (http://arxiv.org/abs/1603.05201), but then with ELU """ # Pytorch ordering axis = len(x.size()) - 3 return F.elu(torch.cat([x, -x], dim=axis))
def concat_elu(x):
""" like concatenated ReLU (http://arxiv.org/abs/1603.05201), but then with ELU """ # Pytorch ordering axis = len(x.size()) - 3 return F.elu(torch.cat([x, -x], dim=axis))
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.utils import weight_norm as wn import numpy as np def concat_elu(x):
37
64
68
6
30
BartlomiejOlber/od-test
models/pixelcnn/utils.py
Python
concat_elu
concat_elu
8
12
8
8
c54d8b2e082fb7025852b59dbb3309f10b481c36
bigcode/the-stack
train
76af1a7e1b7b16eec9c7a421
train
function
def log_sum_exp(x): """ numerically stable log_sum_exp implementation that prevents overflow """ # TF ordering axis = len(x.size()) - 1 m, _ = torch.max(x, dim=axis) m2, _ = torch.max(x, dim=axis, keepdim=True) return m + torch.log(torch.sum(torch.exp(x - m2), dim=axis))
def log_sum_exp(x):
""" numerically stable log_sum_exp implementation that prevents overflow """ # TF ordering axis = len(x.size()) - 1 m, _ = torch.max(x, dim=axis) m2, _ = torch.max(x, dim=axis, keepdim=True) return m + torch.log(torch.sum(torch.exp(x - m2), dim=axis))
ReLU (http://arxiv.org/abs/1603.05201), but then with ELU """ # Pytorch ordering axis = len(x.size()) - 3 return F.elu(torch.cat([x, -x], dim=axis)) def log_sum_exp(x):
63
64
87
6
57
BartlomiejOlber/od-test
models/pixelcnn/utils.py
Python
log_sum_exp
log_sum_exp
15
21
15
15
3c562325790e76ff360167f5ef29ff90193bd062
bigcode/the-stack
train
c1785e2ea18edcdad9954649
train
function
def discretized_mix_logistic_loss(x, l, do_reduce=True): """ log-likelihood for mixture of discretized logistics, assumes the data has been rescaled to [-1,1] interval """ # Pytorch ordering x = x.permute(0, 2, 3, 1) l = l.permute(0, 2, 3, 1) xs = [int(y) for y in x.size()] ls = [int(y) fo...
def discretized_mix_logistic_loss(x, l, do_reduce=True):
""" log-likelihood for mixture of discretized logistics, assumes the data has been rescaled to [-1,1] interval """ # Pytorch ordering x = x.permute(0, 2, 3, 1) l = l.permute(0, 2, 3, 1) xs = [int(y) for y in x.size()] ls = [int(y) for y in l.size()] # here and below: unpacking the...
import numpy as np def concat_elu(x): """ like concatenated ReLU (http://arxiv.org/abs/1603.05201), but then with ELU """ # Pytorch ordering axis = len(x.size()) - 3 return F.elu(torch.cat([x, -x], dim=axis)) def log_sum_exp(x): """ numerically stable log_sum_exp implementation that...
255
256
1,192
15
240
BartlomiejOlber/od-test
models/pixelcnn/utils.py
Python
discretized_mix_logistic_loss
discretized_mix_logistic_loss
32
102
32
32
492a7e9051ee1e05ea63206fb6bbe4c34316f9e5
bigcode/the-stack
train
ff4016fdd673c294d19e4b21
train
function
def load_part_of_model(model, path): params = torch.load(path) added = 0 for name, param in params.items(): if name in model.state_dict().keys(): try : model.state_dict()[name].copy_(param) added += 1 except Exception as e: ...
def load_part_of_model(model, path):
params = torch.load(path) added = 0 for name, param in params.items(): if name in model.state_dict().keys(): try : model.state_dict()[name].copy_(param) added += 1 except Exception as e: print(e) pass ...
:xs[3] - 1] # padding left, padding right, padding top, padding bottom pad = nn.ZeroPad2d((1, 0, 0, 0)) if pad is None else pad return pad(x) def load_part_of_model(model, path):
64
64
97
9
55
BartlomiejOlber/od-test
models/pixelcnn/utils.py
Python
load_part_of_model
load_part_of_model
279
290
279
279
1f1e51a8a3adbddcc8d5ced97c5f10e6a347dfde
bigcode/the-stack
train
4c716dd0334ee08254b88cab
train
function
def discretized_mix_logistic_loss_1d(x, l, do_reduce=True): """ log-likelihood for mixture of discretized logistics, assumes the data has been rescaled to [-1,1] interval """ # Pytorch ordering x = x.permute(0, 2, 3, 1) l = l.permute(0, 2, 3, 1) xs = [int(y) for y in x.size()] ls = [int(y)...
def discretized_mix_logistic_loss_1d(x, l, do_reduce=True):
""" log-likelihood for mixture of discretized logistics, assumes the data has been rescaled to [-1,1] interval """ # Pytorch ordering x = x.permute(0, 2, 3, 1) l = l.permute(0, 2, 3, 1) xs = [int(y) for y in x.size()] ls = [int(y) for y in l.size()] # here and below: unpacking the pa...
= inner_inner_cond * torch.log(torch.clamp(cdf_delta, min=1e-12)) + (1. - inner_inner_cond) * (log_pdf_mid - np.log(127.5)) inner_cond = (x > 0.999).float() inner_out = inner_cond * log_one_minus_cdf_min + (1. - inner_cond) * inner_inner_out cond = (x < -0.999).float() log...
228
228
761
18
209
BartlomiejOlber/od-test
models/pixelcnn/utils.py
Python
discretized_mix_logistic_loss_1d
discretized_mix_logistic_loss_1d
104
152
104
104
405471d2e4880752cfb2fa6311f4b49a34bc0792
bigcode/the-stack
train
0b0aeba40a60604bd8caccdf
train
function
def right_shift(x, pad=None): # Pytorch ordering xs = [int(y) for y in x.size()] # when righshifting, the last column is removed x = x[:, :, :, :xs[3] - 1] # padding left, padding right, padding top, padding bottom pad = nn.ZeroPad2d((1, 0, 0, 0)) if pad is None else pad return pad(x...
def right_shift(x, pad=None): # Pytorch ordering
xs = [int(y) for y in x.size()] # when righshifting, the last column is removed x = x[:, :, :, :xs[3] - 1] # padding left, padding right, padding top, padding bottom pad = nn.ZeroPad2d((1, 0, 0, 0)) if pad is None else pad return pad(x)
1, :] # padding left, padding right, padding top, padding bottom pad = nn.ZeroPad2d((0, 0, 1, 0)) if pad is None else pad return pad(x) def right_shift(x, pad=None): # Pytorch ordering
64
64
104
14
50
BartlomiejOlber/od-test
models/pixelcnn/utils.py
Python
right_shift
right_shift
269
276
269
270
2b77a5e5c33b158462cc4bc6c446a3ccdb3f3f44
bigcode/the-stack
train
bd7950e7a1a8be46f815b0b3
train
function
def sample_from_discretized_mix_logistic_1d(l, nr_mix): # Pytorch ordering l = l.permute(0, 2, 3, 1) ls = [int(y) for y in l.size()] xs = ls[:-1] + [1] #[3] # unpack parameters logit_probs = l[:, :, :, :nr_mix] l = l[:, :, :, nr_mix:].contiguous().view(xs + [nr_mix * 2]) # for mean,...
def sample_from_discretized_mix_logistic_1d(l, nr_mix): # Pytorch ordering
l = l.permute(0, 2, 3, 1) ls = [int(y) for y in l.size()] xs = ls[:-1] + [1] #[3] # unpack parameters logit_probs = l[:, :, :, :nr_mix] l = l[:, :, :, nr_mix:].contiguous().view(xs + [nr_mix * 2]) # for mean, scale # sample mixture indicator from softmax temp = torch.FloatTens...
* obs return loss / deno def to_one_hot(tensor, n, fill_with=1.): # we perform one hot encore with respect to the last axis one_hot = torch.FloatTensor(tensor.size() + (n,)).zero_() if tensor.is_cuda : one_hot = one_hot.cuda() one_hot.scatter_(len(tensor.size()), tensor.unsqueeze(-1), f...
117
117
393
23
93
BartlomiejOlber/od-test
models/pixelcnn/utils.py
Python
sample_from_discretized_mix_logistic_1d
sample_from_discretized_mix_logistic_1d
183
212
183
184
26b5903e36b467b72df2bba7955707e7ef7e5185
bigcode/the-stack
train
7f287191b5f1b38223611147
train
function
def file_to_b64(filename): """Converts image file ti b64 string Args: filename: string variable containing the path and name of the image file on computer new_filename: filepath to save file as Returns: b64_string: string variable containing the image bytes encoded ...
def file_to_b64(filename):
"""Converts image file ti b64 string Args: filename: string variable containing the path and name of the image file on computer new_filename: filepath to save file as Returns: b64_string: string variable containing the image bytes encoded as a bas...
on the local computer with the path and name contained in the new_filename variable """ image_bytes = base64.b64decode(b64_string) with open(new_filename, "wb") as out_file: out_file.write(image_bytes) return None def file_to_b64(filename):
64
64
123
7
56
braden2447/BME547_Final_Project
image_toolbox.py
Python
file_to_b64
file_to_b64
27
43
27
27
14211b7a4cf7adf364a9d90cc86537c4ddfd6c7d
bigcode/the-stack
train
b7aa9ce0526e894c30335305
train
function
def b64_to_file(b64_string, new_filename): """Converts b64 string to image file, saved as new_filename Args: b64_string: string variable containing the image bytes encoded as a base64 string new_filename: filepath to save file as Returns: an image file on the...
def b64_to_file(b64_string, new_filename):
"""Converts b64 string to image file, saved as new_filename Args: b64_string: string variable containing the image bytes encoded as a base64 string new_filename: filepath to save file as Returns: an image file on the local computer with the path and name ...
import base64 import io import matplotlib.image as mpimg from matplotlib import pyplot as plt from skimage.io import imsave def b64_to_file(b64_string, new_filename):
41
64
127
12
28
braden2447/BME547_Final_Project
image_toolbox.py
Python
b64_to_file
b64_to_file
8
24
8
8
a51a2dd6f04e44a97a8d89b01228071348c0535e
bigcode/the-stack
train
6b73659259b6b6a5f7396ccf
train
function
def plot_image(img_ndarray): """Converts b64 string to numpy ndarray Args: img_ndarray: variable containing an ndarray with image data Returns: A `matplotlib` window with an image """ plt.imshow(img_ndarray, interpolation='nearest') plt.show()
def plot_image(img_ndarray):
"""Converts b64 string to numpy ndarray Args: img_ndarray: variable containing an ndarray with image data Returns: A `matplotlib` window with an image """ plt.imshow(img_ndarray, interpolation='nearest') plt.show()
64 string """ f = io.BytesIO() imsave(f, img_ndarray, plugin='pil') y = base64.b64encode(f.getvalue()) b64_string = str(y, encoding='utf-8') return b64_string def plot_image(img_ndarray):
64
64
65
7
56
braden2447/BME547_Final_Project
image_toolbox.py
Python
plot_image
plot_image
79
89
79
79
deda15a0cabcb963d8c51c58db05e6653c01b0ad
bigcode/the-stack
train
5c2d429f884bd114579b3799
train
function
def ndarray_to_b64(img_ndarray): """Converts b64 string to numpy ndarray Args: img_ndarray: variable containing an ndarray with image data Returns: b64_string: string variable containing image bytes encoded as a base64 string """ f = io.BytesIO() imsave(f, im...
def ndarray_to_b64(img_ndarray):
"""Converts b64 string to numpy ndarray Args: img_ndarray: variable containing an ndarray with image data Returns: b64_string: string variable containing image bytes encoded as a base64 string """ f = io.BytesIO() imsave(f, img_ndarray, plugin='pil') y = ...
variable containing an ndarray with image data """ image_bytes = base64.b64decode(b64_string) image_buf = io.BytesIO(image_bytes) img_ndarray = mpimg.imread(image_buf, format='JPG') return img_ndarray def ndarray_to_b64(img_ndarray):
64
64
113
9
54
braden2447/BME547_Final_Project
image_toolbox.py
Python
ndarray_to_b64
ndarray_to_b64
62
76
62
62
600dbe3dacd3cee7e8cb9672ef0dd70d5086b449
bigcode/the-stack
train
0760e328adad86f3c0f74adb
train
function
def b64_to_ndarray(b64_string): """Converts b64 string to numpy ndarray Args: b64_string: string variable containing the image bytes encoded as a base64 string Returns: img_ndarray: variable containing an ndarray with image data """ image_bytes = base64.b64decode(...
def b64_to_ndarray(b64_string):
"""Converts b64 string to numpy ndarray Args: b64_string: string variable containing the image bytes encoded as a base64 string Returns: img_ndarray: variable containing an ndarray with image data """ image_bytes = base64.b64decode(b64_string) image_buf = io.B...
base64 string """ with open(filename, "rb") as image_file: b64_bytes = base64.b64encode(image_file.read()) b64_string = str(b64_bytes, encoding='utf-8') return b64_string def b64_to_ndarray(b64_string):
64
64
107
10
53
braden2447/BME547_Final_Project
image_toolbox.py
Python
b64_to_ndarray
b64_to_ndarray
46
59
46
46
944e25a3ad4a7b85ceb130de2c133958706aa022
bigcode/the-stack
train
ae45b2149866024887f39a6a
train
function
def get_access_token(client_id, auto=True): cache = msal.SerializableTokenCache() if os.path.exists(RefreshTokenFile): cache.deserialize(open(RefreshTokenFile, "r").read()) atexit.register(lambda: open(RefreshTokenFile, "w").write(cache.serialize()) # Hint: The following optional lin...
def get_access_token(client_id, auto=True):
cache = msal.SerializableTokenCache() if os.path.exists(RefreshTokenFile): cache.deserialize(open(RefreshTokenFile, "r").read()) atexit.register(lambda: open(RefreshTokenFile, "w").write(cache.serialize()) # Hint: The following optional line persists only when state changed i...
"""helper functions for Microsoft Graph""" # Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. # See LICENSE in the project root for license information. import base64 import mimetypes import os import urllib import webbrowser import logging import sys import json import msal import atexit ...
133
222
740
10
123
poiriersimon/PythonTeamsPresence
helpers.py
Python
get_access_token
get_access_token
26
102
26
26
413ee4ec2aff05856ae15b41f8b79b9999589670
bigcode/the-stack
train
9bca27809ce9c8880c2e5312
train
function
def api_endpoint(url): """Convert a relative path such as /me/photo/$value to a full URI based on the current RESOURCE and API_VERSION settings in config.py. """ if urllib.parse.urlparse(url).scheme in ['http', 'https']: return url # url is already complete return urllib.parse.urljoin(f'{con...
def api_endpoint(url):
"""Convert a relative path such as /me/photo/$value to a full URI based on the current RESOURCE and API_VERSION settings in config.py. """ if urllib.parse.urlparse(url).scheme in ['http', 'https']: return url # url is already complete return urllib.parse.urljoin(f'{config.RESOURCE}/{config.A...
-python-msal', 'x-client-SKU': 'sample-python-msal'}) return session else: print(result.get("error")) print(result.get("error_description")) print(result.get("correlation_id")) # You may need this when reporting a bug def api_endpoint(url):
64
64
87
5
58
poiriersimon/PythonTeamsPresence
helpers.py
Python
api_endpoint
api_endpoint
104
111
104
104
fe6bdc1e9ea4debf8935fac34f37f159b57ddc77
bigcode/the-stack
train
a43a2190c965a59af7fedf0c
train
class
class NNet(object): def __init__(self, n_input, netDims, n_iter=50, learn = 0.1, tf = sigmoid, dtf = dsigmoid): """ netSizes: network sizes array: output size is in position N input: number of input neurons hidden: number of hidden neurons output: number of output neuron...
class NNet(object):
def __init__(self, n_input, netDims, n_iter=50, learn = 0.1, tf = sigmoid, dtf = dsigmoid): """ netSizes: network sizes array: output size is in position N input: number of input neurons hidden: number of hidden neurons output: number of output neurons n_iter: how man...
import time import random import numpy as np from utils import * from transfer_functions import * class NNet(object):
26
256
1,541
6
20
lucabenedetto/DeepLearning
1_NeuralNetwork_MNIST/NNet.py
Python
NNet
NNet
9
155
9
10
56b1d89522dbada2a77a90dc5fac2b701c1683af
bigcode/the-stack
train
1a037d1f3ec66fda6a06bc67
train
function
def parse_args(): parser = argparse.ArgumentParser(description='Inference on an image') parser.add_argument( '--im', dest='im_file', help='input image', default=None, type=str ) parser.add_argument( '--rpn-pkl', dest='rpn_pkl', help='rpn model file (pkl)', default...
def parse_args():
parser = argparse.ArgumentParser(description='Inference on an image') parser.add_argument( '--im', dest='im_file', help='input image', default=None, type=str ) parser.add_argument( '--rpn-pkl', dest='rpn_pkl', help='rpn model file (pkl)', default=None, typ...
--im [path/to/image.jpg] \ # --rpn-model [path/to/rpn/model.pkl] \ # --rpn-cfg [path/to/rpn/config.yaml] \ # --output-dir [path/to/output/dir] \ # [model1] [config1] [model2] [config2] ... def parse_args():
76
76
254
4
72
summer1719/CBNet
tools/infer.py
Python
parse_args
parse_args
66
101
66
66
53fab843466d019b55ffc6fe7b998742c0cadaaf
bigcode/the-stack
train
e4cf2fbac91afd0d3514eacd
train
function
def main(args): logger = logging.getLogger(__name__) dummy_coco_dataset = dummy_datasets.get_coco_dataset() cfg_orig = load_cfg(yaml.dump(cfg)) im = cv2.imread(args.im_file) if args.rpn_pkl is not None: proposal_boxes, _proposal_scores = get_rpn_box_proposals(im, args) workspace.Res...
def main(args):
logger = logging.getLogger(__name__) dummy_coco_dataset = dummy_datasets.get_coco_dataset() cfg_orig = load_cfg(yaml.dump(cfg)) im = cv2.imread(args.im_file) if args.rpn_pkl is not None: proposal_boxes, _proposal_scores = get_rpn_box_proposals(im, args) workspace.ResetWorkspace() ...
def get_rpn_box_proposals(im, args): cfg.immutable(False) merge_cfg_from_file(args.rpn_cfg) cfg.NUM_GPUS = 1 cfg.MODEL.RPN_ONLY = True cfg.TEST.RPN_PRE_NMS_TOP_N = 10000 cfg.TEST.RPN_POST_NMS_TOP_N = 2000 assert_and_infer_cfg(cache_urls=False) model = model_engine.initialize_model_from_...
137
137
457
4
132
summer1719/CBNet
tools/infer.py
Python
main
main
119
170
119
119
5d0d63aa4c05a025d337e3e42c865911d04ad8ef
bigcode/the-stack
train
4c0d56b8c9576b02bda1a6e7
train
function
def check_args(args): assert ( (args.rpn_pkl is not None and args.rpn_cfg is not None) or (args.rpn_pkl is None and args.rpn_cfg is None) ) if args.rpn_pkl is not None: args.rpn_pkl = cache_url(args.rpn_pkl, cfg.DOWNLOAD_CACHE) assert os.path.exists(args.rpn_pkl) asse...
def check_args(args):
assert ( (args.rpn_pkl is not None and args.rpn_cfg is not None) or (args.rpn_pkl is None and args.rpn_cfg is None) ) if args.rpn_pkl is not None: args.rpn_pkl = cache_url(args.rpn_pkl, cfg.DOWNLOAD_CACHE) assert os.path.exists(args.rpn_pkl) assert os.path.exists(args...
args.im_file, args.output_dir, cls_boxes, cls_segms, cls_keyps, dataset=dummy_coco_dataset, box_alpha=0.3, show_class=True, thresh=0.7, kp_thresh=2 ) def check_args(args):
64
64
204
5
59
summer1719/CBNet
tools/infer.py
Python
check_args
check_args
173
190
173
173
c8cfbfff8df9e66bf0021e2a69bb349c6a4aaa54
bigcode/the-stack
train
ad439bd3de896f23c6af3a30
train
function
def get_rpn_box_proposals(im, args): cfg.immutable(False) merge_cfg_from_file(args.rpn_cfg) cfg.NUM_GPUS = 1 cfg.MODEL.RPN_ONLY = True cfg.TEST.RPN_PRE_NMS_TOP_N = 10000 cfg.TEST.RPN_POST_NMS_TOP_N = 2000 assert_and_infer_cfg(cache_urls=False) model = model_engine.initialize_model_from_...
def get_rpn_box_proposals(im, args):
cfg.immutable(False) merge_cfg_from_file(args.rpn_cfg) cfg.NUM_GPUS = 1 cfg.MODEL.RPN_ONLY = True cfg.TEST.RPN_PRE_NMS_TOP_N = 10000 cfg.TEST.RPN_POST_NMS_TOP_N = 2000 assert_and_infer_cfg(cache_urls=False) model = model_engine.initialize_model_from_cfg(args.rpn_pkl) with c2_utils.N...
[pkl2] [yaml2] ...', default=None, nargs=argparse.REMAINDER ) if len(sys.argv) == 1: parser.print_help() sys.exit(1) return parser.parse_args() def get_rpn_box_proposals(im, args):
64
64
133
11
53
summer1719/CBNet
tools/infer.py
Python
get_rpn_box_proposals
get_rpn_box_proposals
104
116
104
104
a1499d7e60260a13580c6ee474083c582d66b05b
bigcode/the-stack
train
3dee57cad9f3c9f87280bb5f
train
function
def sample(n_samps, n_steps, epsilon, path): if path is not None: dirname = os.path.dirname(path) if not os.path.exists(dirname): os.makedirs(dirname) start = time() samples = hmc(lnpdf, x0=np.random.randn(10), n_samples=int(n_samps), n_steps=n_steps, epsilon=epsilon) end = t...
def sample(n_samps, n_steps, epsilon, path):
if path is not None: dirname = os.path.dirname(path) if not os.path.exists(dirname): os.makedirs(dirname) start = time() samples = hmc(lnpdf, x0=np.random.randn(10), n_samples=int(n_samps), n_steps=n_steps, epsilon=epsilon) end = time() np.savez(path, samples=samples, wal...
(theta): input = np.atleast_2d(theta) lnpdf.counter += len(input) return np.squeeze(tmp_lnpdf(input)), np.squeeze(elementwise_grad(tmp_lnpdf)(input)) lnpdf.counter = 0 def sample(n_samps, n_steps, epsilon, path):
64
64
121
13
50
DrawZeroPoint/VIPS
python/experiments/HMC/planar_robot_10.py
Python
sample
sample
20
30
20
20
b14163d8ca825785c567f3563afc05a3b575f3d1
bigcode/the-stack
train
dfe24835f125e52af9dcf8b8
train
function
def sample_with_progress(repeats, n_samps, n_steps, epsilon, path=None): if path is not None: dirname = os.path.dirname(path) if not os.path.exists(dirname): os.makedirs(dirname) last = np.random.randn(10) timestamps = [] all_samples = [] nfevals = [] start = time() ...
def sample_with_progress(repeats, n_samps, n_steps, epsilon, path=None):
if path is not None: dirname = os.path.dirname(path) if not os.path.exists(dirname): os.makedirs(dirname) last = np.random.randn(10) timestamps = [] all_samples = [] nfevals = [] start = time() for i in range(repeats): timestamps.append(time()) sam...
epsilon=epsilon) end = time() np.savez(path, samples=samples, wallclocktime=end-start) #samples = np.vstack([c[0] for c in chain]) print("done") def sample_with_progress(repeats, n_samps, n_steps, epsilon, path=None):
66
66
221
20
46
DrawZeroPoint/VIPS
python/experiments/HMC/planar_robot_10.py
Python
sample_with_progress
sample_with_progress
32
52
32
32
d3c1eeff0ef39e80e3109f0b122f763f8246697a
bigcode/the-stack
train
d1ccc64baaf3edad98d4737b
train
function
def lnpdf(theta): input = np.atleast_2d(theta) lnpdf.counter += len(input) return np.squeeze(tmp_lnpdf(input)), np.squeeze(elementwise_grad(tmp_lnpdf)(input))
def lnpdf(theta):
input = np.atleast_2d(theta) lnpdf.counter += len(input) return np.squeeze(tmp_lnpdf(input)), np.squeeze(elementwise_grad(tmp_lnpdf)(input))
4e-2 * np.ones(num_dimensions) conf_likelihood_var[0] = 1 cart_likelihood_var = np.array([1e-4, 1e-4]) tmp_lnpdf = build_target_likelihood_planar_autograd(num_dimensions)[0] def lnpdf(theta):
64
64
48
6
58
DrawZeroPoint/VIPS
python/experiments/HMC/planar_robot_10.py
Python
lnpdf
lnpdf
14
17
14
14
c91df028ecb37813850de9f10c86fe7c6a65f360
bigcode/the-stack
train
5963ad3acc0d84274197b16e
train
class
class MUSDBDataset(torch.utils.data.Dataset): def __init__( self, target='vocals', root=None, download=False, is_wav=False, subsets='train', split='train', seq_duration=6.0, samples_per_track=64, source_augmentations=lambda audio: audio...
class MUSDBDataset(torch.utils.data.Dataset):
def __init__( self, target='vocals', root=None, download=False, is_wav=False, subsets='train', split='train', seq_duration=6.0, samples_per_track=64, source_augmentations=lambda audio: audio, random_track_mix=False, dtyp...
ations(y) x += y # Use silence if target does not exist else: y = torch.zeros(audio.shape) return x, y def __len__(self): return len(self.tracks) def get_tracks(self): p = Path(self.root, self.split) for track_path in tqdm.tqdm(p.iterdi...
256
256
1,045
9
247
1uka/open-unmix-pytorch
data.py
Python
MUSDBDataset
MUSDBDataset
679
817
679
679
99f1bcf2a7fd7bf80b4690b92297a61c5c2d4e34
bigcode/the-stack
train
9ebaf871c98d60559184406d
train
function
def _augment_channelswap(audio): """Swap channels of stereo signals with a probability of p=0.5""" if audio.shape[0] == 2 and torch.FloatTensor(1).uniform_() < 0.5: return torch.flip(audio, [0]) else: return audio
def _augment_channelswap(audio):
"""Swap channels of stereo signals with a probability of p=0.5""" if audio.shape[0] == 2 and torch.FloatTensor(1).uniform_() < 0.5: return torch.flip(audio, [0]) else: return audio
def _augment_gain(audio, low=0.25, high=1.25): """Applies a random gain between `low` and `high`""" g = low + torch.rand(1) * (high - low) return audio * g def _augment_channelswap(audio):
64
64
66
7
56
1uka/open-unmix-pytorch
data.py
Python
_augment_channelswap
_augment_channelswap
32
37
32
32
1e3f809c71bd986b5a7346f61169007652ce7877
bigcode/the-stack
train
9260eafbfe436a1324b55ab4
train
function
def _augment_gain(audio, low=0.25, high=1.25): """Applies a random gain between `low` and `high`""" g = low + torch.rand(1) * (high - low) return audio * g
def _augment_gain(audio, low=0.25, high=1.25):
"""Applies a random gain between `low` and `high`""" g = low + torch.rand(1) * (high - low) return audio * g
to compose. """ def __init__(self, transforms): self.transforms = transforms def __call__(self, audio): for t in self.transforms: audio = t(audio) return audio def _augment_gain(audio, low=0.25, high=1.25):
64
64
56
18
45
1uka/open-unmix-pytorch
data.py
Python
_augment_gain
_augment_gain
26
29
26
26
f7bbf0f7137dab22bdbdd2c292fa6479176e6c28
bigcode/the-stack
train
091ce2676c843fd0d73fdeaf
train
class
class VariableSourcesTrackFolderDataset(torch.utils.data.Dataset): def __init__( self, root, split='train', target_file='vocals.wav', ext='.wav', seq_duration=None, random_chunks=False, random_interferer_mix=False, sample_rate=44100, so...
class VariableSourcesTrackFolderDataset(torch.utils.data.Dataset):
def __init__( self, root, split='train', target_file='vocals.wav', ext='.wav', seq_duration=None, random_chunks=False, random_interferer_mix=False, sample_rate=44100, source_augmentations=lambda audio: audio, silence_missing_tar...
audio_sources.append(audio) stems = torch.stack(audio_sources) # # apply linear mix over source index=0 x = stems.sum(0) # target is always the first element in the list y = stems[0] return x, y def __len__(self): return len(self.tracks) def get_tracks...
256
256
1,049
11
245
1uka/open-unmix-pytorch
data.py
Python
VariableSourcesTrackFolderDataset
VariableSourcesTrackFolderDataset
536
676
536
536
8755ee8f09101468d0848ac70e6b4d3a65da6a2b
bigcode/the-stack
train
5fe4769ef82591f41fbf25e7
train
class
class AlignedDataset(torch.utils.data.Dataset): def __init__( self, root, split='train', input_file='mixture.wav', output_file='vocals.wav', seq_duration=None, random_chunks=False, sample_rate=44100 ): """A dataset of that assumes multiple ...
class AlignedDataset(torch.utils.data.Dataset):
def __init__( self, root, split='train', input_file='mixture.wav', output_file='vocals.wav', seq_duration=None, random_chunks=False, sample_rate=44100 ): """A dataset of that assumes multiple track folders where each track includes ...
parser.parse_args() dataset_kwargs = { 'root': args.root, 'is_wav': args.is_wav, 'subsets': 'train', 'target': args.target, 'download': args.root is None, 'seed': args.seed } source_augmentations = Compose( [gl...
192
192
642
9
182
1uka/open-unmix-pytorch
data.py
Python
AlignedDataset
AlignedDataset
237
317
237
237
708a398d429f0ebccc5c7f84f2acb8391009bff4
bigcode/the-stack
train
e3a1272a76b9a0ae0549d1b2
train
class
class FixedSourcesTrackFolderDataset(torch.utils.data.Dataset): def __init__( self, root, split='train', target_file='vocals.wav', interferer_files=['bass.wav', 'drums.wav'], seq_duration=None, random_chunks=False, random_track_mix=False, sourc...
class FixedSourcesTrackFolderDataset(torch.utils.data.Dataset):
def __init__( self, root, split='train', target_file='vocals.wav', interferer_files=['bass.wav', 'drums.wav'], seq_duration=None, random_chunks=False, random_track_mix=False, source_augmentations=lambda audio: audio, sample_rate=44100, ...
0 audio = load_audio( source_path, start=start, dur=self.seq_duration ) audio = self.source_augmentations(audio) audio_sources.append(audio) stems = torch.stack(audio_sources) # # apply linear mix over source index=0 x = stems.sum...
256
256
988
11
244
1uka/open-unmix-pytorch
data.py
Python
FixedSourcesTrackFolderDataset
FixedSourcesTrackFolderDataset
414
533
414
414
8e2c4a977577bfde3e6d960eef207afcb0b77bca
bigcode/the-stack
train
6e3f00019e43d2667146310f
train
class
class SourceFolderDataset(torch.utils.data.Dataset): def __init__( self, root, split='train', target_dir='vocals', interferer_dirs=['bass', 'drums'], ext='.flac', nb_samples=1000, seq_duration=None, random_chunks=False, sample_rate=4410...
class SourceFolderDataset(torch.utils.data.Dataset):
def __init__( self, root, split='train', target_dir='vocals', interferer_dirs=['bass', 'drums'], ext='.flac', nb_samples=1000, seq_duration=None, random_chunks=False, sample_rate=44100, source_augmentations=lambda audio: audio, ...
tensors return X_audio, Y_audio def __len__(self): return len(self.tuple_paths) def _get_paths(self): """Loads input and output tracks""" p = Path(self.root, self.split) for track_path in tqdm.tqdm(p.iterdir()): if track_path.is_dir(): input...
210
210
701
9
201
1uka/open-unmix-pytorch
data.py
Python
SourceFolderDataset
SourceFolderDataset
320
411
320
320
2f0cd33197c4277bd1704b28d83d2df7c466bff9
bigcode/the-stack
train
d7a1db6f225169c13745f64d
train
class
class Compose(object): """Composes several augmentation transforms. Args: augmentations: list of augmentations to compose. """ def __init__(self, transforms): self.transforms = transforms def __call__(self, audio): for t in self.transforms: audio = t(audio) ...
class Compose(object):
"""Composes several augmentation transforms. Args: augmentations: list of augmentations to compose. """ def __init__(self, transforms): self.transforms = transforms def __call__(self, audio): for t in self.transforms: audio = t(audio) return audio
from utils import load_audio, load_info from pathlib import Path import torch.utils.data import argparse import random import musdb import torch import tqdm class Compose(object):
39
64
69
4
34
1uka/open-unmix-pytorch
data.py
Python
Compose
Compose
11
23
11
11
4879d2c68cc8169215b2485c3021fe4f19d40604
bigcode/the-stack
train
cfaa2925361640d56cd71717
train
function
def load_datasets(parser, args): """Loads the specified dataset from commandline arguments Returns: train_dataset, validation_dataset """ if args.dataset == 'aligned': parser.add_argument('--input-file', type=str) parser.add_argument('--output-file', type=str) args = pa...
def load_datasets(parser, args):
"""Loads the specified dataset from commandline arguments Returns: train_dataset, validation_dataset """ if args.dataset == 'aligned': parser.add_argument('--input-file', type=str) parser.add_argument('--output-file', type=str) args = parser.parse_args() # set o...
from utils import load_audio, load_info from pathlib import Path import torch.utils.data import argparse import random import musdb import torch import tqdm class Compose(object): """Composes several augmentation transforms. Args: augmentations: list of augmentations to compose. """ def __ini...
234
256
1,323
8
225
1uka/open-unmix-pytorch
data.py
Python
load_datasets
load_datasets
40
234
40
40
2df80bba1167cd4d9716bf5788ba28aa69fc500a
bigcode/the-stack
train
d7ea8e0e2bce8a862b292d7c
train
function
@mock_kinesis def test_get_records_millis_behind_latest(): conn = boto3.client("kinesis", region_name="us-west-2") stream_name = "my_stream" conn.create_stream(StreamName=stream_name, ShardCount=1) conn.put_record(StreamName=stream_name, Data="0", PartitionKey="0") time.sleep(1.0) conn.put_reco...
@mock_kinesis def test_get_records_millis_behind_latest():
conn = boto3.client("kinesis", region_name="us-west-2") stream_name = "my_stream" conn.create_stream(StreamName=stream_name, ShardCount=1) conn.put_record(StreamName=stream_name, Data="0", PartitionKey="0") time.sleep(1.0) conn.put_record(StreamName=stream_name, Data="1", PartitionKey="1") ...
) response["Records"][0]["PartitionKey"].should.equal("1") response["Records"][0]["ApproximateArrivalTimestamp"].should.be.greater_than( timestamp ) response["MillisBehindLatest"].should.equal(0) @mock_kinesis def test_get_records_millis_behind_latest():
66
66
223
15
51
moseb/moto
tests/test_kinesis/test_kinesis.py
Python
test_get_records_millis_behind_latest
test_get_records_millis_behind_latest
402
421
402
403
67218d87c0f73e1fa6caa99d09ca3e8b767d50f9
bigcode/the-stack
train
94571664e62e0caa5b9ee419
train
function
@mock_kinesis_deprecated def test_add_tags(): conn = boto.kinesis.connect_to_region("us-west-2") stream_name = "my_stream" conn.create_stream(stream_name, 1) conn.describe_stream(stream_name) conn.add_tags_to_stream(stream_name, {"tag1": "val1"}) conn.add_tags_to_stream(stream_name, {"tag2": "v...
@mock_kinesis_deprecated def test_add_tags():
conn = boto.kinesis.connect_to_region("us-west-2") stream_name = "my_stream" conn.create_stream(stream_name, 1) conn.describe_stream(stream_name) conn.add_tags_to_stream(stream_name, {"tag1": "val1"}) conn.add_tags_to_stream(stream_name, {"tag2": "val2"}) conn.add_tags_to_stream(stream_name...
(stream_name) shard_id = response["StreamDescription"]["Shards"][0]["ShardId"] response = conn.get_shard_iterator.when.called_with( stream_name, shard_id, "invalid-type" ).should.throw(InvalidArgumentException) @mock_kinesis_deprecated def test_add_tags():
64
64
120
12
52
moseb/moto
tests/test_kinesis/test_kinesis.py
Python
test_add_tags
test_add_tags
492
502
492
493
eb52f3b8934aff5b13e8f309d6d6d8ab02c4391a
bigcode/the-stack
train
88899d8b8661def7a1e66492
train
function
@mock_kinesis_deprecated def test_basic_shard_iterator(): conn = boto.kinesis.connect_to_region("us-west-2") stream_name = "my_stream" conn.create_stream(stream_name, 1) response = conn.describe_stream(stream_name) shard_id = response["StreamDescription"]["Shards"][0]["ShardId"] response = co...
@mock_kinesis_deprecated def test_basic_shard_iterator():
conn = boto.kinesis.connect_to_region("us-west-2") stream_name = "my_stream" conn.create_stream(stream_name, 1) response = conn.describe_stream(stream_name) shard_id = response["StreamDescription"]["Shards"][0]["ShardId"] response = conn.get_shard_iterator(stream_name, shard_id, "TRIM_HORIZON...
.equal(shard_count) stream["StreamARN"].should.equal( "arn:aws:kinesis:us-west-2:{}:{}".format(ACCOUNT_ID, stream_name) ) stream["StreamStatus"].should.equal("ACTIVE") @mock_kinesis_deprecated def test_basic_shard_iterator():
64
64
143
14
50
moseb/moto
tests/test_kinesis/test_kinesis.py
Python
test_basic_shard_iterator
test_basic_shard_iterator
98
114
98
99
861e13c24d5bd26f3bf4e11d89cd5812182e1b84
bigcode/the-stack
train
b27ca7134edcc249b1263d52
train
function
@mock_kinesis_deprecated def test_get_records_after_sequence_number(): # AFTER_SEQUENCE_NUMBER - Start reading right after the position denoted # by a specific sequence number. conn = boto.kinesis.connect_to_region("us-west-2") stream_name = "my_stream" conn.create_stream(stream_name, 1) # Crea...
@mock_kinesis_deprecated def test_get_records_after_sequence_number(): # AFTER_SEQUENCE_NUMBER - Start reading right after the position denoted # by a specific sequence number.
conn = boto.kinesis.connect_to_region("us-west-2") stream_name = "my_stream" conn.create_stream(stream_name, 1) # Create some data for index in range(1, 5): conn.put_record(stream_name, str(index), str(index)) # Get a shard iterator response = conn.describe_stream(stream_name) ...
= conn.get_records(shard_iterator) # And the first result returned should be the second item response["Records"][0]["SequenceNumber"].should.equal(second_sequence_id) response["Records"][0]["Data"].should.equal("2") @mock_kinesis_deprecated def test_get_records_after_sequence_number(): # AFTER_SEQUENCE...
89
89
297
38
51
moseb/moto
tests/test_kinesis/test_kinesis.py
Python
test_get_records_after_sequence_number
test_get_records_after_sequence_number
224
255
224
227
ddc2b1600f71e6aae9cd39c2bb660391b48aeecb
bigcode/the-stack
train
34b291c1134efb15186cf2b7
train
function
@mock_kinesis_deprecated def test_get_records_at_sequence_number(): # AT_SEQUENCE_NUMBER - Start reading exactly from the position denoted by # a specific sequence number. conn = boto.kinesis.connect_to_region("us-west-2") stream_name = "my_stream" conn.create_stream(stream_name, 1) # Create so...
@mock_kinesis_deprecated def test_get_records_at_sequence_number(): # AT_SEQUENCE_NUMBER - Start reading exactly from the position denoted by # a specific sequence number.
conn = boto.kinesis.connect_to_region("us-west-2") stream_name = "my_stream" conn.create_stream(stream_name, 1) # Create some data for index in range(1, 5): conn.put_record(stream_name, str(index), str(index)) # Get a shard iterator response = conn.describe_stream(stream_name) ...
should.have.length_of(3) # Then get the rest of the results next_shard_iterator = response["NextShardIterator"] response = conn.get_records(next_shard_iterator) response["Records"].should.have.length_of(2) @mock_kinesis_deprecated def test_get_records_at_sequence_number(): # AT_SEQUENCE_NUMBER - St...
90
90
300
38
52
moseb/moto
tests/test_kinesis/test_kinesis.py
Python
test_get_records_at_sequence_number
test_get_records_at_sequence_number
190
221
190
193
4c9889e97b571d6e4862b839b91833241bfa3633
bigcode/the-stack
train
0ef86adeef0f9208e9e363a6
train
function
@mock_kinesis_deprecated def test_get_invalid_shard_iterator(): conn = boto.kinesis.connect_to_region("us-west-2") stream_name = "my_stream" conn.create_stream(stream_name, 1) conn.get_shard_iterator.when.called_with( stream_name, "123", "TRIM_HORIZON" ).should.throw(ResourceNotFoundExcept...
@mock_kinesis_deprecated def test_get_invalid_shard_iterator():
conn = boto.kinesis.connect_to_region("us-west-2") stream_name = "my_stream" conn.create_stream(stream_name, 1) conn.get_shard_iterator.when.called_with( stream_name, "123", "TRIM_HORIZON" ).should.throw(ResourceNotFoundException)
shard_iterator = response["ShardIterator"] response = conn.get_records(shard_iterator) shard_iterator = response["NextShardIterator"] response["Records"].should.equal([]) response["MillisBehindLatest"].should.equal(0) @mock_kinesis_deprecated def test_get_invalid_shard_iterator():
64
64
81
15
49
moseb/moto
tests/test_kinesis/test_kinesis.py
Python
test_get_invalid_shard_iterator
test_get_invalid_shard_iterator
117
126
117
118
ae59fba057e99bd2682a2a0af6ae76c1b49986ad
bigcode/the-stack
train
44488e49895675d302f1e464
train
function
@mock_kinesis def test_list_many_streams(): conn = boto3.client("kinesis", region_name="us-west-2") for i in range(11): conn.create_stream(StreamName="stream%d" % i, ShardCount=1) resp = conn.list_streams() stream_names = resp["StreamNames"] has_more_streams = resp["HasMoreStreams"] st...
@mock_kinesis def test_list_many_streams():
conn = boto3.client("kinesis", region_name="us-west-2") for i in range(11): conn.create_stream(StreamName="stream%d" % i, ShardCount=1) resp = conn.list_streams() stream_names = resp["StreamNames"] has_more_streams = resp["HasMoreStreams"] stream_names.should.have.length_of(10) has...
conn.delete_stream("stream2") conn.list_streams()["StreamNames"].should.have.length_of(1) # Delete invalid id conn.delete_stream.when.called_with("not-a-stream").should.throw( ResourceNotFoundException ) @mock_kinesis def test_list_many_streams():
64
64
166
12
52
moseb/moto
tests/test_kinesis/test_kinesis.py
Python
test_list_many_streams
test_list_many_streams
61
77
61
62
558af402eb98e928ed1339e8d61323f8d7c8ac98
bigcode/the-stack
train
ff345a8bfe201b7b7ab807fc
train
function
@mock_kinesis_deprecated def test_list_tags(): conn = boto.kinesis.connect_to_region("us-west-2") stream_name = "my_stream" conn.create_stream(stream_name, 1) conn.describe_stream(stream_name) conn.add_tags_to_stream(stream_name, {"tag1": "val1"}) tags = dict( [ (tag["Key"],...
@mock_kinesis_deprecated def test_list_tags():
conn = boto.kinesis.connect_to_region("us-west-2") stream_name = "my_stream" conn.create_stream(stream_name, 1) conn.describe_stream(stream_name) conn.add_tags_to_stream(stream_name, {"tag1": "val1"}) tags = dict( [ (tag["Key"], tag["Value"]) for tag in conn.list...
_name, 1) conn.describe_stream(stream_name) conn.add_tags_to_stream(stream_name, {"tag1": "val1"}) conn.add_tags_to_stream(stream_name, {"tag2": "val2"}) conn.add_tags_to_stream(stream_name, {"tag1": "val3"}) conn.add_tags_to_stream(stream_name, {"tag2": "val4"}) @mock_kinesis_deprecated def test_l...
92
93
312
12
80
moseb/moto
tests/test_kinesis/test_kinesis.py
Python
test_list_tags
test_list_tags
505
543
505
506
8879239aeb02b436076e46ff994aaa1d574a81c8
bigcode/the-stack
train
4e0ccd549c6806746e5657e4
train
function
@mock_kinesis_deprecated def test_merge_shards(): conn = boto.kinesis.connect_to_region("us-west-2") stream_name = "my_stream" conn.create_stream(stream_name, 4) # Create some data for index in range(1, 100): conn.put_record(stream_name, str(index), str(index)) stream_response = conn....
@mock_kinesis_deprecated def test_merge_shards():
conn = boto.kinesis.connect_to_region("us-west-2") stream_name = "my_stream" conn.create_stream(stream_name, 4) # Create some data for index in range(1, 100): conn.put_record(stream_name, str(index), str(index)) stream_response = conn.describe_stream(stream_name) stream = stream_...
["EndingHashKey"]) + int(shard_range["StartingHashKey"]) ) // 2 conn.split_shard("my_stream", shards[2]["ShardId"], str(new_starting_hash)) stream_response = conn.describe_stream(stream_name) stream = stream_response["StreamDescription"] shards = stream["Shards"] shards.should.have.length_of(4...
120
120
402
13
107
moseb/moto
tests/test_kinesis/test_kinesis.py
Python
test_merge_shards
test_merge_shards
639
688
639
640
7047fb155b2c6d0a83556936b595b4ff5fc4f7fe
bigcode/the-stack
train
12af1d14164074caf2cf81ce
train
function
@mock_kinesis_deprecated def test_describe_non_existant_stream(): conn = boto.kinesis.connect_to_region("us-east-1") conn.describe_stream.when.called_with("not-a-stream").should.throw( ResourceNotFoundException )
@mock_kinesis_deprecated def test_describe_non_existant_stream():
conn = boto.kinesis.connect_to_region("us-east-1") conn.describe_stream.when.called_with("not-a-stream").should.throw( ResourceNotFoundException )
aws:kinesis:us-west-2:{}:my_stream".format(ACCOUNT_ID) ) stream["StreamStatus"].should.equal("ACTIVE") shards = stream["Shards"] shards.should.have.length_of(3) @mock_kinesis_deprecated def test_describe_non_existant_stream():
64
64
54
16
48
moseb/moto
tests/test_kinesis/test_kinesis.py
Python
test_describe_non_existant_stream
test_describe_non_existant_stream
34
39
34
35
0bfd86e1e2c1e48ecd0a0d3606f32e1d8201a61d
bigcode/the-stack
train
04360b062ad5c81823cd6ccb
train
function
@mock_kinesis_deprecated def test_invalid_shard_iterator_type(): conn = boto.kinesis.connect_to_region("us-west-2") stream_name = "my_stream" conn.create_stream(stream_name, 1) response = conn.describe_stream(stream_name) shard_id = response["StreamDescription"]["Shards"][0]["ShardId"] response...
@mock_kinesis_deprecated def test_invalid_shard_iterator_type():
conn = boto.kinesis.connect_to_region("us-west-2") stream_name = "my_stream" conn.create_stream(stream_name, 1) response = conn.describe_stream(stream_name) shard_id = response["StreamDescription"]["Shards"][0]["ShardId"] response = conn.get_shard_iterator.when.called_with( stream_name,...
) shard_iterator = response["ShardIterator"] response = conn.get_records(ShardIterator=shard_iterator) response["Records"].should.have.length_of(0) response["MillisBehindLatest"].should.equal(0) @mock_kinesis_deprecated def test_invalid_shard_iterator_type():
64
64
106
15
49
moseb/moto
tests/test_kinesis/test_kinesis.py
Python
test_invalid_shard_iterator_type
test_invalid_shard_iterator_type
479
489
479
480
9b611235bf6aad38a83b81e7a90c47736b26fba2
bigcode/the-stack
train
b80e5d8b1ef9208c0029fda8
train
function
@mock_kinesis_deprecated def test_split_shard(): conn = boto.kinesis.connect_to_region("us-west-2") stream_name = "my_stream" conn.create_stream(stream_name, 2) # Create some data for index in range(1, 100): conn.put_record(stream_name, str(index), str(index)) stream_response = conn.d...
@mock_kinesis_deprecated def test_split_shard():
conn = boto.kinesis.connect_to_region("us-west-2") stream_name = "my_stream" conn.create_stream(stream_name, 2) # Create some data for index in range(1, 100): conn.put_record(stream_name, str(index), str(index)) stream_response = conn.describe_stream(stream_name) stream = stream_...
tags = dict( [ (tag["Key"], tag["Value"]) for tag in conn.list_tags_for_stream(stream_name)["Tags"] ] ) tags.get("tag2").should.equal("val2") conn.remove_tags_from_stream(stream_name, ["tag2"]) tags = dict( [ (tag["Key"], tag["Value"]) ...
120
120
402
13
107
moseb/moto
tests/test_kinesis/test_kinesis.py
Python
test_split_shard
test_split_shard
588
636
588
589
6e3222784b36a614c4fe822648c713c0e97e2a1f
bigcode/the-stack
train
7cecdf13d44f408391d8a338
train
function
@mock_kinesis_deprecated def test_remove_tags(): conn = boto.kinesis.connect_to_region("us-west-2") stream_name = "my_stream" conn.create_stream(stream_name, 1) conn.describe_stream(stream_name) conn.add_tags_to_stream(stream_name, {"tag1": "val1"}) tags = dict( [ (tag["Key"...
@mock_kinesis_deprecated def test_remove_tags():
conn = boto.kinesis.connect_to_region("us-west-2") stream_name = "my_stream" conn.create_stream(stream_name, 1) conn.describe_stream(stream_name) conn.add_tags_to_stream(stream_name, {"tag1": "val1"}) tags = dict( [ (tag["Key"], tag["Value"]) for tag in conn.list...
tags.get("tag1").should.equal("val3") conn.add_tags_to_stream(stream_name, {"tag2": "val4"}) tags = dict( [ (tag["Key"], tag["Value"]) for tag in conn.list_tags_for_stream(stream_name)["Tags"] ] ) tags.get("tag2").should.equal("val4") @mock_kinesis_deprecated ...
90
90
300
12
78
moseb/moto
tests/test_kinesis/test_kinesis.py
Python
test_remove_tags
test_remove_tags
546
585
546
547
c7168f621e0f00ed94b82c0e19d9a0d3a99bab9d
bigcode/the-stack
train
a06ca208a081a3e29e5ad4cc
train
function
@mock_kinesis def test_get_records_at_timestamp(): # AT_TIMESTAMP - Read the first record at or after the specified timestamp conn = boto3.client("kinesis", region_name="us-west-2") stream_name = "my_stream" conn.create_stream(StreamName=stream_name, ShardCount=1) # Create some data for index i...
@mock_kinesis def test_get_records_at_timestamp(): # AT_TIMESTAMP - Read the first record at or after the specified timestamp
conn = boto3.client("kinesis", region_name="us-west-2") stream_name = "my_stream" conn.create_stream(StreamName=stream_name, ShardCount=1) # Create some data for index in range(1, 5): conn.put_record( StreamName=stream_name, Data=str(index), PartitionKey=str(index) ) ...
_record(stream_name, "last_record", "last_record") response = conn.get_records(shard_iterator) # And the only result returned should be the new item response["Records"].should.have.length_of(1) response["Records"][0]["PartitionKey"].should.equal("last_record") response["Records"][0]["Data"].should....
118
118
394
28
90
moseb/moto
tests/test_kinesis/test_kinesis.py
Python
test_get_records_at_timestamp
test_get_records_at_timestamp
297
338
297
299
846ffa3ad4ed40330aba29acb3462adf4f6f0bef
bigcode/the-stack
train
6ff42c86a8b94fa1fef6a065
train
function
@mock_kinesis_deprecated def test_put_records(): conn = boto.kinesis.connect_to_region("us-west-2") stream_name = "my_stream" conn.create_stream(stream_name, 1) data = "hello world" partition_key = "1234" conn.put_record.when.called_with(stream_name, data, 1234).should.throw( InvalidA...
@mock_kinesis_deprecated def test_put_records():
conn = boto.kinesis.connect_to_region("us-west-2") stream_name = "my_stream" conn.create_stream(stream_name, 1) data = "hello world" partition_key = "1234" conn.put_record.when.called_with(stream_name, data, 1234).should.throw( InvalidArgumentException ) conn.put_record(strea...
us-west-2") stream_name = "my_stream" conn.create_stream(stream_name, 1) conn.get_shard_iterator.when.called_with( stream_name, "123", "TRIM_HORIZON" ).should.throw(ResourceNotFoundException) @mock_kinesis_deprecated def test_put_records():
68
68
229
12
56
moseb/moto
tests/test_kinesis/test_kinesis.py
Python
test_put_records
test_put_records
129
158
129
130
11e6c894f4b8c307d71e03401cfb3bc048c69ecf
bigcode/the-stack
train
4ba320d6443f2ac1945350d8
train
function
@mock_kinesis_deprecated def test_list_and_delete_stream(): conn = boto.kinesis.connect_to_region("us-west-2") conn.create_stream("stream1", 1) conn.create_stream("stream2", 1) conn.list_streams()["StreamNames"].should.have.length_of(2) conn.delete_stream("stream2") conn.list_streams()["Stre...
@mock_kinesis_deprecated def test_list_and_delete_stream():
conn = boto.kinesis.connect_to_region("us-west-2") conn.create_stream("stream1", 1) conn.create_stream("stream2", 1) conn.list_streams()["StreamNames"].should.have.length_of(2) conn.delete_stream("stream2") conn.list_streams()["StreamNames"].should.have.length_of(1) # Delete invalid id ...
_deprecated def test_describe_non_existant_stream(): conn = boto.kinesis.connect_to_region("us-east-1") conn.describe_stream.when.called_with("not-a-stream").should.throw( ResourceNotFoundException ) @mock_kinesis_deprecated def test_list_and_delete_stream():
64
64
120
14
50
moseb/moto
tests/test_kinesis/test_kinesis.py
Python
test_list_and_delete_stream
test_list_and_delete_stream
42
58
42
43
cea1c935277e0096816df6cecc4f6d0ae25f8da4
bigcode/the-stack
train
3af803ef0fa3b98e17c62683
train
function
@mock_kinesis_deprecated def test_get_records_limit(): conn = boto.kinesis.connect_to_region("us-west-2") stream_name = "my_stream" conn.create_stream(stream_name, 1) # Create some data data = "hello world" for index in range(5): conn.put_record(stream_name, data, str(index)) # G...
@mock_kinesis_deprecated def test_get_records_limit():
conn = boto.kinesis.connect_to_region("us-west-2") stream_name = "my_stream" conn.create_stream(stream_name, 1) # Create some data data = "hello world" for index in range(5): conn.put_record(stream_name, data, str(index)) # Get a shard iterator response = conn.describe_stream...
["Records"].should.have.length_of(1) record = response["Records"][0] record["Data"].should.equal("hello world") record["PartitionKey"].should.equal("1234") record["SequenceNumber"].should.equal("1") @mock_kinesis_deprecated def test_get_records_limit():
66
66
221
13
53
moseb/moto
tests/test_kinesis/test_kinesis.py
Python
test_get_records_limit
test_get_records_limit
161
187
161
162
eedd5a9f8fa42360a3308b694fac62b5709a3fdd
bigcode/the-stack
train
e3d048f4439d67674267f41c
train
function
@mock_kinesis_deprecated def test_create_cluster(): conn = boto.kinesis.connect_to_region("us-west-2") conn.create_stream("my_stream", 3) stream_response = conn.describe_stream("my_stream") stream = stream_response["StreamDescription"] stream["StreamName"].should.equal("my_stream") stream["Ha...
@mock_kinesis_deprecated def test_create_cluster():
conn = boto.kinesis.connect_to_region("us-west-2") conn.create_stream("my_stream", 3) stream_response = conn.describe_stream("my_stream") stream = stream_response["StreamDescription"] stream["StreamName"].should.equal("my_stream") stream["HasMoreShards"].should.equal(False) stream["Stream...
_literals import datetime import time import boto.kinesis import boto3 from boto.kinesis.exceptions import ResourceNotFoundException, InvalidArgumentException from moto import mock_kinesis, mock_kinesis_deprecated from moto.core import ACCOUNT_ID @mock_kinesis_deprecated def test_create_cluster():
64
64
143
12
51
moseb/moto
tests/test_kinesis/test_kinesis.py
Python
test_create_cluster
test_create_cluster
14
31
14
15
b90e657161d9a4999fbba03c9594fe92504db042
bigcode/the-stack
train
b4c2121fd33fd1d6ad2be0c0
train
function
@mock_kinesis def test_get_records_at_very_old_timestamp(): conn = boto3.client("kinesis", region_name="us-west-2") stream_name = "my_stream" conn.create_stream(StreamName=stream_name, ShardCount=1) # Create some data keys = [str(i) for i in range(1, 5)] for k in keys: conn.put_record(S...
@mock_kinesis def test_get_records_at_very_old_timestamp():
conn = boto3.client("kinesis", region_name="us-west-2") stream_name = "my_stream" conn.create_stream(StreamName=stream_name, ShardCount=1) # Create some data keys = [str(i) for i in range(1, 5)] for k in keys: conn.put_record(StreamName=stream_name, Data=k, PartitionKey=k) # Get a ...
conn.get_records(ShardIterator=shard_iterator) response["Records"].should.have.length_of(len(keys)) partition_keys = [r["PartitionKey"] for r in response["Records"]] partition_keys.should.equal(keys) response["MillisBehindLatest"].should.equal(0) @mock_kinesis def test_get_records_at_very_old_timestam...
75
75
252
15
60
moseb/moto
tests/test_kinesis/test_kinesis.py
Python
test_get_records_at_very_old_timestamp
test_get_records_at_very_old_timestamp
341
367
341
342
21ec32dfa4b75c61816eb8c117f83c81306adbfb
bigcode/the-stack
train
9eeda36aa89aa9b98e286857
train
function
@mock_kinesis_deprecated def test_get_records_latest(): # LATEST - Start reading just after the most recent record in the shard, # so that you always read the most recent data in the shard. conn = boto.kinesis.connect_to_region("us-west-2") stream_name = "my_stream" conn.create_stream(stream_name, 1...
@mock_kinesis_deprecated def test_get_records_latest(): # LATEST - Start reading just after the most recent record in the shard, # so that you always read the most recent data in the shard.
conn = boto.kinesis.connect_to_region("us-west-2") stream_name = "my_stream" conn.create_stream(stream_name, 1) # Create some data for index in range(1, 5): conn.put_record(stream_name, str(index), str(index)) # Get a shard iterator response = conn.describe_stream(stream_name) ...
) shard_iterator = response["ShardIterator"] response = conn.get_records(shard_iterator) # And the first result returned should be the third item response["Records"][0]["Data"].should.equal("3") response["MillisBehindLatest"].should.equal(0) @mock_kinesis_deprecated def test_get_records_latest(...
105
105
352
45
60
moseb/moto
tests/test_kinesis/test_kinesis.py
Python
test_get_records_latest
test_get_records_latest
258
294
258
261
9e95782c2a81616c7c58703b309ef9b07b402151
bigcode/the-stack
train
be3a899f5a3fa2a6bba0ce72
train
function
@mock_kinesis def test_describe_stream_summary(): conn = boto3.client("kinesis", region_name="us-west-2") stream_name = "my_stream_summary" shard_count = 5 conn.create_stream(StreamName=stream_name, ShardCount=shard_count) resp = conn.describe_stream_summary(StreamName=stream_name) stream = res...
@mock_kinesis def test_describe_stream_summary():
conn = boto3.client("kinesis", region_name="us-west-2") stream_name = "my_stream_summary" shard_count = 5 conn.create_stream(StreamName=stream_name, ShardCount=shard_count) resp = conn.describe_stream_summary(StreamName=stream_name) stream = resp["StreamDescriptionSummary"] stream["StreamN...
ExclusiveStartStreamName=stream_names[-1]) stream_names = resp2["StreamNames"] has_more_streams = resp2["HasMoreStreams"] stream_names.should.have.length_of(1) has_more_streams.should.equal(False) @mock_kinesis def test_describe_stream_summary():
64
64
155
12
52
moseb/moto
tests/test_kinesis/test_kinesis.py
Python
test_describe_stream_summary
test_describe_stream_summary
80
95
80
81
332ea8defd23d7b93bbf6058ac08b44f113d2d73
bigcode/the-stack
train
b2a4ed681f9e74f29fc238be
train
function
@mock_kinesis def test_get_records_at_very_new_timestamp(): conn = boto3.client("kinesis", region_name="us-west-2") stream_name = "my_stream" conn.create_stream(StreamName=stream_name, ShardCount=1) # Create some data keys = [str(i) for i in range(1, 5)] for k in keys: conn.put_record(S...
@mock_kinesis def test_get_records_at_very_new_timestamp():
conn = boto3.client("kinesis", region_name="us-west-2") stream_name = "my_stream" conn.create_stream(StreamName=stream_name, ShardCount=1) # Create some data keys = [str(i) for i in range(1, 5)] for k in keys: conn.put_record(StreamName=stream_name, Data=k, PartitionKey=k) timestam...
" ) shard_iterator = response["ShardIterator"] response = conn.get_records(ShardIterator=shard_iterator, Limit=1) response["Records"].should.have.length_of(1) response["MillisBehindLatest"].should.be.greater_than(0) @mock_kinesis def test_get_records_at_very_new_timestamp():
72
72
241
15
57
moseb/moto
tests/test_kinesis/test_kinesis.py
Python
test_get_records_at_very_new_timestamp
test_get_records_at_very_new_timestamp
424
451
424
425
4f02220a7b18c06e9f7cfab78381a95c8d0d158a
bigcode/the-stack
train
76cd831ce24d835b208ab0ed
train
function
@mock_kinesis def test_get_records_from_empty_stream_at_timestamp(): conn = boto3.client("kinesis", region_name="us-west-2") stream_name = "my_stream" conn.create_stream(StreamName=stream_name, ShardCount=1) timestamp = datetime.datetime.utcnow() # Get a shard iterator response = conn.describe...
@mock_kinesis def test_get_records_from_empty_stream_at_timestamp():
conn = boto3.client("kinesis", region_name="us-west-2") stream_name = "my_stream" conn.create_stream(StreamName=stream_name, ShardCount=1) timestamp = datetime.datetime.utcnow() # Get a shard iterator response = conn.describe_stream(StreamName=stream_name) shard_id = response["StreamDescri...
) shard_iterator = response["ShardIterator"] response = conn.get_records(ShardIterator=shard_iterator) response["Records"].should.have.length_of(0) response["MillisBehindLatest"].should.equal(0) @mock_kinesis def test_get_records_from_empty_stream_at_timestamp():
64
64
188
15
49
moseb/moto
tests/test_kinesis/test_kinesis.py
Python
test_get_records_from_empty_stream_at_timestamp
test_get_records_from_empty_stream_at_timestamp
454
476
454
455
1f9b8d6ece5cc8b0de89689867df332fdf00c485
bigcode/the-stack
train
9d7484611310dee3fd5b44c7
train
function
@mock_kinesis def test_get_records_timestamp_filtering(): conn = boto3.client("kinesis", region_name="us-west-2") stream_name = "my_stream" conn.create_stream(StreamName=stream_name, ShardCount=1) conn.put_record(StreamName=stream_name, Data="0", PartitionKey="0") time.sleep(1.0) timestamp = d...
@mock_kinesis def test_get_records_timestamp_filtering():
conn = boto3.client("kinesis", region_name="us-west-2") stream_name = "my_stream" conn.create_stream(StreamName=stream_name, ShardCount=1) conn.put_record(StreamName=stream_name, Data="0", PartitionKey="0") time.sleep(1.0) timestamp = datetime.datetime.utcnow() conn.put_record(StreamName=...
Iterator"] response = conn.get_records(ShardIterator=shard_iterator) response["Records"].should.have.length_of(len(keys)) partition_keys = [r["PartitionKey"] for r in response["Records"]] partition_keys.should.equal(keys) response["MillisBehindLatest"].should.equal(0) @mock_kinesis def test_get_rec...
78
78
263
13
65
moseb/moto
tests/test_kinesis/test_kinesis.py
Python
test_get_records_timestamp_filtering
test_get_records_timestamp_filtering
370
399
370
371
90935f0a1b3790179c2fc7e2ea4ff9cb1b0c3dff
bigcode/the-stack
train