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
PKU-Alignment/safe-rlhf
utils.py
seed_everything
seed_everything
Set global random seed for reproducibility.
[ "Set", "global", "random", "seed", "for", "reproducibility." ]
def seed_everything(seed: int) -> None: os.environ['PYTHONHASHSEED'] = str(seed) random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed)
['def', 'seed_everything(seed:', 'int)', '->', 'None:', "os.environ['PYTHONHASHSEED']", '=', 'str(seed)', 'random.seed(seed)', 'np.random.seed(seed)', 'torch.manual_seed(seed)', 'torch.cuda.manual_seed_all(seed)']
829,119
Ruturaj123/Flowchart-Detection
dnn.py
DNNClassifier.predict_classes
predict_classes
Returns predicted classes for given features.
[ "Returns", "predicted", "classes", "for", "given", "features." ]
def predict_classes(self, x=None, input_fn=None, batch_size=None, as_iterable=True): key = prediction_key.PredictionKey.CLASSES preds = super(DNNClassifier, self).predict(x=x, input_fn=input_fn, batch_size=batch_size, outputs=[key], as_iterable=as_iterable) if as_iterable: return (pred[key] for pred...
['def', 'predict_classes(self,', 'x=None,', 'input_fn=None,', 'batch_size=None,', 'as_iterable=True):', 'key', '=', 'prediction_key.PredictionKey.CLASSES', 'preds', '=', 'super(DNNClassifier,', 'self).predict(x=x,', 'input_fn=input_fn,', 'batch_size=batch_size,', 'outputs=[key],', 'as_iterable=as_iterable)', 'if', 'as_...
603,879
sarnsdev/social-alignment-data-mining
basic.py
Split.grad
grad
Join the gradients along the axis that was used to split x.
[ "Join", "the", "gradients", "along", "the", "axis", "that", "was", "used", "to", "split", "x." ]
def grad(self, inputs, g_outputs): (x, axis, n) = inputs outputs = self(*inputs, **dict(return_list=True)) if python_all([isinstance(g.type, DisconnectedType) for g in g_outputs]): return [DisconnectedType()(), grad_undefined(self, 1, axis), grad_undefined(self, 2, n)] new_g_outputs = [] for...
['def', 'grad(self,', 'inputs,', 'g_outputs):', '(x,', 'axis,', 'n)', '=', 'inputs', 'outputs', '=', 'self(*inputs,', '**dict(return_list=True))', 'if', 'python_all([isinstance(g.type,', 'DisconnectedType)', 'for', 'g', 'in', 'g_outputs]):', 'return', '[DisconnectedType()(),', 'grad_undefined(self,', '1,', 'axis),', 'g...
393,055
matsu0228/nlp-jp
connection.py
MWSConnection.get_report_request_count
get_report_request_count
Returns a count of report requests that have been submitted to Amazon MWS for processing.
[ "Returns", "a", "count", "of", "report", "requests", "that", "have", "been", "submitted", "to", "Amazon", "MWS", "for", "processing." ]
def get_report_request_count(self, request, response, **kw): return self._post_request(request, kw, response)
['def', 'get_report_request_count(self,', 'request,', 'response,', '**kw):', 'return', 'self._post_request(request,', 'kw,', 'response)']
784,934
ibarrien/SemiSupervisedLearning
preprocessing.py
TextPreProcessor.process_documents_text
process_documents_text
Apply basic text pre-processing to loaded data.
[ "Apply", "basic", "text", "pre-processing", "to", "loaded", "data." ]
def process_documents_text(self, documents_array: np.ndarray) -> List[str]: assert len(documents_array) > 0, 'Received no documents for text preprocessing' if type(documents_array) == str or type(documents_array) == np.str_: print('Warning in process_documents_text: received single doc as str, not array...
['def', 'process_documents_text(self,', 'documents_array:', 'np.ndarray)', '->', 'List[str]:', 'assert', 'len(documents_array)', '>', '0,', "'Received", 'no', 'documents', 'for', 'text', "preprocessing'", 'if', 'type(documents_array)', '==', 'str', 'or', 'type(documents_array)', '==', 'np.str_:', "print('Warning", 'in'...
343,772
zihuitang/medical_AI_platform
ss1.py
SheetGUI.tab_event
tab_event
Callback for the Tab key.
[ "Callback", "for", "the", "Tab", "key." ]
def tab_event(self, event): self.change_cell() (x, y) = self.currentxy self.setcurrent(x + 1, y) return 'break'
['def', 'tab_event(self,', 'event):', 'self.change_cell()', '(x,', 'y)', '=', 'self.currentxy', 'self.setcurrent(x', '+', '1,', 'y)', 'return', "'break'"]
284,741
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
__init__.py
Canvas.select_adjust
select_adjust
Adjust the end of the selection near the cursor of an item TAGORID to index.
[ "Adjust", "the", "end", "of", "the", "selection", "near", "the", "cursor", "of", "an", "item", "TAGORID", "to", "index." ]
def select_adjust(self, tagOrId, index): self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
['def', 'select_adjust(self,', 'tagOrId,', 'index):', 'self.tk.call(self._w,', "'select',", "'adjust',", 'tagOrId,', 'index)']
376,971
alugupta/ares
utils.py
mkdirs_if_not_exists
mkdirs_if_not_exists
Make dirs if it does not exist.
[ "Make", "dirs", "if", "it", "does", "not", "exist." ]
def mkdirs_if_not_exists(dir): if not os.path.exists(dir): os.makedirs(dir)
['def', 'mkdirs_if_not_exists(dir):', 'if', 'not', 'os.path.exists(dir):', 'os.makedirs(dir)']
402,090
chainer/chainer
babi.py
parse_line
parse_line
Parses each line and make a named tuple.
[ "Parses", "each", "line", "and", "make", "a", "named", "tuple." ]
def parse_line(vocab, line): if '\t' in line: (question, answer, fact_id) = line.split('\t') aid = convert(vocab, [answer])[0] words = split(question) wid = convert(vocab, words) ids = list(map(int, fact_id.split(' '))) return Query(wid, aid, ids) else: wo...
['def', 'parse_line(vocab,', 'line):', 'if', "'\\t'", 'in', 'line:', '(question,', 'answer,', 'fact_id)', '=', "line.split('\\t')", 'aid', '=', 'convert(vocab,', '[answer])[0]', 'words', '=', 'split(question)', 'wid', '=', 'convert(vocab,', 'words)', 'ids', '=', 'list(map(int,', "fact_id.split('", "')))", 'return', 'Qu...
477,676
enuguru/artificial_intelligence_and_machine_
meta.py
DefaultMeta.update_values
update_values
Given a dictionary of values, update values on this `Meta` instance.
[ "Given", "a", "dictionary", "of", "values,", "update", "values", "on", "this", "`Meta`", "instance." ]
def update_values(self, values): for (key, value) in values.items(): setattr(self, key, value)
['def', 'update_values(self,', 'values):', 'for', '(key,', 'value)', 'in', 'values.items():', 'setattr(self,', 'key,', 'value)']
162,884
open-mmlab/mmrotate
utils.py
AlignConv.get_offset
get_offset
Get the offset of AlignConv.
[ "Get", "the", "offset", "of", "AlignConv." ]
def get_offset(self, anchors, featmap_size, stride): (dtype, device) = (anchors.dtype, anchors.device) (feat_h, feat_w) = featmap_size pad = (self.kernel_size - 1) // 2 idx = torch.arange(-pad, pad + 1, dtype=dtype, device=device) (yy, xx) = torch.meshgrid(idx, idx) xx = xx.reshape(-1) yy = ...
['def', 'get_offset(self,', 'anchors,', 'featmap_size,', 'stride):', '(dtype,', 'device)', '=', '(anchors.dtype,', 'anchors.device)', '(feat_h,', 'feat_w)', '=', 'featmap_size', 'pad', '=', '(self.kernel_size', '-', '1)', '//', '2', 'idx', '=', 'torch.arange(-pad,', 'pad', '+', '1,', 'dtype=dtype,', 'device=device)', '...
625,192
onnx/onnx
shape_inference.py
infer_function_output_types
infer_function_output_types
Apply type-and-shape-inference to given function body, with given input types and given input attribute values.
[ "Apply", "type-and-shape-inference", "to", "given", "function", "body,", "with", "given", "input", "types", "and", "given", "input", "attribute", "values." ]
def infer_function_output_types(function: FunctionProto, input_types: Sequence[TypeProto], attributes: Sequence[AttributeProto]) -> list[TypeProto]: result = C.infer_function_output_types(function.SerializeToString(), [x.SerializeToString() for x in input_types], [x.SerializeToString() for x in attributes]) de...
['def', 'infer_function_output_types(function:', 'FunctionProto,', 'input_types:', 'Sequence[TypeProto],', 'attributes:', 'Sequence[AttributeProto])', '->', 'list[TypeProto]:', 'result', '=', 'C.infer_function_output_types(function.SerializeToString(),', '[x.SerializeToString()', 'for', 'x', 'in', 'input_types],', '[x....
756,444
danamyu/hedgehog_detector
check.py
Is
Is
Raises an error if |lhs| is not |rhs|.
[ "Raises", "an", "error", "if", "|lhs|", "is", "not", "|rhs|." ]
def Is(lhs, rhs, message='', error=ValueError): if lhs is not rhs: raise error('Expected (%s) is (%s): %s' % (lhs, rhs, message))
['def', 'Is(lhs,', 'rhs,', "message='',", 'error=ValueError):', 'if', 'lhs', 'is', 'not', 'rhs:', 'raise', "error('Expected", '(%s)', 'is', '(%s):', "%s'", '%', '(lhs,', 'rhs,', 'message))']
590,690
BigEggStudy/UC-Berkeley-CS-188-Artificial-
town.py
Town.getDistance
getDistance
loc1: A name of a place ('home' or the name of a FruitShop in town) loc2: A name of a place ('home' or the name of a FruitShop in town) Returns the distance between these two places in this town.
[ "loc1:", "A", "name", "of", "a", "place", "('home'", "or", "the", "name", "of", "a", "FruitShop", "in", "town)", "loc2:", "A", "name", "of", "a", "place", "('home'", "or", "the", "name", "of", "a", "FruitShop", "in", "town)", "Returns", "the", "distanc...
def getDistance(self, loc1, loc2): if (loc1, loc2) in self.distances: return self.distances[loc1, loc2] return self.distances[loc2, loc1]
['def', 'getDistance(self,', 'loc1,', 'loc2):', 'if', '(loc1,', 'loc2)', 'in', 'self.distances:', 'return', 'self.distances[loc1,', 'loc2]', 'return', 'self.distances[loc2,', 'loc1]']
426,671
JanMarcelKezmann/Semi-Supervised-Learning-Image-Classification
mixup.py
mixup
mixup
Applies mixup algorithm to input images and its corresponding labels and returns them.
[ "Applies", "mixup", "algorithm", "to", "input", "images", "and", "its", "corresponding", "labels", "and", "returns", "them." ]
def mixup(x1, x2, y1, y2, beta, alg): beta = tf.maximum(beta, 1 - beta) if alg.lower() == 'mixmatch': x = beta * x1 + (1 - beta) * x2 y = beta * y1 + (1 - beta) * y2 elif alg.lower() in ['mixup', 'vat']: x = beta * x1 + (1 - beta) * x2 y = beta[:, :, 0, 0] * y1 + (1 - beta[:,...
['def', 'mixup(x1,', 'x2,', 'y1,', 'y2,', 'beta,', 'alg):', 'beta', '=', 'tf.maximum(beta,', '1', '-', 'beta)', 'if', 'alg.lower()', '==', "'mixmatch':", 'x', '=', 'beta', '*', 'x1', '+', '(1', '-', 'beta)', '*', 'x2', 'y', '=', 'beta', '*', 'y1', '+', '(1', '-', 'beta)', '*', 'y2', 'elif', 'alg.lower()', 'in', "['mixu...
343,353
QData/deepWordBug
keyboard.py
Keystroke.is_sequence
is_sequence
Whether the value represents a multibyte sequence (bool).
[ "Whether", "the", "value", "represents", "a", "multibyte", "sequence", "(bool)." ]
def is_sequence(self): return self._code is not None
['def', 'is_sequence(self):', 'return', 'self._code', 'is', 'not', 'None']
541,058
sunishsheth2009/ChatterBot
test_password.py
TestPasswordType.test_check
test_check
Should be able to compare the plaintext against the encrypted form.
[ "Should", "be", "able", "to", "compare", "the", "plaintext", "against", "the", "encrypted", "form." ]
def test_check(self): obj = self.User() obj.password = 'b' assert obj.password == 'b' assert obj.password != 'a' self.session.add(obj) self.session.commit() obj = self.session.query(self.User).get(obj.id) assert obj.password == b'b' assert obj.password != 'a'
['def', 'test_check(self):', 'obj', '=', 'self.User()', 'obj.password', '=', "'b'", 'assert', 'obj.password', '==', "'b'", 'assert', 'obj.password', '!=', "'a'", 'self.session.add(obj)', 'self.session.commit()', 'obj', '=', 'self.session.query(self.User).get(obj.id)', 'assert', 'obj.password', '==', "b'b'", 'assert', '...
482,966
codekansas/gandlf
reversing_gan.py
get_mnist_data
get_mnist_data
Puts the MNIST data in the right format.
[ "Puts", "the", "MNIST", "data", "in", "the", "right", "format." ]
def get_mnist_data(binarize=False): ((X_train, y_train), (X_test, y_test)) = mnist.load_data() if binarize: X_test = np.where(X_test >= 10, 1, -1) X_train = np.where(X_train >= 10, 1, -1) else: X_train = (X_train.astype(np.float32) - 127.5) / 127.5 X_test = (X_test.astype(np....
['def', 'get_mnist_data(binarize=False):', '((X_train,', 'y_train),', '(X_test,', 'y_test))', '=', 'mnist.load_data()', 'if', 'binarize:', 'X_test', '=', 'np.where(X_test', '>=', '10,', '1,', '-1)', 'X_train', '=', 'np.where(X_train', '>=', '10,', '1,', '-1)', 'else:', 'X_train', '=', '(X_train.astype(np.float32)', '-'...
566,526
huawei-noah/xingtian
model.py
SimclrModel.forward
forward
Compute the output of simclr model.
[ "Compute", "the", "output", "of", "simclr", "model." ]
def forward(self, x): x = self.f(x) feature = torch.flatten(x, start_dim=1) out = self.g(feature) return (F.normalize(feature, dim=-1), F.normalize(out, dim=-1))
['def', 'forward(self,', 'x):', 'x', '=', 'self.f(x)', 'feature', '=', 'torch.flatten(x,', 'start_dim=1)', 'out', '=', 'self.g(feature)', 'return', '(F.normalize(feature,', 'dim=-1),', 'F.normalize(out,', 'dim=-1))']
968,520
jrieke/traingenerator
sidebar.py
show
show
Shows the sidebar components for the template and returns user inputs as dict.
[ "Shows", "the", "sidebar", "components", "for", "the", "template", "and", "returns", "user", "inputs", "as", "dict." ]
def show(): inputs = {} with st.sidebar: st.write('Coming soon! [Tell me](mailto:johannes.rieke@gmail.com) what you need.') return inputs
['def', 'show():', 'inputs', '=', '{}', 'with', 'st.sidebar:', "st.write('Coming", 'soon!', '[Tell', 'me](mailto:johannes.rieke@gmail.com)', 'what', 'you', "need.')", 'return', 'inputs']
903,829
voxel51/fiftyone
metadata.py
ImageMetadata.build_for
build_for
Builds an :class:`ImageMetadata` object for the given image.
[ "Builds", "an", ":class:`ImageMetadata`", "object", "for", "the", "given", "image." ]
def build_for(cls, img_or_path_or_url, mime_type=None): if not etau.is_str(img_or_path_or_url): return cls._build_for_img(img_or_path_or_url, mime_type=mime_type) if img_or_path_or_url.startswith('http'): return cls._build_for_url(img_or_path_or_url, mime_type=mime_type) return cls._build_fo...
['def', 'build_for(cls,', 'img_or_path_or_url,', 'mime_type=None):', 'if', 'not', 'etau.is_str(img_or_path_or_url):', 'return', 'cls._build_for_img(img_or_path_or_url,', 'mime_type=mime_type)', 'if', "img_or_path_or_url.startswith('http'):", 'return', 'cls._build_for_url(img_or_path_or_url,', 'mime_type=mime_type)', 'r...
583,186
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
categorical.py
Categorical.T
T
Return transposed numpy array.
[ "Return", "transposed", "numpy", "array." ]
def T(self): return self
['def', 'T(self):', 'return', 'self']
967,347
tobegit3hub/deep_image_model
subgraph.py
SubGraphView.input_index
input_index
Find the input index corresponding to the given input tensor t.
[ "Find", "the", "input", "index", "corresponding", "to", "the", "given", "input", "tensor", "t." ]
def input_index(self, t): try: subgraph_id = self._input_ts.index(t) except: raise ValueError("Can't find {} in inputs of subgraph {}.".format(t.name, self.name)) return subgraph_id
['def', 'input_index(self,', 't):', 'try:', 'subgraph_id', '=', 'self._input_ts.index(t)', 'except:', 'raise', 'ValueError("Can\'t', 'find', '{}', 'in', 'inputs', 'of', 'subgraph', '{}.".format(t.name,', 'self.name))', 'return', 'subgraph_id']
181,385
aws/sagemaker-python-sdk
model.py
XGBoostModel.serving_image_uri
serving_image_uri
Create a URI for the serving image.
[ "Create", "a", "URI", "for", "the", "serving", "image." ]
def serving_image_uri(self, region_name, instance_type, serverless_inference_config=None): return image_uris.retrieve(self._framework_name, region_name, version=self.framework_version, instance_type=instance_type, serverless_inference_config=serverless_inference_config)
['def', 'serving_image_uri(self,', 'region_name,', 'instance_type,', 'serverless_inference_config=None):', 'return', 'image_uris.retrieve(self._framework_name,', 'region_name,', 'version=self.framework_version,', 'instance_type=instance_type,', 'serverless_inference_config=serverless_inference_config)']
830,722
KKKSQJ/DeepLearning
evaluator.py
Evaluator.eval_func
eval_func
Evaluation with market1501 metric Key: for each query identity, its gallery images from the same camera view are discarded.
[ "Evaluation", "with", "market1501", "metric", "Key:", "for", "each", "query", "identity,", "its", "gallery", "images", "from", "the", "same", "camera", "view", "are", "discarded." ]
def eval_func(self, distmat, q_pids, g_pids, q_camids, g_camids, max_rank=50): (num_q, num_g) = distmat.shape if num_g < max_rank: max_rank = num_g print('Note: number of gallery samples is quite small, got {}'.format(num_g)) indices = np.argsort(distmat, axis=1) matches = (g_pids[indice...
['def', 'eval_func(self,', 'distmat,', 'q_pids,', 'g_pids,', 'q_camids,', 'g_camids,', 'max_rank=50):', '(num_q,', 'num_g)', '=', 'distmat.shape', 'if', 'num_g', '<', 'max_rank:', 'max_rank', '=', 'num_g', "print('Note:", 'number', 'of', 'gallery', 'samples', 'is', 'quite', 'small,', 'got', "{}'.format(num_g))", 'indic...
180,569
gopinath-balu/computer_vision
app.py
start_from_terminal
start_from_terminal
Parse command line options and start the server.
[ "Parse", "command", "line", "options", "and", "start", "the", "server." ]
def start_from_terminal(app): parser = optparse.OptionParser() parser.add_option('-d', '--debug', help='enable debug mode', action='store_true', default=False) parser.add_option('-p', '--port', help='which port to serve content on', type='int', default=5000) parser.add_option('-g', '--gpu', help='use gp...
['def', 'start_from_terminal(app):', 'parser', '=', 'optparse.OptionParser()', "parser.add_option('-d',", "'--debug',", "help='enable", 'debug', "mode',", "action='store_true',", 'default=False)', "parser.add_option('-p',", "'--port',", "help='which", 'port', 'to', 'serve', 'content', "on',", "type='int',", 'default=50...
472,430
rudranil723/mini-main
enum_type_wrapper.py
EnumTypeWrapper.Name
Name
Returns a string containing the name of an enum value.
[ "Returns", "a", "string", "containing", "the", "name", "of", "an", "enum", "value." ]
def Name(self, number): try: return self._enum_type.values_by_number[number].name except KeyError: pass if not isinstance(number, int): raise TypeError('Enum value for {} must be an int, but got {} {!r}.'.format(self._enum_type.name, type(number), number)) else: raise Val...
['def', 'Name(self,', 'number):', 'try:', 'return', 'self._enum_type.values_by_number[number].name', 'except', 'KeyError:', 'pass', 'if', 'not', 'isinstance(number,', 'int):', 'raise', "TypeError('Enum", 'value', 'for', '{}', 'must', 'be', 'an', 'int,', 'but', 'got', '{}', "{!r}.'.format(self._enum_type.name,", 'type(n...
318,388
feast-dev/feast
data_source.py
DataSource.validate
validate
Validates the underlying data source.
[ "Validates", "the", "underlying", "data", "source." ]
def validate(self, config: RepoConfig): raise NotImplementedError
['def', 'validate(self,', 'config:', 'RepoConfig):', 'raise', 'NotImplementedError']
544,208
RasaHQ/rasa
common.py
extract_duplicates
extract_duplicates
Extracts duplicates from two lists.
[ "Extracts", "duplicates", "from", "two", "lists." ]
def extract_duplicates(list1: List[Any], list2: List[Any]) -> List[Any]: if list1: dict1 = {sorted(list(i.keys()))[0] if isinstance(i, dict) else i: i for i in list1} else: dict1 = {} if list2: dict2 = {sorted(list(i.keys()))[0] if isinstance(i, dict) else i: i for i in list2} el...
['def', 'extract_duplicates(list1:', 'List[Any],', 'list2:', 'List[Any])', '->', 'List[Any]:', 'if', 'list1:', 'dict1', '=', '{sorted(list(i.keys()))[0]', 'if', 'isinstance(i,', 'dict)', 'else', 'i:', 'i', 'for', 'i', 'in', 'list1}', 'else:', 'dict1', '=', '{}', 'if', 'list2:', 'dict2', '=', '{sorted(list(i.keys()))[0]...
837,785
weimin17/Object-Detection_HelmetDetection
mnist_eager.py
train
train
Trains model on `dataset` using `optimizer`.
[ "Trains", "model", "on", "`dataset`", "using", "`optimizer`." ]
def train(model, optimizer, dataset, step_counter, log_interval=None): start = time.time() for (batch, (images, labels)) in enumerate(tfe.Iterator(dataset)): with tf.contrib.summary.record_summaries_every_n_global_steps(10, global_step=step_counter): with tf.GradientTape() as tape: ...
['def', 'train(model,', 'optimizer,', 'dataset,', 'step_counter,', 'log_interval=None):', 'start', '=', 'time.time()', 'for', '(batch,', '(images,', 'labels))', 'in', 'enumerate(tfe.Iterator(dataset)):', 'with', 'tf.contrib.summary.record_summaries_every_n_global_steps(10,', 'global_step=step_counter):', 'with', 'tf.Gr...
748,578
sktime/sktime
test_tsfresh.py
test_tsfresh_extractor
test_tsfresh_extractor
Test that mean feature of TSFreshFeatureExtract is identical with sample mean.
[ "Test", "that", "mean", "feature", "of", "TSFreshFeatureExtract", "is", "identical", "with", "sample", "mean." ]
def test_tsfresh_extractor(default_fc_parameters): (X, _) = make_classification_problem() transformer = TSFreshFeatureExtractor(default_fc_parameters=default_fc_parameters, disable_progressbar=True) Xt = transformer.fit_transform(X) actual = Xt.filter(like='__mean', axis=1).values.ravel() converted ...
['def', 'test_tsfresh_extractor(default_fc_parameters):', '(X,', '_)', '=', 'make_classification_problem()', 'transformer', '=', 'TSFreshFeatureExtractor(default_fc_parameters=default_fc_parameters,', 'disable_progressbar=True)', 'Xt', '=', 'transformer.fit_transform(X)', 'actual', '=', "Xt.filter(like='__mean',", 'axi...
877,774
Farama-Foundation/Gymnasium
sequence.py
Sequence.seed
seed
Seed the PRNG of this space and the feature space.
[ "Seed", "the", "PRNG", "of", "this", "space", "and", "the", "feature", "space." ]
def seed(self, seed: int | None=None) -> list[int]: seeds = super().seed(seed) seeds += self.feature_space.seed(seed) return seeds
['def', 'seed(self,', 'seed:', 'int', '|', 'None=None)', '->', 'list[int]:', 'seeds', '=', 'super().seed(seed)', 'seeds', '+=', 'self.feature_space.seed(seed)', 'return', 'seeds']
573,267
AiIsBetter/computer_vision
text_dataflow.py
affine_transform
affine_transform
Conduct same affine transform for both image and polygon for data augmentation.
[ "Conduct", "same", "affine", "transform", "for", "both", "image", "and", "polygon", "for", "data", "augmentation." ]
def affine_transform(image, polygon): (height, width, _) = image.shape (center_x, center_y) = (width / 2, height / 2) angle = 0 if np.random.uniform() > 0.5 else np.random.uniform(-20.0, 20.0) (shear_x, shear_y) = (0, 0) if np.random.uniform() > 0.5 else (np.random.uniform(-0.2, 0.2), np.random.uniform(...
['def', 'affine_transform(image,', 'polygon):', '(height,', 'width,', '_)', '=', 'image.shape', '(center_x,', 'center_y)', '=', '(width', '/', '2,', 'height', '/', '2)', 'angle', '=', '0', 'if', 'np.random.uniform()', '>', '0.5', 'else', 'np.random.uniform(-20.0,', '20.0)', '(shear_x,', 'shear_y)', '=', '(0,', '0)', 'i...
501,507
wandb/wandb
filesystem.py
safe_copy
safe_copy
Copy a file, ensuring any changes only apply atomically once finished.
[ "Copy", "a", "file,", "ensuring", "any", "changes", "only", "apply", "atomically", "once", "finished." ]
def safe_copy(source_path: StrPath, target_path: StrPath) -> StrPath: output_path = Path(target_path).resolve() output_path.parent.mkdir(parents=True, exist_ok=True) with tempfile.TemporaryDirectory(dir=output_path.parent) as tmp_dir: tmp_path = (Path(tmp_dir) / Path(source_path).name).with_suffix('...
['def', 'safe_copy(source_path:', 'StrPath,', 'target_path:', 'StrPath)', '->', 'StrPath:', 'output_path', '=', 'Path(target_path).resolve()', 'output_path.parent.mkdir(parents=True,', 'exist_ok=True)', 'with', 'tempfile.TemporaryDirectory(dir=output_path.parent)', 'as', 'tmp_dir:', 'tmp_path', '=', '(Path(tmp_dir)', '...
941,910
TrellixVulnTeam/Unsupervised_Learning_HFI7
test_templateexporter.py
TestExporter.test_raw_template_dereassignment
test_raw_template_dereassignment
Test `raw_template` does not overwrite template_file if deassigned after being assigned to a non-custom Exporter.
[ "Test", "`raw_template`", "does", "not", "overwrite", "template_file", "if", "deassigned", "after", "being", "assigned", "to", "a", "non-custom", "Exporter." ]
def test_raw_template_dereassignment(self): nb = v4.new_notebook() nb.cells.append(v4.new_code_cell('some_text')) exporter_dereassign = RSTExporter() exporter_dereassign.raw_template = raw_template (output_dereassign, _) = exporter_dereassign.from_notebook_node(nb) assert 'blah' in output_dereas...
['def', 'test_raw_template_dereassignment(self):', 'nb', '=', 'v4.new_notebook()', "nb.cells.append(v4.new_code_cell('some_text'))", 'exporter_dereassign', '=', 'RSTExporter()', 'exporter_dereassign.raw_template', '=', 'raw_template', '(output_dereassign,', '_)', '=', 'exporter_dereassign.from_notebook_node(nb)', 'asse...
451,694
ryu-ed/SpaceInvaders_Ros
statemachine.py
StateMachine.abs_line_offset
abs_line_offset
Return line offset of current line, from beginning of file.
[ "Return", "line", "offset", "of", "current", "line,", "from", "beginning", "of", "file." ]
def abs_line_offset(self): return self.line_offset + self.input_offset
['def', 'abs_line_offset(self):', 'return', 'self.line_offset', '+', 'self.input_offset']
394,810
danaugrs/huskarl
simulation.py
Simulation.train
train
Trains the agent on the specified number of environment instances.
[ "Trains", "the", "agent", "on", "the", "specified", "number", "of", "environment", "instances." ]
def train(self, max_steps=100000, instances=1, visualize=False, plot=None, max_subprocesses=0): self.agent.training = True if max_subprocesses == 0: self._sp_train(max_steps, instances, visualize, plot) elif max_subprocesses is None or max_subprocesses > 0: self._mp_train(max_steps, instance...
['def', 'train(self,', 'max_steps=100000,', 'instances=1,', 'visualize=False,', 'plot=None,', 'max_subprocesses=0):', 'self.agent.training', '=', 'True', 'if', 'max_subprocesses', '==', '0:', 'self._sp_train(max_steps,', 'instances,', 'visualize,', 'plot)', 'elif', 'max_subprocesses', 'is', 'None', 'or', 'max_subproces...
206,826
QData/deepWordBug
references.py
Footnotes.symbolize_footnotes
symbolize_footnotes
Add symbols indexes to "[*]"-style footnotes and references.
[ "Add", "symbols", "indexes", "to", "\"[*]\"-style", "footnotes", "and", "references." ]
def symbolize_footnotes(self): labels = [] for footnote in self.document.symbol_footnotes: (reps, index) = divmod(self.document.symbol_footnote_start, len(self.symbols)) labeltext = self.symbols[index] * (reps + 1) labels.append(labeltext) footnote.insert(0, nodes.label('', label...
['def', 'symbolize_footnotes(self):', 'labels', '=', '[]', 'for', 'footnote', 'in', 'self.document.symbol_footnotes:', '(reps,', 'index)', '=', 'divmod(self.document.symbol_footnote_start,', 'len(self.symbols))', 'labeltext', '=', 'self.symbols[index]', '*', '(reps', '+', '1)', 'labels.append(labeltext)', 'footnote.ins...
542,254
Firyuza/SGAN
extract_pfd_features.py
chunks
chunks
Yield n-sized chunks from list of pfd files.
[ "Yield", "n-sized", "chunks", "from", "list", "of", "pfd", "files." ]
def chunks(pfd_files, n): for i in range(0, len(pfd_files), n): yield pfd_files[i:i + n]
['def', 'chunks(pfd_files,', 'n):', 'for', 'i', 'in', 'range(0,', 'len(pfd_files),', 'n):', 'yield', 'pfd_files[i:i', '+', 'n]']
898,665
TheCurryMan/MedicAI
datastructures.py
Range.range_for_length
range_for_length
If the range is for bytes, the length is not None and there is exactly one range and it is satisfiable it returns a ``(start, stop)`` tuple, otherwise `None`.
[ "If", "the", "range", "is", "for", "bytes,", "the", "length", "is", "not", "None", "and", "there", "is", "exactly", "one", "range", "and", "it", "is", "satisfiable", "it", "returns", "a", "``(start,", "stop)``", "tuple,", "otherwise", "`None`." ]
def range_for_length(self, length): if self.units != 'bytes' or length is None or len(self.ranges) != 1: return None (start, end) = self.ranges[0] if end is None: end = length if start < 0: start += length if is_byte_range_valid(start, end, length): return (st...
['def', 'range_for_length(self,', 'length):', 'if', 'self.units', '!=', "'bytes'", 'or', 'length', 'is', 'None', 'or', 'len(self.ranges)', '!=', '1:', 'return', 'None', '(start,', 'end)', '=', 'self.ranges[0]', 'if', 'end', 'is', 'None:', 'end', '=', 'length', 'if', 'start', '<', '0:', 'start', '+=', 'length', 'if', 'i...
649,572
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
registry_test.py
RegistryTest.testCannotCreateMissingPackage
testCannotCreateMissingPackage
Tests that Create fails if the package does not exist.
[ "Tests", "that", "Create", "fails", "if", "the", "package", "does", "not", "exist." ]
def testCannotCreateMissingPackage(self): with self.assertRaisesRegexp(ValueError, 'Failed to create'): registry_test_base.Base.Create('missing.package.path.module.SomeClass', 'hello world')
['def', 'testCannotCreateMissingPackage(self):', 'with', 'self.assertRaisesRegexp(ValueError,', "'Failed", 'to', "create'):", "registry_test_base.Base.Create('missing.package.path.module.SomeClass',", "'hello", "world')"]
111,921
enuguru/artificial_intelligence_and_machine_
compiler.py
FrameIdentifierVisitor.visit_Name
visit_Name
All assignments to names go through this function.
[ "All", "assignments", "to", "names", "go", "through", "this", "function." ]
def visit_Name(self, node): if node.ctx == 'store': self.identifiers.declared_locally.add(node.name) elif node.ctx == 'param': self.identifiers.declared_parameter.add(node.name) elif node.ctx == 'load' and (not self.identifiers.is_declared(node.name)): self.identifiers.undeclared.add...
['def', 'visit_Name(self,', 'node):', 'if', 'node.ctx', '==', "'store':", 'self.identifiers.declared_locally.add(node.name)', 'elif', 'node.ctx', '==', "'param':", 'self.identifiers.declared_parameter.add(node.name)', 'elif', 'node.ctx', '==', "'load'", 'and', '(not', 'self.identifiers.is_declared(node.name)):', 'self....
129,067
GMvandeVen/brain-inspired-replay
vae.py
AutoEncoder.layer_info
layer_info
Return list with shape of all hidden layers.
[ "Return", "list", "with", "shape", "of", "all", "hidden", "layers." ]
def layer_info(self): layer_list = self.convE.layer_info(image_size=self.image_size) if not self.hidden else [] if (self.fc_layers > 0 and self.depth > 0) and (not self.hidden): layer_list.append([self.conv_out_channels, self.conv_out_size, self.conv_out_size]) if self.fc_layers > 1: for lay...
['def', 'layer_info(self):', 'layer_list', '=', 'self.convE.layer_info(image_size=self.image_size)', 'if', 'not', 'self.hidden', 'else', '[]', 'if', '(self.fc_layers', '>', '0', 'and', 'self.depth', '>', '0)', 'and', '(not', 'self.hidden):', 'layer_list.append([self.conv_out_channels,', 'self.conv_out_size,', 'self.con...
466,037
lvwerra/trl
core.py
set_seed
set_seed
Helper function for reproducible behavior to set the seed in `random`, `numpy`, and `torch`.
[ "Helper", "function", "for", "reproducible", "behavior", "to", "set", "the", "seed", "in", "`random`,", "`numpy`,", "and", "`torch`." ]
def set_seed(seed: int): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed)
['def', 'set_seed(seed:', 'int):', 'random.seed(seed)', 'np.random.seed(seed)', 'torch.manual_seed(seed)', 'torch.cuda.manual_seed_all(seed)']
425,863
PacktPublishing/Hands-On-Artificial--for-Banking
test_nlargest.py
s_main_dtypes_split
s_main_dtypes_split
Each series in s_main_dtypes.
[ "Each", "series", "in", "s_main_dtypes." ]
def s_main_dtypes_split(request, s_main_dtypes): return s_main_dtypes[request.param]
['def', 's_main_dtypes_split(request,', 's_main_dtypes):', 'return', 's_main_dtypes[request.param]']
237,325
openvinotoolkit/training_extensions
base_task.py
OTXTask.export
export
Export function of OTX Task.
[ "Export", "function", "of", "OTX", "Task." ]
def export(self, export_type: ExportType, output_model: ModelEntity, precision: ModelPrecision=ModelPrecision.FP32, dump_features: bool=True): raise NotImplementedError
['def', 'export(self,', 'export_type:', 'ExportType,', 'output_model:', 'ModelEntity,', 'precision:', 'ModelPrecision=ModelPrecision.FP32,', 'dump_features:', 'bool=True):', 'raise', 'NotImplementedError']
917,987
deepmind/meltingpot
builder.py
builder
builder
Builds a Melting Pot environment.
[ "Builds", "a", "Melting", "Pot", "environment." ]
def builder(lab2d_settings: Settings, prefab_overrides: Optional[Settings]=None, env_seed: Optional[int]=None, **settings) -> dmlab2d.Environment: del settings assert 'simulation' in lab2d_settings lab2d_settings = config_dict.ConfigDict(copy.deepcopy(lab2d_settings)).unlock() apply_prefab_overrides(lab...
['def', 'builder(lab2d_settings:', 'Settings,', 'prefab_overrides:', 'Optional[Settings]=None,', 'env_seed:', 'Optional[int]=None,', '**settings)', '->', 'dmlab2d.Environment:', 'del', 'settings', 'assert', "'simulation'", 'in', 'lab2d_settings', 'lab2d_settings', '=', 'config_dict.ConfigDict(copy.deepcopy(lab2d_settin...
285,943
lhotse-speech/lhotse
libricss.py
parse_transcript
parse_transcript
Parses the transcript file and returns a list of SupervisionSegment objects.
[ "Parses", "the", "transcript", "file", "and", "returns", "a", "list", "of", "SupervisionSegment", "objects." ]
def parse_transcript(file_name): segments = [] with open(file_name, 'r') as f: next(f) for line in f: (start, end, speaker, utt_id, text) = line.split('\t') segments.append((float(start), float(end), speaker, utt_id, text)) return segments
['def', 'parse_transcript(file_name):', 'segments', '=', '[]', 'with', 'open(file_name,', "'r')", 'as', 'f:', 'next(f)', 'for', 'line', 'in', 'f:', '(start,', 'end,', 'speaker,', 'utt_id,', 'text)', '=', "line.split('\\t')", 'segments.append((float(start),', 'float(end),', 'speaker,', 'utt_id,', 'text))', 'return', 'se...
600,966
batra-mlp-lab/visdial-rl
rank_answerer.py
rankOptions
rankOptions
Rank a batch of examples against a list of options.
[ "Rank", "a", "batch", "of", "examples", "against", "a", "list", "of", "options." ]
def rankOptions(options, gtOptions, scores): numOptions = options.size(1) gtScores = scores.gather(1, gtOptions.unsqueeze(1)) (sortedScore, _) = torch.sort(scores, 1) ranks = torch.sum(sortedScore.gt(gtScores).float(), 1) return ranks + 1
['def', 'rankOptions(options,', 'gtOptions,', 'scores):', 'numOptions', '=', 'options.size(1)', 'gtScores', '=', 'scores.gather(1,', 'gtOptions.unsqueeze(1))', '(sortedScore,', '_)', '=', 'torch.sort(scores,', '1)', 'ranks', '=', 'torch.sum(sortedScore.gt(gtScores).float(),', '1)', 'return', 'ranks', '+', '1']
933,529
Eric3911/OpenAGI
aligner.py
AlignmentEncoder.get_dist
get_dist
Calculation of distance matrix.
[ "Calculation", "of", "distance", "matrix." ]
def get_dist(self, keys, queries, mask=None): keys_enc = self.key_proj(keys) queries_enc = self.query_proj(queries) attn = (queries_enc[:, :, :, None] - keys_enc[:, :, None]) ** 2 dist = attn.sum(1, keepdim=True) if mask is not None: dist.data.masked_fill_(mask.permute(0, 2, 1).unsqueeze(2),...
['def', 'get_dist(self,', 'keys,', 'queries,', 'mask=None):', 'keys_enc', '=', 'self.key_proj(keys)', 'queries_enc', '=', 'self.query_proj(queries)', 'attn', '=', '(queries_enc[:,', ':,', ':,', 'None]', '-', 'keys_enc[:,', ':,', 'None])', '**', '2', 'dist', '=', 'attn.sum(1,', 'keepdim=True)', 'if', 'mask', 'is', 'not'...
273,912
open-mmlab/mmdetection3d
partial_bin_based_bbox_coder.py
PartialBinBasedBBoxCoder.encode
encode
Encode ground truth to prediction targets.
[ "Encode", "ground", "truth", "to", "prediction", "targets." ]
def encode(self, gt_bboxes_3d: BaseInstance3DBoxes, gt_labels_3d: Tensor) -> tuple: center_target = gt_bboxes_3d.gravity_center size_class_target = gt_labels_3d size_res_target = gt_bboxes_3d.dims - gt_bboxes_3d.tensor.new_tensor(self.mean_sizes)[size_class_target] box_num = gt_labels_3d.shape[0] if...
['def', 'encode(self,', 'gt_bboxes_3d:', 'BaseInstance3DBoxes,', 'gt_labels_3d:', 'Tensor)', '->', 'tuple:', 'center_target', '=', 'gt_bboxes_3d.gravity_center', 'size_class_target', '=', 'gt_labels_3d', 'size_res_target', '=', 'gt_bboxes_3d.dims', '-', 'gt_bboxes_3d.tensor.new_tensor(self.mean_sizes)[size_class_target...
632,190
PacktPublishing/Hands-On-Artificial--for-Banking
test_nanfunctions.py
test__replace_nan
test__replace_nan
Test that _replace_nan returns the original array if there are no NaNs, not a copy.
[ "Test", "that", "_replace_nan", "returns", "the", "original", "array", "if", "there", "are", "no", "NaNs,", "not", "a", "copy." ]
def test__replace_nan(): for dtype in [np.bool, np.int32, np.int64]: arr = np.array([0, 1], dtype=dtype) (result, mask) = _replace_nan(arr, 0) assert mask is None assert result is arr for dtype in [np.float32, np.float64]: arr = np.array([0, 1], dtype=dtype) (resu...
['def', 'test__replace_nan():', 'for', 'dtype', 'in', '[np.bool,', 'np.int32,', 'np.int64]:', 'arr', '=', 'np.array([0,', '1],', 'dtype=dtype)', '(result,', 'mask)', '=', '_replace_nan(arr,', '0)', 'assert', 'mask', 'is', 'None', 'assert', 'result', 'is', 'arr', 'for', 'dtype', 'in', '[np.float32,', 'np.float64]:', 'ar...
235,705
ShengdingHu/GraphPolicyNetworkActiveLearning
utils.py
normalize_adj
normalize_adj
Symmetrically normalize adjacency matrix.
[ "Symmetrically", "normalize", "adjacency", "matrix." ]
def normalize_adj(adj): adj = sp.coo_matrix(adj) rowsum = np.array(adj.sum(1)) d_inv_sqrt = np.power(rowsum, -0.5).flatten() d_inv_sqrt[np.isinf(d_inv_sqrt)] = 0.0 d_mat_inv_sqrt = sp.diags(d_inv_sqrt) return adj.dot(d_mat_inv_sqrt).transpose().dot(d_mat_inv_sqrt).tocoo()
['def', 'normalize_adj(adj):', 'adj', '=', 'sp.coo_matrix(adj)', 'rowsum', '=', 'np.array(adj.sum(1))', 'd_inv_sqrt', '=', 'np.power(rowsum,', '-0.5).flatten()', 'd_inv_sqrt[np.isinf(d_inv_sqrt)]', '=', '0.0', 'd_mat_inv_sqrt', '=', 'sp.diags(d_inv_sqrt)', 'return', 'adj.dot(d_mat_inv_sqrt).transpose().dot(d_mat_inv_sq...
580,763
Davide-sd/GIMP-style-transfer
utils.py
denormalize_arr_of_imgs
denormalize_arr_of_imgs
Inverse of the normalize_arr_of_imgs function.
[ "Inverse", "of", "the", "normalize_arr_of_imgs", "function." ]
def denormalize_arr_of_imgs(arr): return (arr + 1.0) * 127.5
['def', 'denormalize_arr_of_imgs(arr):', 'return', '(arr', '+', '1.0)', '*', '127.5']
202,430
gunthercox/ChatterBot
__init__.py
relation
relation
A synonym for :func:`relationship`.
[ "A", "synonym", "for", ":func:`relationship`." ]
def relation(*arg, **kw): return relationship(*arg, **kw)
['def', 'relation(*arg,', '**kw):', 'return', 'relationship(*arg,', '**kw)']
481,551
KChen-lab/Cyclum
postproc.py
circular_divide
circular_divide
Find the best three dividing point for a circular array made up with three different characters.
[ "Find", "the", "best", "three", "dividing", "point", "for", "a", "circular", "array", "made", "up", "with", "three", "different", "characters." ]
def circular_divide(x, a, b, c): n = len(x) best_loc = None best_penalty = float('inf') for i in range(n): (loc, penalty) = linear_divide(np.append(x[i:], x[:i]), a, b, c) if loc[1] > loc[0] and penalty < best_penalty: best_penalty = penalty best_loc = (i, (loc[0]...
['def', 'circular_divide(x,', 'a,', 'b,', 'c):', 'n', '=', 'len(x)', 'best_loc', '=', 'None', 'best_penalty', '=', "float('inf')", 'for', 'i', 'in', 'range(n):', '(loc,', 'penalty)', '=', 'linear_divide(np.append(x[i:],', 'x[:i]),', 'a,', 'b,', 'c)', 'if', 'loc[1]', '>', 'loc[0]', 'and', 'penalty', '<', 'best_penalty:'...
524,445
CMU-CREATE-Lab/deep-smoke-machine
viz_functional.py
get_example_params
get_example_params
Gets used variables for almost all visualizations, like the image, model etc.
[ "Gets", "used", "variables", "for", "almost", "all", "visualizations,", "like", "the", "image,", "model", "etc." ]
def get_example_params(example_index): example_list = (('../input_images/snake.jpg', 56), ('../input_images/cat_dog.png', 243), ('../input_images/spider.png', 72)) img_path = example_list[example_index][0] target_class = example_list[example_index][1] file_name_to_export = img_path[img_path.rfind('/') +...
['def', 'get_example_params(example_index):', 'example_list', '=', "(('../input_images/snake.jpg',", '56),', "('../input_images/cat_dog.png',", '243),', "('../input_images/spider.png',", '72))', 'img_path', '=', 'example_list[example_index][0]', 'target_class', '=', 'example_list[example_index][1]', 'file_name_to_expor...
519,703
rlberry-py/rlberry
old_finite_mdp.py
Old_FiniteMDP.reset
reset
Reset the environment to a default state.
[ "Reset", "the", "environment", "to", "a", "default", "state." ]
def reset(self): if isinstance(self.initial_state_distribution, np.ndarray): self.state = self.rng.choice(self._states, p=self.initial_state_distribution) else: self.state = self.initial_state_distribution return self.state
['def', 'reset(self):', 'if', 'isinstance(self.initial_state_distribution,', 'np.ndarray):', 'self.state', '=', 'self.rng.choice(self._states,', 'p=self.initial_state_distribution)', 'else:', 'self.state', '=', 'self.initial_state_distribution', 'return', 'self.state']
862,260
huaweicloud/trace_generation_rnn
dur_utils.py
encode_dur_str
encode_dur_str
Create the duration output symbol.
[ "Create", "the", "duration", "output", "symbol." ]
def encode_dur_str(interval, censored): censor_char = CensorChar.CENSORED.value if censored else CensorChar.UNCENSORED.value out_str = '{}{}'.format(censor_char, interval) return out_str
['def', 'encode_dur_str(interval,', 'censored):', 'censor_char', '=', 'CensorChar.CENSORED.value', 'if', 'censored', 'else', 'CensorChar.UNCENSORED.value', 'out_str', '=', "'{}{}'.format(censor_char,", 'interval)', 'return', 'out_str']
355,968
mariacer/cl_in_rnns
train_args_copy.py
check_invalid_args_sequential
check_invalid_args_sequential
Sanity check for some command-line arguments specific to training on the copy task.
[ "Sanity", "check", "for", "some", "command-line", "arguments", "specific", "to", "training", "on", "the", "copy", "task." ]
def check_invalid_args_sequential(config): if config.first_task_input_len <= 0: raise ValueError('"first_task_input_len" must be a strictly positive ' + 'integer.') if config.input_len_step < 0: raise ValueError('"input_len_step" must be a positive integer.') if config.input_len_variability ...
['def', 'check_invalid_args_sequential(config):', 'if', 'config.first_task_input_len', '<=', '0:', 'raise', 'ValueError(\'"first_task_input_len"', 'must', 'be', 'a', 'strictly', 'positive', "'", '+', "'integer.')", 'if', 'config.input_len_step', '<', '0:', 'raise', 'ValueError(\'"input_len_step"', 'must', 'be', 'a', 'p...
122,961
tensorx/tensorx
init.py
uniform_init
uniform_init
Random Uniform Initializer Initializer that generates tensors with a uniform distribution.
[ "Random", "Uniform", "Initializer", "Initializer", "that", "generates", "tensors", "with", "a", "uniform", "distribution." ]
def uniform_init(minval: float=-0.05, maxval: float=0.05, seed=None): return tf.random_uniform_initializer(minval=minval, maxval=maxval, seed=seed)
['def', 'uniform_init(minval:', 'float=-0.05,', 'maxval:', 'float=0.05,', 'seed=None):', 'return', 'tf.random_uniform_initializer(minval=minval,', 'maxval=maxval,', 'seed=seed)']
924,123
0x5eba/Anime-Character-Generator
utils_.py
eye_grad
eye_grad
Generate random image samples with fixed hair class and noise, change eye color.
[ "Generate", "random", "image", "samples", "with", "fixed", "hair", "class", "and", "noise,", "change", "eye", "color." ]
def eye_grad(model, device, latent_dim, hair_classes, eye_classes, sample_dir): hair = torch.zeros(hair_classes).to(device) hair[np.random.randint(hair_classes)] = 1 hair.unsqueeze_(0) z = torch.randn(latent_dim).unsqueeze(0).to(device) img_list = [] for i in range(eye_classes): eye = to...
['def', 'eye_grad(model,', 'device,', 'latent_dim,', 'hair_classes,', 'eye_classes,', 'sample_dir):', 'hair', '=', 'torch.zeros(hair_classes).to(device)', 'hair[np.random.randint(hair_classes)]', '=', '1', 'hair.unsqueeze_(0)', 'z', '=', 'torch.randn(latent_dim).unsqueeze(0).to(device)', 'img_list', '=', '[]', 'for', '...
416,295
twke18/Adaptive_Affinity_Fields
image_reader.py
crop_and_pad_image_and_labels
crop_and_pad_image_and_labels
Randomly crops and pads the images and their labels.
[ "Randomly", "crops", "and", "pads", "the", "images", "and", "their", "labels." ]
def crop_and_pad_image_and_labels(image, label, crop_h, crop_w, ignore_label=255, random_crop=True): label = tf.cast(label, dtype=tf.float32) label = label - ignore_label combined = tf.concat(axis=2, values=[image, label]) image_shape = tf.shape(image) combined_pad = tf.image.pad_to_bounding_box(com...
['def', 'crop_and_pad_image_and_labels(image,', 'label,', 'crop_h,', 'crop_w,', 'ignore_label=255,', 'random_crop=True):', 'label', '=', 'tf.cast(label,', 'dtype=tf.float32)', 'label', '=', 'label', '-', 'ignore_label', 'combined', '=', 'tf.concat(axis=2,', 'values=[image,', 'label])', 'image_shape', '=', 'tf.shape(ima...
409,439
hamza-murad/AALU
visual_recognition_v4.py
TrainingEvents.from_dict
from_dict
Initialize a TrainingEvents object from a json dictionary.
[ "Initialize", "a", "TrainingEvents", "object", "from", "a", "json", "dictionary." ]
def from_dict(cls, _dict: Dict) -> 'TrainingEvents': args = {} valid_keys = ['start_time', 'end_time', 'completed_events', 'trained_images', 'events'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError('Unrecognized keys detected in dictionary for class TrainingEvents: ...
['def', 'from_dict(cls,', '_dict:', 'Dict)', '->', "'TrainingEvents':", 'args', '=', '{}', 'valid_keys', '=', "['start_time',", "'end_time',", "'completed_events',", "'trained_images',", "'events']", 'bad_keys', '=', 'set(_dict.keys())', '-', 'set(valid_keys)', 'if', 'bad_keys:', 'raise', "ValueError('Unrecognized", 'k...
6,208
JanMarcelKezmann/Semi-Supervised-Learning-Image-Classification
data_augmentations.py
random_rotate
random_rotate
Devides batch of images into four equally large smaller batches and rotates each batch by either 0, 90, 180 or 270 degrees.
[ "Devides", "batch", "of", "images", "into", "four", "equally", "large", "smaller", "batches", "and", "rotates", "each", "batch", "by", "either", "0,", "90,", "180", "or", "270", "degrees." ]
def random_rotate(x): b4 = x.shape[0] // 4 l = np.zeros(b4, np.int32) l = tf.constant(np.concatenate([l, l + 1, l + 2, l + 3], axis=0)) return (tf.concat([x[:b4], tf.image.rot90(x[b4:2 * b4], k=1), tf.image.rot90(x[2 * b4:3 * b4], k=2), tf.image.rot90(x[3 * b4:], k=3)], axis=0), l)
['def', 'random_rotate(x):', 'b4', '=', 'x.shape[0]', '//', '4', 'l', '=', 'np.zeros(b4,', 'np.int32)', 'l', '=', 'tf.constant(np.concatenate([l,', 'l', '+', '1,', 'l', '+', '2,', 'l', '+', '3],', 'axis=0))', 'return', '(tf.concat([x[:b4],', 'tf.image.rot90(x[b4:2', '*', 'b4],', 'k=1),', 'tf.image.rot90(x[2', '*', 'b4:...
343,369
PaddlePaddle/PaddleSpeech
ngram.py
Ngrambase.score_partial_
score_partial_
Score interface for both full and partial scorer.
[ "Score", "interface", "for", "both", "full", "and", "partial", "scorer." ]
def score_partial_(self, y, next_token, state, x): out_state = kenlm.State() ys = self.chardict[y[-1]] if y.shape[0] > 1 else '<s>' self.lm.BaseScore(state, ys, out_state) scores = paddle.empty_like(next_token, dtype=x.dtype) for (i, j) in enumerate(next_token): scores[i] = self.lm.BaseScore...
['def', 'score_partial_(self,', 'y,', 'next_token,', 'state,', 'x):', 'out_state', '=', 'kenlm.State()', 'ys', '=', 'self.chardict[y[-1]]', 'if', 'y.shape[0]', '>', '1', 'else', "'<s>'", 'self.lm.BaseScore(state,', 'ys,', 'out_state)', 'scores', '=', 'paddle.empty_like(next_token,', 'dtype=x.dtype)', 'for', '(i,', 'j)'...
276,605
rudranil723/mini-main
transforms.py
BboxBase.splity
splity
Return a list of new `Bbox` objects formed by splitting the original one with horizontal lines at fractional positions given by *args*.
[ "Return", "a", "list", "of", "new", "`Bbox`", "objects", "formed", "by", "splitting", "the", "original", "one", "with", "horizontal", "lines", "at", "fractional", "positions", "given", "by", "*args*." ]
def splity(self, *args): yf = [0, *args, 1] (x0, y0, x1, y1) = self.extents h = y1 - y0 return [Bbox([[x0, y0 + yf0 * h], [x1, y0 + yf1 * h]]) for (yf0, yf1) in zip(yf[:-1], yf[1:])]
['def', 'splity(self,', '*args):', 'yf', '=', '[0,', '*args,', '1]', '(x0,', 'y0,', 'x1,', 'y1)', '=', 'self.extents', 'h', '=', 'y1', '-', 'y0', 'return', '[Bbox([[x0,', 'y0', '+', 'yf0', '*', 'h],', '[x1,', 'y0', '+', 'yf1', '*', 'h]])', 'for', '(yf0,', 'yf1)', 'in', 'zip(yf[:-1],', 'yf[1:])]']
319,773
xiaoaleiBLUE/computer_vision
sast_postprocess.py
SASTPostProcess.point_pair2poly
point_pair2poly
Transfer vertical point_pairs into poly point in clockwise.
[ "Transfer", "vertical", "point_pairs", "into", "poly", "point", "in", "clockwise." ]
def point_pair2poly(self, point_pair_list): point_num = len(point_pair_list) * 2 point_list = [0] * point_num for (idx, point_pair) in enumerate(point_pair_list): point_list[idx] = point_pair[0] point_list[point_num - 1 - idx] = point_pair[1] return np.array(point_list).reshape(-1, 2)
['def', 'point_pair2poly(self,', 'point_pair_list):', 'point_num', '=', 'len(point_pair_list)', '*', '2', 'point_list', '=', '[0]', '*', 'point_num', 'for', '(idx,', 'point_pair)', 'in', 'enumerate(point_pair_list):', 'point_list[idx]', '=', 'point_pair[0]', 'point_list[point_num', '-', '1', '-', 'idx]', '=', 'point_pa...
474,466
Megvii-BaseDetection/cvpods
transform.py
CropPadTransform.apply_polygons
apply_polygons
Apply crop and pad transform on a list of polygons, each represented by a Nx2 array.
[ "Apply", "crop", "and", "pad", "transform", "on", "a", "list", "of", "polygons,", "each", "represented", "by", "a", "Nx2", "array." ]
def apply_polygons(self, polygons: list) -> list: polygons = self.crop_trans.apply_polygons(polygons) polygons = self.pad_trans.apply_polygons(polygons) return polygons
['def', 'apply_polygons(self,', 'polygons:', 'list)', '->', 'list:', 'polygons', '=', 'self.crop_trans.apply_polygons(polygons)', 'polygons', '=', 'self.pad_trans.apply_polygons(polygons)', 'return', 'polygons']
510,894
cleanlab/cleanlab
test_datalab.py
TestDatalab.test_load
test_load
Test that the save and load methods work.
[ "Test", "that", "the", "save", "and", "load", "methods", "work." ]
def test_load(self, lab, tmp_path, dataset, monkeypatch): mock_issues = pd.DataFrame({'is_foo_issue': [False, True, False, False, False], 'foo_score': [0.6, 0.8, 0.7, 0.7, 0.8]}) monkeypatch.setattr(lab, 'issues', mock_issues) mock_issue_summary = pd.DataFrame({'issue_type': ['foo'], 'score': [0.72]}) m...
['def', 'test_load(self,', 'lab,', 'tmp_path,', 'dataset,', 'monkeypatch):', 'mock_issues', '=', "pd.DataFrame({'is_foo_issue':", '[False,', 'True,', 'False,', 'False,', 'False],', "'foo_score':", '[0.6,', '0.8,', '0.7,', '0.7,', '0.8]})', 'monkeypatch.setattr(lab,', "'issues',", 'mock_issues)', 'mock_issue_summary', '...
488,109
suarez12138/AI-Reversi_IMP_TextDichotomy
test_peak_finding.py
TestLocalMaxima1d.test_linear
test_linear
Test with linear signal.
[ "Test", "with", "linear", "signal." ]
def test_linear(self): x = np.linspace(0, 100) for array in _local_maxima_1d(x): assert_equal(array, np.array([])) assert_(array.base is None)
['def', 'test_linear(self):', 'x', '=', 'np.linspace(0,', '100)', 'for', 'array', 'in', '_local_maxima_1d(x):', 'assert_equal(array,', 'np.array([]))', 'assert_(array.base', 'is', 'None)']
100,043
intra2net/guibot
test_calibrator.py
CalibratorTest.test_calibrate_rotation
test_calibrate_rotation
Check that minimal calibration with a rotated image improves over time.
[ "Check", "that", "minimal", "calibration", "with", "a", "rotated", "image", "improves", "over", "time." ]
def test_calibrate_rotation(self): raw_similarity = self.calibration_setUp('n_ibs', 'h_ibs_rotated', []) cal_similarity = self.calibration_setUp('n_ibs', 'h_ibs_rotated', ['find', 'feature', 'fdetect', 'fextract', 'fmatch']) self.assertLessEqual(raw_similarity, cal_similarity, 'Match similarity before calib...
['def', 'test_calibrate_rotation(self):', 'raw_similarity', '=', "self.calibration_setUp('n_ibs',", "'h_ibs_rotated',", '[])', 'cal_similarity', '=', "self.calibration_setUp('n_ibs',", "'h_ibs_rotated',", "['find',", "'feature',", "'fdetect',", "'fextract',", "'fmatch'])", 'self.assertLessEqual(raw_similarity,', 'cal_s...
572,598
google-research/scenic
test_regression_model.py
get_fake_batch_and_predictions
get_fake_batch_and_predictions
Generates a fake `batch`.
[ "Generates", "a", "fake", "`batch`." ]
def get_fake_batch_and_predictions(): targets = jnp.array([[2.0, 1.0, 0.0, 1.0], [2.0, 1.0, 0.0, 1.0], [5.0, 7.0, 0.0, 1.0]]) predictions = jnp.array([[2.0, 0.0, 0.0, 1.0], [2.0, 1.0, 0.0, 1.0], [4.0, 10.0, 0.0, 1.0]]) fake_batch = {'inputs': None, 'targets': targets} return (fake_batch, predictions)
['def', 'get_fake_batch_and_predictions():', 'targets', '=', 'jnp.array([[2.0,', '1.0,', '0.0,', '1.0],', '[2.0,', '1.0,', '0.0,', '1.0],', '[5.0,', '7.0,', '0.0,', '1.0]])', 'predictions', '=', 'jnp.array([[2.0,', '0.0,', '0.0,', '1.0],', '[2.0,', '1.0,', '0.0,', '1.0],', '[4.0,', '10.0,', '0.0,', '1.0]])', 'fake_batc...
846,243
LaoYang1994/PanopticSegmentation
model.py
MaskRCNN.find_trainable_layer
find_trainable_layer
If a layer is encapsulated by another layer, this function digs through the encapsulation and returns the layer that holds the weights.
[ "If", "a", "layer", "is", "encapsulated", "by", "another", "layer,", "this", "function", "digs", "through", "the", "encapsulation", "and", "returns", "the", "layer", "that", "holds", "the", "weights." ]
def find_trainable_layer(self, layer): if layer.__class__.__name__ == 'TimeDistributed': return self.find_trainable_layer(layer.layer) return layer
['def', 'find_trainable_layer(self,', 'layer):', 'if', 'layer.__class__.__name__', '==', "'TimeDistributed':", 'return', 'self.find_trainable_layer(layer.layer)', 'return', 'layer']
779,039
MaartenGr/ReinLife
grid.py
Grid.fov
fov
Get the fov (also through walls) for location i, j with distance dist If grid is given, use that grid to extract the fov from i, j, and dist.
[ "Get", "the", "fov", "(also", "through", "walls)", "for", "location", "i,", "j", "with", "distance", "dist", "If", "grid", "is", "given,", "use", "that", "grid", "to", "extract", "the", "fov", "from", "i,", "j,", "and", "dist." ]
def fov(self, i: int, j: int, dist: int, grid: np.ndarray=None) -> np.ndarray: if grid is None: grid = self.grid top = grid[:dist, :] bottom = grid[self.height - dist:, :] right = grid[:, self.width - dist:] left = grid[:, :dist] lower_left = grid[self.height - dist:, :dist] lower_ri...
['def', 'fov(self,', 'i:', 'int,', 'j:', 'int,', 'dist:', 'int,', 'grid:', 'np.ndarray=None)', '->', 'np.ndarray:', 'if', 'grid', 'is', 'None:', 'grid', '=', 'self.grid', 'top', '=', 'grid[:dist,', ':]', 'bottom', '=', 'grid[self.height', '-', 'dist:,', ':]', 'right', '=', 'grid[:,', 'self.width', '-', 'dist:]', 'left'...
839,017
deepmind/acme
agent_distributed.py
DistributedMCTS.build
build
Builds the distributed agent topology.
[ "Builds", "the", "distributed", "agent", "topology." ]
def build(self, name='MCTS'): program = lp.Program(name=name) with program.group('replay'): replay = program.add_node(lp.ReverbNode(self.replay), label='replay') with program.group('counter'): counter = program.add_node(lp.CourierNode(counting.Counter), label='counter') with program.grou...
['def', 'build(self,', "name='MCTS'):", 'program', '=', 'lp.Program(name=name)', 'with', "program.group('replay'):", 'replay', '=', 'program.add_node(lp.ReverbNode(self.replay),', "label='replay')", 'with', "program.group('counter'):", 'counter', '=', 'program.add_node(lp.CourierNode(counting.Counter),', "label='counte...
8,249
suarez12138/AI-Reversi_IMP_TextDichotomy
_base.py
Executor.map
map
Returns an iterator equivalent to map(fn, iter).
[ "Returns", "an", "iterator", "equivalent", "to", "map(fn,", "iter)." ]
def map(self, fn, *iterables, **kwargs): timeout = kwargs.get('timeout') if timeout is not None: end_time = timeout + time.time() fs = [self.submit(fn, *args) for args in zip(*iterables)] def result_iterator(): try: for future in fs: if timeout is None: ...
['def', 'map(self,', 'fn,', '*iterables,', '**kwargs):', 'timeout', '=', "kwargs.get('timeout')", 'if', 'timeout', 'is', 'not', 'None:', 'end_time', '=', 'timeout', '+', 'time.time()', 'fs', '=', '[self.submit(fn,', '*args)', 'for', 'args', 'in', 'zip(*iterables)]', 'def', 'result_iterator():', 'try:', 'for', 'future',...
95,928
rifqind/Agent-Programs-3KS1
pandocfilters.py
toJSONFilter
toJSONFilter
Like `toJSONFilters`, but takes a single action as argument.
[ "Like", "`toJSONFilters`,", "but", "takes", "a", "single", "action", "as", "argument." ]
def toJSONFilter(action): toJSONFilters([action])
['def', 'toJSONFilter(action):', 'toJSONFilters([action])']
40,506
bp-kelley/descriptastorus
QED.py
weights_none
weights_none
Calculates the QED descriptor using unit weights.
[ "Calculates", "the", "QED", "descriptor", "using", "unit", "weights." ]
def weights_none(mol): return qed(mol, w=[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0])
['def', 'weights_none(mol):', 'return', 'qed(mol,', 'w=[1.0,', '1.0,', '1.0,', '1.0,', '1.0,', '1.0,', '1.0,', '1.0])']
538,355
jnkl314/DeepLabV3FineTuning
custom_model.py
initialize_model
initialize_model
DeepLabV3 pretrained on a subset of COCO train2017, on the 20 categories that are present in the Pascal VOC dataset.
[ "DeepLabV3", "pretrained", "on", "a", "subset", "of", "COCO", "train2017,", "on", "the", "20", "categories", "that", "are", "present", "in", "the", "Pascal", "VOC", "dataset." ]
def initialize_model(num_classes, keep_feature_extract=False, use_pretrained=True): model_deeplabv3 = models.segmentation.deeplabv3_resnet101(pretrained=use_pretrained, progress=True) model_deeplabv3.aux_classifier = None if keep_feature_extract: for param in model_deeplabv3.parameters(): ...
['def', 'initialize_model(num_classes,', 'keep_feature_extract=False,', 'use_pretrained=True):', 'model_deeplabv3', '=', 'models.segmentation.deeplabv3_resnet101(pretrained=use_pretrained,', 'progress=True)', 'model_deeplabv3.aux_classifier', '=', 'None', 'if', 'keep_feature_extract:', 'for', 'param', 'in', 'model_deep...
521,387
nhsx/SynthVAE
common.py
GradSampleHooks_test.compute_opacus_grad_sample
compute_opacus_grad_sample
Runs Opacus to compute per-sample gradients and return them for testing purposes.
[ "Runs", "Opacus", "to", "compute", "per-sample", "gradients", "and", "return", "them", "for", "testing", "purposes." ]
def compute_opacus_grad_sample(self, x: Union[torch.Tensor, PackedSequence], module: nn.Module, batch_first=True, loss_reduction='mean') -> Dict[str, torch.tensor]: torch.use_deterministic_algorithms(True) torch.manual_seed(0) np.random.seed(0) gs_module = GradSampleModule(clone_module(module), batch_fi...
['def', 'compute_opacus_grad_sample(self,', 'x:', 'Union[torch.Tensor,', 'PackedSequence],', 'module:', 'nn.Module,', 'batch_first=True,', "loss_reduction='mean')", '->', 'Dict[str,', 'torch.tensor]:', 'torch.use_deterministic_algorithms(True)', 'torch.manual_seed(0)', 'np.random.seed(0)', 'gs_module', '=', 'GradSample...
906,234
43Carrig/recurrent_neural_networks_practice
select.py
filter_ops
filter_ops
Get the ops passing the given filter.
[ "Get", "the", "ops", "passing", "the", "given", "filter." ]
def filter_ops(ops, positive_filter): ops = util.make_list_of_op(ops) if positive_filter is not True: ops = [op for op in ops if positive_filter(op)] return ops
['def', 'filter_ops(ops,', 'positive_filter):', 'ops', '=', 'util.make_list_of_op(ops)', 'if', 'positive_filter', 'is', 'not', 'True:', 'ops', '=', '[op', 'for', 'op', 'in', 'ops', 'if', 'positive_filter(op)]', 'return', 'ops']
313,228
AiIsBetter/computer_vision
cpp_lint.py
ResetNolintSuppressions
ResetNolintSuppressions
Resets the set of NOLINT suppressions to empty.
[ "Resets", "the", "set", "of", "NOLINT", "suppressions", "to", "empty." ]
def ResetNolintSuppressions(): _error_suppressions.clear()
['def', 'ResetNolintSuppressions():', '_error_suppressions.clear()']
473,752
Alexander-Parker/youtube_nlp
message.py
query
query
Get a **query** message.
[ "Get", "a", "**query**", "message." ]
def query(options, collection_name, num_to_skip, num_to_return, query, field_selector, opts, check_keys=False, ctx=None): if ctx: return _query_compressed(options, collection_name, num_to_skip, num_to_return, query, field_selector, opts, check_keys, ctx) return _query_uncompressed(options, collection_na...
['def', 'query(options,', 'collection_name,', 'num_to_skip,', 'num_to_return,', 'query,', 'field_selector,', 'opts,', 'check_keys=False,', 'ctx=None):', 'if', 'ctx:', 'return', '_query_compressed(options,', 'collection_name,', 'num_to_skip,', 'num_to_return,', 'query,', 'field_selector,', 'opts,', 'check_keys,', 'ctx)'...
970,456
intelligent-environments-lab/CityLearn
building.py
Building.heating_demand
heating_demand
Space heating demand to be met by `heating_device` and/or `heating_storage` time series, in [kWh].
[ "Space", "heating", "demand", "to", "be", "met", "by", "`heating_device`", "and/or", "`heating_storage`", "time", "series,", "in", "[kWh]." ]
def heating_demand(self) -> np.ndarray: return self.energy_simulation.heating_demand[0:self.time_step + 1]
['def', 'heating_demand(self)', '->', 'np.ndarray:', 'return', 'self.energy_simulation.heating_demand[0:self.time_step', '+', '1]']
105,321
zcablii/LSKNet
gliding_vertex_coder.py
GVFixCoder.decode
decode
Apply transformation `fix_deltas` to `boxes`.
[ "Apply", "transformation", "`fix_deltas`", "to", "`boxes`." ]
def decode(self, hbboxes, fix_deltas): x1 = hbboxes[:, 0::4] y1 = hbboxes[:, 1::4] x2 = hbboxes[:, 2::4] y2 = hbboxes[:, 3::4] w = hbboxes[:, 2::4] - hbboxes[:, 0::4] h = hbboxes[:, 3::4] - hbboxes[:, 1::4] pred_t_x = x1 + w * fix_deltas[:, 0::4] pred_r_y = y1 + h * fix_deltas[:, 1::4] ...
['def', 'decode(self,', 'hbboxes,', 'fix_deltas):', 'x1', '=', 'hbboxes[:,', '0::4]', 'y1', '=', 'hbboxes[:,', '1::4]', 'x2', '=', 'hbboxes[:,', '2::4]', 'y2', '=', 'hbboxes[:,', '3::4]', 'w', '=', 'hbboxes[:,', '2::4]', '-', 'hbboxes[:,', '0::4]', 'h', '=', 'hbboxes[:,', '3::4]', '-', 'hbboxes[:,', '1::4]', 'pred_t_x'...
616,055
Ruturaj123/Flowchart-Detection
distribution_util.py
prefer_static_broadcast_shape
prefer_static_broadcast_shape
Convenience function which statically broadcasts shape when possible.
[ "Convenience", "function", "which", "statically", "broadcasts", "shape", "when", "possible." ]
def prefer_static_broadcast_shape(shape1, shape2, name='prefer_static_broadcast_shape'): with ops.name_scope(name, values=[shape1, shape2]): def make_shape_tensor(x): return ops.convert_to_tensor(x, name='shape', dtype=dtypes.int32) def get_tensor_shape(s): if isinstance(s,...
['def', 'prefer_static_broadcast_shape(shape1,', 'shape2,', "name='prefer_static_broadcast_shape'):", 'with', 'ops.name_scope(name,', 'values=[shape1,', 'shape2]):', 'def', 'make_shape_tensor(x):', 'return', 'ops.convert_to_tensor(x,', "name='shape',", 'dtype=dtypes.int32)', 'def', 'get_tensor_shape(s):', 'if', 'isinst...
602,892
PaddlePaddle/Paddle3D
infer.py
imnormalize
imnormalize
normalize an image with mean and std.
[ "normalize", "an", "image", "with", "mean", "and", "std." ]
def imnormalize(img, mean, std, to_rgb=True): img = img.copy().astype(np.float32) mean = np.float64(mean.reshape(1, -1)) stdinv = 1 / np.float64(std.reshape(1, -1)) if to_rgb: cv2.cvtColor(img, cv2.COLOR_BGR2RGB, img) cv2.subtract(img, mean, img) cv2.multiply(img, stdinv, img) return...
['def', 'imnormalize(img,', 'mean,', 'std,', 'to_rgb=True):', 'img', '=', 'img.copy().astype(np.float32)', 'mean', '=', 'np.float64(mean.reshape(1,', '-1))', 'stdinv', '=', '1', '/', 'np.float64(std.reshape(1,', '-1))', 'if', 'to_rgb:', 'cv2.cvtColor(img,', 'cv2.COLOR_BGR2RGB,', 'img)', 'cv2.subtract(img,', 'mean,', 'i...
777,163
TonyLianLong/VAI-ReinforcementLearning
wrappers.py
MjuiSectionWrapper.shortcut
shortcut
shortcut key; 0: undefined.
[ "shortcut", "key;", "0:", "undefined." ]
def shortcut(self): return self._ptr.contents.shortcut
['def', 'shortcut(self):', 'return', 'self._ptr.contents.shortcut']
440,696
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
trainable_optimizer.py
TrainableOptimizer.train
train
Creates graph operations to train the optimizer.
[ "Creates", "graph", "operations", "to", "train", "the", "optimizer." ]
def train(self, problem, dataset): obj_weights = tf.placeholder(tf.float32) num_iter = tf.shape(obj_weights)[0] (data, labels) = dataset data = tf.constant(data) labels = tf.constant(labels) batches = tf.placeholder(tf.int32) first_unroll = tf.placeholder_with_default(False, []) reset_st...
['def', 'train(self,', 'problem,', 'dataset):', 'obj_weights', '=', 'tf.placeholder(tf.float32)', 'num_iter', '=', 'tf.shape(obj_weights)[0]', '(data,', 'labels)', '=', 'dataset', 'data', '=', 'tf.constant(data)', 'labels', '=', 'tf.constant(labels)', 'batches', '=', 'tf.placeholder(tf.int32)', 'first_unroll', '=', 'tf...
55,461
zcablii/LSKNet
test_loss.py
test_gaussian_regression_losses
test_gaussian_regression_losses
Tests gaussian regression losses.
[ "Tests", "gaussian", "regression", "losses." ]
def test_gaussian_regression_losses(loss_type): pred = torch.rand((10, 5)) target = torch.rand((10, 5)) weight = torch.rand((10, 5)) loss = GDLoss(loss_type)(pred, target, weight) assert isinstance(loss, torch.Tensor) loss = GDLoss(loss_type)(pred, target, weight, reduction_override='mean') ...
['def', 'test_gaussian_regression_losses(loss_type):', 'pred', '=', 'torch.rand((10,', '5))', 'target', '=', 'torch.rand((10,', '5))', 'weight', '=', 'torch.rand((10,', '5))', 'loss', '=', 'GDLoss(loss_type)(pred,', 'target,', 'weight)', 'assert', 'isinstance(loss,', 'torch.Tensor)', 'loss', '=', 'GDLoss(loss_type)(pre...
616,265
explosion/spaCy
test_pipe_factories.py
test_pipe_factories_empty_dict_default
test_pipe_factories_empty_dict_default
Test that default config values can be empty dicts and that no config validation error is raised.
[ "Test", "that", "default", "config", "values", "can", "be", "empty", "dicts", "and", "that", "no", "config", "validation", "error", "is", "raised." ]
def test_pipe_factories_empty_dict_default(): name = 'test_pipe_factories_empty_dict_default' @Language.factory(name, default_config={'foo': {}}) def factory(nlp: Language, name: str, foo: dict): ... nlp = Language() nlp.create_pipe(name)
['def', 'test_pipe_factories_empty_dict_default():', 'name', '=', "'test_pipe_factories_empty_dict_default'", '@Language.factory(name,', "default_config={'foo':", '{}})', 'def', 'factory(nlp:', 'Language,', 'name:', 'str,', 'foo:', 'dict):', '...', 'nlp', '=', 'Language()', 'nlp.create_pipe(name)']
894,296
jbwang1997/CrossKD
horizontal_boxes.py
HorizontalBoxes.corner2hbox
corner2hbox
Convert box coordinates from corners ((x1, y1), (x2, y1), (x1, y2), (x2, y2)) to (x1, y1, x2, y2).
[ "Convert", "box", "coordinates", "from", "corners", "((x1,", "y1),", "(x2,", "y1),", "(x1,", "y2),", "(x2,", "y2))", "to", "(x1,", "y1,", "x2,", "y2)." ]
def corner2hbox(corners: Tensor) -> Tensor: if corners.numel() == 0: return corners.new_zeros((0, 4)) min_xy = corners.min(dim=-2)[0] max_xy = corners.max(dim=-2)[0] return torch.cat([min_xy, max_xy], dim=-1)
['def', 'corner2hbox(corners:', 'Tensor)', '->', 'Tensor:', 'if', 'corners.numel()', '==', '0:', 'return', 'corners.new_zeros((0,', '4))', 'min_xy', '=', 'corners.min(dim=-2)[0]', 'max_xy', '=', 'corners.max(dim=-2)[0]', 'return', 'torch.cat([min_xy,', 'max_xy],', 'dim=-1)']
491,698
luojie1024/Computer-vision-Classwork
check.py
get_incompatible_reqs
get_incompatible_reqs
Return all of the requirements of `dist` that are present in `installed_dists`, but have incompatible versions.
[ "Return", "all", "of", "the", "requirements", "of", "`dist`", "that", "are", "present", "in", "`installed_dists`,", "but", "have", "incompatible", "versions." ]
def get_incompatible_reqs(dist, installed_dists): installed_dists_by_name = {} for installed_dist in installed_dists: installed_dists_by_name[installed_dist.project_name] = installed_dist for requirement in dist.requires(): present_dist = installed_dists_by_name.get(requirement.project_name)...
['def', 'get_incompatible_reqs(dist,', 'installed_dists):', 'installed_dists_by_name', '=', '{}', 'for', 'installed_dist', 'in', 'installed_dists:', 'installed_dists_by_name[installed_dist.project_name]', '=', 'installed_dist', 'for', 'requirement', 'in', 'dist.requires():', 'present_dist', '=', 'installed_dists_by_nam...
467,680
greydanus/mr_london
files.py
actual_path
actual_path
Get the actual path of `path`, including the correct case.
[ "Get", "the", "actual", "path", "of", "`path`,", "including", "the", "correct", "case." ]
def actual_path(path): if env.PY2 and isinstance(path, unicode_class): path = path.encode(sys.getfilesystemencoding()) if path in _ACTUAL_PATH_CACHE: return _ACTUAL_PATH_CACHE[path] (head, tail) = os.path.split(path) if not tail: actpath = head.upper() elif not head: ...
['def', 'actual_path(path):', 'if', 'env.PY2', 'and', 'isinstance(path,', 'unicode_class):', 'path', '=', 'path.encode(sys.getfilesystemencoding())', 'if', 'path', 'in', '_ACTUAL_PATH_CACHE:', 'return', '_ACTUAL_PATH_CACHE[path]', '(head,', 'tail)', '=', 'os.path.split(path)', 'if', 'not', 'tail:', 'actpath', '=', 'hea...
242,157
wanhch/CS181-Artificial-Intelligence-I
agents.py
ModelBasedVacuumAgent
ModelBasedVacuumAgent
An agent that keeps track of what locations are clean or dirty.
[ "An", "agent", "that", "keeps", "track", "of", "what", "locations", "are", "clean", "or", "dirty." ]
def ModelBasedVacuumAgent(): model = {loc_A: None, loc_B: None} def program(l_s): model[l_s[0]] = l_s[1] if model[loc_A] == model[loc_B] == 'Clean': return 'NoOp' elif l_s[1] == 'Dirty': return 'Suck' elif l_s[0] == loc_A: return 'Right' ...
['def', 'ModelBasedVacuumAgent():', 'model', '=', '{loc_A:', 'None,', 'loc_B:', 'None}', 'def', 'program(l_s):', 'model[l_s[0]]', '=', 'l_s[1]', 'if', 'model[loc_A]', '==', 'model[loc_B]', '==', "'Clean':", 'return', "'NoOp'", 'elif', 'l_s[1]', '==', "'Dirty':", 'return', "'Suck'", 'elif', 'l_s[0]', '==', 'loc_A:', 're...
219,908
intelligent-environments-lab/CityLearn
base.py
Environment.time_step
time_step
Current environment time step.
[ "Current", "environment", "time", "step." ]
def time_step(self) -> int: return self.__time_step
['def', 'time_step(self)', '->', 'int:', 'return', 'self.__time_step']
105,270
AgnostiqHQ/covalent
write_result_to_db_test.py
test_get_electron_type
test_get_electron_type
Test that given an electron node, the correct electron type is returned.
[ "Test", "that", "given", "an", "electron", "node,", "the", "correct", "electron", "type", "is", "returned." ]
def test_get_electron_type(node_name, electron_type): assert get_electron_type(node_name) == electron_type
['def', 'test_get_electron_type(node_name,', 'electron_type):', 'assert', 'get_electron_type(node_name)', '==', 'electron_type']
489,747
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
__init__.py
Misc.winfo_height
winfo_height
Return height of this widget.
[ "Return", "height", "of", "this", "widget." ]
def winfo_height(self): return self.tk.getint(self.tk.call('winfo', 'height', self._w))
['def', 'winfo_height(self):', 'return', "self.tk.getint(self.tk.call('winfo',", "'height',", 'self._w))']
376,808
weimin17/Object-Detection_HelmetDetection
layer_test.py
BaseTest.regenerate
regenerate
Create reference data files for ResNet layer tests.
[ "Create", "reference", "data", "files", "for", "ResNet", "layer", "tests." ]
def regenerate(self): self._batch_norm_ops(test=False) for block_params in BLOCK_TESTS: self._resnet_block_ops(test=False, batch_size=BATCH_SIZE, **block_params)
['def', 'regenerate(self):', 'self._batch_norm_ops(test=False)', 'for', 'block_params', 'in', 'BLOCK_TESTS:', 'self._resnet_block_ops(test=False,', 'batch_size=BATCH_SIZE,', '**block_params)']
748,643