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
Ruturaj123/Flowchart-Detection
parser.py
ReferenceResolver.from_visitor
from_visitor
A factory function for building a ReferenceResolver from a visitor.
[ "A", "factory", "function", "for", "building", "a", "ReferenceResolver", "from", "a", "visitor." ]
def from_visitor(cls, visitor, doc_index, **kwargs): is_class = {name: tf_inspect.isclass(visitor.index[name]) for (name, obj) in visitor.index.items()} is_module = {name: tf_inspect.ismodule(visitor.index[name]) for (name, obj) in visitor.index.items()} return cls(duplicate_of=visitor.duplicate_of, doc_ind...
['def', 'from_visitor(cls,', 'visitor,', 'doc_index,', '**kwargs):', 'is_class', '=', '{name:', 'tf_inspect.isclass(visitor.index[name])', 'for', '(name,', 'obj)', 'in', 'visitor.index.items()}', 'is_module', '=', '{name:', 'tf_inspect.ismodule(visitor.index[name])', 'for', '(name,', 'obj)', 'in', 'visitor.index.items(...
606,735
voxel51/fiftyone
openlabel.py
OpenLABELAnnotations.parse_labels
parse_labels
Parses a single OpenLABEL labels file.
[ "Parses", "a", "single", "OpenLABEL", "labels", "file." ]
def parse_labels(self, base_dir, labels_path): abs_path = labels_path if not os.path.isabs(abs_path): abs_path = os.path.join(base_dir, labels_path) labels = etas.load_json(abs_path).get('openlabel', {}) label_file_id = _remove_ext(labels_path) potential_file_ids = [label_file_id] metada...
['def', 'parse_labels(self,', 'base_dir,', 'labels_path):', 'abs_path', '=', 'labels_path', 'if', 'not', 'os.path.isabs(abs_path):', 'abs_path', '=', 'os.path.join(base_dir,', 'labels_path)', 'labels', '=', "etas.load_json(abs_path).get('openlabel',", '{})', 'label_file_id', '=', '_remove_ext(labels_path)', 'potential_...
584,126
hamza-murad/AALU
visual_recognition_v3.py
ClassResult.from_dict
from_dict
Initialize a ClassResult object from a json dictionary.
[ "Initialize", "a", "ClassResult", "object", "from", "a", "json", "dictionary." ]
def from_dict(cls, _dict: Dict) -> 'ClassResult': args = {} valid_keys = ['class_', 'class', 'score', 'type_hierarchy'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError('Unrecognized keys detected in dictionary for class ClassResult: ' + ', '.join(bad_keys)) if 'c...
['def', 'from_dict(cls,', '_dict:', 'Dict)', '->', "'ClassResult':", 'args', '=', '{}', 'valid_keys', '=', "['class_',", "'class',", "'score',", "'type_hierarchy']", 'bad_keys', '=', 'set(_dict.keys())', '-', 'set(valid_keys)', 'if', 'bad_keys:', 'raise', "ValueError('Unrecognized", 'keys', 'detected', 'in', 'dictionar...
6,139
Speedwagon13/CS-3600-Introduction-to--
_pyio.py
BytesIO.read1
read1
This is the same as read.
[ "This", "is", "the", "same", "as", "read." ]
def read1(self, n): return self.read(n)
['def', 'read1(self,', 'n):', 'return', 'self.read(n)']
140,042
tobegit3hub/deep_image_model
variables.py
get_unique_variable
get_unique_variable
Gets the variable uniquely identified by that var_op_name.
[ "Gets", "the", "variable", "uniquely", "identified", "by", "that", "var_op_name." ]
def get_unique_variable(var_op_name): candidates = get_variables(scope=var_op_name) if not candidates: raise ValueError('Couldnt find variable %s' % var_op_name) for candidate in candidates: if candidate.op.name == var_op_name: return candidate raise ValueError('Variable %s d...
['def', 'get_unique_variable(var_op_name):', 'candidates', '=', 'get_variables(scope=var_op_name)', 'if', 'not', 'candidates:', 'raise', "ValueError('Couldnt", 'find', 'variable', "%s'", '%', 'var_op_name)', 'for', 'candidate', 'in', 'candidates:', 'if', 'candidate.op.name', '==', 'var_op_name:', 'return', 'candidate',...
181,320
gunthercox/ChatterBot
datastructures.py
MIMEAccept.accept_html
accept_html
True if this object accepts HTML.
[ "True", "if", "this", "object", "accepts", "HTML." ]
def accept_html(self): return 'text/html' in self or 'application/xhtml+xml' in self or self.accept_xhtml
['def', 'accept_html(self):', 'return', "'text/html'", 'in', 'self', 'or', "'application/xhtml+xml'", 'in', 'self', 'or', 'self.accept_xhtml']
482,050
f-dangel/cockpit
run_mnist_mlp.py
const_schedule
const_schedule
Constant schedule with a small decay at the end.
[ "Constant", "schedule", "with", "a", "small", "decay", "at", "the", "end." ]
def const_schedule(num_epochs): return lambda epoch: 1.0
['def', 'const_schedule(num_epochs):', 'return', 'lambda', 'epoch:', '1.0']
493,225
devashish-patel/webcam-motion-detector
channels.py
ZMQSocketChannel.get_msg
get_msg
Gets a message if there is one that is ready.
[ "Gets", "a", "message", "if", "there", "is", "one", "that", "is", "ready." ]
def get_msg(self, block=True, timeout=None): if block: if timeout is not None: timeout *= 1000 ready = self.socket.poll(timeout) else: ready = self.socket.poll(timeout=0) if ready: return self._recv() else: raise Empty
['def', 'get_msg(self,', 'block=True,', 'timeout=None):', 'if', 'block:', 'if', 'timeout', 'is', 'not', 'None:', 'timeout', '*=', '1000', 'ready', '=', 'self.socket.poll(timeout)', 'else:', 'ready', '=', 'self.socket.poll(timeout=0)', 'if', 'ready:', 'return', 'self._recv()', 'else:', 'raise', 'Empty']
980,051
TrellixVulnTeam/Unsupervised_Learning_HFI7
zmqshell.py
ZMQInteractiveShell.init_environment
init_environment
Configure the user's environment.
[ "Configure", "the", "user's", "environment." ]
def init_environment(self): env = os.environ env['TERM'] = 'xterm-color' env['CLICOLOR'] = '1' env['PAGER'] = 'cat' env['GIT_PAGER'] = 'cat'
['def', 'init_environment(self):', 'env', '=', 'os.environ', "env['TERM']", '=', "'xterm-color'", "env['CLICOLOR']", '=', "'1'", "env['PAGER']", '=', "'cat'", "env['GIT_PAGER']", '=', "'cat'"]
447,861
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
preprocessing.py
decode_images
decode_images
Decodes a tensor of image strings.
[ "Decodes", "a", "tensor", "of", "image", "strings." ]
def decode_images(image_strs): return tf.map_fn(decode_image, image_strs, dtype=tf.float32)
['def', 'decode_images(image_strs):', 'return', 'tf.map_fn(decode_image,', 'image_strs,', 'dtype=tf.float32)']
112,293
bnpy/bnpy
DCollector.py
getSize
getSize
Return the integer size of the provided dataset.
[ "Return", "the", "integer", "size", "of", "the", "provided", "dataset." ]
def getSize(Data): if Data is None: return 0 elif hasattr(Data, 'nDoc'): return Data.nDoc else: return Data.nObs
['def', 'getSize(Data):', 'if', 'Data', 'is', 'None:', 'return', '0', 'elif', 'hasattr(Data,', "'nDoc'):", 'return', 'Data.nDoc', 'else:', 'return', 'Data.nObs']
464,661
PaddlePaddle/Paddle3D
xarfile.py
XarFile.getnames
getnames
Return a list of file names in the archive.
[ "Return", "a", "list", "of", "file", "names", "in", "the", "archive." ]
def getnames(self) -> List[str]: if self.arctype == 'tar': return self._archive_fp.getnames() return self._archive_fp.namelist()
['def', 'getnames(self)', '->', 'List[str]:', 'if', 'self.arctype', '==', "'tar':", 'return', 'self._archive_fp.getnames()', 'return', 'self._archive_fp.namelist()']
778,108
ashwanitanwar/nmt-transfer-learning-xlm-r
dictionary.py
Dictionary.update
update
Updates counts from new dictionary.
[ "Updates", "counts", "from", "new", "dictionary." ]
def update(self, new_dict): for word in new_dict.symbols: idx2 = new_dict.indices[word] if word in self.indices: idx = self.indices[word] self.count[idx] = self.count[idx] + new_dict.count[idx2] else: idx = len(self.symbols) self.indices[word] ...
['def', 'update(self,', 'new_dict):', 'for', 'word', 'in', 'new_dict.symbols:', 'idx2', '=', 'new_dict.indices[word]', 'if', 'word', 'in', 'self.indices:', 'idx', '=', 'self.indices[word]', 'self.count[idx]', '=', 'self.count[idx]', '+', 'new_dict.count[idx2]', 'else:', 'idx', '=', 'len(self.symbols)', 'self.indices[wo...
733,705
Megvii-BaseDetection/cvpods
functions.py
find_first
find_first
Finds the index of the first instance of true in a vector or None if not found.
[ "Finds", "the", "index", "of", "the", "first", "instance", "of", "true", "in", "a", "vector", "or", "None", "if", "not", "found." ]
def find_first(arr: np.array) -> int: if len(arr) == 0: return None idx = arr.argmax() if idx == 0 and (not arr[0]): return None return idx
['def', 'find_first(arr:', 'np.array)', '->', 'int:', 'if', 'len(arr)', '==', '0:', 'return', 'None', 'idx', '=', 'arr.argmax()', 'if', 'idx', '==', '0', 'and', '(not', 'arr[0]):', 'return', 'None', 'return', 'idx']
510,822
IIM-TTIJ/MVA2023SmallObjectDetection4SpottingBirds
lad_head.py
LADHead.forward_train
forward_train
Forward train with the available label assignment (student receives from teacher).
[ "Forward", "train", "with", "the", "available", "label", "assignment", "(student", "receives", "from", "teacher)." ]
def forward_train(self, x, label_assignment_results, img_metas, gt_bboxes, gt_labels=None, gt_bboxes_ignore=None, **kwargs): outs = self(x) if gt_labels is None: loss_inputs = outs + (gt_bboxes, img_metas) else: loss_inputs = outs + (gt_bboxes, gt_labels, img_metas) losses = self.loss(*l...
['def', 'forward_train(self,', 'x,', 'label_assignment_results,', 'img_metas,', 'gt_bboxes,', 'gt_labels=None,', 'gt_bboxes_ignore=None,', '**kwargs):', 'outs', '=', 'self(x)', 'if', 'gt_labels', 'is', 'None:', 'loss_inputs', '=', 'outs', '+', '(gt_bboxes,', 'img_metas)', 'else:', 'loss_inputs', '=', 'outs', '+', '(gt_...
650,950
adamshamsudeen/vision.ai
test.py
Client.delete
delete
Like open but method is enforced to DELETE.
[ "Like", "open", "but", "method", "is", "enforced", "to", "DELETE." ]
def delete(self, *args, **kw): kw['method'] = 'DELETE' return self.open(*args, **kw)
['def', 'delete(self,', '*args,', '**kw):', "kw['method']", '=', "'DELETE'", 'return', 'self.open(*args,', '**kw)']
944,560
SALT-NLP/Adaptive-Compositional-Modules
base.py
JsonPipelineDataFormat.save
save
Save the provided data object in a json file.
[ "Save", "the", "provided", "data", "object", "in", "a", "json", "file." ]
def save(self, data: dict): with open(self.output_path, 'w') as f: json.dump(data, f)
['def', 'save(self,', 'data:', 'dict):', 'with', 'open(self.output_path,', "'w')", 'as', 'f:', 'json.dump(data,', 'f)']
409,258
gunthercox/ChatterBot
reading.py
TermInfo.min_id
min_id
Returns the lowest document ID this term appears in.
[ "Returns", "the", "lowest", "document", "ID", "this", "term", "appears", "in." ]
def min_id(self): return self._minid
['def', 'min_id(self):', 'return', 'self._minid']
484,051
Kvatsx/Artificial-Intelligence-Assignments
setup.py
visibility_define
visibility_define
Return the define value to use for NPY_VISIBILITY_HIDDEN (may be empty string).
[ "Return", "the", "define", "value", "to", "use", "for", "NPY_VISIBILITY_HIDDEN", "(may", "be", "empty", "string)." ]
def visibility_define(config): if config.check_compiler_gcc4(): return '__attribute__((visibility("hidden")))' else: return ''
['def', 'visibility_define(config):', 'if', 'config.check_compiler_gcc4():', 'return', '\'__attribute__((visibility("hidden")))\'', 'else:', 'return', "''"]
2,476
deepmind/spriteworld
shapes.py
star
star
Generate the vertices of a regular star shape.
[ "Generate", "the", "vertices", "of", "a", "regular", "star", "shape." ]
def star(num_sides, point_height=1, theta_0=0.0): point_to_center = 1 + point_height theta = 2 * np.pi / num_sides path = np.empty([2 * num_sides, 2]) for i in range(num_sides): path[2 * i] = _polar2cartesian(1, i * theta + theta_0) path[2 * i + 1] = _polar2cartesian(point_to_center, (i ...
['def', 'star(num_sides,', 'point_height=1,', 'theta_0=0.0):', 'point_to_center', '=', '1', '+', 'point_height', 'theta', '=', '2', '*', 'np.pi', '/', 'num_sides', 'path', '=', 'np.empty([2', '*', 'num_sides,', '2])', 'for', 'i', 'in', 'range(num_sides):', 'path[2', '*', 'i]', '=', '_polar2cartesian(1,', 'i', '*', 'the...
897,188
flairNLP/flair
samplers.py
FlairSampler.set_dataset
set_dataset
Initialize the data source for the FlairSampler.
[ "Initialize", "the", "data", "source", "for", "the", "FlairSampler." ]
def set_dataset(self, data_source): self.data_source = data_source self.num_samples = len(self.data_source)
['def', 'set_dataset(self,', 'data_source):', 'self.data_source', '=', 'data_source', 'self.num_samples', '=', 'len(self.data_source)']
584,757
zhyhan/TransPar
segmentation_list.py
SegmentationList.decode_target
decode_target
Decode label (each value is integer) into the corresponding RGB value.
[ "Decode", "label", "(each", "value", "is", "integer)", "into", "the", "corresponding", "RGB", "value." ]
def decode_target(self, target): target = target.copy() target[target == 255] = self.num_classes target = self.train_id_to_color[target] return Image.fromarray(target.astype(np.uint8))
['def', 'decode_target(self,', 'target):', 'target', '=', 'target.copy()', 'target[target', '==', '255]', '=', 'self.num_classes', 'target', '=', 'self.train_id_to_color[target]', 'return', 'Image.fromarray(target.astype(np.uint8))']
356,069
Alexander-Parker/youtube_nlp
server.py
Server.request_check
request_check
Check the server's state soon.
[ "Check", "the", "server's", "state", "soon." ]
def request_check(self): self._monitor.request_check()
['def', 'request_check(self):', 'self._monitor.request_check()']
970,628
pedromzadeh/numpy-based-mnist-classifier
network.py
Network.cost
cost
Compute the cost function for this `batch` of data.
[ "Compute", "the", "cost", "function", "for", "this", "`batch`", "of", "data." ]
def cost(self, batch): M = len(batch) err = 0 for (x, y) in batch: C_m = (self.feedforward(x) - y).squeeze() C_m = np.dot(C_m, C_m) err += C_m / (2 * M) return err
['def', 'cost(self,', 'batch):', 'M', '=', 'len(batch)', 'err', '=', '0', 'for', '(x,', 'y)', 'in', 'batch:', 'C_m', '=', '(self.feedforward(x)', '-', 'y).squeeze()', 'C_m', '=', 'np.dot(C_m,', 'C_m)', 'err', '+=', 'C_m', '/', '(2', '*', 'M)', 'return', 'err']
730,018
Makkar/deep-neural-network
utils.py
relu
relu
Returns the ReLU of z.
[ "Returns", "the", "ReLU", "of", "z." ]
def relu(z): s = z * (z > 0) return s
['def', 'relu(z):', 's', '=', 'z', '*', '(z', '>', '0)', 'return', 's']
519,124
Ze-Yang/Context-Transformer
solver.py
build_optimizer
build_optimizer
Build an optimizer from args.
[ "Build", "an", "optimizer", "from", "args." ]
def build_optimizer(args, model: torch.nn.Module) -> torch.optim.Optimizer: params: List[Dict[str, Any]] = [] for (key, value) in model.named_parameters(): if not value.requires_grad: continue lr = args.lr weight_decay = args.weight_decay if args.phase == 2 and args.m...
['def', 'build_optimizer(args,', 'model:', 'torch.nn.Module)', '->', 'torch.optim.Optimizer:', 'params:', 'List[Dict[str,', 'Any]]', '=', '[]', 'for', '(key,', 'value)', 'in', 'model.named_parameters():', 'if', 'not', 'value.requires_grad:', 'continue', 'lr', '=', 'args.lr', 'weight_decay', '=', 'args.weight_decay', 'i...
515,293
ArdaGunay99/Key_Detection_Unsupervised_Learning
compressor.py
LZMACompressorWrapper.compressor_file
compressor_file
Returns an instance of a compressor file object.
[ "Returns", "an", "instance", "of", "a", "compressor", "file", "object." ]
def compressor_file(self, fileobj, compresslevel=None): if compresslevel is None: return self.fileobj_factory(fileobj, 'wb', format=lzma.FORMAT_ALONE) else: return self.fileobj_factory(fileobj, 'wb', format=lzma.FORMAT_ALONE, preset=compresslevel)
['def', 'compressor_file(self,', 'fileobj,', 'compresslevel=None):', 'if', 'compresslevel', 'is', 'None:', 'return', 'self.fileobj_factory(fileobj,', "'wb',", 'format=lzma.FORMAT_ALONE)', 'else:', 'return', 'self.fileobj_factory(fileobj,', "'wb',", 'format=lzma.FORMAT_ALONE,', 'preset=compresslevel)']
256,314
huma-teknofest/Keras-RetinaNet-for-Teknofest-2019
generator.py
Generator.random_transform_group
random_transform_group
Randomly transforms each image and its annotations.
[ "Randomly", "transforms", "each", "image", "and", "its", "annotations." ]
def random_transform_group(self, image_group, annotations_group): assert len(image_group) == len(annotations_group) for index in range(len(image_group)): (image_group[index], annotations_group[index]) = self.random_transform_group_entry(image_group[index], annotations_group[index]) return (image_gro...
['def', 'random_transform_group(self,', 'image_group,', 'annotations_group):', 'assert', 'len(image_group)', '==', 'len(annotations_group)', 'for', 'index', 'in', 'range(len(image_group)):', '(image_group[index],', 'annotations_group[index])', '=', 'self.random_transform_group_entry(image_group[index],', 'annotations_g...
248,003
noahfl/densenet-sdr
dense_net.py
DenseNet.add_internal_layer
add_internal_layer
Perform H_l composite function for the layer and after concatenate input with output from composite function.
[ "Perform", "H_l", "composite", "function", "for", "the", "layer", "and", "after", "concatenate", "input", "with", "output", "from", "composite", "function." ]
def add_internal_layer(self, _input, growth_rate): if not self.bc_mode: comp_out = self.composite_function(_input, out_features=growth_rate, kernel_size=3) elif self.bc_mode: bottleneck_out = self.bottleneck(_input, out_features=growth_rate) comp_out = self.composite_function(bottleneck_...
['def', 'add_internal_layer(self,', '_input,', 'growth_rate):', 'if', 'not', 'self.bc_mode:', 'comp_out', '=', 'self.composite_function(_input,', 'out_features=growth_rate,', 'kernel_size=3)', 'elif', 'self.bc_mode:', 'bottleneck_out', '=', 'self.bottleneck(_input,', 'out_features=growth_rate)', 'comp_out', '=', 'self....
183,842
ArtificialIntelligenceToolkit/aitk.robots
robot.py
Robot.get_max_trace_length
get_max_trace_length
Get the max length of the trace in seconds.
[ "Get", "the", "max", "length", "of", "the", "trace", "in", "seconds." ]
def get_max_trace_length(self): return self.max_trace_length
['def', 'get_max_trace_length(self):', 'return', 'self.max_trace_length']
86,633
eddylau328/fyp-artificial-intelligence-ac-control-device
_download.py
ChunkedDownload.consume_next_chunk
consume_next_chunk
Consume the next chunk of the resource to be downloaded.
[ "Consume", "the", "next", "chunk", "of", "the", "resource", "to", "be", "downloaded." ]
def consume_next_chunk(self, transport): raise NotImplementedError(u'This implementation is virtual.')
['def', 'consume_next_chunk(self,', 'transport):', 'raise', "NotImplementedError(u'This", 'implementation', 'is', "virtual.')"]
215,440
Kvatsx/Artificial-Intelligence-Assignments
test_real_transforms.py
idst_2d_ref
idst_2d_ref
used as a reference in testing idst2.
[ "used", "as", "a", "reference", "in", "testing", "idst2." ]
def idst_2d_ref(x, **kwargs): x = np.array(x, copy=True) for row in range(x.shape[0]): x[row, :] = idst(x[row, :], **kwargs) for col in range(x.shape[1]): x[:, col] = idst(x[:, col], **kwargs) return x
['def', 'idst_2d_ref(x,', '**kwargs):', 'x', '=', 'np.array(x,', 'copy=True)', 'for', 'row', 'in', 'range(x.shape[0]):', 'x[row,', ':]', '=', 'idst(x[row,', ':],', '**kwargs)', 'for', 'col', 'in', 'range(x.shape[1]):', 'x[:,', 'col]', '=', 'idst(x[:,', 'col],', '**kwargs)', 'return', 'x']
77,454
devashish-patel/webcam-motion-detector
browser.py
view
view
Open a browser to view the specified location.
[ "Open", "a", "browser", "to", "view", "the", "specified", "location." ]
def view(location, browser=None, new='same', autoraise=True): try: new = {'same': 0, 'window': 1, 'tab': 2}[new] except KeyError: raise RuntimeError("invalid 'new' value passed to view: %r, valid values are: 'same', 'window', or 'tab'" % new) if location.startswith('http'): url = loc...
['def', 'view(location,', 'browser=None,', "new='same',", 'autoraise=True):', 'try:', 'new', '=', "{'same':", '0,', "'window':", '1,', "'tab':", '2}[new]', 'except', 'KeyError:', 'raise', 'RuntimeError("invalid', "'new'", 'value', 'passed', 'to', 'view:', '%r,', 'valid', 'values', 'are:', "'same',", "'window',", 'or', ...
977,490
DPerrySvendsen/COS30002
matrix33.py
Matrix33.rotate_by_vectors
rotate_by_vectors
Update self with rotation based on forward and side vectors.
[ "Update", "self", "with", "rotation", "based", "on", "forward", "and", "side", "vectors." ]
def rotate_by_vectors(self, fwd, side): return self * Matrix33([fwd.x, fwd.y, 0.0, side.x, side.y, 0.0, 0.0, 0.0, 1.0])
['def', 'rotate_by_vectors(self,', 'fwd,', 'side):', 'return', 'self', '*', 'Matrix33([fwd.x,', 'fwd.y,', '0.0,', 'side.x,', 'side.y,', '0.0,', '0.0,', '0.0,', '1.0])']
137,395
ananthpn/nlp
rnnlm.py
PTBModel.import_ops
import_ops
Imports ops from collections.
[ "Imports", "ops", "from", "collections." ]
def import_ops(self): if self._is_training: self._train_op = tf.get_collection_ref('train_op')[0] self._lr = tf.get_collection_ref('lr')[0] self._new_lr = tf.get_collection_ref('new_lr')[0] self._lr_update = tf.get_collection_ref('lr_update')[0] rnn_params = tf.get_collection...
['def', 'import_ops(self):', 'if', 'self._is_training:', 'self._train_op', '=', "tf.get_collection_ref('train_op')[0]", 'self._lr', '=', "tf.get_collection_ref('lr')[0]", 'self._new_lr', '=', "tf.get_collection_ref('new_lr')[0]", 'self._lr_update', '=', "tf.get_collection_ref('lr_update')[0]", 'rnn_params', '=', "tf.ge...
986,067
thaines/helit
corpus.py
Corpus.setCalcPhi
setCalcPhi
Set False to have phi constant as the algorithm runs, leave True if you want it recalculated based on the cluster multinomials over behaviour drawn from it.
[ "Set", "False", "to", "have", "phi", "constant", "as", "the", "algorithm", "runs,", "leave", "True", "if", "you", "want", "it", "recalculated", "based", "on", "the", "cluster", "multinomials", "over", "behaviour", "drawn", "from", "it." ]
def setCalcPhi(self, val): self.calcPhi = val
['def', 'setCalcPhi(self,', 'val):', 'self.calcPhi', '=', 'val']
591,011
neuroailab/unsup_vvs
train_tfutils.py
tfutils_func_params
tfutils_func_params
Helper for creating parameters describing a function to be passed to tfutils.
[ "Helper", "for", "creating", "parameters", "describing", "a", "function", "to", "be", "passed", "to", "tfutils." ]
def tfutils_func_params(func, to_record, **kwargs): for k in to_record: if k not in kwargs: raise Exception('Cannot record parameter %r which does not appear in kwargs.' % k) (params, partial_kwargs) = ({}, {}) for (k, v) in kwargs.items(): if k in to_record: params[k...
['def', 'tfutils_func_params(func,', 'to_record,', '**kwargs):', 'for', 'k', 'in', 'to_record:', 'if', 'k', 'not', 'in', 'kwargs:', 'raise', "Exception('Cannot", 'record', 'parameter', '%r', 'which', 'does', 'not', 'appear', 'in', "kwargs.'", '%', 'k)', '(params,', 'partial_kwargs)', '=', '({},', '{})', 'for', '(k,', '...
438,418
adamshamsudeen/vision.ai
datastructures.py
ETags.contains_weak
contains_weak
Check if an etag is part of the set including weak and strong tags.
[ "Check", "if", "an", "etag", "is", "part", "of", "the", "set", "including", "weak", "and", "strong", "tags." ]
def contains_weak(self, etag): return self.is_weak(etag) or self.contains(etag)
['def', 'contains_weak(self,', 'etag):', 'return', 'self.is_weak(etag)', 'or', 'self.contains(etag)']
944,418
voxel51/fiftyone
zoo.py
TorchCLIPModel.embed_prompts
embed_prompts
Generates an embedding for the given text prompts.
[ "Generates", "an", "embedding", "for", "the", "given", "text", "prompts." ]
def embed_prompts(self, prompts): return self._embed_prompts(prompts).detach().cpu().numpy()
['def', 'embed_prompts(self,', 'prompts):', 'return', 'self._embed_prompts(prompts).detach().cpu().numpy()']
584,245
matsu0228/nlp-jp
axis.py
Axis.iter_ticks
iter_ticks
Iterate through all of the major and minor ticks.
[ "Iterate", "through", "all", "of", "the", "major", "and", "minor", "ticks." ]
def iter_ticks(self): majorLocs = self.major.locator() majorTicks = self.get_major_ticks(len(majorLocs)) self.major.formatter.set_locs(majorLocs) majorLabels = [self.major.formatter(val, i) for (i, val) in enumerate(majorLocs)] minorLocs = self.minor.locator() minorTicks = self.get_minor_ticks(l...
['def', 'iter_ticks(self):', 'majorLocs', '=', 'self.major.locator()', 'majorTicks', '=', 'self.get_major_ticks(len(majorLocs))', 'self.major.formatter.set_locs(majorLocs)', 'majorLabels', '=', '[self.major.formatter(val,', 'i)', 'for', '(i,', 'val)', 'in', 'enumerate(majorLocs)]', 'minorLocs', '=', 'self.minor.locator...
788,287
uzh-rpg/ess
base_trainer.py
BaseTrainer.createDDD17EventsDataset
createDDD17EventsDataset
Creates the validation and the training data based on the provided paths and parameters.
[ "Creates", "the", "validation", "and", "the", "training", "data", "based", "on", "the", "provided", "paths", "and", "parameters." ]
def createDDD17EventsDataset(self, dataset_name, root, split_train, batch_size, nr_events_data, delta_t_per_data, nr_events_per_data, augmentation, event_representation, nr_bins_per_data, require_paired_data_train, require_paired_data_val, separate_pol, normalize_event, fixed_duration): dataset_builder = self.getDa...
['def', 'createDDD17EventsDataset(self,', 'dataset_name,', 'root,', 'split_train,', 'batch_size,', 'nr_events_data,', 'delta_t_per_data,', 'nr_events_per_data,', 'augmentation,', 'event_representation,', 'nr_bins_per_data,', 'require_paired_data_train,', 'require_paired_data_val,', 'separate_pol,', 'normalize_event,', ...
563,356
aimclub/FEDOT
assumptions_builder.py
UniModalAssumptionsBuilder.to_builders
to_builders
Return a list of valid builders satisfying internal OperationsFilter or a single fallback builder.
[ "Return", "a", "list", "of", "valid", "builders", "satisfying", "internal", "OperationsFilter", "or", "a", "single", "fallback", "builder." ]
def to_builders(self, initial_node: Optional[PipelineNode]=None, use_input_preprocessing: bool=True) -> List[PipelineBuilder]: preprocessing = PreprocessingBuilder.builder_for_data(self.data.task.task_type, self.data, initial_node, use_input_preprocessing=use_input_preprocessing) valid_builders = [] for pro...
['def', 'to_builders(self,', 'initial_node:', 'Optional[PipelineNode]=None,', 'use_input_preprocessing:', 'bool=True)', '->', 'List[PipelineBuilder]:', 'preprocessing', '=', 'PreprocessingBuilder.builder_for_data(self.data.task.task_type,', 'self.data,', 'initial_node,', 'use_input_preprocessing=use_input_preprocessing...
545,596
Kvatsx/Artificial-Intelligence-Assignments
mathtext.py
Fonts.render_glyph
render_glyph
Draw a glyph at - *ox*, *oy*: position - *facename*: One of the TeX face names - *font_class*: - *sym*: TeX symbol name or single character - *fontsize*: fontsize in points - *dpi*: The dpi to draw at.
[ "Draw", "a", "glyph", "at", "-", "*ox*,", "*oy*:", "position", "-", "*facename*:", "One", "of", "the", "TeX", "face", "names", "-", "*font_class*:", "-", "*sym*:", "TeX", "symbol", "name", "or", "single", "character", "-", "*fontsize*:", "fontsize", "in", ...
def render_glyph(self, ox, oy, facename, font_class, sym, fontsize, dpi): info = self._get_info(facename, font_class, sym, fontsize, dpi) (realpath, stat_key) = get_realpath_and_stat(info.font.fname) used_characters = self.used_characters.setdefault(stat_key, (realpath, set())) used_characters[1].add(in...
['def', 'render_glyph(self,', 'ox,', 'oy,', 'facename,', 'font_class,', 'sym,', 'fontsize,', 'dpi):', 'info', '=', 'self._get_info(facename,', 'font_class,', 'sym,', 'fontsize,', 'dpi)', '(realpath,', 'stat_key)', '=', 'get_realpath_and_stat(info.font.fname)', 'used_characters', '=', 'self.used_characters.setdefault(st...
628
sunishsheth2009/ChatterBot
ma.py
identity
identity
identity(n) returns the identity matrix of shape n x n.
[ "identity(n)", "returns", "the", "identity", "matrix", "of", "shape", "n", "x", "n." ]
def identity(n): return array(numeric.identity(n))
['def', 'identity(n):', 'return', 'array(numeric.identity(n))']
532,300
triaquae/triaquae
numbertheory.py
lcm2
lcm2
Least common multiple of two integers.
[ "Least", "common", "multiple", "of", "two", "integers." ]
def lcm2(a, b): return a * b // gcd(a, b)
['def', 'lcm2(a,', 'b):', 'return', 'a', '*', 'b', '//', 'gcd(a,', 'b)']
356,730
matsu0228/nlp-jp
magics.py
TerminalMagics.rerun_pasted
rerun_pasted
Rerun a previously pasted command.
[ "Rerun", "a", "previously", "pasted", "command." ]
def rerun_pasted(self, name='pasted_block'): b = self.shell.user_ns.get(name) if b is None: raise UsageError('No previous pasted block available') if not isinstance(b, str): raise UsageError("Variable 'pasted_block' is not a string, can't execute") print("Re-executing '%s...' (%d chars)"...
['def', 'rerun_pasted(self,', "name='pasted_block'):", 'b', '=', 'self.shell.user_ns.get(name)', 'if', 'b', 'is', 'None:', 'raise', "UsageError('No", 'previous', 'pasted', 'block', "available')", 'if', 'not', 'isinstance(b,', 'str):', 'raise', 'UsageError("Variable', "'pasted_block'", 'is', 'not', 'a', 'string,', "can'...
787,303
lebrice/Sequoia
setting_test.py
TestIncrementalSLSetting.test_setting_obs_space_changes_when_transforms_change
test_setting_obs_space_changes_when_transforms_change
TODO: Test that the `observation_space` property on the ClassIncrementalSetting reflects the data produced by the dataloaders, and that changing a transform on a Setting also changes the value of that property on both the Setting itself, as well as on the corresponding dataloaders/environments.
[ "TODO:", "Test", "that", "the", "`observation_space`", "property", "on", "the", "ClassIncrementalSetting", "reflects", "the", "data", "produced", "by", "the", "dataloaders,", "and", "that", "changing", "a", "transform", "on", "a", "Setting", "also", "changes", "th...
def test_setting_obs_space_changes_when_transforms_change(self, dataset_name: str): import torch setting = self.Setting(dataset=dataset_name, nb_tasks=1, transforms=[], train_transforms=[], val_transforms=[], test_transforms=[], batch_size=None, num_workers=0, config=Config(device=torch.device('cpu'))) base...
['def', 'test_setting_obs_space_changes_when_transforms_change(self,', 'dataset_name:', 'str):', 'import', 'torch', 'setting', '=', 'self.Setting(dataset=dataset_name,', 'nb_tasks=1,', 'transforms=[],', 'train_transforms=[],', 'val_transforms=[],', 'test_transforms=[],', 'batch_size=None,', 'num_workers=0,', "config=Co...
349,693
myothida/Supervised-Machine-Learning
test_rotation_groups.py
test_octahedral
test_octahedral
Test that the octahedral group correctly fixes the rotations of an octahedron.
[ "Test", "that", "the", "octahedral", "group", "correctly", "fixes", "the", "rotations", "of", "an", "octahedron." ]
def test_octahedral(): P = _generate_octahedron() for g in Rotation.create_group('O'): assert _calculate_rmsd(P, g.apply(P)) < TOL
['def', 'test_octahedral():', 'P', '=', '_generate_octahedron()', 'for', 'g', 'in', "Rotation.create_group('O'):", 'assert', '_calculate_rmsd(P,', 'g.apply(P))', '<', 'TOL']
446,428
zhang614/MicroGrid
test_fir_filter_design.py
TestFirWinMore.test_even_highpass_raises_value_error
test_even_highpass_raises_value_error
Test that attempt to create a highpass filter with an even number of taps raises a ValueError exception.
[ "Test", "that", "attempt", "to", "create", "a", "highpass", "filter", "with", "an", "even", "number", "of", "taps", "raises", "a", "ValueError", "exception." ]
def test_even_highpass_raises_value_error(self): assert_raises(ValueError, firwin, 40, 0.5, pass_zero=False) assert_raises(ValueError, firwin, 40, [0.25, 0.5])
['def', 'test_even_highpass_raises_value_error(self):', 'assert_raises(ValueError,', 'firwin,', '40,', '0.5,', 'pass_zero=False)', 'assert_raises(ValueError,', 'firwin,', '40,', '[0.25,', '0.5])']
669,688
epfl-ml4ed/meta-transfer-learning
args.py
evaluate_kwargs
evaluate_kwargs
Build kwargs for the evaluate() function from the parsed command-line arguments.
[ "Build", "kwargs", "for", "the", "evaluate()", "function", "from", "the", "parsed", "command-line", "arguments." ]
def evaluate_kwargs(parsed_args): return {'num_classes': parsed_args.classes, 'num_shots': parsed_args.shots, 'eval_inner_batch_size': parsed_args.eval_batch, 'eval_inner_iters': parsed_args.eval_iters, 'replacement': parsed_args.replacement, 'weight_decay_rate': parsed_args.weight_decay, 'num_samples': parsed_args...
['def', 'evaluate_kwargs(parsed_args):', 'return', "{'num_classes':", 'parsed_args.classes,', "'num_shots':", 'parsed_args.shots,', "'eval_inner_batch_size':", 'parsed_args.eval_batch,', "'eval_inner_iters':", 'parsed_args.eval_iters,', "'replacement':", 'parsed_args.replacement,', "'weight_decay_rate':", 'parsed_args....
633,372
Eric3911/OpenAGI
utilities.py
read_metadata
read_metadata
Read metadata of AudioSet from a csv file.
[ "Read", "metadata", "of", "AudioSet", "from", "a", "csv", "file." ]
def read_metadata(csv_path, classes_num, id_to_ix): with open(csv_path, 'r') as fr: lines = fr.readlines() lines = lines[3:] audios_num = len(lines) targets = np.zeros((audios_num, classes_num), dtype=np.bool) audio_names = [] for (n, line) in enumerate(lines): items = line.s...
['def', 'read_metadata(csv_path,', 'classes_num,', 'id_to_ix):', 'with', 'open(csv_path,', "'r')", 'as', 'fr:', 'lines', '=', 'fr.readlines()', 'lines', '=', 'lines[3:]', 'audios_num', '=', 'len(lines)', 'targets', '=', 'np.zeros((audios_num,', 'classes_num),', 'dtype=np.bool)', 'audio_names', '=', '[]', 'for', '(n,', ...
250,488
instadeepai/jumanji
types_test.py
test_position__add
test_position__add
Validates the addition of two `Position` instances.
[ "Validates", "the", "addition", "of", "two", "`Position`", "instances." ]
def test_position__add() -> None: assert Position(3, 5) + Position(3, 5) == Position(6, 10) assert Position(0, 1) + Position(2, 3) == Position(2, 4) assert Position(-2, 1) + Position(1, -4) != Position(0, 0)
['def', 'test_position__add()', '->', 'None:', 'assert', 'Position(3,', '5)', '+', 'Position(3,', '5)', '==', 'Position(6,', '10)', 'assert', 'Position(0,', '1)', '+', 'Position(2,', '3)', '==', 'Position(2,', '4)', 'assert', 'Position(-2,', '1)', '+', 'Position(1,', '-4)', '!=', 'Position(0,', '0)']
594,524
daijifeng001/MNC
bbox_transform.py
filter_small_boxes
filter_small_boxes
Remove all boxes with any side smaller than min_size.
[ "Remove", "all", "boxes", "with", "any", "side", "smaller", "than", "min_size." ]
def filter_small_boxes(boxes, min_size): ws = boxes[:, 2] - boxes[:, 0] + 1 hs = boxes[:, 3] - boxes[:, 1] + 1 keep = np.where((ws >= min_size) & (hs >= min_size))[0] return keep
['def', 'filter_small_boxes(boxes,', 'min_size):', 'ws', '=', 'boxes[:,', '2]', '-', 'boxes[:,', '0]', '+', '1', 'hs', '=', 'boxes[:,', '3]', '-', 'boxes[:,', '1]', '+', '1', 'keep', '=', 'np.where((ws', '>=', 'min_size)', '&', '(hs', '>=', 'min_size))[0]', 'return', 'keep']
625,976
mmaaz60/ssl_for_fgvc
common.py
Trainer.get_trainer
get_trainer
The function returns the selected trainer.
[ "The", "function", "returns", "the", "selected", "trainer." ]
def get_trainer(self): return self.trainer
['def', 'get_trainer(self):', 'return', 'self.trainer']
382,400
gunthercox/ChatterBot
tbtools.py
Frame.eval
eval
Evaluate code in the context of the frame.
[ "Evaluate", "code", "in", "the", "context", "of", "the", "frame." ]
def eval(self, code, mode='single'): if isinstance(code, string_types): if PY2 and isinstance(code, unicode): code = UTF8_COOKIE + code.encode('utf-8') code = compile(code, '<interactive>', mode) return eval(code, self.globals, self.locals)
['def', 'eval(self,', 'code,', "mode='single'):", 'if', 'isinstance(code,', 'string_types):', 'if', 'PY2', 'and', 'isinstance(code,', 'unicode):', 'code', '=', 'UTF8_COOKIE', '+', "code.encode('utf-8')", 'code', '=', 'compile(code,', "'<interactive>',", 'mode)', 'return', 'eval(code,', 'self.globals,', 'self.locals)']
483,793
dojoteef/dvae
dataloader.py
Dataset.num_channels
num_channels
Return the number of color channels of the images in the dataset.
[ "Return", "the", "number", "of", "color", "channels", "of", "the", "images", "in", "the", "dataset." ]
def num_channels(self): return self.train.images.shape[3]
['def', 'num_channels(self):', 'return', 'self.train.images.shape[3]']
554,980
rifqind/Agent-Programs-3KS1
mask_test.py
MaskTypeTest.test_draw__invalid_offset_arg
test_draw__invalid_offset_arg
Ensure draw handles invalid offset arguments correctly.
[ "Ensure", "draw", "handles", "invalid", "offset", "arguments", "correctly." ]
def test_draw__invalid_offset_arg(self): size = (5, 7) offset = '(0, 0)' mask1 = pygame.mask.Mask(size) mask2 = pygame.mask.Mask(size) with self.assertRaises(TypeError): mask1.draw(mask2, offset)
['def', 'test_draw__invalid_offset_arg(self):', 'size', '=', '(5,', '7)', 'offset', '=', "'(0,", "0)'", 'mask1', '=', 'pygame.mask.Mask(size)', 'mask2', '=', 'pygame.mask.Mask(size)', 'with', 'self.assertRaises(TypeError):', 'mask1.draw(mask2,', 'offset)']
45,844
nicknochnack/RealTimeSignLanguageTFJS
feature_extractor.py
CalculateReceptiveBoxes
CalculateReceptiveBoxes
Calculate receptive boxes for each feature point.
[ "Calculate", "receptive", "boxes", "for", "each", "feature", "point." ]
def CalculateReceptiveBoxes(height, width, rf, stride, padding): (x, y) = tf.meshgrid(tf.range(width), tf.range(height)) coordinates = tf.reshape(tf.stack([y, x], axis=2), [-1, 2]) point_boxes = tf.cast(tf.concat([coordinates, coordinates], 1), dtype=tf.float32) bias = [-padding, -padding, -padding + rf...
['def', 'CalculateReceptiveBoxes(height,', 'width,', 'rf,', 'stride,', 'padding):', '(x,', 'y)', '=', 'tf.meshgrid(tf.range(width),', 'tf.range(height))', 'coordinates', '=', 'tf.reshape(tf.stack([y,', 'x],', 'axis=2),', '[-1,', '2])', 'point_boxes', '=', 'tf.cast(tf.concat([coordinates,', 'coordinates],', '1),', 'dtyp...
851,647
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
trainer.py
create_input_queue
create_input_queue
Sets up reader, prefetcher and returns input queue.
[ "Sets", "up", "reader,", "prefetcher", "and", "returns", "input", "queue." ]
def create_input_queue(batch_size_per_clone, create_tensor_dict_fn, batch_queue_capacity, num_batch_queue_threads, prefetch_queue_capacity, data_augmentation_options): tensor_dict = create_tensor_dict_fn() tensor_dict[fields.InputDataFields.image] = tf.expand_dims(tensor_dict[fields.InputDataFields.image], 0) ...
['def', 'create_input_queue(batch_size_per_clone,', 'create_tensor_dict_fn,', 'batch_queue_capacity,', 'num_batch_queue_threads,', 'prefetch_queue_capacity,', 'data_augmentation_options):', 'tensor_dict', '=', 'create_tensor_dict_fn()', 'tensor_dict[fields.InputDataFields.image]', '=', 'tf.expand_dims(tensor_dict[field...
56,627
zebrium/zebrium-kubernetes-demo
manage.py
start
start
Start a GKE Cluster with Zebrium's demo environment deployed.
[ "Start", "a", "GKE", "Cluster", "with", "Zebrium's", "demo", "environment", "deployed." ]
def start(args): print_color(f'Starting GKE cluster in project {args.project} with name {args.name} in zone {args.zone}', bcolors.OKBLUE) run_shell('gcloud components update') run_shell(f'gcloud config set project "{args.project}"') run_shell(f'gcloud container clusters create {args.name} --zone {args.z...
['def', 'start(args):', "print_color(f'Starting", 'GKE', 'cluster', 'in', 'project', '{args.project}', 'with', 'name', '{args.name}', 'in', 'zone', "{args.zone}',", 'bcolors.OKBLUE)', "run_shell('gcloud", 'components', "update')", "run_shell(f'gcloud", 'config', 'set', 'project', '"{args.project}"\')', "run_shell(f'gcl...
374,975
ForrestPi/ObjectDetection
rpn_helpers.py
create_rpn
create_rpn
Creates a region proposal network for object detection as proposed in the "Faster R-CNN" paper: Shaoqing Ren and Kaiming He and Ross Girshick and Jian Sun: "Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks" Outputs object detection proposals by applying estimated bounding-box transformatio...
[ "Creates", "a", "region", "proposal", "network", "for", "object", "detection", "as", "proposed", "in", "the", "\"Faster", "R-CNN\"", "paper:", "Shaoqing", "Ren", "and", "Kaiming", "He", "and", "Ross", "Girshick", "and", "Jian", "Sun:", "\"Faster", "R-CNN:", "T...
def create_rpn(conv_out, scaled_gt_boxes, im_info, cfg, add_loss_functions=True): num_channels = cfg['MODEL'].RPN_NUM_CHANNELS rpn_conv_3x3 = Convolution((3, 3), num_channels, activation=relu, pad=True, strides=1, init=normal(scale=0.01), init_bias=0.0)(conv_out) rpn_cls_score = Convolution((1, 1), 18, acti...
['def', 'create_rpn(conv_out,', 'scaled_gt_boxes,', 'im_info,', 'cfg,', 'add_loss_functions=True):', 'num_channels', '=', "cfg['MODEL'].RPN_NUM_CHANNELS", 'rpn_conv_3x3', '=', 'Convolution((3,', '3),', 'num_channels,', 'activation=relu,', 'pad=True,', 'strides=1,', 'init=normal(scale=0.01),', 'init_bias=0.0)(conv_out)'...
743,721
hyz-xmaster/swa_object_detection
test_corner_head.py
test_corner_head_encode_and_decode_heatmap
test_corner_head_encode_and_decode_heatmap
Tests corner head generating and decoding the heatmap.
[ "Tests", "corner", "head", "generating", "and", "decoding", "the", "heatmap." ]
def test_corner_head_encode_and_decode_heatmap(): s = 256 img_metas = [{'img_shape': (s, s, 3), 'scale_factor': 1, 'pad_shape': (s, s, 3), 'border': (0, 0, 0, 0)}] gt_bboxes = [torch.Tensor([[10, 20, 200, 240], [40, 50, 100, 200], [10, 20, 200, 240]])] gt_labels = [torch.LongTensor([1, 1, 2])] self ...
['def', 'test_corner_head_encode_and_decode_heatmap():', 's', '=', '256', 'img_metas', '=', "[{'img_shape':", '(s,', 's,', '3),', "'scale_factor':", '1,', "'pad_shape':", '(s,', 's,', '3),', "'border':", '(0,', '0,', '0,', '0)}]', 'gt_bboxes', '=', '[torch.Tensor([[10,', '20,', '200,', '240],', '[40,', '50,', '100,', '...
882,765
roboflow/supervision
core.py
DetectionDataset.from_pascal_voc
from_pascal_voc
Creates a Dataset instance from PASCAL VOC formatted data.
[ "Creates", "a", "Dataset", "instance", "from", "PASCAL", "VOC", "formatted", "data." ]
def from_pascal_voc(cls, images_directory_path: str, annotations_directory_path: str, force_masks: bool=False) -> DetectionDataset: (classes, images, annotations) = load_pascal_voc_annotations(images_directory_path=images_directory_path, annotations_directory_path=annotations_directory_path, force_masks=force_masks...
['def', 'from_pascal_voc(cls,', 'images_directory_path:', 'str,', 'annotations_directory_path:', 'str,', 'force_masks:', 'bool=False)', '->', 'DetectionDataset:', '(classes,', 'images,', 'annotations)', '=', 'load_pascal_voc_annotations(images_directory_path=images_directory_path,', 'annotations_directory_path=annotati...
882,021
suarez12138/AI-Reversi_IMP_TextDichotomy
afm.py
AFM.get_str_bbox
get_str_bbox
Return the string bounding box.
[ "Return", "the", "string", "bounding", "box." ]
def get_str_bbox(self, s): return self.get_str_bbox_and_descent(s)[:4]
['def', 'get_str_bbox(self,', 's):', 'return', 'self.get_str_bbox_and_descent(s)[:4]']
96,008
weimin17/Object-Detection_HelmetDetection
utils.py
generate_model_name
generate_model_name
Generate a full model name for the given model number.
[ "Generate", "a", "full", "model", "name", "for", "the", "given", "model", "number." ]
def generate_model_name(model_num): if model_num == 0: new_name = 'bootstrap' else: new_name = random_generator() full_name = '{:06d}-{}'.format(model_num, new_name) return full_name
['def', 'generate_model_name(model_num):', 'if', 'model_num', '==', '0:', 'new_name', '=', "'bootstrap'", 'else:', 'new_name', '=', 'random_generator()', 'full_name', '=', "'{:06d}-{}'.format(model_num,", 'new_name)', 'return', 'full_name']
758,207
takuseno/d3rlpy
encoders.py
EncoderFactory.create
create
Returns PyTorch's state enocder module.
[ "Returns", "PyTorch's", "state", "enocder", "module." ]
def create(self, observation_shape: Shape) -> Encoder: raise NotImplementedError
['def', 'create(self,', 'observation_shape:', 'Shape)', '->', 'Encoder:', 'raise', 'NotImplementedError']
197,974
nicknochnack/RealTimeSignLanguageTFJS
resnet_deeplab_test.py
ResNetTest.test_input_specs
test_input_specs
Test different input feature dimensions.
[ "Test", "different", "input", "feature", "dimensions." ]
def test_input_specs(self, input_dim): tf.keras.backend.set_image_data_format('channels_last') input_specs = tf.keras.layers.InputSpec(shape=[None, None, None, input_dim]) network = resnet_deeplab.DilatedResNet(model_id=50, output_stride=8, input_specs=input_specs) inputs = tf.keras.Input(shape=(128, 12...
['def', 'test_input_specs(self,', 'input_dim):', "tf.keras.backend.set_image_data_format('channels_last')", 'input_specs', '=', 'tf.keras.layers.InputSpec(shape=[None,', 'None,', 'None,', 'input_dim])', 'network', '=', 'resnet_deeplab.DilatedResNet(model_id=50,', 'output_stride=8,', 'input_specs=input_specs)', 'inputs'...
850,824
sooftware/nlp-tasks
metric.py
CharacterErrorRate.metric
metric
Computes the Character Error Rate, defined as the edit distance between the two provided sentences after tokenizing to characters.
[ "Computes", "the", "Character", "Error", "Rate,", "defined", "as", "the", "edit", "distance", "between", "the", "two", "provided", "sentences", "after", "tokenizing", "to", "characters." ]
def metric(self, s1: str, s2: str) -> Tuple[float, int]: s1 = s1.replace(' ', '') s2 = s2.replace(' ', '') if '_' in s1: s1 = s1.replace('_', '') if '_' in s2: s2 = s2.replace('_', '') dist = Lev.distance(s2, s1) length = len(s1.replace(' ', '')) return (dist, length)
['def', 'metric(self,', 's1:', 'str,', 's2:', 'str)', '->', 'Tuple[float,', 'int]:', 's1', '=', "s1.replace('", "',", "'')", 's2', '=', "s2.replace('", "',", "'')", 'if', "'_'", 'in', 's1:', 's1', '=', "s1.replace('_',", "'')", 'if', "'_'", 'in', 's2:', 's2', '=', "s2.replace('_',", "'')", 'dist', '=', 'Lev.distance(s2...
731,362
paulorauber/rl
ray.py
RayCollector.remote_collectors
remote_collectors
Returns list of remote collectors.
[ "Returns", "list", "of", "remote", "collectors." ]
def remote_collectors(self): return self._remote_collectors
['def', 'remote_collectors(self):', 'return', 'self._remote_collectors']
858,633
nlp-uoregon/trankit
tokenization_gpt2.py
GPT2Tokenizer.save_vocabulary
save_vocabulary
Save the vocabulary and special tokens file to a directory.
[ "Save", "the", "vocabulary", "and", "special", "tokens", "file", "to", "a", "directory." ]
def save_vocabulary(self, save_directory): if not os.path.isdir(save_directory): logger.error('Vocabulary path ({}) should be a directory'.format(save_directory)) return vocab_file = os.path.join(save_directory, VOCAB_FILES_NAMES['vocab_file']) merge_file = os.path.join(save_directory, VOCAB...
['def', 'save_vocabulary(self,', 'save_directory):', 'if', 'not', 'os.path.isdir(save_directory):', "logger.error('Vocabulary", 'path', '({})', 'should', 'be', 'a', "directory'.format(save_directory))", 'return', 'vocab_file', '=', 'os.path.join(save_directory,', "VOCAB_FILES_NAMES['vocab_file'])", 'merge_file', '=', '...
920,291
rifqind/Agent-Programs-3KS1
document.py
Document.get_start_of_line_position
get_start_of_line_position
Relative position for the start of this line.
[ "Relative", "position", "for", "the", "start", "of", "this", "line." ]
def get_start_of_line_position(self, after_whitespace=False): if after_whitespace: current_line = self.current_line return len(current_line) - len(current_line.lstrip()) - self.cursor_position_col else: return -len(self.current_line_before_cursor)
['def', 'get_start_of_line_position(self,', 'after_whitespace=False):', 'if', 'after_whitespace:', 'current_line', '=', 'self.current_line', 'return', 'len(current_line)', '-', 'len(current_line.lstrip())', '-', 'self.cursor_position_col', 'else:', 'return', '-len(self.current_line_before_cursor)']
44,980
rudranil723/mini-main
test_preprocess_data.py
test_function_call_with_dict_data
test_function_call_with_dict_data
Test with dict data -> label comes from the value of 'x' parameter.
[ "Test", "with", "dict", "data", "->", "label", "comes", "from", "the", "value", "of", "'x'", "parameter." ]
def test_function_call_with_dict_data(func): data = {'a': [1, 2], 'b': [8, 9], 'w': 'NOT'} assert func(None, 'a', 'b', data=data) == 'x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b' assert func(None, x='a', y='b', data=data) == 'x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b' assert func(None, 'a', 'b', l...
['def', 'test_function_call_with_dict_data(func):', 'data', '=', "{'a':", '[1,', '2],', "'b':", '[8,', '9],', "'w':", "'NOT'}", 'assert', 'func(None,', "'a',", "'b',", 'data=data)', '==', "'x:", '[1,', '2],', 'y:', '[8,', '9],', 'ls:', 'x,', 'w:', 'xyz,', 'label:', "b'", 'assert', 'func(None,', "x='a',", "y='b',", 'dat...
320,317
feast-dev/feast
snowflake_source.py
SnowflakeSource.query
query
Returns the snowflake options of this snowflake source.
[ "Returns", "the", "snowflake", "options", "of", "this", "snowflake", "source." ]
def query(self): return self.snowflake_options.query
['def', 'query(self):', 'return', 'self.snowflake_options.query']
544,407
bislara/Object-detection-GUI
exporter.py
build_detection_graph
build_detection_graph
Build the detection graph.
[ "Build", "the", "detection", "graph." ]
def build_detection_graph(input_type, detection_model, input_shape, output_collection_name, graph_hook_fn): if input_type not in input_placeholder_fn_map: raise ValueError('Unknown input type: {}'.format(input_type)) placeholder_args = {} if input_shape is not None: if input_type != 'image_t...
['def', 'build_detection_graph(input_type,', 'detection_model,', 'input_shape,', 'output_collection_name,', 'graph_hook_fn):', 'if', 'input_type', 'not', 'in', 'input_placeholder_fn_map:', 'raise', "ValueError('Unknown", 'input', 'type:', "{}'.format(input_type))", 'placeholder_args', '=', '{}', 'if', 'input_shape', 'i...
726,293
Katja-M/Python_NaturalLanguageProcessing
tgrep.py
treepositions_no_leaves
treepositions_no_leaves
Returns all the tree positions in the given tree which are not leaf nodes.
[ "Returns", "all", "the", "tree", "positions", "in", "the", "given", "tree", "which", "are", "not", "leaf", "nodes." ]
def treepositions_no_leaves(tree): treepositions = tree.treepositions() prefixes = set() for pos in treepositions: for length in range(len(pos)): prefixes.add(pos[:length]) return [pos for pos in treepositions if pos in prefixes]
['def', 'treepositions_no_leaves(tree):', 'treepositions', '=', 'tree.treepositions()', 'prefixes', '=', 'set()', 'for', 'pos', 'in', 'treepositions:', 'for', 'length', 'in', 'range(len(pos)):', 'prefixes.add(pos[:length])', 'return', '[pos', 'for', 'pos', 'in', 'treepositions', 'if', 'pos', 'in', 'prefixes]']
865,898
arshpreetsingh/quantopian-machinelearning
offsets.py
BusinessHourMixin.rollforward
rollforward
Roll provided date forward to next offset only if not on offset.
[ "Roll", "provided", "date", "forward", "to", "next", "offset", "only", "if", "not", "on", "offset." ]
def rollforward(self, dt): if not self.onOffset(dt): if self.n >= 0: return self._next_opening_time(dt) else: return self._prev_opening_time(dt) return dt
['def', 'rollforward(self,', 'dt):', 'if', 'not', 'self.onOffset(dt):', 'if', 'self.n', '>=', '0:', 'return', 'self._next_opening_time(dt)', 'else:', 'return', 'self._prev_opening_time(dt)', 'return', 'dt']
890,777
pedrojrv/nucml
utilities.py
cat_plot
cat_plot
Plot a categorical bar plot.
[ "Plot", "a", "categorical", "bar", "plot." ]
def cat_plot(features, df, groupby, top=10, reverse=False, save=False): catplot_fn = partial(sns.catplot, kind='count', palette='GnBu_r', height=15, aspect=2) for i in features: for_plotting = df[[i, groupby]].drop_duplicates() vc = for_plotting[i].value_counts() catplot_fn(x=i, data=for...
['def', 'cat_plot(features,', 'df,', 'groupby,', 'top=10,', 'reverse=False,', 'save=False):', 'catplot_fn', '=', 'partial(sns.catplot,', "kind='count',", "palette='GnBu_r',", 'height=15,', 'aspect=2)', 'for', 'i', 'in', 'features:', 'for_plotting', '=', 'df[[i,', 'groupby]].drop_duplicates()', 'vc', '=', 'for_plotting[...
249,776
jshilong/DDQ
file_client.py
PetrelBackend.exists
exists
Check whether a file path exists.
[ "Check", "whether", "a", "file", "path", "exists." ]
def exists(self, filepath: Union[str, Path]) -> bool: if not (has_method(self._client, 'contains') and has_method(self._client, 'isdir')): raise NotImplementedError('Current version of Petrel Python SDK has not supported the `contains` and `isdir` methods, please use a higherversion or dev branch instead.')...
['def', 'exists(self,', 'filepath:', 'Union[str,', 'Path])', '->', 'bool:', 'if', 'not', '(has_method(self._client,', "'contains')", 'and', 'has_method(self._client,', "'isdir')):", 'raise', "NotImplementedError('Current", 'version', 'of', 'Petrel', 'Python', 'SDK', 'has', 'not', 'supported', 'the', '`contains`', 'and'...
499,002
Marsan-Ma-zz/tf_chatbot_seq2seq_antilm
seq2seq.py
embedding_attention_decoder
embedding_attention_decoder
RNN decoder with embedding and attention and a pure-decoding option.
[ "RNN", "decoder", "with", "embedding", "and", "attention", "and", "a", "pure-decoding", "option." ]
def embedding_attention_decoder(decoder_inputs, initial_state, attention_states, cell, num_symbols, embedding_size, num_heads=1, output_size=None, output_projection=None, feed_previous=False, update_embedding_for_previous=True, dtype=None, scope=None, initial_state_attention=False): if output_size is None: ...
['def', 'embedding_attention_decoder(decoder_inputs,', 'initial_state,', 'attention_states,', 'cell,', 'num_symbols,', 'embedding_size,', 'num_heads=1,', 'output_size=None,', 'output_projection=None,', 'feed_previous=False,', 'update_embedding_for_previous=True,', 'dtype=None,', 'scope=None,', 'initial_state_attention=...
915,872
aws/sagemaker-python-sdk
notebook_utils.py
list_jumpstart_tasks
list_jumpstart_tasks
List tasks for JumpStart, and optionally apply filters to result.
[ "List", "tasks", "for", "JumpStart,", "and", "optionally", "apply", "filters", "to", "result." ]
def list_jumpstart_tasks(filter: Union[Operator, str]=Constant(BooleanValues.TRUE), region: str=JUMPSTART_DEFAULT_REGION_NAME) -> List[str]: tasks: Set[str] = set() for (model_id, _) in _generate_jumpstart_model_versions(filter=filter, region=region): (_, task, _) = extract_framework_task_model(model_id...
['def', 'list_jumpstart_tasks(filter:', 'Union[Operator,', 'str]=Constant(BooleanValues.TRUE),', 'region:', 'str=JUMPSTART_DEFAULT_REGION_NAME)', '->', 'List[str]:', 'tasks:', 'Set[str]', '=', 'set()', 'for', '(model_id,', '_)', 'in', '_generate_jumpstart_model_versions(filter=filter,', 'region=region):', '(_,', 'task,...
830,175
Katja-M/Python_NaturalLanguageProcessing
backend_bases.py
GraphicsContextBase.get_capstyle
get_capstyle
Return the capstyle as a string in ('butt', 'round', 'projecting').
[ "Return", "the", "capstyle", "as", "a", "string", "in", "('butt',", "'round',", "'projecting')." ]
def get_capstyle(self): return self._capstyle
['def', 'get_capstyle(self):', 'return', 'self._capstyle']
864,231
megvii-research/PETR
nuscenes_converter_seg.py
obtain_map_info
obtain_map_info
Export 2d annotation from the info file and raw data.
[ "Export", "2d", "annotation", "from", "the", "info", "file", "and", "raw", "data." ]
def obtain_map_info(nusc, nusc_maps, sample, l2e_r_mat, l2e_t, e2g_r_mat, e2g_t, lidar_path, info_prefix, patch_size=(100, 100), canvas_size=(200, 200), layer_names=['lane_divider', 'road_divider'], thickness=10): scene = nusc.get('scene', sample['scene_token']) log = nusc.get('log', scene['log_token']) nus...
['def', 'obtain_map_info(nusc,', 'nusc_maps,', 'sample,', 'l2e_r_mat,', 'l2e_t,', 'e2g_r_mat,', 'e2g_t,', 'lidar_path,', 'info_prefix,', 'patch_size=(100,', '100),', 'canvas_size=(200,', '200),', "layer_names=['lane_divider',", "'road_divider'],", 'thickness=10):', 'scene', '=', "nusc.get('scene',", "sample['scene_toke...
767,607
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
seq2seq_model.py
Seq2SeqModel.step
step
Run a step of the model feeding the given inputs.
[ "Run", "a", "step", "of", "the", "model", "feeding", "the", "given", "inputs." ]
def step(self, session, encoder_inputs, decoder_inputs, target_weights, bucket_id, forward_only): (encoder_size, decoder_size) = self.buckets[bucket_id] if len(encoder_inputs) != encoder_size: raise ValueError('Encoder length must be equal to the one in bucket, %d != %d.' % (len(encoder_inputs), encoder...
['def', 'step(self,', 'session,', 'encoder_inputs,', 'decoder_inputs,', 'target_weights,', 'bucket_id,', 'forward_only):', '(encoder_size,', 'decoder_size)', '=', 'self.buckets[bucket_id]', 'if', 'len(encoder_inputs)', '!=', 'encoder_size:', 'raise', "ValueError('Encoder", 'length', 'must', 'be', 'equal', 'to', 'the', ...
113,385
hamza-murad/AALU
compare_comply_v1.py
UpdatedLabelsOut.from_dict
from_dict
Initialize a UpdatedLabelsOut object from a json dictionary.
[ "Initialize", "a", "UpdatedLabelsOut", "object", "from", "a", "json", "dictionary." ]
def from_dict(cls, _dict: Dict) -> 'UpdatedLabelsOut': args = {} valid_keys = ['types', 'categories', 'modification'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError('Unrecognized keys detected in dictionary for class UpdatedLabelsOut: ' + ', '.join(bad_keys)) if...
['def', 'from_dict(cls,', '_dict:', 'Dict)', '->', "'UpdatedLabelsOut':", 'args', '=', '{}', 'valid_keys', '=', "['types',", "'categories',", "'modification']", 'bad_keys', '=', 'set(_dict.keys())', '-', 'set(valid_keys)', 'if', 'bad_keys:', 'raise', "ValueError('Unrecognized", 'keys', 'detected', 'in', 'dictionary', '...
5,462
chainer/chainer
static_graph.py
StaticScheduleFunction.run_out_var_hooks
run_out_var_hooks
Run hooks to update output variable array references.
[ "Run", "hooks", "to", "update", "output", "variable", "array", "references." ]
def run_out_var_hooks(self): for hook in self.out_var_hooks: (out_var_ind, unique_list_index) = hook out_var = self.out_vars[out_var_ind] out_var.data = self.unique_arrays[unique_list_index] if self.verbosity_level >= 2: print('StaticScheduleFunction: running output varia...
['def', 'run_out_var_hooks(self):', 'for', 'hook', 'in', 'self.out_var_hooks:', '(out_var_ind,', 'unique_list_index)', '=', 'hook', 'out_var', '=', 'self.out_vars[out_var_ind]', 'out_var.data', '=', 'self.unique_arrays[unique_list_index]', 'if', 'self.verbosity_level', '>=', '2:', "print('StaticScheduleFunction:", 'run...
477,409
noahshinn024/reflexion
rs_executor.py
transform_asserts
transform_asserts
Transform all asserts into assert_eq_nopanic! asserts, inserting the macro definition at the top of the code.
[ "Transform", "all", "asserts", "into", "assert_eq_nopanic!", "asserts,", "inserting", "the", "macro", "definition", "at", "the", "top", "of", "the", "code." ]
def transform_asserts(code: str) -> str: code.replace('assert_eq!', 'assert_eq_nopanic!') return assert_no_panic + code
['def', 'transform_asserts(code:', 'str)', '->', 'str:', "code.replace('assert_eq!',", "'assert_eq_nopanic!')", 'return', 'assert_no_panic', '+', 'code']
340,431
facebookresearch/CompilerGym
__init__.py
Inst2vecEncoder.preprocess
preprocess
Produce a list of pre-processed statements from an IR.
[ "Produce", "a", "list", "of", "pre-processed", "statements", "from", "an", "IR." ]
def preprocess(self, ir: str) -> List[str]: lines = [[x] for x in ir.split('\n')] try: structs = inst2vec_preprocess.GetStructTypes(ir) for line in lines: for (struct, definition) in structs.items(): line[0] = line[0].replace(struct, definition) except ValueError:...
['def', 'preprocess(self,', 'ir:', 'str)', '->', 'List[str]:', 'lines', '=', '[[x]', 'for', 'x', 'in', "ir.split('\\n')]", 'try:', 'structs', '=', 'inst2vec_preprocess.GetStructTypes(ir)', 'for', 'line', 'in', 'lines:', 'for', '(struct,', 'definition)', 'in', 'structs.items():', 'line[0]', '=', 'line[0].replace(struct,...
126,270
TrellixVulnTeam/Unsupervised_Learning_HFI7
test_mlab.py
TestGaussianKDEEvaluate.test_evaluate_diff_dim
test_evaluate_diff_dim
Test the evaluate method when the dim's of dataset and points have different dimensions.
[ "Test", "the", "evaluate", "method", "when", "the", "dim's", "of", "dataset", "and", "points", "have", "different", "dimensions." ]
def test_evaluate_diff_dim(self): x1 = np.arange(3, 10, 2) kde = mlab.GaussianKDE(x1) x2 = np.arange(3, 12, 2) y_expected = [0.08797252, 0.11774109, 0.11774109, 0.08797252, 0.0370153] y = kde.evaluate(x2) np.testing.assert_array_almost_equal(y, y_expected, 7)
['def', 'test_evaluate_diff_dim(self):', 'x1', '=', 'np.arange(3,', '10,', '2)', 'kde', '=', 'mlab.GaussianKDE(x1)', 'x2', '=', 'np.arange(3,', '12,', '2)', 'y_expected', '=', '[0.08797252,', '0.11774109,', '0.11774109,', '0.08797252,', '0.0370153]', 'y', '=', 'kde.evaluate(x2)', 'np.testing.assert_array_almost_equal(y...
451,433
43Carrig/recurrent_neural_networks_practice
file_io.py
FileIO.seek
seek
Seeks to the offset in the file.
[ "Seeks", "to", "the", "offset", "in", "the", "file." ]
def seek(self, offset=None, whence=0, position=None): self._preread_check() if offset is None and position is None: raise TypeError('seek(): offset argument required') if offset is not None and position is not None: raise TypeError('seek(): offset and position may not be set simultaneously.'...
['def', 'seek(self,', 'offset=None,', 'whence=0,', 'position=None):', 'self._preread_check()', 'if', 'offset', 'is', 'None', 'and', 'position', 'is', 'None:', 'raise', "TypeError('seek():", 'offset', 'argument', "required')", 'if', 'offset', 'is', 'not', 'None', 'and', 'position', 'is', 'not', 'None:', 'raise', "TypeEr...
337,058
PaddlePaddle/PARL
obs_filter.py
Filter.apply_changes
apply_changes
Updates self with "new state" from other filter.
[ "Updates", "self", "with", "\"new", "state\"", "from", "other", "filter." ]
def apply_changes(self, other, *args, **kwargs): raise NotImplementedError
['def', 'apply_changes(self,', 'other,', '*args,', '**kwargs):', 'raise', 'NotImplementedError']
277,591
instadeepai/Mava
ff_ippo_rware.py
get_learner_fn
get_learner_fn
Get the learner function.
[ "Get", "the", "learner", "function." ]
def get_learner_fn(env: jumanji.Environment, apply_fns: Tuple[Callable, Callable], update_fns: Tuple[Callable, Callable], config: Dict) -> Callable: (actor_apply_fn, critic_apply_fn) = apply_fns (actor_update_fn, critic_update_fn) = update_fns def _update_step(learner_state: LearnerState, _: Any) -> Tuple[...
['def', 'get_learner_fn(env:', 'jumanji.Environment,', 'apply_fns:', 'Tuple[Callable,', 'Callable],', 'update_fns:', 'Tuple[Callable,', 'Callable],', 'config:', 'Dict)', '->', 'Callable:', '(actor_apply_fn,', 'critic_apply_fn)', '=', 'apply_fns', '(actor_update_fn,', 'critic_update_fn)', '=', 'update_fns', 'def', '_upd...
209,874
tonybeltramelli/Graphics-And-Vision
CamerasParameters.py
CamerasParameters.DistCoeffs2
DistCoeffs2
Set the second camera distortion parameters.
[ "Set", "the", "second", "camera", "distortion", "parameters." ]
def DistCoeffs2(self, value): self.__distCoeffs2 = value
['def', 'DistCoeffs2(self,', 'value):', 'self.__distCoeffs2', '=', 'value']
580,589
GatorEducator/GatorMiner
test_analyzer.py
test_tfidf
test_tfidf
Test tfidf return result.
[ "Test", "tfidf", "return", "result." ]
def test_tfidf(): input_tokens = ['test', 'tokenize', 'break', 'str', 'list', 'str', 'correctly'] (term_frequency, vector) = az.compute_tfidf(input_tokens) assert term_frequency is not None assert vector is not None
['def', 'test_tfidf():', 'input_tokens', '=', "['test',", "'tokenize',", "'break',", "'str',", "'list',", "'str',", "'correctly']", '(term_frequency,', 'vector)', '=', 'az.compute_tfidf(input_tokens)', 'assert', 'term_frequency', 'is', 'not', 'None', 'assert', 'vector', 'is', 'not', 'None']
567,461
arshpreetsingh/quantopian-machinelearning
kill_ring.py
KillRing.clear
clear
Clears the kill ring.
[ "Clears", "the", "kill", "ring." ]
def clear(self): self._index = -1 self._ring = []
['def', 'clear(self):', 'self._index', '=', '-1', 'self._ring', '=', '[]']
892,894
RasaHQ/rasa
structures.py
StoryStep.is_action_unlikely_intent
is_action_unlikely_intent
Checks if the executed action is a `action_unlikely_intent`.
[ "Checks", "if", "the", "executed", "action", "is", "a", "`action_unlikely_intent`." ]
def is_action_unlikely_intent(event: Event) -> bool: return type(event) == ActionExecuted and event.action_name == ACTION_UNLIKELY_INTENT_NAME
['def', 'is_action_unlikely_intent(event:', 'Event)', '->', 'bool:', 'return', 'type(event)', '==', 'ActionExecuted', 'and', 'event.action_name', '==', 'ACTION_UNLIKELY_INTENT_NAME']
837,568
enlite-ai/maze
torch_policy_output.py
PolicySubStepOutput.entropy
entropy
The entropy of the probability distribution.
[ "The", "entropy", "of", "the", "probability", "distribution." ]
def entropy(self) -> torch.Tensor: return self.prob_dist.entropy()
['def', 'entropy(self)', '->', 'torch.Tensor:', 'return', 'self.prob_dist.entropy()']
646,538
sunishsheth2009/ChatterBot
test_password.py
TestPasswordType.test_compare_none
test_compare_none
Should be able to compare a password of ``None``.
[ "Should", "be", "able", "to", "compare", "a", "password", "of", "``None``." ]
def test_compare_none(self): obj = self.User() obj.password = None assert obj.password is None assert obj.password == None obj.password = 'b' assert obj.password is not None assert obj.password != None
['def', 'test_compare_none(self):', 'obj', '=', 'self.User()', 'obj.password', '=', 'None', 'assert', 'obj.password', 'is', 'None', 'assert', 'obj.password', '==', 'None', 'obj.password', '=', "'b'", 'assert', 'obj.password', 'is', 'not', 'None', 'assert', 'obj.password', '!=', 'None']
482,970
cm-amaya/UNet_Multiclass
utils.py
visualize
visualize
PLot images in one row.
[ "PLot", "images", "in", "one", "row." ]
def visualize(**images): n = len(images) plt.figure(figsize=(16, 5)) for (i, (name, image)) in enumerate(images.items()): plt.subplot(1, n, i + 1) plt.xticks([]) plt.yticks([]) plt.title(' '.join(name.split('_')).title()) plt.imshow(image) plt.show()
['def', 'visualize(**images):', 'n', '=', 'len(images)', 'plt.figure(figsize=(16,', '5))', 'for', '(i,', '(name,', 'image))', 'in', 'enumerate(images.items()):', 'plt.subplot(1,', 'n,', 'i', '+', '1)', 'plt.xticks([])', 'plt.yticks([])', "plt.title('", "'.join(name.split('_')).title())", 'plt.imshow(image)', 'plt.show(...
947,943
instadeepai/jumanji
wrappers_test.py
TestJumanjiEnvironmentToDeepMindEnv.test_jumanji_environment_to_deep_mind_env__step
test_jumanji_environment_to_deep_mind_env__step
Validates step function of the wrapped environment.
[ "Validates", "step", "function", "of", "the", "wrapped", "environment." ]
def test_jumanji_environment_to_deep_mind_env__step(self, fake_dm_env: JumanjiToDMEnvWrapper) -> None: timestep = fake_dm_env.reset() action = fake_dm_env.action_spec().generate_value() next_timestep = fake_dm_env.step(action) assert next_timestep != timestep
['def', 'test_jumanji_environment_to_deep_mind_env__step(self,', 'fake_dm_env:', 'JumanjiToDMEnvWrapper)', '->', 'None:', 'timestep', '=', 'fake_dm_env.reset()', 'action', '=', 'fake_dm_env.action_spec().generate_value()', 'next_timestep', '=', 'fake_dm_env.step(action)', 'assert', 'next_timestep', '!=', 'timestep']
593,930
google-research/batch_rl
atari_helpers.py
random_stochastic_matrix
random_stochastic_matrix
Generates a random left stochastic matrix.
[ "Generates", "a", "random", "left", "stochastic", "matrix." ]
def random_stochastic_matrix(dim, num_cols=None, dtype=tf.float32): mat_shape = (dim, dim) if num_cols is None else (dim, num_cols) mat = tf.random.uniform(shape=mat_shape, dtype=dtype) mat /= tf.norm(mat, ord=1, axis=0, keepdims=True) return mat
['def', 'random_stochastic_matrix(dim,', 'num_cols=None,', 'dtype=tf.float32):', 'mat_shape', '=', '(dim,', 'dim)', 'if', 'num_cols', 'is', 'None', 'else', '(dim,', 'num_cols)', 'mat', '=', 'tf.random.uniform(shape=mat_shape,', 'dtype=dtype)', 'mat', '/=', 'tf.norm(mat,', 'ord=1,', 'axis=0,', 'keepdims=True)', 'return'...
105,889