project_name
stringlengths
6
104
file_name
stringlengths
4
89
full_name
stringlengths
1
102
func_name
stringlengths
1
85
docstring
stringlengths
13
836
docstring_tokens
listlengths
4
122
code
stringlengths
23
39.7k
code_tokens
stringlengths
29
44.6k
url
int64
3
986k
samxuxiang/SkexGen
geom_utils.py
center_vertices
center_vertices
Translate the vertices so that bounding box is centered at zero.
[ "Translate", "the", "vertices", "so", "that", "bounding", "box", "is", "centered", "at", "zero." ]
def center_vertices(vertices): vert_min = vertices.min(axis=0) vert_max = vertices.max(axis=0) vert_center = 0.5 * (vert_min + vert_max) return (vertices - vert_center, vert_center)
['def', 'center_vertices(vertices):', 'vert_min', '=', 'vertices.min(axis=0)', 'vert_max', '=', 'vertices.max(axis=0)', 'vert_center', '=', '0.5', '*', '(vert_min', '+', 'vert_max)', 'return', '(vertices', '-', 'vert_center,', 'vert_center)']
884,713
nosmokingbandit/watcher
_cptools.py
SessionTool.regenerate
regenerate
Drop the current session and make a new one (with a new id).
[ "Drop", "the", "current", "session", "and", "make", "a", "new", "one", "(with", "a", "new", "id)." ]
def regenerate(self): sess = cherrypy.serving.session sess.regenerate() conf = dict([(k, v) for (k, v) in self._merged_args().items() if k in ('path', 'path_header', 'name', 'timeout', 'domain', 'secure')]) _sessions.set_response_cookie(**conf)
['def', 'regenerate(self):', 'sess', '=', 'cherrypy.serving.session', 'sess.regenerate()', 'conf', '=', 'dict([(k,', 'v)', 'for', '(k,', 'v)', 'in', 'self._merged_args().items()', 'if', 'k', 'in', "('path',", "'path_header',", "'name',", "'timeout',", "'domain',", "'secure')])", '_sessions.set_response_cookie(**conf)']
381,345
TheCurryMan/MedicAI
urls.py
URL.encode_netloc
encode_netloc
Encodes the netloc part to an ASCII safe URL as bytes.
[ "Encodes", "the", "netloc", "part", "to", "an", "ASCII", "safe", "URL", "as", "bytes." ]
def encode_netloc(self): rv = self.ascii_host or '' if ':' in rv: rv = '[%s]' % rv port = self.port if port is not None: rv = '%s:%d' % (rv, port) auth = ':'.join(filter(None, [url_quote(self.raw_username or '', 'utf-8', 'strict', '/:%'), url_quote(self.raw_password or '', 'utf-8', '...
['def', 'encode_netloc(self):', 'rv', '=', 'self.ascii_host', 'or', "''", 'if', "':'", 'in', 'rv:', 'rv', '=', "'[%s]'", '%', 'rv', 'port', '=', 'self.port', 'if', 'port', 'is', 'not', 'None:', 'rv', '=', "'%s:%d'", '%', '(rv,', 'port)', 'auth', '=', "':'.join(filter(None,", '[url_quote(self.raw_username', 'or', "'',",...
649,736
matsu0228/nlp-jp
screen.py
screen.cr
cr
This moves the cursor to the beginning (col 1) of the current row.
[ "This", "moves", "the", "cursor", "to", "the", "beginning", "(col", "1)", "of", "the", "current", "row." ]
def cr(self): self.cursor_home(self.cur_r, 1)
['def', 'cr(self):', 'self.cursor_home(self.cur_r,', '1)']
803,231
tensorflow/hub
keras_layer_test.py
KerasTest.testBatchNormRetraining
testBatchNormRetraining
Tests imported batch norm with trainable=True.
[ "Tests", "imported", "batch", "norm", "with", "trainable=True." ]
def testBatchNormRetraining(self, save_from_keras): export_dir = os.path.join(self.get_temp_dir(), 'batch-norm') _save_batch_norm_model(export_dir, save_from_keras=save_from_keras) inp = tf.keras.layers.Input(shape=(1,), dtype=tf.float32) imported = hub.KerasLayer(export_dir, trainable=True) (var_be...
['def', 'testBatchNormRetraining(self,', 'save_from_keras):', 'export_dir', '=', 'os.path.join(self.get_temp_dir(),', "'batch-norm')", '_save_batch_norm_model(export_dir,', 'save_from_keras=save_from_keras)', 'inp', '=', 'tf.keras.layers.Input(shape=(1,),', 'dtype=tf.float32)', 'imported', '=', 'hub.KerasLayer(export_d...
570,945
myothida/Supervised-Machine-Learning
test_confusion_matrix_display.py
test_confusion_matrix_text_kw
test_confusion_matrix_text_kw
Check that text_kw is passed to the text call.
[ "Check", "that", "text_kw", "is", "passed", "to", "the", "text", "call." ]
def test_confusion_matrix_text_kw(pyplot): font_size = 15.0 (X, y) = make_classification(random_state=0) classifier = SVC().fit(X, y) disp = ConfusionMatrixDisplay.from_estimator(classifier, X, y, text_kw={'fontsize': font_size}) for text in disp.text_.reshape(-1): assert text.get_fontsize()...
['def', 'test_confusion_matrix_text_kw(pyplot):', 'font_size', '=', '15.0', '(X,', 'y)', '=', 'make_classification(random_state=0)', 'classifier', '=', 'SVC().fit(X,', 'y)', 'disp', '=', 'ConfusionMatrixDisplay.from_estimator(classifier,', 'X,', 'y,', "text_kw={'fontsize':", 'font_size})', 'for', 'text', 'in', 'disp.te...
364,298
kaka-lin/object-detection
base_camera.py
BaseCamera.get_frame
get_frame
Return the current camera frame.
[ "Return", "the", "current", "camera", "frame." ]
def get_frame(self): self.launch_thread() self.last_access = time.time() self.event.wait() self.event.clear() return self.frame
['def', 'get_frame(self):', 'self.launch_thread()', 'self.last_access', '=', 'time.time()', 'self.event.wait()', 'self.event.clear()', 'return', 'self.frame']
745,606
Emory-HITI/Niffler
RtaExtractor.py
load_data
load_data
Loads the json data from labs, meds and orders into corresponsing MongoDB Collection.
[ "Loads", "the", "json", "data", "from", "labs,", "meds", "and", "orders", "into", "corresponsing", "MongoDB", "Collection." ]
def load_data(url, user, passcode, db_json=None, first_index=None, second_index=None): global total_data load_time = time.time() data_collection = db[db_json] data = requests.get(url, auth=(user, passcode)) data = data.json() items_data = data['items'] for record in items_data: if re...
['def', 'load_data(url,', 'user,', 'passcode,', 'db_json=None,', 'first_index=None,', 'second_index=None):', 'global', 'total_data', 'load_time', '=', 'time.time()', 'data_collection', '=', 'db[db_json]', 'data', '=', 'requests.get(url,', 'auth=(user,', 'passcode))', 'data', '=', 'data.json()', 'items_data', '=', "data...
723,474
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
nb_007.py
dropout_mask
dropout_mask
Returns a dropout mask of the same type as x, size sz, with probability p to cancel an element.
[ "Returns", "a", "dropout", "mask", "of", "the", "same", "type", "as", "x,", "size", "sz,", "with", "probability", "p", "to", "cancel", "an", "element." ]
def dropout_mask(x: Tensor, sz: Collection[int], p: float): return x.new(*sz).bernoulli_(1 - p).div_(1 - p)
['def', 'dropout_mask(x:', 'Tensor,', 'sz:', 'Collection[int],', 'p:', 'float):', 'return', 'x.new(*sz).bernoulli_(1', '-', 'p).div_(1', '-', 'p)']
81,497
nilearn/nilearn
test_plot_stat_map.py
test_plot_stat_map_colorbar_variations
test_plot_stat_map_colorbar_variations
Smoke test for plot_stat_map with different colorbar configurations.
[ "Smoke", "test", "for", "plot_stat_map", "with", "different", "colorbar", "configurations." ]
def test_plot_stat_map_colorbar_variations(params, img_3d_mni, affine_mni): data_positive = get_data(img_3d_mni) rng = np.random.RandomState(42) data_negative = -data_positive data_heterogeneous = data_positive * rng.standard_normal(size=data_positive.shape) img_negative = Nifti1Image(data_negative,...
['def', 'test_plot_stat_map_colorbar_variations(params,', 'img_3d_mni,', 'affine_mni):', 'data_positive', '=', 'get_data(img_3d_mni)', 'rng', '=', 'np.random.RandomState(42)', 'data_negative', '=', '-data_positive', 'data_heterogeneous', '=', 'data_positive', '*', 'rng.standard_normal(size=data_positive.shape)', 'img_n...
724,219
utiasASRL/hero_radar_odometry
utils.py
get_transform
get_transform
Returns a 4x4 homogeneous 3D transform for a given 2D (x, y, theta).
[ "Returns", "a", "4x4", "homogeneous", "3D", "transform", "for", "a", "given", "2D", "(x,", "y,", "theta)." ]
def get_transform(x, y, theta): T = np.identity(4, dtype=np.float32) T[0:2, 0:2] = np.array([[np.cos(theta), np.sin(theta)], [-np.sin(theta), np.cos(theta)]]) T[0, 3] = x T[1, 3] = y return T
['def', 'get_transform(x,', 'y,', 'theta):', 'T', '=', 'np.identity(4,', 'dtype=np.float32)', 'T[0:2,', '0:2]', '=', 'np.array([[np.cos(theta),', 'np.sin(theta)],', '[-np.sin(theta),', 'np.cos(theta)]])', 'T[0,', '3]', '=', 'x', 'T[1,', '3]', '=', 'y', 'return', 'T']
205,955
rlworkgroup/garage
context_conditioned_policy.py
ContextConditionedPolicy.reset_belief
reset_belief
Reset :math:`q(z \| c)` to the prior and sample a new z from the prior.
[ "Reset", ":math:`q(z", "\\|", "c)`", "to", "the", "prior", "and", "sample", "a", "new", "z", "from", "the", "prior." ]
def reset_belief(self, num_tasks=1): mu = torch.zeros(num_tasks, self._latent_dim).to(global_device()) if self._use_information_bottleneck: var = torch.ones(num_tasks, self._latent_dim).to(global_device()) else: var = torch.zeros(num_tasks, self._latent_dim).to(global_device()) self.z_me...
['def', 'reset_belief(self,', 'num_tasks=1):', 'mu', '=', 'torch.zeros(num_tasks,', 'self._latent_dim).to(global_device())', 'if', 'self._use_information_bottleneck:', 'var', '=', 'torch.ones(num_tasks,', 'self._latent_dim).to(global_device())', 'else:', 'var', '=', 'torch.zeros(num_tasks,', 'self._latent_dim).to(globa...
200,807
suarez12138/AI-Reversi_IMP_TextDichotomy
lazy_wheel.py
LazyZipOverHTTP.name
name
Path to the underlying file.
[ "Path", "to", "the", "underlying", "file." ]
def name(self): return self._file.name
['def', 'name(self):', 'return', 'self._file.name']
98,414
mlefkovitz/Unsupervised-Learning
utils.py
convert_to_list
convert_to_list
Convert list of lists to list.
[ "Convert", "list", "of", "lists", "to", "list." ]
def convert_to_list(data): final_list = [] for i in data: try: for j in i: final_list.append(j) except: print('ERROR') final_list = np.array(final_list) return final_list
['def', 'convert_to_list(data):', 'final_list', '=', '[]', 'for', 'i', 'in', 'data:', 'try:', 'for', 'j', 'in', 'i:', 'final_list.append(j)', 'except:', "print('ERROR')", 'final_list', '=', 'np.array(final_list)', 'return', 'final_list']
353,543
bytedance/ParaGen
abstract_model.py
AbstractModel.update_states
update_states
Update internal networks states.
[ "Update", "internal", "networks", "states." ]
def update_states(self, *args, **kwargs): raise NotImplementedError
['def', 'update_states(self,', '*args,', '**kwargs):', 'raise', 'NotImplementedError']
779,448
rlgraph/rlgraph
intrinsic_curiosity_world_option_model.py
IntrinsicCuriosityWorldOptionModel.get_phi
get_phi
Returns the (automatically learnt) feature vector given some state (s).
[ "Returns", "the", "(automatically", "learnt)", "feature", "vector", "given", "some", "state", "(s)." ]
def get_phi(self, states, deterministic=None): deterministic = self.deterministic if deterministic is None else deterministic phi = self.state_encoder.predict(states, deterministic=deterministic) phi['phi'] = phi['predictions'] return phi
['def', 'get_phi(self,', 'states,', 'deterministic=None):', 'deterministic', '=', 'self.deterministic', 'if', 'deterministic', 'is', 'None', 'else', 'deterministic', 'phi', '=', 'self.state_encoder.predict(states,', 'deterministic=deterministic)', "phi['phi']", '=', "phi['predictions']", 'return', 'phi']
862,496
zackmcnulty/CSE_446-Machine_Learning
__init__.py
get_f77flags
get_f77flags
Search the first 20 lines of fortran 77 code for line pattern `CF77FLAGS(<fcompiler type>)=<f77 flags>` Return a dictionary {<fcompiler type>:<f77 flags>}.
[ "Search", "the", "first", "20", "lines", "of", "fortran", "77", "code", "for", "line", "pattern", "`CF77FLAGS(<fcompiler", "type>)=<f77", "flags>`", "Return", "a", "dictionary", "{<fcompiler", "type>:<f77", "flags>}." ]
def get_f77flags(src): flags = {} f = open_latin1(src, 'r') i = 0 for line in f: i += 1 if i > 20: break m = _f77flags_re.match(line) if not m: continue fcname = m.group('fcname').strip() fflags = m.group('fflags').strip() f...
['def', 'get_f77flags(src):', 'flags', '=', '{}', 'f', '=', 'open_latin1(src,', "'r')", 'i', '=', '0', 'for', 'line', 'in', 'f:', 'i', '+=', '1', 'if', 'i', '>', '20:', 'break', 'm', '=', '_f77flags_re.match(line)', 'if', 'not', 'm:', 'continue', 'fcname', '=', "m.group('fcname').strip()", 'fflags', '=', "m.group('ffla...
195,813
joao-montanari/artificial_intelligence
ipaddress.py
_BaseNetwork.supernet
supernet
The supernet containing the current network.
[ "The", "supernet", "containing", "the", "current", "network." ]
def supernet(self, prefixlen_diff=1, new_prefix=None): if self._prefixlen == 0: return self if new_prefix is not None: if new_prefix > self._prefixlen: raise ValueError('new prefix must be shorter') if prefixlen_diff != 1: raise ValueError('cannot set prefixlen_di...
['def', 'supernet(self,', 'prefixlen_diff=1,', 'new_prefix=None):', 'if', 'self._prefixlen', '==', '0:', 'return', 'self', 'if', 'new_prefix', 'is', 'not', 'None:', 'if', 'new_prefix', '>', 'self._prefixlen:', 'raise', "ValueError('new", 'prefix', 'must', 'be', "shorter')", 'if', 'prefixlen_diff', '!=', '1:', 'raise', ...
142,952
QinganZhao/Deep-Learning-Based-Structural-Damage-Detection
test_coord_map.py
TestCoordMap.test_catch_negative_crop
test_catch_negative_crop
Catch impossible offsets, such as when the top to be cropped is mapped to a larger reference top.
[ "Catch", "impossible", "offsets,", "such", "as", "when", "the", "top", "to", "be", "cropped", "is", "mapped", "to", "a", "larger", "reference", "top." ]
def test_catch_negative_crop(self): n = coord_net_spec(dpad=10) with self.assertRaises(AssertionError): crop(n.deconv, n.data)
['def', 'test_catch_negative_crop(self):', 'n', '=', 'coord_net_spec(dpad=10)', 'with', 'self.assertRaises(AssertionError):', 'crop(n.deconv,', 'n.data)']
127,510
deepmind/acme
fakes.py
transition_dataset
transition_dataset
Constructs fake dataset of Reverb N-step transition samples.
[ "Constructs", "fake", "dataset", "of", "Reverb", "N-step", "transition", "samples." ]
def transition_dataset(environment: dm_env.Environment) -> tf.data.Dataset: return transition_dataset_from_spec(specs.make_environment_spec(environment))
['def', 'transition_dataset(environment:', 'dm_env.Environment)', '->', 'tf.data.Dataset:', 'return', 'transition_dataset_from_spec(specs.make_environment_spec(environment))']
8,373
yufeiwang63/ROLL
box2d_viewer.py
PygameDraw.DrawCircle
DrawCircle
Draw a wireframe circle given the center, radius, axis of orientation and color.
[ "Draw", "a", "wireframe", "circle", "given", "the", "center,", "radius,", "axis", "of", "orientation", "and", "color." ]
def DrawCircle(self, center, radius, color, drawwidth=1): radius *= self.zoom if radius < 1: radius = 1 else: radius = int(radius) pygame.draw.circle(self.surface, color.bytes, center, radius, drawwidth)
['def', 'DrawCircle(self,', 'center,', 'radius,', 'color,', 'drawwidth=1):', 'radius', '*=', 'self.zoom', 'if', 'radius', '<', '1:', 'radius', '=', '1', 'else:', 'radius', '=', 'int(radius)', 'pygame.draw.circle(self.surface,', 'color.bytes,', 'center,', 'radius,', 'drawwidth)']
326,615
weimin17/Object-Detection_HelmetDetection
nav_utils.py
plot_trajectories
plot_trajectories
Processes the collected outputs during validation to plot the trajectories in the top view.
[ "Processes", "the", "collected", "outputs", "during", "validation", "to", "plot", "the", "trajectories", "in", "the", "top", "view." ]
def plot_trajectories(outputs, global_step, output_dir, metric_summary, N): if N >= 0: outputs = outputs[:N] N = len(outputs) plt.set_cmap('gray') (fig, axes) = utils.subplot(plt, (N, outputs[0][1].shape[0]), (5, 5)) axes = axes.ravel()[::-1].tolist() for i in range(N): (locs, or...
['def', 'plot_trajectories(outputs,', 'global_step,', 'output_dir,', 'metric_summary,', 'N):', 'if', 'N', '>=', '0:', 'outputs', '=', 'outputs[:N]', 'N', '=', 'len(outputs)', "plt.set_cmap('gray')", '(fig,', 'axes)', '=', 'utils.subplot(plt,', '(N,', 'outputs[0][1].shape[0]),', '(5,', '5))', 'axes', '=', 'axes.ravel()[...
749,499
Farama-Foundation/Gymnasium
normalize.py
RunningMeanStd.update_from_moments
update_from_moments
Updates from batch mean, variance and count moments.
[ "Updates", "from", "batch", "mean,", "variance", "and", "count", "moments." ]
def update_from_moments(self, batch_mean, batch_var, batch_count): (self.mean, self.var, self.count) = update_mean_var_count_from_moments(self.mean, self.var, self.count, batch_mean, batch_var, batch_count)
['def', 'update_from_moments(self,', 'batch_mean,', 'batch_var,', 'batch_count):', '(self.mean,', 'self.var,', 'self.count)', '=', 'update_mean_var_count_from_moments(self.mean,', 'self.var,', 'self.count,', 'batch_mean,', 'batch_var,', 'batch_count)']
573,385
sek788432/Waymo-2D-Object-Detection
utils.py
get_all_vars
get_all_vars
Get all tf variables in scope.
[ "Get", "all", "tf", "variables", "in", "scope." ]
def get_all_vars(ignore_scopes=None): all_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES) all_vars = [var for var in all_vars if ignore_scopes is None or not any((var.name.startswith(scope) for scope in ignore_scopes))] return all_vars
['def', 'get_all_vars(ignore_scopes=None):', 'all_vars', '=', 'tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)', 'all_vars', '=', '[var', 'for', 'var', 'in', 'all_vars', 'if', 'ignore_scopes', 'is', 'None', 'or', 'not', 'any((var.name.startswith(scope)', 'for', 'scope', 'in', 'ignore_scopes))]', 'return', 'all_vars']
974,406
fptudsc/artificial-intelligence
configuration.py
Configuration.save
save
Save the currentin-memory state.
[ "Save", "the", "currentin-memory", "state." ]
def save(self): self._ensure_have_load_only() for (fname, parser) in self._modified_parsers: logger.info('Writing to %s', fname) ensure_dir(os.path.dirname(fname)) with open(fname, 'w') as f: parser.write(f)
['def', 'save(self):', 'self._ensure_have_load_only()', 'for', '(fname,', 'parser)', 'in', 'self._modified_parsers:', "logger.info('Writing", 'to', "%s',", 'fname)', 'ensure_dir(os.path.dirname(fname))', 'with', 'open(fname,', "'w')", 'as', 'f:', 'parser.write(f)']
87,836
suarez12138/AI-Reversi_IMP_TextDichotomy
test_decomp.py
TestEig.test_not_square_error
test_not_square_error
Check that passing a non-square array raises a ValueError.
[ "Check", "that", "passing", "a", "non-square", "array", "raises", "a", "ValueError." ]
def test_not_square_error(self): A = np.arange(6).reshape(3, 2) assert_raises(ValueError, eig, A)
['def', 'test_not_square_error(self):', 'A', '=', 'np.arange(6).reshape(3,', '2)', 'assert_raises(ValueError,', 'eig,', 'A)']
99,640
matsu0228/nlp-jp
config.py
is_callable
is_callable
Parameters ---------- `obj` - the object to be checked Returns ------- validator - returns True if object is callable raises ValueError otherwise.
[ "Parameters", "----------", "`obj`", "-", "the", "object", "to", "be", "checked", "Returns", "-------", "validator", "-", "returns", "True", "if", "object", "is", "callable", "raises", "ValueError", "otherwise." ]
def is_callable(obj): if not callable(obj): raise ValueError('Value must be a callable') return True
['def', 'is_callable(obj):', 'if', 'not', 'callable(obj):', 'raise', "ValueError('Value", 'must', 'be', 'a', "callable')", 'return', 'True']
802,055
Sentdex/Carla-RL
sensor.py
PointCloud.has_colors
has_colors
Return whether the points have color.
[ "Return", "whether", "the", "points", "have", "color." ]
def has_colors(self): return self._has_colors
['def', 'has_colors(self):', 'return', 'self._has_colors']
103,012
tobegit3hub/deep_image_model
operator_pd_cholesky.py
OperatorPDCholesky.inputs
inputs
List of tensors that were provided as initialization inputs.
[ "List", "of", "tensors", "that", "were", "provided", "as", "initialization", "inputs." ]
def inputs(self): return [self._chol]
['def', 'inputs(self):', 'return', '[self._chol]']
181,207
eddylau328/fyp-artificial-intelligence-ac-control-device
descriptor.py
_NestedDescriptorBase.CopyToProto
CopyToProto
Copies this to the matching proto in descriptor_pb2.
[ "Copies", "this", "to", "the", "matching", "proto", "in", "descriptor_pb2." ]
def CopyToProto(self, proto): if self.file is not None and self._serialized_start is not None and (self._serialized_end is not None): proto.ParseFromString(self.file.serialized_pb[self._serialized_start:self._serialized_end]) else: raise Error('Descriptor does not contain serialization.')
['def', 'CopyToProto(self,', 'proto):', 'if', 'self.file', 'is', 'not', 'None', 'and', 'self._serialized_start', 'is', 'not', 'None', 'and', '(self._serialized_end', 'is', 'not', 'None):', 'proto.ParseFromString(self.file.serialized_pb[self._serialized_start:self._serialized_end])', 'else:', 'raise', "Error('Descriptor...
215,179
prakharg24/yoloret
efficientnet.py
get_model_params
get_model_params
Get the block args and global params for a given model.
[ "Get", "the", "block", "args", "and", "global", "params", "for", "a", "given", "model." ]
def get_model_params(model_name, override_params=None): if model_name.startswith('efficientnet'): (width_coefficient, depth_coefficient, input_shape, dropout_rate) = efficientnet_params(model_name) (blocks_args, global_params) = efficientnet(width_coefficient, depth_coefficient, dropout_rate) el...
['def', 'get_model_params(model_name,', 'override_params=None):', 'if', "model_name.startswith('efficientnet'):", '(width_coefficient,', 'depth_coefficient,', 'input_shape,', 'dropout_rate)', '=', 'efficientnet_params(model_name)', '(blocks_args,', 'global_params)', '=', 'efficientnet(width_coefficient,', 'depth_coeffi...
969,437
PaddlePaddle/PaddleSpeech
trainer.py
Trainer.do_train
do_train
The training process control by epoch.
[ "The", "training", "process", "control", "by", "epoch." ]
def do_train(self): self.before_train() logger.info(f'Train Total Examples: {len(self.train_loader.dataset)}') while self.epoch < self.config.n_epoch: with Timer('Epoch-Train Time Cost: {}'): self.model.train() try: data_start_time = time.time() ...
['def', 'do_train(self):', 'self.before_train()', "logger.info(f'Train", 'Total', 'Examples:', "{len(self.train_loader.dataset)}')", 'while', 'self.epoch', '<', 'self.config.n_epoch:', 'with', "Timer('Epoch-Train", 'Time', 'Cost:', "{}'):", 'self.model.train()', 'try:', 'data_start_time', '=', 'time.time()', 'for', '(b...
276,964
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
evaluate.py
restore_from_checkpoint
restore_from_checkpoint
Restore model from checkpoint.
[ "Restore", "model", "from", "checkpoint." ]
def restore_from_checkpoint(sess, saver): ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir) if not ckpt or not ckpt.model_checkpoint_path: tf.logging.info('No checkpoint found at %s', FLAGS.checkpoint_dir) return False saver.restore(sess, ckpt.model_checkpoint_path) return True
['def', 'restore_from_checkpoint(sess,', 'saver):', 'ckpt', '=', 'tf.train.get_checkpoint_state(FLAGS.checkpoint_dir)', 'if', 'not', 'ckpt', 'or', 'not', 'ckpt.model_checkpoint_path:', "tf.logging.info('No", 'checkpoint', 'found', 'at', "%s',", 'FLAGS.checkpoint_dir)', 'return', 'False', 'saver.restore(sess,', 'ckpt.mo...
14,190
Griffin98/Segmentation_based_Semantic_Matting
model.py
unmold_image
unmold_image
Takes a image normalized with mold() and returns the original.
[ "Takes", "a", "image", "normalized", "with", "mold()", "and", "returns", "the", "original." ]
def unmold_image(normalized_images, config): return (normalized_images + config.MEAN_PIXEL).astype(np.uint8)
['def', 'unmold_image(normalized_images,', 'config):', 'return', '(normalized_images', '+', 'config.MEAN_PIXEL).astype(np.uint8)']
842,720
netket/netket
abstract_variational_driver.py
AbstractVariationalDriver.estimate
estimate
Return MCMC statistics for the expectation value of observables in the current state of the driver.
[ "Return", "MCMC", "statistics", "for", "the", "expectation", "value", "of", "observables", "in", "the", "current", "state", "of", "the", "driver." ]
def estimate(self, observables): return tree_map(self._estimate_stats, observables)
['def', 'estimate(self,', 'observables):', 'return', 'tree_map(self._estimate_stats,', 'observables)']
735,928
weimin17/Object-Detection_HelmetDetection
mobilenet_v2_test.py
find_ops
find_ops
Find ops of a given type in graphdef or a graph.
[ "Find", "ops", "of", "a", "given", "type", "in", "graphdef", "or", "a", "graph." ]
def find_ops(optype): gd = tf.get_default_graph() return [var for var in gd.get_operations() if var.type == optype]
['def', 'find_ops(optype):', 'gd', '=', 'tf.get_default_graph()', 'return', '[var', 'for', 'var', 'in', 'gd.get_operations()', 'if', 'var.type', '==', 'optype]']
753,004
ryu-ed/SpaceInvaders_Ros
server.py
ServerHTMLDoc.docroutine
docroutine
Produce HTML documentation for a function or method object.
[ "Produce", "HTML", "documentation", "for", "a", "function", "or", "method", "object." ]
def docroutine(self, object, name, mod=None, funcs={}, classes={}, methods={}, cl=None): anchor = (cl and cl.__name__ or '') + '-' + name note = '' title = '<a name="%s"><strong>%s</strong></a>' % (self.escape(anchor), self.escape(name)) if inspect.ismethod(object): args = inspect.getfullargspec...
['def', 'docroutine(self,', 'object,', 'name,', 'mod=None,', 'funcs={},', 'classes={},', 'methods={},', 'cl=None):', 'anchor', '=', '(cl', 'and', 'cl.__name__', 'or', "'')", '+', "'-'", '+', 'name', 'note', '=', "''", 'title', '=', "'<a", 'name="%s"><strong>%s</strong></a>\'', '%', '(self.escape(anchor),', 'self.escape...
395,972
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
test_zipfile.py
AbstractTestsWithSourceFile.test_low_compression
test_low_compression
Check for cases where compressed data is larger than original.
[ "Check", "for", "cases", "where", "compressed", "data", "is", "larger", "than", "original." ]
def test_low_compression(self): with zipfile.ZipFile(TESTFN2, 'w', self.compression) as zipfp: zipfp.writestr('strfile', '12') with zipfile.ZipFile(TESTFN2, 'r', self.compression) as zipfp: with zipfp.open('strfile') as openobj: self.assertEqual(openobj.read(1), b'1') sel...
['def', 'test_low_compression(self):', 'with', 'zipfile.ZipFile(TESTFN2,', "'w',", 'self.compression)', 'as', 'zipfp:', "zipfp.writestr('strfile',", "'12')", 'with', 'zipfile.ZipFile(TESTFN2,', "'r',", 'self.compression)', 'as', 'zipfp:', 'with', "zipfp.open('strfile')", 'as', 'openobj:', 'self.assertEqual(openobj.read...
376,476
edwardlib/observations
gen_data_files.py
gen_context
gen_context
Generate context for jinja templated python file.
[ "Generate", "context", "for", "jinja", "templated", "python", "file." ]
def gen_context(row): URL_WRAP_LEN = 63 WRAP_INDENT = 10 function = row['function_name'] rst_loc = row['rst_files'] try: rows = int(row['rows']) except ValueError: print(function) rows = '' try: cols = int(row['cols']) except ValueError: print(func...
['def', 'gen_context(row):', 'URL_WRAP_LEN', '=', '63', 'WRAP_INDENT', '=', '10', 'function', '=', "row['function_name']", 'rst_loc', '=', "row['rst_files']", 'try:', 'rows', '=', "int(row['rows'])", 'except', 'ValueError:', 'print(function)', 'rows', '=', "''", 'try:', 'cols', '=', "int(row['cols'])", 'except', 'Value...
740,775
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
videos_to_tfrecords.py
GetNumFrames
GetNumFrames
Gets the number of frames in a video.
[ "Gets", "the", "number", "of", "frames", "in", "a", "video." ]
def GetNumFrames(vid_path): cap = cv2.VideoCapture(vid_path) total_frames = cap.get(7) cap.release() return int(total_frames)
['def', 'GetNumFrames(vid_path):', 'cap', '=', 'cv2.VideoCapture(vid_path)', 'total_frames', '=', 'cap.get(7)', 'cap.release()', 'return', 'int(total_frames)']
112,431
enuguru/artificial_intelligence_and_machine_
bccache.py
Bucket.load_bytecode
load_bytecode
Loads bytecode from a file or file like object.
[ "Loads", "bytecode", "from", "a", "file", "or", "file", "like", "object." ]
def load_bytecode(self, f): magic = f.read(len(bc_magic)) if magic != bc_magic: self.reset() return checksum = pickle.load(f) if self.checksum != checksum: self.reset() return try: self.code = marshal_load(f) except (EOFError, ValueError, TypeError): ...
['def', 'load_bytecode(self,', 'f):', 'magic', '=', 'f.read(len(bc_magic))', 'if', 'magic', '!=', 'bc_magic:', 'self.reset()', 'return', 'checksum', '=', 'pickle.load(f)', 'if', 'self.checksum', '!=', 'checksum:', 'self.reset()', 'return', 'try:', 'self.code', '=', 'marshal_load(f)', 'except', '(EOFError,', 'ValueError...
129,011
tensorflow/privacy
multi_label_head_test.py
DPMultiLabelHeadTest.testLoss
testLoss
Tests loss() returns per-example losses.
[ "Tests", "loss()", "returns", "per-example", "losses." ]
def testLoss(self): head = multi_label_head.DPMultiLabelHead(3) features = {'feature_a': np.full(4, 1.0)} labels = np.array([[0, 1, 1], [1, 1, 0], [0, 1, 0], [1, 1, 1]]) logits = np.array([[2.0, 1.5, 4.1], [2.0, 1.5, 4.1], [2.0, 1.5, 4.1], [2.0, 1.5, 4.1]]) actual_loss = head.loss(labels, logits, fe...
['def', 'testLoss(self):', 'head', '=', 'multi_label_head.DPMultiLabelHead(3)', 'features', '=', "{'feature_a':", 'np.full(4,', '1.0)}', 'labels', '=', 'np.array([[0,', '1,', '1],', '[1,', '1,', '0],', '[0,', '1,', '0],', '[1,', '1,', '1]])', 'logits', '=', 'np.array([[2.0,', '1.5,', '4.1],', '[2.0,', '1.5,', '4.1],', ...
824,752
ryu-ed/SpaceInvaders_Ros
projections.py
qr_factorization_projections
qr_factorization_projections
Return linear operators for matrix A using ``QRFactorization`` approach.
[ "Return", "linear", "operators", "for", "matrix", "A", "using", "``QRFactorization``", "approach." ]
def qr_factorization_projections(A, m, n, orth_tol, max_refin, tol): (Q, R, P) = scipy.linalg.qr(A.T, pivoting=True, mode='economic') if np.linalg.norm(R[-1, :], np.inf) < tol: warn('Singular Jacobian matrix. Using SVD decomposition to ' + 'perform the factorizations.') return svd_factorization_...
['def', 'qr_factorization_projections(A,', 'm,', 'n,', 'orth_tol,', 'max_refin,', 'tol):', '(Q,', 'R,', 'P)', '=', 'scipy.linalg.qr(A.T,', 'pivoting=True,', "mode='economic')", 'if', 'np.linalg.norm(R[-1,', ':],', 'np.inf)', '<', 'tol:', "warn('Singular", 'Jacobian', 'matrix.', 'Using', 'SVD', 'decomposition', 'to', "'...
370,834
facebookresearch/CompilerGym
benchmark_cache_test.py
test_make_benchmark_of_size
test_make_benchmark_of_size
Sanity check for test helper function.
[ "Sanity", "check", "for", "test", "helper", "function." ]
def test_make_benchmark_of_size(size: int): assert make_benchmark_of_size(size).ByteSize() == size
['def', 'test_make_benchmark_of_size(size:', 'int):', 'assert', 'make_benchmark_of_size(size).ByteSize()', '==', 'size']
135,908
mj-will/nessai
test_plot.py
test_plot_live_points_bounds
test_plot_live_points_bounds
Test generating a plot for a set of live points.
[ "Test", "generating", "a", "plot", "for", "a", "set", "of", "live", "points." ]
def test_plot_live_points_bounds(live_points, bounds, model): if bounds: bounds = model.bounds fig = plot.plot_live_points(live_points, bounds=bounds) assert fig is not None plt.close()
['def', 'test_plot_live_points_bounds(live_points,', 'bounds,', 'model):', 'if', 'bounds:', 'bounds', '=', 'model.bounds', 'fig', '=', 'plot.plot_live_points(live_points,', 'bounds=bounds)', 'assert', 'fig', 'is', 'not', 'None', 'plt.close()']
292,361
PartnershipOnAI/safelife
env_factory.py
safelife_env_factory
safelife_env_factory
Factory for creating SafeLifeEnv instances with useful wrappers.
[ "Factory", "for", "creating", "SafeLifeEnv", "instances", "with", "useful", "wrappers." ]
def safelife_env_factory(level_iterator, *, num_envs=1, env_args={}, data_logger=None, training=True, exit_difficulty=1.0, se_baseline='starting-state', se_penalty=0.0): envs = [] for _ in range(num_envs): env = SafeLifeEnv(level_iterator, **env_args) if training: env = env_wrappers....
['def', 'safelife_env_factory(level_iterator,', '*,', 'num_envs=1,', 'env_args={},', 'data_logger=None,', 'training=True,', 'exit_difficulty=1.0,', "se_baseline='starting-state',", 'se_penalty=0.0):', 'envs', '=', '[]', 'for', '_', 'in', 'range(num_envs):', 'env', '=', 'SafeLifeEnv(level_iterator,', '**env_args)', 'if'...
829,279
Ruturaj123/Flowchart-Detection
affine_linear_operator_impl.py
AffineLinearOperator.scale
scale
The `scale` `LinearOperator` in `Y = scale @ X + shift`.
[ "The", "`scale`", "`LinearOperator`", "in", "`Y", "=", "scale", "@", "X", "+", "shift`." ]
def scale(self): return self._scale
['def', 'scale(self):', 'return', 'self._scale']
602,974
Riashat/Active-Learning-Bayesian-Convolutional--
test_vector_data_tasks.py
test_vector_classification
test_vector_classification
Classify random float vectors into 2 classes with logistic regression using 2 layer neural network with ReLU hidden units.
[ "Classify", "random", "float", "vectors", "into", "2", "classes", "with", "logistic", "regression", "using", "2", "layer", "neural", "network", "with", "ReLU", "hidden", "units." ]
def test_vector_classification(): np.random.seed(1337) nb_hidden = 10 ((X_train, y_train), (X_test, y_test)) = get_test_data(nb_train=500, nb_test=200, input_shape=(20,), classification=True, nb_class=2) y_train = to_categorical(y_train) y_test = to_categorical(y_test) model = Sequential([Dense(...
['def', 'test_vector_classification():', 'np.random.seed(1337)', 'nb_hidden', '=', '10', '((X_train,', 'y_train),', '(X_test,', 'y_test))', '=', 'get_test_data(nb_train=500,', 'nb_test=200,', 'input_shape=(20,),', 'classification=True,', 'nb_class=2)', 'y_train', '=', 'to_categorical(y_train)', 'y_test', '=', 'to_categ...
39,684
sek788432/Waymo-2D-Object-Detection
xlnet_base_test.py
MaskComputationTests.test_permutation_mask_no_input_mask
test_permutation_mask_no_input_mask
Tests if a permutation mask is provided but not input.
[ "Tests", "if", "a", "permutation", "mask", "is", "provided", "but", "not", "input." ]
def test_permutation_mask_no_input_mask(self): seq_length = 2 batch_size = 1 memory_length = 0 input_mask = None permutation_mask = np.array([[[1, 0], [1, 0]]]) expected_query_mask = permutation_mask[:, None, :, :] expected_content_mask = np.array([[[[1, 0], [1, 1]]]]) (query_mask, conte...
['def', 'test_permutation_mask_no_input_mask(self):', 'seq_length', '=', '2', 'batch_size', '=', '1', 'memory_length', '=', '0', 'input_mask', '=', 'None', 'permutation_mask', '=', 'np.array([[[1,', '0],', '[1,', '0]]])', 'expected_query_mask', '=', 'permutation_mask[:,', 'None,', ':,', ':]', 'expected_content_mask', '...
972,691
nicknochnack/RealTimeSignLanguageTFJS
ncf_keras_main.py
build_stats
build_stats
Normalizes and returns dictionary of stats.
[ "Normalizes", "and", "returns", "dictionary", "of", "stats." ]
def build_stats(loss, eval_result, time_callback): stats = {} if loss: stats['loss'] = loss if eval_result: stats['eval_loss'] = eval_result[0] stats['eval_hit_rate'] = eval_result[1] if time_callback: timestamp_log = time_callback.timestamp_log stats['step_timest...
['def', 'build_stats(loss,', 'eval_result,', 'time_callback):', 'stats', '=', '{}', 'if', 'loss:', "stats['loss']", '=', 'loss', 'if', 'eval_result:', "stats['eval_loss']", '=', 'eval_result[0]', "stats['eval_hit_rate']", '=', 'eval_result[1]', 'if', 'time_callback:', 'timestamp_log', '=', 'time_callback.timestamp_log'...
850,701
tencent-ailab/TriNet
iterators.py
EpochBatchIterating.state_dict
state_dict
Returns a dictionary containing a whole state of the iterator.
[ "Returns", "a", "dictionary", "containing", "a", "whole", "state", "of", "the", "iterator." ]
def state_dict(self): raise NotImplementedError
['def', 'state_dict(self):', 'raise', 'NotImplementedError']
425,160
huawei-noah/xingtian
share_by_plasma.py
ShareByPlasma.send_bytes
send_bytes
Send data to plasma server without serialize.
[ "Send", "data", "to", "plasma", "server", "without", "serialize." ]
def send_bytes(self, data_buffer, data_type='data'): client = self.connect() object_id = client.put_raw_buffer(data_buffer) self.control_q.put((object_id, data_type))
['def', 'send_bytes(self,', 'data_buffer,', "data_type='data'):", 'client', '=', 'self.connect()', 'object_id', '=', 'client.put_raw_buffer(data_buffer)', 'self.control_q.put((object_id,', 'data_type))']
962,371
thaines/helit
pruners.py
PruneCap.setMinGain
setMinGain
Sets the minimum gain that is allowed for a split to be accepted.
[ "Sets", "the", "minimum", "gain", "that", "is", "allowed", "for", "a", "split", "to", "be", "accepted." ]
def setMinGain(self, mingain): self.minGain = mingain
['def', 'setMinGain(self,', 'mingain):', 'self.minGain', '=', 'mingain']
591,341
Visual-Attention-Network/SegNeXt
uper_head.py
UPerHead.psp_forward
psp_forward
Forward function of PSP module.
[ "Forward", "function", "of", "PSP", "module." ]
def psp_forward(self, inputs): x = inputs[-1] psp_outs = [x] psp_outs.extend(self.psp_modules(x)) psp_outs = torch.cat(psp_outs, dim=1) output = self.bottleneck(psp_outs) return output
['def', 'psp_forward(self,', 'inputs):', 'x', '=', 'inputs[-1]', 'psp_outs', '=', '[x]', 'psp_outs.extend(self.psp_modules(x))', 'psp_outs', '=', 'torch.cat(psp_outs,', 'dim=1)', 'output', '=', 'self.bottleneck(psp_outs)', 'return', 'output']
843,052
zhaocq-nlp/NJUNMT-tf
vocab.py
Vocab.convert_to_wordlist
convert_to_wordlist
Converts list of token ids to list of word tokens.
[ "Converts", "list", "of", "token", "ids", "to", "list", "of", "word", "tokens." ]
def convert_to_wordlist(self, pred_ids, bpe_decoding=True, reverse_seq=True): pred_tokens = [self.vocab_r_dict[i] for i in pred_ids] if Constants.SEQUENCE_END in pred_tokens: if len(pred_tokens) == 1: return [''] pred_tokens = pred_tokens[:pred_tokens.index(Constants.SEQUENCE_END)] ...
['def', 'convert_to_wordlist(self,', 'pred_ids,', 'bpe_decoding=True,', 'reverse_seq=True):', 'pred_tokens', '=', '[self.vocab_r_dict[i]', 'for', 'i', 'in', 'pred_ids]', 'if', 'Constants.SEQUENCE_END', 'in', 'pred_tokens:', 'if', 'len(pred_tokens)', '==', '1:', 'return', "['']", 'pred_tokens', '=', 'pred_tokens[:pred_t...
782,810
yinguobing/models
shufflenet_v2.py
shuffle
shuffle
Shuffle x from the channel dimension.
[ "Shuffle", "x", "from", "the", "channel", "dimension." ]
def shuffle(x, groups=2): (batch_size, height, width, _) = tf.shape(x) (_, _, _, channels) = x.shape channels_per_group = channels // groups x = tf.reshape(x, [batch_size, height, width, groups, channels_per_group]) x = tf.transpose(x, [0, 1, 2, 4, 3]) x = tf.reshape(x, [batch_size, height, widt...
['def', 'shuffle(x,', 'groups=2):', '(batch_size,', 'height,', 'width,', '_)', '=', 'tf.shape(x)', '(_,', '_,', '_,', 'channels)', '=', 'x.shape', 'channels_per_group', '=', 'channels', '//', 'groups', 'x', '=', 'tf.reshape(x,', '[batch_size,', 'height,', 'width,', 'groups,', 'channels_per_group])', 'x', '=', 'tf.trans...
626,428
pkumusic/E-DRL
symbolic_functions.py
batch_flatten
batch_flatten
Flatten the tensor except the first dimension.
[ "Flatten", "the", "tensor", "except", "the", "first", "dimension." ]
def batch_flatten(x): shape = x.get_shape().as_list()[1:] if None not in shape: return tf.reshape(x, [-1, np.prod(shape)]) return tf.reshape(x, tf.pack([tf.shape(x)[0], -1]))
['def', 'batch_flatten(x):', 'shape', '=', 'x.get_shape().as_list()[1:]', 'if', 'None', 'not', 'in', 'shape:', 'return', 'tf.reshape(x,', '[-1,', 'np.prod(shape)])', 'return', 'tf.reshape(x,', 'tf.pack([tf.shape(x)[0],', '-1]))']
555,527
zihuitang/medical_AI_platform
operator.py
contains
contains
Same as b in a (note reversed operands).
[ "Same", "as", "b", "in", "a", "(note", "reversed", "operands)." ]
def contains(a, b): return b in a
['def', 'contains(a,', 'b):', 'return', 'b', 'in', 'a']
280,899
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
graphs.py
VatxtBidirModel.cl_loss_from_embedding
cl_loss_from_embedding
Compute classification loss from embedding.
[ "Compute", "classification", "loss", "from", "embedding." ]
def cl_loss_from_embedding(self, embedded, inputs=None, return_intermediates=False): if inputs is None: inputs = self.cl_inputs out = [] for (layer_name, emb, inp) in zip(['lstm', 'lstm_reverse'], embedded, inputs): out.append(self.layers[layer_name](emb, inp.state, inp.length)) (lstm_ou...
['def', 'cl_loss_from_embedding(self,', 'embedded,', 'inputs=None,', 'return_intermediates=False):', 'if', 'inputs', 'is', 'None:', 'inputs', '=', 'self.cl_inputs', 'out', '=', '[]', 'for', '(layer_name,', 'emb,', 'inp)', 'in', "zip(['lstm',", "'lstm_reverse'],", 'embedded,', 'inputs):', 'out.append(self.layers[layer_n...
20,375
salesforce/CodeRL
trainer_tf.py
TFTrainer.train
train
Train method to train the model.
[ "Train", "method", "to", "train", "the", "model." ]
def train(self) -> None: train_ds = self.get_train_tfdataset() if self.args.debug: tf.summary.trace_on(graph=True, profiler=True) self.gradient_accumulator.reset() num_update_steps_per_epoch = self.num_train_examples / self.total_train_batch_size approx = math.floor if self.args.dataloader_d...
['def', 'train(self)', '->', 'None:', 'train_ds', '=', 'self.get_train_tfdataset()', 'if', 'self.args.debug:', 'tf.summary.trace_on(graph=True,', 'profiler=True)', 'self.gradient_accumulator.reset()', 'num_update_steps_per_epoch', '=', 'self.num_train_examples', '/', 'self.total_train_batch_size', 'approx', '=', 'math....
494,197
TrellixVulnTeam/Unsupervised_Learning_HFI7
test_interactiveshell.py
InteractiveShellTestCase.test_gh_597
test_gh_597
Pretty-printing lists of objects with non-ascii reprs may cause problems.
[ "Pretty-printing", "lists", "of", "objects", "with", "non-ascii", "reprs", "may", "cause", "problems." ]
def test_gh_597(self): class Spam(object): def __repr__(self): return 'é' * 50 import IPython.core.formatters f = IPython.core.formatters.PlainTextFormatter() f([Spam(), Spam()])
['def', 'test_gh_597(self):', 'class', 'Spam(object):', 'def', '__repr__(self):', 'return', "'é'", '*', '50', 'import', 'IPython.core.formatters', 'f', '=', 'IPython.core.formatters.PlainTextFormatter()', 'f([Spam(),', 'Spam()])']
448,520
HamPerdredes/SOOD
sample_tools.py
xywha2rbox
xywha2rbox
Random Sampling within rotate boxes.
[ "Random", "Sampling", "within", "rotate", "boxes." ]
def xywha2rbox(rotate_boxes, gpu_device, h=1024, w=1024, img_meta=None, ret_instance_pts=False, ratio=0.25, ret_base_ang=False, score_map=None, topk=False): cls_labels = rotate_boxes[:, -1] (obj_masks, _) = multi_apply(xywha2mask_single, rotate_boxes[:, :-2]) num_obj = len(obj_masks) obj_masks = torch.s...
['def', 'xywha2rbox(rotate_boxes,', 'gpu_device,', 'h=1024,', 'w=1024,', 'img_meta=None,', 'ret_instance_pts=False,', 'ratio=0.25,', 'ret_base_ang=False,', 'score_map=None,', 'topk=False):', 'cls_labels', '=', 'rotate_boxes[:,', '-1]', '(obj_masks,', '_)', '=', 'multi_apply(xywha2mask_single,', 'rotate_boxes[:,', ':-2]...
879,493
hroark-architect/aquitania
doji.py
Doji.indicator_logic
indicator_logic
Logic of the indicator that will be run candle by candle.
[ "Logic", "of", "the", "indicator", "that", "will", "be", "run", "candle", "by", "candle." ]
def indicator_logic(self, candle): (profit, loss, entry) = (0.0, 0.0, 0.0) self.up = candle.upper_shadow(True) < candle.lower_shadow(True) is_ok = candle.is_doji(self.up) if is_ok: loss = candle.close[self.up] * 0.997 profit = candle.close[self.up] * 1.003 entry = candle.close[se...
['def', 'indicator_logic(self,', 'candle):', '(profit,', 'loss,', 'entry)', '=', '(0.0,', '0.0,', '0.0)', 'self.up', '=', 'candle.upper_shadow(True)', '<', 'candle.lower_shadow(True)', 'is_ok', '=', 'candle.is_doji(self.up)', 'if', 'is_ok:', 'loss', '=', 'candle.close[self.up]', '*', '0.997', 'profit', '=', 'candle.clo...
34,192
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
gym_problems.py
GymRealDiscreteProblem.collect_statistics_and_generate_debug_image
collect_statistics_and_generate_debug_image
Collects info required to calculate mean reward.
[ "Collects", "info", "required", "to", "calculate", "mean", "reward." ]
def collect_statistics_and_generate_debug_image(self, index, observation, reward, done, action): self.statistics.sum_of_rewards_current_episode += reward if done and (not self.statistics.last_done): self.statistics.number_of_dones += int(done) self.statistics.sum_of_rewards += self.statistics.su...
['def', 'collect_statistics_and_generate_debug_image(self,', 'index,', 'observation,', 'reward,', 'done,', 'action):', 'self.statistics.sum_of_rewards_current_episode', '+=', 'reward', 'if', 'done', 'and', '(not', 'self.statistics.last_done):', 'self.statistics.number_of_dones', '+=', 'int(done)', 'self.statistics.sum_...
964,880
pythonlessons/mltu
layers.py
PositionalEmbedding.compute_mask
compute_mask
Computes the mask to be applied to the embeddings.
[ "Computes", "the", "mask", "to", "be", "applied", "to", "the", "embeddings." ]
def compute_mask(self, *args, **kwargs): if hasattr(self, 'embedding'): return self.embedding.compute_mask(*args, **kwargs) else: return None
['def', 'compute_mask(self,', '*args,', '**kwargs):', 'if', 'hasattr(self,', "'embedding'):", 'return', 'self.embedding.compute_mask(*args,', '**kwargs)', 'else:', 'return', 'None']
631,023
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform
base.py
Index.is_type_compatible
is_type_compatible
Whether the index type is compatible with the provided type.
[ "Whether", "the", "index", "type", "is", "compatible", "with", "the", "provided", "type." ]
def is_type_compatible(self, kind) -> bool: return kind == self.inferred_type
['def', 'is_type_compatible(self,', 'kind)', '->', 'bool:', 'return', 'kind', '==', 'self.inferred_type']
82,878
cyberdelia/metrology
histogram.py
Histogram.mean
mean
Returns the mean value.
[ "Returns", "the", "mean", "value." ]
def mean(self): if self.counter.value > 0: return self.sum.value / self.counter.value return 0.0
['def', 'mean(self):', 'if', 'self.counter.value', '>', '0:', 'return', 'self.sum.value', '/', 'self.counter.value', 'return', '0.0']
286,115
Katja-M/Python_NaturalLanguageProcessing
association.py
BigramAssocMeasures.dice
dice
Scores bigrams using Dice's coefficient.
[ "Scores", "bigrams", "using", "Dice's", "coefficient." ]
def dice(n_ii, n_ix_xi_tuple, n_xx): (n_ix, n_xi) = n_ix_xi_tuple return 2 * n_ii / (n_ix + n_xi)
['def', 'dice(n_ii,', 'n_ix_xi_tuple,', 'n_xx):', '(n_ix,', 'n_xi)', '=', 'n_ix_xi_tuple', 'return', '2', '*', 'n_ii', '/', '(n_ix', '+', 'n_xi)']
866,582
hayd/pep8radius
util.py
remove
remove
Delete file filename and don't raise if missing.
[ "Delete", "file", "filename", "and", "don't", "raise", "if", "missing." ]
def remove(filename): try: os.remove(filename) except OSError: pass
['def', 'remove(filename):', 'try:', 'os.remove(filename)', 'except', 'OSError:', 'pass']
279,771
devashish-patel/webcam-motion-detector
util.py
create_hosts_whitelist
create_hosts_whitelist
This whitelist can be used to restrict websocket or other connections to only those explicitly originating from approved hosts.
[ "This", "whitelist", "can", "be", "used", "to", "restrict", "websocket", "or", "other", "connections", "to", "only", "those", "explicitly", "originating", "from", "approved", "hosts." ]
def create_hosts_whitelist(host_list, port): if not host_list: return ['localhost:' + str(port)] hosts = [] for host in host_list: if '*' in host: log.warning('Host wildcard %r will allow connections originating from multiple (or possibly all) hostnames or IPs. Use non-wildcard v...
['def', 'create_hosts_whitelist(host_list,', 'port):', 'if', 'not', 'host_list:', 'return', "['localhost:'", '+', 'str(port)]', 'hosts', '=', '[]', 'for', 'host', 'in', 'host_list:', 'if', "'*'", 'in', 'host:', "log.warning('Host", 'wildcard', '%r', 'will', 'allow', 'connections', 'originating', 'from', 'multiple', '(o...
977,465
weimin17/Object-Detection_HelmetDetection
dragnn_model_saver_lib_test.py
DragnnModelSaverLibTest.GetHookNodeNames
GetHookNodeNames
Returns hook node names to use in tests.
[ "Returns", "hook", "node", "names", "to", "use", "in", "tests." ]
def GetHookNodeNames(self, master_spec): component_name = None for component_spec in master_spec.component: if component_spec.fixed_feature: component_name = component_spec.name break if not component_name: raise ValueError('Cannot infer hook node names') non_aver...
['def', 'GetHookNodeNames(self,', 'master_spec):', 'component_name', '=', 'None', 'for', 'component_spec', 'in', 'master_spec.component:', 'if', 'component_spec.fixed_feature:', 'component_name', '=', 'component_spec.name', 'break', 'if', 'not', 'component_name:', 'raise', "ValueError('Cannot", 'infer', 'hook', 'node',...
753,297
albertonietos/artificial-intelligence
misc_util.py
get_npy_pkg_dir
get_npy_pkg_dir
Return the path where to find the npy-pkg-config directory.
[ "Return", "the", "path", "where", "to", "find", "the", "npy-pkg-config", "directory." ]
def get_npy_pkg_dir(): import numpy d = os.path.join(os.path.dirname(numpy.__file__), 'core', 'lib', 'npy-pkg-config') return d
['def', 'get_npy_pkg_dir():', 'import', 'numpy', 'd', '=', 'os.path.join(os.path.dirname(numpy.__file__),', "'core',", "'lib',", "'npy-pkg-config')", 'return', 'd']
62,887
xiaoaleiBLUE/computer_vision
dataset.py
strQ2B
strQ2B
Convert full-width character to half-width character.
[ "Convert", "full-width", "character", "to", "half-width", "character." ]
def strQ2B(uchar): inside_code = ord(uchar) if inside_code == 12288: inside_code = 32 elif inside_code >= 65281 and inside_code <= 65374: inside_code -= 65248 return chr(inside_code)
['def', 'strQ2B(uchar):', 'inside_code', '=', 'ord(uchar)', 'if', 'inside_code', '==', '12288:', 'inside_code', '=', '32', 'elif', 'inside_code', '>=', '65281', 'and', 'inside_code', '<=', '65374:', 'inside_code', '-=', '65248', 'return', 'chr(inside_code)']
501,389
triaquae/triaquae
__init__.py
Field.pre_save
pre_save
Returns field's value just before saving.
[ "Returns", "field's", "value", "just", "before", "saving." ]
def pre_save(self, model_instance, add): return getattr(model_instance, self.attname)
['def', 'pre_save(self,', 'model_instance,', 'add):', 'return', 'getattr(model_instance,', 'self.attname)']
423,526
43Carrig/recurrent_neural_networks_practice
anno.py
dup
dup
Recursively copies annotations in an AST tree.
[ "Recursively", "copies", "annotations", "in", "an", "AST", "tree." ]
def dup(node, copy_map, field_name='___pyct_anno'): for n in gast.walk(node): for k in copy_map: if hasanno(n, k, field_name): setanno(n, copy_map[k], getanno(n, k, field_name), field_name)
['def', 'dup(node,', 'copy_map,', "field_name='___pyct_anno'):", 'for', 'n', 'in', 'gast.walk(node):', 'for', 'k', 'in', 'copy_map:', 'if', 'hasanno(n,', 'k,', 'field_name):', 'setanno(n,', 'copy_map[k],', 'getanno(n,', 'k,', 'field_name),', 'field_name)']
312,375
xmed-lab/URN
test_backbone.py
check_norm_state
check_norm_state
Check if norm layer is in correct train state.
[ "Check", "if", "norm", "layer", "is", "in", "correct", "train", "state." ]
def check_norm_state(modules, train_state): for mod in modules: if isinstance(mod, _BatchNorm): if mod.training != train_state: return False return True
['def', 'check_norm_state(modules,', 'train_state):', 'for', 'mod', 'in', 'modules:', 'if', 'isinstance(mod,', '_BatchNorm):', 'if', 'mod.training', '!=', 'train_state:', 'return', 'False', 'return', 'True']
930,433
lalwanii26/openscope-barcodingstim
behavior.py
GNGFlashStimulus.hit
hit
A hit was triggered.
[ "A", "hit", "was", "triggered." ]
def hit(self): self._available = False self.sigHit.emit() logging.debug('Hit @ {}'.format(self.update_count))
['def', 'hit(self):', 'self._available', '=', 'False', 'self.sigHit.emit()', "logging.debug('Hit", '@', "{}'.format(self.update_count))"]
757,467
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
network_units.py
embedding_lookup
embedding_lookup
Performs a weighted embedding lookup.
[ "Performs", "a", "weighted", "embedding", "lookup." ]
def embedding_lookup(embedding_matrix, indices, ids, weights, size): embeddings = tf.nn.embedding_lookup([embedding_matrix], ids) broadcast_weights_shape = tf.concat([tf.shape(weights), [1]], 0) embeddings *= tf.reshape(weights, broadcast_weights_shape) embeddings = tf.unsorted_segment_sum(embeddings, i...
['def', 'embedding_lookup(embedding_matrix,', 'indices,', 'ids,', 'weights,', 'size):', 'embeddings', '=', 'tf.nn.embedding_lookup([embedding_matrix],', 'ids)', 'broadcast_weights_shape', '=', 'tf.concat([tf.shape(weights),', '[1]],', '0)', 'embeddings', '*=', 'tf.reshape(weights,', 'broadcast_weights_shape)', 'embeddi...
28,488
zfergus/face-preserving-style-transfer
image_transform_net.py
ResidualBlock.forward
forward
Forward the input through the block.
[ "Forward", "the", "input", "through", "the", "block." ]
def forward(self, x): residual = x[:, :, 2:-2, 2:-2] out = self.nonlinearity(self.norm_conv1(self.conv1(x))) out = self.norm_conv2(self.conv2(out)) return out + residual
['def', 'forward(self,', 'x):', 'residual', '=', 'x[:,', ':,', '2:-2,', '2:-2]', 'out', '=', 'self.nonlinearity(self.norm_conv1(self.conv1(x)))', 'out', '=', 'self.norm_conv2(self.conv2(out))', 'return', 'out', '+', 'residual']
558,239
AIChallenger/AI_Challenger_2017
image_processing.py
distort_image
distort_image
Perform random distortions on an image.
[ "Perform", "random", "distortions", "on", "an", "image." ]
def distort_image(image, thread_id): with tf.name_scope('flip_horizontal', values=[image]): image = tf.image.random_flip_left_right(image) color_ordering = thread_id % 2 with tf.name_scope('distort_color', values=[image]): if color_ordering == 0: image = tf.image.random_brightnes...
['def', 'distort_image(image,', 'thread_id):', 'with', "tf.name_scope('flip_horizontal',", 'values=[image]):', 'image', '=', 'tf.image.random_flip_left_right(image)', 'color_ordering', '=', 'thread_id', '%', '2', 'with', "tf.name_scope('distort_color',", 'values=[image]):', 'if', 'color_ordering', '==', '0:', 'image', ...
86,836
mme/vergeml
io.py
SourcePlugin.num_samples
num_samples
Returns the total number of samples available in the split.
[ "Returns", "the", "total", "number", "of", "samples", "available", "in", "the", "split." ]
def num_samples(self, split: str) -> int: raise NotImplementedError
['def', 'num_samples(self,', 'split:', 'str)', '->', 'int:', 'raise', 'NotImplementedError']
931,535
arshpreetsingh/quantopian-machinelearning
parser.py
Parser.parse
parse
Parse the whole template into a `Template` node.
[ "Parse", "the", "whole", "template", "into", "a", "`Template`", "node." ]
def parse(self): result = nodes.Template(self.subparse(), lineno=1) result.set_environment(self.environment) return result
['def', 'parse(self):', 'result', '=', 'nodes.Template(self.subparse(),', 'lineno=1)', 'result.set_environment(self.environment)', 'return', 'result']
887,609
weimin17/Object-Detection_HelmetDetection
variational_neural_bandit_model.py
VariationalNeuralBanditModel.build_action_noise
build_action_noise
Defines a model for additive noise per action, and its KL term.
[ "Defines", "a", "model", "for", "additive", "noise", "per", "action,", "and", "its", "KL", "term." ]
def build_action_noise(self): noise_sigma_mu = self.build_mu_variable([1, self.n_out]) + self.inverse_sigma_transform(self.hparams.noise_sigma) noise_sigma_sigma = self.sigma_transform(self.build_sigma_variable([1, self.n_out])) pre_noise_sigma = noise_sigma_mu + tf.random_normal([1, self.n_out]) * noise_si...
['def', 'build_action_noise(self):', 'noise_sigma_mu', '=', 'self.build_mu_variable([1,', 'self.n_out])', '+', 'self.inverse_sigma_transform(self.hparams.noise_sigma)', 'noise_sigma_sigma', '=', 'self.sigma_transform(self.build_sigma_variable([1,', 'self.n_out]))', 'pre_noise_sigma', '=', 'noise_sigma_mu', '+', 'tf.ran...
762,308
AEProgrammer/object_detection
mask_rcnn_heads.py
mask_rcnn_fcn_head_v1upXconvs
mask_rcnn_fcn_head_v1upXconvs
v1upXconvs design: X * (conv 3x3), convT 2x2.
[ "v1upXconvs", "design:", "X", "*", "(conv", "3x3),", "convT", "2x2." ]
def mask_rcnn_fcn_head_v1upXconvs(model, blob_in, dim_in, spatial_scale, num_convs): current = model.RoIFeatureTransform(blob_in, blob_out='_[mask]_roi_feat', blob_rois='mask_rois', method=cfg.MRCNN.ROI_XFORM_METHOD, resolution=cfg.MRCNN.ROI_XFORM_RESOLUTION, sampling_ratio=cfg.MRCNN.ROI_XFORM_SAMPLING_RATIO, spati...
['def', 'mask_rcnn_fcn_head_v1upXconvs(model,', 'blob_in,', 'dim_in,', 'spatial_scale,', 'num_convs):', 'current', '=', 'model.RoIFeatureTransform(blob_in,', "blob_out='_[mask]_roi_feat',", "blob_rois='mask_rois',", 'method=cfg.MRCNN.ROI_XFORM_METHOD,', 'resolution=cfg.MRCNN.ROI_XFORM_RESOLUTION,', 'sampling_ratio=cfg....
772,776
devashish-patel/webcam-motion-detector
config_manager.py
BaseJSONConfigManager.set
set
Store the given config data.
[ "Store", "the", "given", "config", "data." ]
def set(self, section_name, data): filename = self.file_name(section_name) self.ensure_config_dir_exists() if PY3: f = io.open(filename, 'w', encoding='utf-8') else: f = open(filename, 'wb') with f: json.dump(data, f, indent=2)
['def', 'set(self,', 'section_name,', 'data):', 'filename', '=', 'self.file_name(section_name)', 'self.ensure_config_dir_exists()', 'if', 'PY3:', 'f', '=', 'io.open(filename,', "'w',", "encoding='utf-8')", 'else:', 'f', '=', 'open(filename,', "'wb')", 'with', 'f:', 'json.dump(data,', 'f,', 'indent=2)']
980,535
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
template.py
Base.adopt
adopt
Adds child to this objecs children and sets the childs parent.
[ "Adds", "child", "to", "this", "objecs", "children", "and", "sets", "the", "childs", "parent." ]
def adopt(self, child, index=-1): self.children.insert(index, child) child.parent = self
['def', 'adopt(self,', 'child,', 'index=-1):', 'self.children.insert(index,', 'child)', 'child.parent', '=', 'self']
17,002
palVikram/Machine-Learning-using-Python
opt.py
local_useless_inc_subtensor_alloc
local_useless_inc_subtensor_alloc
Replaces an [Advanced]IncSubtensor[1], whose increment is an `alloc` of a fully or partially broadcastable variable, by one that skips the intermediate `alloc` where possible.
[ "Replaces", "an", "[Advanced]IncSubtensor[1],", "whose", "increment", "is", "an", "`alloc`", "of", "a", "fully", "or", "partially", "broadcastable", "variable,", "by", "one", "that", "skips", "the", "intermediate", "`alloc`", "where", "possible." ]
def local_useless_inc_subtensor_alloc(node): if isinstance(node.op, (IncSubtensor, AdvancedIncSubtensor, AdvancedIncSubtensor1)): x = node.inputs[0] y = node.inputs[1] i = node.inputs[2:] if y.owner is not None and isinstance(y.owner.op, T.Alloc): z = y.owner.inputs[0] ...
['def', 'local_useless_inc_subtensor_alloc(node):', 'if', 'isinstance(node.op,', '(IncSubtensor,', 'AdvancedIncSubtensor,', 'AdvancedIncSubtensor1)):', 'x', '=', 'node.inputs[0]', 'y', '=', 'node.inputs[1]', 'i', '=', 'node.inputs[2:]', 'if', 'y.owner', 'is', 'not', 'None', 'and', 'isinstance(y.owner.op,', 'T.Alloc):',...
714,455
43Carrig/recurrent_neural_networks_practice
tbtools.py
Traceback.render_full
render_full
Render the Full HTML page with the traceback info.
[ "Render", "the", "Full", "HTML", "page", "with", "the", "traceback", "info." ]
def render_full(self, evalex=False, secret=None, evalex_trusted=True): exc = escape(self.exception) return PAGE_HTML % {'evalex': evalex and 'true' or 'false', 'evalex_trusted': evalex_trusted and 'true' or 'false', 'console': 'false', 'title': exc, 'exception': exc, 'exception_type': escape(self.exception_type...
['def', 'render_full(self,', 'evalex=False,', 'secret=None,', 'evalex_trusted=True):', 'exc', '=', 'escape(self.exception)', 'return', 'PAGE_HTML', '%', "{'evalex':", 'evalex', 'and', "'true'", 'or', "'false',", "'evalex_trusted':", 'evalex_trusted', 'and', "'true'", 'or', "'false',", "'console':", "'false',", "'title'...
340,309
enuguru/artificial_intelligence_and_machine_
writing.py
CLEAR
CLEAR
This policy DELETES all existing segments and only writes the new segment.
[ "This", "policy", "DELETES", "all", "existing", "segments", "and", "only", "writes", "the", "new", "segment." ]
def CLEAR(writer, segments): return []
['def', 'CLEAR(writer,', 'segments):', 'return', '[]']
133,221
bayerj/theano-rnn
hf_example.py
test_real
test_real
Test RNN with real-valued outputs.
[ "Test", "RNN", "with", "real-valued", "outputs." ]
def test_real(n_updates=100): n_hidden = 10 n_in = 5 n_out = 3 n_steps = 10 n_seq = 1000 np.random.seed(0) seq = np.random.randn(n_seq, n_steps, n_in) targets = np.zeros((n_seq, n_steps, n_out)) targets[:, 1:, 0] = seq[:, :-1, 3] targets[:, 1:, 1] = seq[:, :-1, 2] targets[:, ...
['def', 'test_real(n_updates=100):', 'n_hidden', '=', '10', 'n_in', '=', '5', 'n_out', '=', '3', 'n_steps', '=', '10', 'n_seq', '=', '1000', 'np.random.seed(0)', 'seq', '=', 'np.random.randn(n_seq,', 'n_steps,', 'n_in)', 'targets', '=', 'np.zeros((n_seq,', 'n_steps,', 'n_out))', 'targets[:,', '1:,', '0]', '=', 'seq[:,'...
354,456
matsu0228/nlp-jp
completion_plain.py
CompletionPlain.show_items
show_items
Shows the completion widget with 'items' at the position specified by 'cursor'.
[ "Shows", "the", "completion", "widget", "with", "'items'", "at", "the", "position", "specified", "by", "'cursor'." ]
def show_items(self, cursor, items): if not items: return self.cancel_completion() strng = text.columnize(items) self._console_widget._fill_temporary_buffer(cursor, strng, html=False)
['def', 'show_items(self,', 'cursor,', 'items):', 'if', 'not', 'items:', 'return', 'self.cancel_completion()', 'strng', '=', 'text.columnize(items)', 'self._console_widget._fill_temporary_buffer(cursor,', 'strng,', 'html=False)']
805,162
noahshinn024/reflexion
rs_executor.py
revert_asserts
revert_asserts
Revert all assert_eq_nopanic! asserts back into assert_eq! asserts.
[ "Revert", "all", "assert_eq_nopanic!", "asserts", "back", "into", "assert_eq!", "asserts." ]
def revert_asserts(code: str) -> str: normal = code.replace('assert_eq_nopanic!', 'assert_eq!') return normal[len(assert_no_panic):]
['def', 'revert_asserts(code:', 'str)', '->', 'str:', 'normal', '=', "code.replace('assert_eq_nopanic!',", "'assert_eq!')", 'return', 'normal[len(assert_no_panic):]']
340,432
VarunJoshi10/Traffic-Signal-Violation-Detection-System-Using--
sort.py
KalmanBoxTracker.get_state
get_state
Returns the current bounding box estimate.
[ "Returns", "the", "current", "bounding", "box", "estimate." ]
def get_state(self): return convert_x_to_bbox(self.kf.x)
['def', 'get_state(self):', 'return', 'convert_x_to_bbox(self.kf.x)']
903,798
microsoft/maro
parsers.py
parse_vessels
parse_vessels
Parse specified vessel configurations.
[ "Parse", "specified", "vessel", "configurations." ]
def parse_vessels(conf: dict) -> (Dict[str, int], List[VesselSetting]): mapping: Dict[str, int] = {} vessels: List[VesselSetting] = [] index = 0 for (vessel_name, vessel_node) in conf.items(): mapping[vessel_name] = index sailing = vessel_node['sailing'] parking = vessel_node['pa...
['def', 'parse_vessels(conf:', 'dict)', '->', '(Dict[str,', 'int],', 'List[VesselSetting]):', 'mapping:', 'Dict[str,', 'int]', '=', '{}', 'vessels:', 'List[VesselSetting]', '=', '[]', 'index', '=', '0', 'for', '(vessel_name,', 'vessel_node)', 'in', 'conf.items():', 'mapping[vessel_name]', '=', 'index', 'sailing', '=', ...
628,435
avalonstrel/SketchBERT
utils.py
extend_strokes
extend_strokes
Pad stroke-3 format to given length.
[ "Pad", "stroke-3", "format", "to", "given", "length." ]
def extend_strokes(stroke, max_len=250): result = np.zeros((max_len, stroke.shape[1]), dtype=float) l = len(stroke) assert l <= max_len result[:l] = stroke return result
['def', 'extend_strokes(stroke,', 'max_len=250):', 'result', '=', 'np.zeros((max_len,', 'stroke.shape[1]),', 'dtype=float)', 'l', '=', 'len(stroke)', 'assert', 'l', '<=', 'max_len', 'result[:l]', '=', 'stroke', 'return', 'result']
350,971
kubeflow/pipelines
_data_passing.py
get_serializer_func_for_type_name
get_serializer_func_for_type_name
Find the serializer code for the given type name.
[ "Find", "the", "serializer", "code", "for", "the", "given", "type", "name." ]
def get_serializer_func_for_type_name(type_name: str) -> Optional[Callable]: try: return type_name_to_serializer.get(type_annotation_utils.get_short_type_name(type_name), None) except: return None
['def', 'get_serializer_func_for_type_name(type_name:', 'str)', '->', 'Optional[Callable]:', 'try:', 'return', 'type_name_to_serializer.get(type_annotation_utils.get_short_type_name(type_name),', 'None)', 'except:', 'return', 'None']
780,045
zihuitang/medical_AI_platform
__init__.py
Wm.wm_title
wm_title
Set the title of this widget.
[ "Set", "the", "title", "of", "this", "widget." ]
def wm_title(self, string=None): return self.tk.call('wm', 'title', self._w, string)
['def', 'wm_title(self,', 'string=None):', 'return', "self.tk.call('wm',", "'title',", 'self._w,', 'string)']
284,185
zehuichen123/AutoAlignV2
groupfree3d_head.py
GroupFree3DHead.get_targets_single
get_targets_single
Generate targets of GroupFree3D head for single batch.
[ "Generate", "targets", "of", "GroupFree3D", "head", "for", "single", "batch." ]
def get_targets_single(self, points, gt_bboxes_3d, gt_labels_3d, pts_semantic_mask=None, pts_instance_mask=None, max_gt_nums=None, seed_points=None, seed_indices=None, candidate_indices=None, seed_points_obj_topk=4): assert self.bbox_coder.with_rot or pts_semantic_mask is not None gt_bboxes_3d = gt_bboxes_3d.to...
['def', 'get_targets_single(self,', 'points,', 'gt_bboxes_3d,', 'gt_labels_3d,', 'pts_semantic_mask=None,', 'pts_instance_mask=None,', 'max_gt_nums=None,', 'seed_points=None,', 'seed_indices=None,', 'candidate_indices=None,', 'seed_points_obj_topk=4):', 'assert', 'self.bbox_coder.with_rot', 'or', 'pts_semantic_mask', '...
416,853
matsu0228/nlp-jp
common.py
reflective_transformation
reflective_transformation
Compute reflective transformation and its gradient.
[ "Compute", "reflective", "transformation", "and", "its", "gradient." ]
def reflective_transformation(y, lb, ub): if in_bounds(y, lb, ub): return (y, np.ones_like(y)) lb_finite = np.isfinite(lb) ub_finite = np.isfinite(ub) x = y.copy() g_negative = np.zeros_like(y, dtype=bool) mask = lb_finite & ~ub_finite x[mask] = np.maximum(y[mask], 2 * lb[mask] - y[m...
['def', 'reflective_transformation(y,', 'lb,', 'ub):', 'if', 'in_bounds(y,', 'lb,', 'ub):', 'return', '(y,', 'np.ones_like(y))', 'lb_finite', '=', 'np.isfinite(lb)', 'ub_finite', '=', 'np.isfinite(ub)', 'x', '=', 'y.copy()', 'g_negative', '=', 'np.zeros_like(y,', 'dtype=bool)', 'mask', '=', 'lb_finite', '&', '~ub_finit...
805,708
utiasDSL/gym-pybullet-drones
aer1216_fall2020_hw1_ctrl.py
HW1Control.reset
reset
Resets the controller counter.
[ "Resets", "the", "controller", "counter." ]
def reset(self): self.control_counter = 0
['def', 'reset(self):', 'self.control_counter', '=', '0']
234,427