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 |
|---|---|---|---|---|---|---|---|---|
JosephKJ/iOD | train_net.py | setup | setup | Create configs and perform basic setups. | [
"Create",
"configs",
"and",
"perform",
"basic",
"setups."
] | def setup(args):
cfg = get_cfg()
cfg.merge_from_file(args.config_file)
cfg.merge_from_list(args.opts)
default_setup(cfg, args)
return cfg | ['def', 'setup(args):', 'cfg', '=', 'get_cfg()', 'cfg.merge_from_file(args.config_file)', 'cfg.merge_from_list(args.opts)', 'default_setup(cfg,', 'args)', 'return', 'cfg'] | 577,005 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | errorcounter_test.py | ErrorcounterTest.testCountErrors | testCountErrors | Tests that the error counter works as expected. | [
"Tests",
"that",
"the",
"error",
"counter",
"works",
"as",
"expected."
] | def testCountErrors(self):
truth_str = 'farm barn'
counts = ec.CountErrors(ocr_text=truth_str, truth_text=truth_str)
self.assertEqual(counts, ec.ErrorCounts(fn=0, fp=0, truth_count=9, test_count=9))
dot_str = 'farm barn.'
counts = ec.CountErrors(ocr_text=dot_str, truth_text=truth_str)
self.asser... | ['def', 'testCountErrors(self):', 'truth_str', '=', "'farm", "barn'", 'counts', '=', 'ec.CountErrors(ocr_text=truth_str,', 'truth_text=truth_str)', 'self.assertEqual(counts,', 'ec.ErrorCounts(fn=0,', 'fp=0,', 'truth_count=9,', 'test_count=9))', 'dot_str', '=', "'farm", "barn.'", 'counts', '=', 'ec.CountErrors(ocr_text=... | 27,622 |
nicknochnack/RealTimeSignLanguageTFJS | box_list_ops.py | prune_small_boxes | prune_small_boxes | Prunes small boxes in the boxlist which have a side smaller than min_side. | [
"Prunes",
"small",
"boxes",
"in",
"the",
"boxlist",
"which",
"have",
"a",
"side",
"smaller",
"than",
"min_side."
] | def prune_small_boxes(boxlist, min_side, scope=None):
with tf.name_scope(scope, 'PruneSmallBoxes'):
(height, width) = height_width(boxlist)
is_valid = tf.logical_and(tf.greater_equal(width, min_side), tf.greater_equal(height, min_side))
return gather(boxlist, tf.reshape(tf.where(is_valid), [... | ['def', 'prune_small_boxes(boxlist,', 'min_side,', 'scope=None):', 'with', 'tf.name_scope(scope,', "'PruneSmallBoxes'):", '(height,', 'width)', '=', 'height_width(boxlist)', 'is_valid', '=', 'tf.logical_and(tf.greater_equal(width,', 'min_side),', 'tf.greater_equal(height,', 'min_side))', 'return', 'gather(boxlist,', 't... | 851,041 |
santhoshkolloju/Abstractive-Summarization-With-Transfer- | episodic_agent_base.py | EpisodicAgentBase.reset | reset | Resets the states to begin new episode. | [
"Resets",
"the",
"states",
"to",
"begin",
"new",
"episode."
] | def reset(self):
self._reset_tmplt_fn() | ['def', 'reset(self):', 'self._reset_tmplt_fn()'] | 405,955 |
shery322/Lunar-Lander-ANN | ipaddress.py | _BaseNetwork.subnet_of | subnet_of | Return True if this network is a subnet of other. | [
"Return",
"True",
"if",
"this",
"network",
"is",
"a",
"subnet",
"of",
"other."
] | def subnet_of(self, other):
return self._is_subnet_of(self, other) | ['def', 'subnet_of(self,', 'other):', 'return', 'self._is_subnet_of(self,', 'other)'] | 618,000 |
Yuting-Gao/DisCo-pytorch | resnet.py | resnet200 | resnet200 | Constructs a ResNet-200 model. | [
"Constructs",
"a",
"ResNet-200",
"model."
] | def resnet200(pretrained=False, **kwargs):
model_args = dict(block=Bottleneck, layers=[3, 24, 36, 3], **kwargs)
return _create_resnet('resnet200', pretrained, **model_args) | ['def', 'resnet200(pretrained=False,', '**kwargs):', 'model_args', '=', 'dict(block=Bottleneck,', 'layers=[3,', '24,', '36,', '3],', '**kwargs)', 'return', "_create_resnet('resnet200',", 'pretrained,', '**model_args)'] | 186,548 |
Ruturaj123/Flowchart-Detection | dataset_factory.py | provide_batch | provide_batch | Provides a batch of images and corresponding labels. | [
"Provides",
"a",
"batch",
"of",
"images",
"and",
"corresponding",
"labels."
] | def provide_batch(dataset_name, split_name, dataset_dir, num_readers, batch_size, num_preprocessing_threads):
dataset = get_dataset(dataset_name, split_name, dataset_dir)
provider = slim.dataset_data_provider.DatasetDataProvider(dataset, num_readers=num_readers, common_queue_capacity=20 * batch_size, common_que... | ['def', 'provide_batch(dataset_name,', 'split_name,', 'dataset_dir,', 'num_readers,', 'batch_size,', 'num_preprocessing_threads):', 'dataset', '=', 'get_dataset(dataset_name,', 'split_name,', 'dataset_dir)', 'provider', '=', 'slim.dataset_data_provider.DatasetDataProvider(dataset,', 'num_readers=num_readers,', 'common_... | 585,591 |
jiacheng-xu/vmf_vae_nlp | lm.py | DataLM.tokenize | tokenize | Tokenizes a PTB style text file for language model. | [
"Tokenizes",
"a",
"PTB",
"style",
"text",
"file",
"for",
"language",
"model."
] | def tokenize(self, path, condition=False):
assert os.path.exists(path)
bag = []
len_stat = []
with open(path, 'r', errors='ignore') as f:
for line in f:
words = line.split()
if len(words) < 2:
continue
words = line.split() + ['<eos>']
... | ['def', 'tokenize(self,', 'path,', 'condition=False):', 'assert', 'os.path.exists(path)', 'bag', '=', '[]', 'len_stat', '=', '[]', 'with', 'open(path,', "'r',", "errors='ignore')", 'as', 'f:', 'for', 'line', 'in', 'f:', 'words', '=', 'line.split()', 'if', 'len(words)', '<', '2:', 'continue', 'words', '=', 'line.split()... | 946,138 |
augmentedstartups/AS-One | events.py | load_yaml | load_yaml | Load data from yaml file. | [
"Load",
"data",
"from",
"yaml",
"file."
] | def load_yaml(file_path):
if isinstance(file_path, str):
with open(file_path, errors='ignore') as f:
data_dict = yaml.safe_load(f)
return data_dict | ['def', 'load_yaml(file_path):', 'if', 'isinstance(file_path,', 'str):', 'with', 'open(file_path,', "errors='ignore')", 'as', 'f:', 'data_dict', '=', 'yaml.safe_load(f)', 'return', 'data_dict'] | 402,279 |
HCIILAB/DeRPN | bbox_transform.py | clip_boxes | clip_boxes | Clip boxes to image boundaries. | [
"Clip",
"boxes",
"to",
"image",
"boundaries."
] | def clip_boxes(boxes, im_shape):
boxes[:, 0::4] = np.maximum(np.minimum(boxes[:, 0::4], im_shape[1] - 1), 0)
boxes[:, 1::4] = np.maximum(np.minimum(boxes[:, 1::4], im_shape[0] - 1), 0)
boxes[:, 2::4] = np.maximum(np.minimum(boxes[:, 2::4], im_shape[1] - 1), 0)
boxes[:, 3::4] = np.maximum(np.minimum(boxe... | ['def', 'clip_boxes(boxes,', 'im_shape):', 'boxes[:,', '0::4]', '=', 'np.maximum(np.minimum(boxes[:,', '0::4],', 'im_shape[1]', '-', '1),', '0)', 'boxes[:,', '1::4]', '=', 'np.maximum(np.minimum(boxes[:,', '1::4],', 'im_shape[0]', '-', '1),', '0)', 'boxes[:,', '2::4]', '=', 'np.maximum(np.minimum(boxes[:,', '2::4],', '... | 184,168 |
zihuitang/medical_AI_platform | mailbox.py | Babyl.remove | remove | Remove the keyed message; raise KeyError if it doesn't exist. | [
"Remove",
"the",
"keyed",
"message;",
"raise",
"KeyError",
"if",
"it",
"doesn't",
"exist."
] | def remove(self, key):
_singlefileMailbox.remove(self, key)
if key in self._labels:
del self._labels[key] | ['def', 'remove(self,', 'key):', '_singlefileMailbox.remove(self,', 'key)', 'if', 'key', 'in', 'self._labels:', 'del', 'self._labels[key]'] | 280,766 |
JonasLandman/QCNN | tarfile.py | TarFile.utime | utime | Set modification time of targetpath according to tarinfo. | [
"Set",
"modification",
"time",
"of",
"targetpath",
"according",
"to",
"tarinfo."
] | def utime(self, tarinfo, targetpath):
if not hasattr(os, 'utime'):
return
try:
os.utime(targetpath, (tarinfo.mtime, tarinfo.mtime))
except EnvironmentError as e:
raise ExtractError('could not change modification time') | ['def', 'utime(self,', 'tarinfo,', 'targetpath):', 'if', 'not', 'hasattr(os,', "'utime'):", 'return', 'try:', 'os.utime(targetpath,', '(tarinfo.mtime,', 'tarinfo.mtime))', 'except', 'EnvironmentError', 'as', 'e:', 'raise', "ExtractError('could", 'not', 'change', 'modification', "time')"] | 303,301 |
NoGameNoLife00/mybolg | i18n.py | messages_path | messages_path | Determine the path to the 'messages' directory as best possible. | [
"Determine",
"the",
"path",
"to",
"the",
"'messages'",
"directory",
"as",
"best",
"possible."
] | def messages_path():
module_path = os.path.abspath(__file__)
locale_path = os.path.join(os.path.dirname(module_path), 'locale')
if not os.path.exists(locale_path):
locale_path = '/usr/share/locale'
return locale_path | ['def', 'messages_path():', 'module_path', '=', 'os.path.abspath(__file__)', 'locale_path', '=', 'os.path.join(os.path.dirname(module_path),', "'locale')", 'if', 'not', 'os.path.exists(locale_path):', 'locale_path', '=', "'/usr/share/locale'", 'return', 'locale_path'] | 290,109 |
jordanlui/NaturalLanguageProcessing | create_pretraining_data.py | create_instances_from_document | create_instances_from_document | Creates `TrainingInstance`s for a single document. | [
"Creates",
"`TrainingInstance`s",
"for",
"a",
"single",
"document."
] | def create_instances_from_document(all_documents, document_index, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab_words, rng):
document = all_documents[document_index]
max_num_tokens = max_seq_length - 3
target_seq_length = max_num_tokens
if rng.random() < short_seq_prob:
... | ['def', 'create_instances_from_document(all_documents,', 'document_index,', 'max_seq_length,', 'short_seq_prob,', 'masked_lm_prob,', 'max_predictions_per_seq,', 'vocab_words,', 'rng):', 'document', '=', 'all_documents[document_index]', 'max_num_tokens', '=', 'max_seq_length', '-', '3', 'target_seq_length', '=', 'max_nu... | 710,148 |
ashwin-phadke/cvplayground | inputs_test.py | InputsTest.test_faster_rcnn_resnet50_train_input_with_additional_channels | test_faster_rcnn_resnet50_train_input_with_additional_channels | Tests the training input function for FasterRcnnResnet50. | [
"Tests",
"the",
"training",
"input",
"function",
"for",
"FasterRcnnResnet50."
] | def test_faster_rcnn_resnet50_train_input_with_additional_channels(self):
configs = _get_configs_for_model('faster_rcnn_resnet50_pets')
model_config = configs['model']
configs['train_input_config'].num_additional_channels = 2
configs['train_config'].retain_original_images = True
model_config.faster_... | ['def', 'test_faster_rcnn_resnet50_train_input_with_additional_channels(self):', 'configs', '=', "_get_configs_for_model('faster_rcnn_resnet50_pets')", 'model_config', '=', "configs['model']", "configs['train_input_config'].num_additional_channels", '=', '2', "configs['train_config'].retain_original_images", '=', 'True... | 509,716 |
Mdominik/artificial_intelligence | req_file.py | ignore_comments | ignore_comments | Strips comments and filter empty lines. | [
"Strips",
"comments",
"and",
"filter",
"empty",
"lines."
] | def ignore_comments(lines_enum):
for (line_number, line) in lines_enum:
line = COMMENT_RE.sub('', line)
line = line.strip()
if line:
yield (line_number, line) | ['def', 'ignore_comments(lines_enum):', 'for', '(line_number,', 'line)', 'in', 'lines_enum:', 'line', '=', "COMMENT_RE.sub('',", 'line)', 'line', '=', 'line.strip()', 'if', 'line:', 'yield', '(line_number,', 'line)'] | 72,323 |
mohammadtavakoli78/Artificial-Intelligence | search.py | simulated_annealing_full | simulated_annealing_full | This version returns all the states encountered in reaching the goal state. | [
"This",
"version",
"returns",
"all",
"the",
"states",
"encountered",
"in",
"reaching",
"the",
"goal",
"state."
] | def simulated_annealing_full(problem, schedule=exp_schedule()):
states = []
current = Node(problem.initial)
for t in range(sys.maxsize):
states.append(current.state)
T = schedule(t)
if T == 0:
return states
neighbors = current.expand(problem)
if not neighb... | ['def', 'simulated_annealing_full(problem,', 'schedule=exp_schedule()):', 'states', '=', '[]', 'current', '=', 'Node(problem.initial)', 'for', 't', 'in', 'range(sys.maxsize):', 'states.append(current.state)', 'T', '=', 'schedule(t)', 'if', 'T', '==', '0:', 'return', 'states', 'neighbors', '=', 'current.expand(problem)'... | 118,538 |
wandb/wandb | test_gcp_artifact_registry.py | test_init | test_init | Test the initialization of the GoogleArtifactRegistry class. | [
"Test",
"the",
"initialization",
"of",
"the",
"GoogleArtifactRegistry",
"class."
] | def test_init():
registry = GoogleArtifactRegistry(repository='test-repository', image_name='test-image', environment=MagicMock(), verify=False)
assert registry.repository == 'test-repository'
assert registry.image_name == 'test-image'
assert registry.environment | ['def', 'test_init():', 'registry', '=', "GoogleArtifactRegistry(repository='test-repository',", "image_name='test-image',", 'environment=MagicMock(),', 'verify=False)', 'assert', 'registry.repository', '==', "'test-repository'", 'assert', 'registry.image_name', '==', "'test-image'", 'assert', 'registry.environment'] | 941,278 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | offline_eval_map_corloc.py | write_metrics | write_metrics | Write metrics to the output directory. | [
"Write",
"metrics",
"to",
"the",
"output",
"directory."
] | def write_metrics(metrics, output_dir):
tf.logging.info('Writing metrics.')
with open(os.path.join(output_dir, 'metrics.csv'), 'w') as csvfile:
metrics_writer = csv.writer(csvfile, delimiter=',')
for (metric_name, metric_value) in metrics.items():
metrics_writer.writerow([metric_name... | ['def', 'write_metrics(metrics,', 'output_dir):', "tf.logging.info('Writing", "metrics.')", 'with', 'open(os.path.join(output_dir,', "'metrics.csv'),", "'w')", 'as', 'csvfile:', 'metrics_writer', '=', 'csv.writer(csvfile,', "delimiter=',')", 'for', '(metric_name,', 'metric_value)', 'in', 'metrics.items():', 'metrics_wr... | 57,854 |
mattchorlian/Berkeley-CS188-Spring21 | pacman.py | readCommand | readCommand | Processes the command used to run pacman from the command line. | [
"Processes",
"the",
"command",
"used",
"to",
"run",
"pacman",
"from",
"the",
"command",
"line."
] | def readCommand(argv):
from optparse import OptionParser
usageStr = '\n USAGE: python pacman.py <options>\n EXAMPLES: (1) python pacman.py\n - starts an interactive game\n (2) python pacman.py --layout smallClassic --zoom 2\n OR python pacman.py -l ... | ['def', 'readCommand(argv):', 'from', 'optparse', 'import', 'OptionParser', 'usageStr', '=', "'\\n", 'USAGE:', 'python', 'pacman.py', '<options>\\n', 'EXAMPLES:', '(1)', 'python', 'pacman.py\\n', '-', 'starts', 'an', 'interactive', 'game\\n', '(2)', 'python', 'pacman.py', '--layout', 'smallClassic', '--zoom', '2\\n', '... | 106,644 |
for-ai/rl | collectors.py | SyncDataCollector.reset | reset | Resets the environments to a new initial state. | [
"Resets",
"the",
"environments",
"to",
"a",
"new",
"initial",
"state."
] | def reset(self, index=None, **kwargs) -> None:
md = self._tensordict.get('collector').clone()
if index is not None:
if prod(self.env.batch_size) == 0:
raise RuntimeError('resetting unique env with index is not permitted.')
_reset = torch.zeros(self.env.done_spec.shape, dtype=torch.bo... | ['def', 'reset(self,', 'index=None,', '**kwargs)', '->', 'None:', 'md', '=', "self._tensordict.get('collector').clone()", 'if', 'index', 'is', 'not', 'None:', 'if', 'prod(self.env.batch_size)', '==', '0:', 'raise', "RuntimeError('resetting", 'unique', 'env', 'with', 'index', 'is', 'not', "permitted.')", '_reset', '=', ... | 858,593 |
csjunxu/Noisy-As-Clean-TIP2020 | debug.py | show_actual_vendor_versions | show_actual_vendor_versions | Log the actual version and print extra info if there is a conflict or if the actual version could not be imported. | [
"Log",
"the",
"actual",
"version",
"and",
"print",
"extra",
"info",
"if",
"there",
"is",
"a",
"conflict",
"or",
"if",
"the",
"actual",
"version",
"could",
"not",
"be",
"imported."
] | def show_actual_vendor_versions(vendor_txt_versions):
for (module_name, expected_version) in vendor_txt_versions.items():
extra_message = ''
actual_version = get_vendor_version_from_module(module_name)
if not actual_version:
extra_message = ' (Unable to locate actual module versi... | ['def', 'show_actual_vendor_versions(vendor_txt_versions):', 'for', '(module_name,', 'expected_version)', 'in', 'vendor_txt_versions.items():', 'extra_message', '=', "''", 'actual_version', '=', 'get_vendor_version_from_module(module_name)', 'if', 'not', 'actual_version:', 'extra_message', '=', "'", '(Unable', 'to', 'l... | 294,651 |
google-research/tensor2robot | distortion.py | preprocess_image | preprocess_image | Shared preprocessing function for images. | [
"Shared",
"preprocessing",
"function",
"for",
"images."
] | def preprocess_image(image, mode, is_sequence, input_size, target_size, crop_size=None, image_distortion_fn=maybe_distort_image_batch):
leading_shape = tf.shape(image)[:-3]
image = tf.image.convert_image_dtype(image, tf.float32)
if is_sequence:
image = tf.reshape(image, [-1] + image.shape[-3:].as_li... | ['def', 'preprocess_image(image,', 'mode,', 'is_sequence,', 'input_size,', 'target_size,', 'crop_size=None,', 'image_distortion_fn=maybe_distort_image_batch):', 'leading_shape', '=', 'tf.shape(image)[:-3]', 'image', '=', 'tf.image.convert_image_dtype(image,', 'tf.float32)', 'if', 'is_sequence:', 'image', '=', 'tf.resha... | 908,315 |
gunthercox/ChatterBot | support.py | NullTranslations.udnpgettext | udnpgettext | Like ``unpgettext``, but look the message up in the specified `domain`. | [
"Like",
"``unpgettext``,",
"but",
"look",
"the",
"message",
"up",
"in",
"the",
"specified",
"`domain`."
] | def udnpgettext(self, domain, context, singular, plural, num):
return self._domains.get(domain, self).unpgettext(context, singular, plural, num) | ['def', 'udnpgettext(self,', 'domain,', 'context,', 'singular,', 'plural,', 'num):', 'return', 'self._domains.get(domain,', 'self).unpgettext(context,', 'singular,', 'plural,', 'num)'] | 528,652 |
explosion/spaCy | test_tokenizer.py | test_issue792 | test_issue792 | Test for Issue #792: Trailing whitespace is removed after tokenization. | [
"Test",
"for",
"Issue",
"#792:",
"Trailing",
"whitespace",
"is",
"removed",
"after",
"tokenization."
] | def test_issue792(en_tokenizer, text):
doc = en_tokenizer(text)
assert ''.join([token.text_with_ws for token in doc]) == text | ['def', 'test_issue792(en_tokenizer,', 'text):', 'doc', '=', 'en_tokenizer(text)', 'assert', "''.join([token.text_with_ws", 'for', 'token', 'in', 'doc])', '==', 'text'] | 894,162 |
meowoodie/Reinforcement-Learning-of-Spatio-Temporal-Point-Processes | utils.py | l2_norm | l2_norm | This helper function calculates distance (l2 norm) between two arbitrary data points from tensor x and tensor y respectively, where x and y have the same shape [length, data_dim]. | [
"This",
"helper",
"function",
"calculates",
"distance",
"(l2",
"norm)",
"between",
"two",
"arbitrary",
"data",
"points",
"from",
"tensor",
"x",
"and",
"tensor",
"y",
"respectively,",
"where",
"x",
"and",
"y",
"have",
"the",
"same",
"shape",
"[length,",
"data_d... | def l2_norm(x, y):
x = tf.cast(x, dtype=tf.float32)
y = tf.cast(y, dtype=tf.float32)
x_sqr = tf.expand_dims(tf.reduce_sum(x * x, 1), -1)
y_sqr = tf.expand_dims(tf.reduce_sum(y * y, 1), -1)
xy = tf.matmul(x, tf.transpose(y))
dist_mat = x_sqr + tf.transpose(y_sqr) - 2 * xy
return dist_mat | ['def', 'l2_norm(x,', 'y):', 'x', '=', 'tf.cast(x,', 'dtype=tf.float32)', 'y', '=', 'tf.cast(y,', 'dtype=tf.float32)', 'x_sqr', '=', 'tf.expand_dims(tf.reduce_sum(x', '*', 'x,', '1),', '-1)', 'y_sqr', '=', 'tf.expand_dims(tf.reduce_sum(y', '*', 'y,', '1),', '-1)', 'xy', '=', 'tf.matmul(x,', 'tf.transpose(y))', 'dist_ma... | 833,502 |
noambassat/SpeechTrainer | tarfile.py | TarFile.taropen | taropen | Open uncompressed tar archive name for reading or writing. | [
"Open",
"uncompressed",
"tar",
"archive",
"name",
"for",
"reading",
"or",
"writing."
] | def taropen(cls, name, mode='r', fileobj=None, **kwargs):
if len(mode) > 1 or mode not in 'raw':
raise ValueError("mode must be 'r', 'a' or 'w'")
return cls(name, mode, fileobj, **kwargs) | ['def', 'taropen(cls,', 'name,', "mode='r',", 'fileobj=None,', '**kwargs):', 'if', 'len(mode)', '>', '1', 'or', 'mode', 'not', 'in', "'raw':", 'raise', 'ValueError("mode', 'must', 'be', "'r',", "'a'", 'or', '\'w\'")', 'return', 'cls(name,', 'mode,', 'fileobj,', '**kwargs)'] | 895,466 |
mfbx9da4/neuron-astrocyte-networks | mdlstm.py | MDLSTMLayer.meatSlice | meatSlice | Return a moduleslice that wraps the meat part of the layer. | [
"Return",
"a",
"moduleslice",
"that",
"wraps",
"the",
"meat",
"part",
"of",
"the",
"layer."
] | def meatSlice(self):
return ModuleSlice(self, inSliceTo=self.dim * (3 + self.dimensions), outSliceTo=self.dim) | ['def', 'meatSlice(self):', 'return', 'ModuleSlice(self,', 'inSliceTo=self.dim', '*', '(3', '+', 'self.dimensions),', 'outSliceTo=self.dim)'] | 723,198 |
nddbk/tf-object-detection | category_util.py | save_categories_to_csv_file | save_categories_to_csv_file | Saves categories to a csv file. | [
"Saves",
"categories",
"to",
"a",
"csv",
"file."
] | def save_categories_to_csv_file(categories, csv_path):
categories.sort(key=lambda x: x['id'])
with tf.gfile.Open(csv_path, 'w') as csvfile:
writer = csv.writer(csvfile, delimiter=',', quotechar='"')
for category in categories:
writer.writerow([category['id'], category['name']]) | ['def', 'save_categories_to_csv_file(categories,', 'csv_path):', 'categories.sort(key=lambda', 'x:', "x['id'])", 'with', 'tf.gfile.Open(csv_path,', "'w')", 'as', 'csvfile:', 'writer', '=', 'csv.writer(csvfile,', "delimiter=',',", 'quotechar=\'"\')', 'for', 'category', 'in', 'categories:', "writer.writerow([category['id... | 914,962 |
FenHua/Robust_Logo_Detection | cascade_rpn_head.py | StageCascadeRPNHead.init_weights | init_weights | Init weights of a CascadeRPN stage. | [
"Init",
"weights",
"of",
"a",
"CascadeRPN",
"stage."
] | def init_weights(self):
self.rpn_conv.init_weights()
normal_init(self.rpn_reg, std=0.01)
if self.with_cls:
normal_init(self.rpn_cls, std=0.01) | ['def', 'init_weights(self):', 'self.rpn_conv.init_weights()', 'normal_init(self.rpn_reg,', 'std=0.01)', 'if', 'self.with_cls:', 'normal_init(self.rpn_cls,', 'std=0.01)'] | 826,725 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | graph_builder_test.py | GraphBuilderTest.testTraining | testTraining | Tests the default hyperparameter settings. | [
"Tests",
"the",
"default",
"hyperparameter",
"settings."
] | def testTraining(self):
self.RunTraining(self.MakeHyperparams()) | ['def', 'testTraining(self):', 'self.RunTraining(self.MakeHyperparams())'] | 28,337 |
open-mmlab/mmsegmentation | da_head.py | DAHead.loss_by_feat | loss_by_feat | Compute ``pam_cam``, ``pam``, ``cam`` loss. | [
"Compute",
"``pam_cam``,",
"``pam``,",
"``cam``",
"loss."
] | def loss_by_feat(self, seg_logit: Tuple[Tensor], batch_data_samples: SampleList, **kwargs) -> dict:
(pam_cam_seg_logit, pam_seg_logit, cam_seg_logit) = seg_logit
loss = dict()
loss.update(add_prefix(super().loss_by_feat(pam_cam_seg_logit, batch_data_samples), 'pam_cam'))
loss.update(add_prefix(super().l... | ['def', 'loss_by_feat(self,', 'seg_logit:', 'Tuple[Tensor],', 'batch_data_samples:', 'SampleList,', '**kwargs)', '->', 'dict:', '(pam_cam_seg_logit,', 'pam_seg_logit,', 'cam_seg_logit)', '=', 'seg_logit', 'loss', '=', 'dict()', 'loss.update(add_prefix(super().loss_by_feat(pam_cam_seg_logit,', 'batch_data_samples),', "'... | 625,403 |
salesforce/CodeRL | trainer_pt_utils.py | get_parameter_names | get_parameter_names | Returns the names of the model parameters that are not inside a forbidden layer. | [
"Returns",
"the",
"names",
"of",
"the",
"model",
"parameters",
"that",
"are",
"not",
"inside",
"a",
"forbidden",
"layer."
] | def get_parameter_names(model, forbidden_layer_types):
result = []
for (name, child) in model.named_children():
result += [f'{name}.{n}' for n in get_parameter_names(child, forbidden_layer_types) if not isinstance(child, tuple(forbidden_layer_types))]
result += list(model._parameters.keys())
ret... | ['def', 'get_parameter_names(model,', 'forbidden_layer_types):', 'result', '=', '[]', 'for', '(name,', 'child)', 'in', 'model.named_children():', 'result', '+=', "[f'{name}.{n}'", 'for', 'n', 'in', 'get_parameter_names(child,', 'forbidden_layer_types)', 'if', 'not', 'isinstance(child,', 'tuple(forbidden_layer_types))]'... | 494,181 |
rudranil723/mini-main | test_tgrep.py | TestSequenceFunctions.test_tokenize_encoding | test_tokenize_encoding | Test that tokenization handles bytes and strs the same way. | [
"Test",
"that",
"tokenization",
"handles",
"bytes",
"and",
"strs",
"the",
"same",
"way."
] | def test_tokenize_encoding(self):
self.assertEqual(tgrep.tgrep_tokenize(b'A .. (B !< C . D) | ![<< (E , F) $ G]'), tgrep.tgrep_tokenize('A .. (B !< C . D) | ![<< (E , F) $ G]')) | ['def', 'test_tokenize_encoding(self):', "self.assertEqual(tgrep.tgrep_tokenize(b'A", '..', '(B', '!<', 'C', '.', 'D)', '|', '![<<', '(E', ',', 'F)', '$', "G]'),", "tgrep.tgrep_tokenize('A", '..', '(B', '!<', 'C', '.', 'D)', '|', '![<<', '(E', ',', 'F)', '$', "G]'))"] | 321,853 |
open-mmlab/mmselfsup | position_embedding.py | build_2d_sincos_position_embedding | build_2d_sincos_position_embedding | The function is to build position embedding for model to obtain the position information of the image patches. | [
"The",
"function",
"is",
"to",
"build",
"position",
"embedding",
"for",
"model",
"to",
"obtain",
"the",
"position",
"information",
"of",
"the",
"image",
"patches."
] | def build_2d_sincos_position_embedding(patches_resolution: Union[int, Sequence[int]], embed_dims: int, temperature: Optional[int]=10000.0, cls_token: Optional[bool]=False) -> torch.Tensor:
if isinstance(patches_resolution, int):
patches_resolution = (patches_resolution, patches_resolution)
(h, w) = patc... | ['def', 'build_2d_sincos_position_embedding(patches_resolution:', 'Union[int,', 'Sequence[int]],', 'embed_dims:', 'int,', 'temperature:', 'Optional[int]=10000.0,', 'cls_token:', 'Optional[bool]=False)', '->', 'torch.Tensor:', 'if', 'isinstance(patches_resolution,', 'int):', 'patches_resolution', '=', '(patches_resoluti... | 240,468 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | managers.py | BlockManager.iget | iget | Return the data as a SingleBlockManager. | [
"Return",
"the",
"data",
"as",
"a",
"SingleBlockManager."
] | def iget(self, i: int) -> 'SingleBlockManager':
block = self.blocks[self.blknos[i]]
values = block.iget(self.blklocs[i])
return SingleBlockManager(block.make_block_same_class(values, placement=slice(0, len(values)), ndim=1), self.axes[1]) | ['def', 'iget(self,', 'i:', 'int)', '->', "'SingleBlockManager':", 'block', '=', 'self.blocks[self.blknos[i]]', 'values', '=', 'block.iget(self.blklocs[i])', 'return', 'SingleBlockManager(block.make_block_same_class(values,', 'placement=slice(0,', 'len(values)),', 'ndim=1),', 'self.axes[1])'] | 453,291 |
asyml/texar | network_base.py | FeedForwardNetworkBase.layers | layers | A list of the layers. | [
"A",
"list",
"of",
"the",
"layers."
] | def layers(self):
return self._layers | ['def', 'layers(self):', 'return', 'self._layers'] | 924,737 |
ArdaGunay99/Key_Detection_Unsupervised_Learning | ltisys.py | dlti.dt | dt | Return the sampling time of the system. | [
"Return",
"the",
"sampling",
"time",
"of",
"the",
"system."
] | def dt(self):
return self._dt | ['def', 'dt(self):', 'return', 'self._dt'] | 260,194 |
DongChen06/MARL_CAVs | prediction.py | IntervalVehicle.store_trajectories | store_trajectories | Store the current model, min and max states to a trajectory list. | [
"Store",
"the",
"current",
"model,",
"min",
"and",
"max",
"states",
"to",
"a",
"trajectory",
"list."
] | def store_trajectories(self) -> None:
self.trajectory.append(LinearVehicle.create_from(self))
self.interval_trajectory.append(copy.deepcopy(self.interval)) | ['def', 'store_trajectories(self)', '->', 'None:', 'self.trajectory.append(LinearVehicle.create_from(self))', 'self.interval_trajectory.append(copy.deepcopy(self.interval))'] | 628,110 |
clvrai/spirl | skill_prior_mdl.py | SkillPriorMdl.reset | reset | Resets action plan (should be called at beginning of episode when used in RL loop). | [
"Resets",
"action",
"plan",
"(should",
"be",
"called",
"at",
"beginning",
"of",
"episode",
"when",
"used",
"in",
"RL",
"loop)."
] | def reset(self):
self._action_plan = deque() | ['def', 'reset(self):', 'self._action_plan', '=', 'deque()'] | 896,949 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | models.py | PreparedRequest.prepare_url | prepare_url | Prepares the given HTTP URL. | [
"Prepares",
"the",
"given",
"HTTP",
"URL."
] | def prepare_url(self, url, params):
if isinstance(url, bytes):
url = url.decode('utf8')
else:
url = unicode(url) if is_py2 else str(url)
url = url.lstrip()
if ':' in url and (not url.lower().startswith('http')):
self.url = url
return
try:
(scheme, auth, host, ... | ['def', 'prepare_url(self,', 'url,', 'params):', 'if', 'isinstance(url,', 'bytes):', 'url', '=', "url.decode('utf8')", 'else:', 'url', '=', 'unicode(url)', 'if', 'is_py2', 'else', 'str(url)', 'url', '=', 'url.lstrip()', 'if', "':'", 'in', 'url', 'and', '(not', "url.lower().startswith('http')):", 'self.url', '=', 'url',... | 434,552 |
googleapis/python-aiplatform | client.py | TensorboardServiceClient.tensorboard_time_series_path | tensorboard_time_series_path | Returns a fully-qualified tensorboard_time_series string. | [
"Returns",
"a",
"fully-qualified",
"tensorboard_time_series",
"string."
] | def tensorboard_time_series_path(project: str, location: str, tensorboard: str, experiment: str, run: str, time_series: str) -> str:
return 'projects/{project}/locations/{location}/tensorboards/{tensorboard}/experiments/{experiment}/runs/{run}/timeSeries/{time_series}'.format(project=project, location=location, ten... | ['def', 'tensorboard_time_series_path(project:', 'str,', 'location:', 'str,', 'tensorboard:', 'str,', 'experiment:', 'str,', 'run:', 'str,', 'time_series:', 'str)', '->', 'str:', 'return', "'projects/{project}/locations/{location}/tensorboards/{tensorboard}/experiments/{experiment}/runs/{run}/timeSeries/{time_series}'.... | 811,892 |
qianduoduolr/Spa-then-Temp | misc.py | get_thread_id | get_thread_id | Get current thread id. | [
"Get",
"current",
"thread",
"id."
] | def get_thread_id():
thread_id = ctypes.CDLL('libc.so.6').syscall(186)
return thread_id | ['def', 'get_thread_id():', 'thread_id', '=', "ctypes.CDLL('libc.so.6').syscall(186)", 'return', 'thread_id'] | 393,968 |
ryu-ed/SpaceInvaders_Ros | scrap_test.py | ScrapModuleClipboardNotOwnedTest.test_get__not_owned | test_get__not_owned | Ensures get works when there is no data of the requested type in the clipboard and the clipboard is not owned by the pygame application. | [
"Ensures",
"get",
"works",
"when",
"there",
"is",
"no",
"data",
"of",
"the",
"requested",
"type",
"in",
"the",
"clipboard",
"and",
"the",
"clipboard",
"is",
"not",
"owned",
"by",
"the",
"pygame",
"application."
] | def test_get__not_owned(self):
self._skip_if_clipboard_owned()
DATA_TYPE = 'test_get__not_owned'
data = scrap.get(DATA_TYPE)
self.assertIsNone(data) | ['def', 'test_get__not_owned(self):', 'self._skip_if_clipboard_owned()', 'DATA_TYPE', '=', "'test_get__not_owned'", 'data', '=', 'scrap.get(DATA_TYPE)', 'self.assertIsNone(data)'] | 369,152 |
fcjian/TOOD | create_result_gif.py | create_frame_by_matplotlib | create_frame_by_matplotlib | Create gif frame image through matplotlib. | [
"Create",
"gif",
"frame",
"image",
"through",
"matplotlib."
] | def create_frame_by_matplotlib(image_dir, nrows=1, fig_size=(300, 300), font_size=15):
result_dir_names = os.listdir(image_dir)
assert len(result_dir_names) == 2
result_dir_names.reverse()
images_list = []
for dir_names in result_dir_names:
images_list.append(mmcv.scandir(osp.join(image_dir,... | ['def', 'create_frame_by_matplotlib(image_dir,', 'nrows=1,', 'fig_size=(300,', '300),', 'font_size=15):', 'result_dir_names', '=', 'os.listdir(image_dir)', 'assert', 'len(result_dir_names)', '==', '2', 'result_dir_names.reverse()', 'images_list', '=', '[]', 'for', 'dir_names', 'in', 'result_dir_names:', 'images_list.ap... | 901,718 |
EconomistGrant/HTFE-tensortrade | instrument_exchange.py | InstrumentExchange.generated_columns | generated_columns | The list of column names of the observation data frame generated by the exchange, before feature transformations. | [
"The",
"list",
"of",
"column",
"names",
"of",
"the",
"observation",
"data",
"frame",
"generated",
"by",
"the",
"exchange,",
"before",
"feature",
"transformations."
] | def generated_columns(self) -> List[str]:
raise NotImplementedError | ['def', 'generated_columns(self)', '->', 'List[str]:', 'raise', 'NotImplementedError'] | 570,815 |
zcablii/LSKNet | re_resnet.py | Bottleneck.forward | forward | Forward function of Bottleneck. | [
"Forward",
"function",
"of",
"Bottleneck."
] | def forward(self, x):
def _inner_forward(x):
identity = x
out = self.conv1(x)
out = self.norm1(out)
out = self.relu1(out)
out = self.conv2(out)
out = self.norm2(out)
out = self.relu2(out)
out = self.conv3(out)
out = self.norm3(out)
if ... | ['def', 'forward(self,', 'x):', 'def', '_inner_forward(x):', 'identity', '=', 'x', 'out', '=', 'self.conv1(x)', 'out', '=', 'self.norm1(out)', 'out', '=', 'self.relu1(out)', 'out', '=', 'self.conv2(out)', 'out', '=', 'self.norm2(out)', 'out', '=', 'self.relu2(out)', 'out', '=', 'self.conv3(out)', 'out', '=', 'self.norm... | 616,105 |
weimin17/Object-Detection_HelmetDetection | model_losses.py | create_dis_loss | create_dis_loss | Compute Discriminator loss across real/fake. | [
"Compute",
"Discriminator",
"loss",
"across",
"real/fake."
] | def create_dis_loss(fake_predictions, real_predictions, targets_present):
missing = tf.cast(targets_present, tf.int32)
missing = 1 - missing
missing = tf.cast(missing, tf.bool)
real_labels = tf.ones([FLAGS.batch_size, FLAGS.sequence_length])
dis_loss_real = tf.losses.sigmoid_cross_entropy(real_label... | ['def', 'create_dis_loss(fake_predictions,', 'real_predictions,', 'targets_present):', 'missing', '=', 'tf.cast(targets_present,', 'tf.int32)', 'missing', '=', '1', '-', 'missing', 'missing', '=', 'tf.cast(missing,', 'tf.bool)', 'real_labels', '=', 'tf.ones([FLAGS.batch_size,', 'FLAGS.sequence_length])', 'dis_loss_real... | 758,043 |
open-mmlab/mmsegmentation | self_attention_block.py | SelfAttentionBlock.build_project | build_project | Build projection layer for key/query/value/out. | [
"Build",
"projection",
"layer",
"for",
"key/query/value/out."
] | def build_project(self, in_channels, channels, num_convs, use_conv_module, conv_cfg, norm_cfg, act_cfg):
if use_conv_module:
convs = [ConvModule(in_channels, channels, 1, conv_cfg=conv_cfg, norm_cfg=norm_cfg, act_cfg=act_cfg)]
for _ in range(num_convs - 1):
convs.append(ConvModule(channe... | ['def', 'build_project(self,', 'in_channels,', 'channels,', 'num_convs,', 'use_conv_module,', 'conv_cfg,', 'norm_cfg,', 'act_cfg):', 'if', 'use_conv_module:', 'convs', '=', '[ConvModule(in_channels,', 'channels,', '1,', 'conv_cfg=conv_cfg,', 'norm_cfg=norm_cfg,', 'act_cfg=act_cfg)]', 'for', '_', 'in', 'range(num_convs'... | 625,484 |
rifqind/Agent-Programs-3KS1 | filters.py | do_striptags | do_striptags | Strip SGML/XML tags and replace adjacent whitespace by one space. | [
"Strip",
"SGML/XML",
"tags",
"and",
"replace",
"adjacent",
"whitespace",
"by",
"one",
"space."
] | def do_striptags(value):
if hasattr(value, '__html__'):
value = value.__html__()
return Markup(text_type(value)).striptags() | ['def', 'do_striptags(value):', 'if', 'hasattr(value,', "'__html__'):", 'value', '=', 'value.__html__()', 'return', 'Markup(text_type(value)).striptags()'] | 42,273 |
danamyu/hedgehog_detector | problem_generator.py | Problem2D.surface | surface | Computes the objective surface over a 2d mesh. | [
"Computes",
"the",
"objective",
"surface",
"over",
"a",
"2d",
"mesh."
] | def surface(self, n=50, xlim=5, ylim=5):
(xm, ym) = _mesh(xlim, ylim, n)
with tf.Graph().as_default(), tf.Session() as sess:
x = tf.placeholder(tf.float32, shape=xm.shape)
y = tf.placeholder(tf.float32, shape=ym.shape)
obj = self.objective([[x, y]])
zm = sess.run(obj, feed_dict={... | ['def', 'surface(self,', 'n=50,', 'xlim=5,', 'ylim=5):', '(xm,', 'ym)', '=', '_mesh(xlim,', 'ylim,', 'n)', 'with', 'tf.Graph().as_default(),', 'tf.Session()', 'as', 'sess:', 'x', '=', 'tf.placeholder(tf.float32,', 'shape=xm.shape)', 'y', '=', 'tf.placeholder(tf.float32,', 'shape=ym.shape)', 'obj', '=', 'self.objective(... | 589,769 |
gunthercox/ChatterBot | lexer.py | describe_token_expr | describe_token_expr | Like `describe_token` but for token expressions. | [
"Like",
"`describe_token`",
"but",
"for",
"token",
"expressions."
] | def describe_token_expr(expr):
if ':' in expr:
(type, value) = expr.split(':', 1)
if type == 'name':
return value
else:
type = expr
return _describe_token_type(type) | ['def', 'describe_token_expr(expr):', 'if', "':'", 'in', 'expr:', '(type,', 'value)', '=', "expr.split(':',", '1)', 'if', 'type', '==', "'name':", 'return', 'value', 'else:', 'type', '=', 'expr', 'return', '_describe_token_type(type)'] | 529,388 |
enuguru/artificial_intelligence_and_machine_learning | filters.py | do_upper | do_upper | Convert a value to uppercase. | [
"Convert",
"a",
"value",
"to",
"uppercase."
] | def do_upper(s):
return soft_unicode(s).upper() | ['def', 'do_upper(s):', 'return', 'soft_unicode(s).upper()'] | 158,318 |
spite-triangle/artificial_intelligence | misc.py | consume | consume | Consume an iterable at C speed. | [
"Consume",
"an",
"iterable",
"at",
"C",
"speed."
] | def consume(iterator):
deque(iterator, maxlen=0) | ['def', 'consume(iterator):', 'deque(iterator,', 'maxlen=0)'] | 152,198 |
sarnsdev/social-alignment-data-mining | Transitions.py | TransitionMap.get_special | get_special | Get state set for special event, adding a new entry if necessary. | [
"Get",
"state",
"set",
"for",
"special",
"event,",
"adding",
"a",
"new",
"entry",
"if",
"necessary."
] | def get_special(self, event):
special = self.special
set = special.get(event, None)
if not set:
set = {}
special[event] = set
return set | ['def', 'get_special(self,', 'event):', 'special', '=', 'self.special', 'set', '=', 'special.get(event,', 'None)', 'if', 'not', 'set:', 'set', '=', '{}', 'special[event]', '=', 'set', 'return', 'set'] | 352,361 |
KhadeejaArshadAli/Artificial-Intelligence | csp.py | CSP.display | display | Show a human-readable representation of the CSP. | [
"Show",
"a",
"human-readable",
"representation",
"of",
"the",
"CSP."
] | def display(self, assignment):
print(assignment) | ['def', 'display(self,', 'assignment):', 'print(assignment)'] | 116,038 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | registry_test.py | RegistryTest.testCanCreateByAlias | testCanCreateByAlias | Tests that Create can create an Impl subclass via Alias. | [
"Tests",
"that",
"Create",
"can",
"create",
"an",
"Impl",
"subclass",
"via",
"Alias."
] | def testCanCreateByAlias(self):
try:
impl = registry_test_base.Base.Create(PATH + 'registry_test_impl.Alias', 'hello world')
except ValueError:
self.fail('Create raised ValueError: %s' % traceback.format_exc())
self.assertEqual('hello world', impl.Get()) | ['def', 'testCanCreateByAlias(self):', 'try:', 'impl', '=', 'registry_test_base.Base.Create(PATH', '+', "'registry_test_impl.Alias',", "'hello", "world')", 'except', 'ValueError:', "self.fail('Create", 'raised', 'ValueError:', "%s'", '%', 'traceback.format_exc())', "self.assertEqual('hello", "world',", 'impl.Get())'] | 111,936 |
googleapis/python-aiplatform | grpc_asyncio.py | VizierServiceGrpcAsyncIOTransport.delete_operation | delete_operation | Return a callable for the delete_operation method over gRPC. | [
"Return",
"a",
"callable",
"for",
"the",
"delete_operation",
"method",
"over",
"gRPC."
] | def delete_operation(self) -> Callable[[operations_pb2.DeleteOperationRequest], None]:
if 'delete_operation' not in self._stubs:
self._stubs['delete_operation'] = self.grpc_channel.unary_unary('/google.longrunning.Operations/DeleteOperation', request_serializer=operations_pb2.DeleteOperationRequest.Serializ... | ['def', 'delete_operation(self)', '->', 'Callable[[operations_pb2.DeleteOperationRequest],', 'None]:', 'if', "'delete_operation'", 'not', 'in', 'self._stubs:', "self._stubs['delete_operation']", '=', "self.grpc_channel.unary_unary('/google.longrunning.Operations/DeleteOperation',", 'request_serializer=operations_pb2.De... | 812,126 |
QData/deepWordBug | tarfile.py | _Stream.tell | tell | Return the stream's file pointer position. | [
"Return",
"the",
"stream's",
"file",
"pointer",
"position."
] | def tell(self):
return self.pos | ['def', 'tell(self):', 'return', 'self.pos'] | 535,256 |
Khan/guacamole | regression_util.py | quantile | quantile | Generate the q'th quantile of x Arguments: x: a numpy array q: the quantile of interest (a float) Returns: the element of x closest to the qth quantile. | [
"Generate",
"the",
"q'th",
"quantile",
"of",
"x",
"Arguments:",
"x:",
"a",
"numpy",
"array",
"q:",
"the",
"quantile",
"of",
"interest",
"(a",
"float)",
"Returns:",
"the",
"element",
"of",
"x",
"closest",
"to",
"the",
"qth",
"quantile."
] | def quantile(x, q):
if len(x.shape) != 1:
return None
x = x.tolist()
x.sort()
return x[int((len(x) - 1) * float(q))] | ['def', 'quantile(x,', 'q):', 'if', 'len(x.shape)', '!=', '1:', 'return', 'None', 'x', '=', 'x.tolist()', 'x.sort()', 'return', 'x[int((len(x)', '-', '1)', '*', 'float(q))]'] | 572,211 |
Jakaria08/EESRGAN | util.py | inf_loop | inf_loop | wrapper function for endless data loader. | [
"wrapper",
"function",
"for",
"endless",
"data",
"loader."
] | def inf_loop(data_loader):
for loader in repeat(data_loader):
yield from loader | ['def', 'inf_loop(data_loader):', 'for', 'loader', 'in', 'repeat(data_loader):', 'yield', 'from', 'loader'] | 548,438 |
Speedwagon13/CS-3600-Introduction-to-- | datetime.py | datetime.ctime | ctime | Return ctime() style string. | [
"Return",
"ctime()",
"style",
"string."
] | def ctime(self):
weekday = self.toordinal() % 7 or 7
return '%s %s %2d %02d:%02d:%02d %04d' % (_DAYNAMES[weekday], _MONTHNAMES[self._month], self._day, self._hour, self._minute, self._second, self._year) | ['def', 'ctime(self):', 'weekday', '=', 'self.toordinal()', '%', '7', 'or', '7', 'return', "'%s", '%s', '%2d', '%02d:%02d:%02d', "%04d'", '%', '(_DAYNAMES[weekday],', '_MONTHNAMES[self._month],', 'self._day,', 'self._hour,', 'self._minute,', 'self._second,', 'self._year)'] | 219,756 |
jbwang1997/CrossKD | yolo_bbox_coder.py | YOLOBBoxCoder.encode | encode | Get box regression transformation deltas that can be used to transform the ``bboxes`` into the ``gt_bboxes``. | [
"Get",
"box",
"regression",
"transformation",
"deltas",
"that",
"can",
"be",
"used",
"to",
"transform",
"the",
"``bboxes``",
"into",
"the",
"``gt_bboxes``."
] | def encode(self, bboxes, gt_bboxes, stride):
bboxes = get_box_tensor(bboxes)
gt_bboxes = get_box_tensor(gt_bboxes)
assert bboxes.size(0) == gt_bboxes.size(0)
assert bboxes.size(-1) == gt_bboxes.size(-1) == 4
x_center_gt = (gt_bboxes[..., 0] + gt_bboxes[..., 2]) * 0.5
y_center_gt = (gt_bboxes[...... | ['def', 'encode(self,', 'bboxes,', 'gt_bboxes,', 'stride):', 'bboxes', '=', 'get_box_tensor(bboxes)', 'gt_bboxes', '=', 'get_box_tensor(gt_bboxes)', 'assert', 'bboxes.size(0)', '==', 'gt_bboxes.size(0)', 'assert', 'bboxes.size(-1)', '==', 'gt_bboxes.size(-1)', '==', '4', 'x_center_gt', '=', '(gt_bboxes[...,', '0]', '+'... | 491,555 |
jialeli1/lidarseg3d | box_np_ops.py | rotation_box | rotation_box | rotation 2d points based on origin point clockwise when angle positive. | [
"rotation",
"2d",
"points",
"based",
"on",
"origin",
"point",
"clockwise",
"when",
"angle",
"positive."
] | def rotation_box(box_corners, angle):
rot_sin = np.sin(angle)
rot_cos = np.cos(angle)
rot_mat_T = np.array([[rot_cos, -rot_sin], [rot_sin, rot_cos]], dtype=box_corners.dtype)
return box_corners @ rot_mat_T | ['def', 'rotation_box(box_corners,', 'angle):', 'rot_sin', '=', 'np.sin(angle)', 'rot_cos', '=', 'np.cos(angle)', 'rot_mat_T', '=', 'np.array([[rot_cos,', '-rot_sin],', '[rot_sin,', 'rot_cos]],', 'dtype=box_corners.dtype)', 'return', 'box_corners', '@', 'rot_mat_T'] | 601,389 |
neurospin/pylearn-parsimony | estimators.py | LogisticRegressionEstimator.fit | fit | Fit the model to the data. | [
"Fit",
"the",
"model",
"to",
"the",
"data."
] | def fit(self, X, y):
raise NotImplementedError('Abstract method "fit" must be specialised!') | ['def', 'fit(self,', 'X,', 'y):', 'raise', "NotImplementedError('Abstract", 'method', '"fit"', 'must', 'be', "specialised!')"] | 819,882 |
liber145/rlpack | env_wrapper.py | AsyncMujocoWrapper.dim_observation | dim_observation | The dimension of observation. | [
"The",
"dimension",
"of",
"observation."
] | def dim_observation(self):
return self._dim_observation | ['def', 'dim_observation(self):', 'return', 'self._dim_observation'] | 825,099 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | problem_generator.py | Problem.init_tensors | init_tensors | Returns a list of tensors with the given shape. | [
"Returns",
"a",
"list",
"of",
"tensors",
"with",
"the",
"given",
"shape."
] | def init_tensors(self, seed=None):
return [tf.random_normal(shape, seed=seed) for shape in self.param_shapes] | ['def', 'init_tensors(self,', 'seed=None):', 'return', '[tf.random_normal(shape,', 'seed=seed)', 'for', 'shape', 'in', 'self.param_shapes]'] | 55,655 |
enuguru/artificial_intelligence_and_machine_ | speaklater.py | make_lazy_string | make_lazy_string | Creates a lazy string by invoking func with args. | [
"Creates",
"a",
"lazy",
"string",
"by",
"invoking",
"func",
"with",
"args."
] | def make_lazy_string(__func, *args, **kwargs):
return _LazyString(__func, args, kwargs) | ['def', 'make_lazy_string(__func,', '*args,', '**kwargs):', 'return', '_LazyString(__func,', 'args,', 'kwargs)'] | 156,825 |
intel/neural-compressor | keras.py | KerasAdaptor.quantize_input | quantize_input | Quantize the model to be able to take quantized input. | [
"Quantize",
"the",
"model",
"to",
"be",
"able",
"to",
"take",
"quantized",
"input."
] | def quantize_input(self, model):
return (model, 1.0) | ['def', 'quantize_input(self,', 'model):', 'return', '(model,', '1.0)'] | 737,316 |
QingbeiGuo/SG-CNN | ds_utils.py | unique_boxes | unique_boxes | Return indices of unique boxes. | [
"Return",
"indices",
"of",
"unique",
"boxes."
] | def unique_boxes(boxes, scale=1.0):
v = np.array([1, 1000.0, 1000000.0, 1000000000.0])
hashes = np.round(boxes * scale).dot(v)
(_, index) = np.unique(hashes, return_index=True)
return np.sort(index) | ['def', 'unique_boxes(boxes,', 'scale=1.0):', 'v', '=', 'np.array([1,', '1000.0,', '1000000.0,', '1000000000.0])', 'hashes', '=', 'np.round(boxes', '*', 'scale).dot(v)', '(_,', 'index)', '=', 'np.unique(hashes,', 'return_index=True)', 'return', 'np.sort(index)'] | 349,968 |
Katja-M/Python_NaturalLanguageProcessing | pyparsing.py | ParseResults.clear | clear | Clear all elements and results names. | [
"Clear",
"all",
"elements",
"and",
"results",
"names."
] | def clear(self):
del self.__toklist[:]
self.__tokdict.clear() | ['def', 'clear(self):', 'del', 'self.__toklist[:]', 'self.__tokdict.clear()'] | 868,928 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | renderer.py | Renderer.rows_above_layout | rows_above_layout | Return the number of rows visible in the terminal above the layout. | [
"Return",
"the",
"number",
"of",
"rows",
"visible",
"in",
"the",
"terminal",
"above",
"the",
"layout."
] | def rows_above_layout(self) -> int:
if self._in_alternate_screen:
return 0
elif self._min_available_height > 0:
total_rows = self.output.get_size().rows
last_screen_height = self._last_screen.height if self._last_screen else 0
return total_rows - max(self._min_available_height, l... | ['def', 'rows_above_layout(self)', '->', 'int:', 'if', 'self._in_alternate_screen:', 'return', '0', 'elif', 'self._min_available_height', '>', '0:', 'total_rows', '=', 'self.output.get_size().rows', 'last_screen_height', '=', 'self._last_screen.height', 'if', 'self._last_screen', 'else', '0', 'return', 'total_rows', '-... | 435,040 |
dgseten/bad-cv-tfm | exporter.py | write_graph_and_checkpoint | write_graph_and_checkpoint | Writes the graph and the checkpoint into disk. | [
"Writes",
"the",
"graph",
"and",
"the",
"checkpoint",
"into",
"disk."
] | def write_graph_and_checkpoint(inference_graph_def, model_path, input_saver_def, trained_checkpoint_prefix):
for node in inference_graph_def.node:
node.device = ''
with tf.Graph().as_default():
tf.import_graph_def(inference_graph_def, name='')
with tf.Session() as sess:
saver... | ['def', 'write_graph_and_checkpoint(inference_graph_def,', 'model_path,', 'input_saver_def,', 'trained_checkpoint_prefix):', 'for', 'node', 'in', 'inference_graph_def.node:', 'node.device', '=', "''", 'with', 'tf.Graph().as_default():', 'tf.import_graph_def(inference_graph_def,', "name='')", 'with', 'tf.Session()', 'as... | 421,323 |
Kvatsx/Artificial-Intelligence-Assignments | util.py | looks_like_xml | looks_like_xml | Check if a doctype exists or if we have some tags. | [
"Check",
"if",
"a",
"doctype",
"exists",
"or",
"if",
"we",
"have",
"some",
"tags."
] | def looks_like_xml(text):
if xml_decl_re.match(text):
return True
key = hash(text)
try:
return _looks_like_xml_cache[key]
except KeyError:
m = doctype_lookup_re.match(text)
if m is not None:
return True
rv = tag_re.search(text[:1000]) is not None
... | ['def', 'looks_like_xml(text):', 'if', 'xml_decl_re.match(text):', 'return', 'True', 'key', '=', 'hash(text)', 'try:', 'return', '_looks_like_xml_cache[key]', 'except', 'KeyError:', 'm', '=', 'doctype_lookup_re.match(text)', 'if', 'm', 'is', 'not', 'None:', 'return', 'True', 'rv', '=', 'tag_re.search(text[:1000])', 'is... | 77,134 |
PacktPublishing/Hands-On-Artificial--for-Banking | test_utils.py | TestArrayEqual.test_string_arrays | test_string_arrays | Test two arrays with different shapes are found not equal. | [
"Test",
"two",
"arrays",
"with",
"different",
"shapes",
"are",
"found",
"not",
"equal."
] | def test_string_arrays(self):
a = np.array(['floupi', 'floupa'])
b = np.array(['floupi', 'floupa'])
self._test_equal(a, b)
c = np.array(['floupipi', 'floupa'])
self._test_not_equal(c, b) | ['def', 'test_string_arrays(self):', 'a', '=', "np.array(['floupi',", "'floupa'])", 'b', '=', "np.array(['floupi',", "'floupa'])", 'self._test_equal(a,', 'b)', 'c', '=', "np.array(['floupipi',", "'floupa'])", 'self._test_not_equal(c,', 'b)'] | 235,890 |
zhaocq-nlp/NJUNMT-tf | feedback.py | TrainingFeedback.next_symbols | next_symbols | Returns the output at `time`, also known as the input at `time`+1. | [
"Returns",
"the",
"output",
"at",
"`time`,",
"also",
"known",
"as",
"the",
"input",
"at",
"`time`+1."
] | def next_symbols(self, time, sample_ids):
_ = sample_ids
next_time = time + 1
finished = tf.greater_equal(next_time, self._maximum_labels_length)
return (finished, self._label_sequence_tas.read(time)) | ['def', 'next_symbols(self,', 'time,', 'sample_ids):', '_', '=', 'sample_ids', 'next_time', '=', 'time', '+', '1', 'finished', '=', 'tf.greater_equal(next_time,', 'self._maximum_labels_length)', 'return', '(finished,', 'self._label_sequence_tas.read(time))'] | 782,977 |
fudan-zvg/SETR | ema.py | BaseEMAHook.before_train_epoch | before_train_epoch | We recover model's parameter from ema backup after last epoch's EvalHook. | [
"We",
"recover",
"model's",
"parameter",
"from",
"ema",
"backup",
"after",
"last",
"epoch's",
"EvalHook."
] | def before_train_epoch(self, runner):
self._swap_ema_parameters() | ['def', 'before_train_epoch(self,', 'runner):', 'self._swap_ema_parameters()'] | 897,869 |
caiiiac/Machine-Learning-with-Python | disk.py | memstr_to_bytes | memstr_to_bytes | Convert a memory text to its value in bytes. | [
"Convert",
"a",
"memory",
"text",
"to",
"its",
"value",
"in",
"bytes."
] | def memstr_to_bytes(text):
kilo = 1024
units = dict(K=kilo, M=kilo ** 2, G=kilo ** 3)
try:
size = int(units[text[-1]] * float(text[:-1]))
except (KeyError, ValueError):
raise ValueError("Invalid literal for size give: %s (type %s) should be alike '10G', '500M', '50K'." % (text, type(text... | ['def', 'memstr_to_bytes(text):', 'kilo', '=', '1024', 'units', '=', 'dict(K=kilo,', 'M=kilo', '**', '2,', 'G=kilo', '**', '3)', 'try:', 'size', '=', 'int(units[text[-1]]', '*', 'float(text[:-1]))', 'except', '(KeyError,', 'ValueError):', 'raise', 'ValueError("Invalid', 'literal', 'for', 'size', 'give:', '%s', '(type',... | 720,687 |
replit-archive/empythoned | inspect.py | stack | stack | Return a list of records for the stack above the caller's frame. | [
"Return",
"a",
"list",
"of",
"records",
"for",
"the",
"stack",
"above",
"the",
"caller's",
"frame."
] | def stack(context=1):
return getouterframes(sys._getframe(1), context) | ['def', 'stack(context=1):', 'return', 'getouterframes(sys._getframe(1),', 'context)'] | 177,295 |
tensorflow/hub | tf_utils.py | read_file_to_string | read_file_to_string | Returns the entire contents of a file to a string. | [
"Returns",
"the",
"entire",
"contents",
"of",
"a",
"file",
"to",
"a",
"string."
] | def read_file_to_string(filename):
return tf.compat.v1.gfile.GFile(filename, mode='r').read() | ['def', 'read_file_to_string(filename):', 'return', 'tf.compat.v1.gfile.GFile(filename,', "mode='r').read()"] | 571,045 |
asyml/texar-pytorch | data_utils.py | get_filename | get_filename | Extracts the filename of the downloaded checkpoint file from the URL. | [
"Extracts",
"the",
"filename",
"of",
"the",
"downloaded",
"checkpoint",
"file",
"from",
"the",
"URL."
] | def get_filename(url: str) -> str:
if 'drive.google.com' in url:
return _extract_google_drive_file_id(url)
(url, filename) = os.path.split(url)
return filename or os.path.basename(url) | ['def', 'get_filename(url:', 'str)', '->', 'str:', 'if', "'drive.google.com'", 'in', 'url:', 'return', '_extract_google_drive_file_id(url)', '(url,', 'filename)', '=', 'os.path.split(url)', 'return', 'filename', 'or', 'os.path.basename(url)'] | 925,012 |
Ekim-Yurtsever/Hybrid-DeepRL-Automated-Driving | global_route_planner.py | GlobalRoutePlanner.setup | setup | Performs initial server data lookup for detailed topology and builds graph representation of the world map. | [
"Performs",
"initial",
"server",
"data",
"lookup",
"for",
"detailed",
"topology",
"and",
"builds",
"graph",
"representation",
"of",
"the",
"world",
"map."
] | def setup(self):
self._topology = self._dao.get_topology()
(self._graph, self._id_map, self._road_id_to_edge) = self._build_graph()
self._find_loose_ends()
self._lane_change_link() | ['def', 'setup(self):', 'self._topology', '=', 'self._dao.get_topology()', '(self._graph,', 'self._id_map,', 'self._road_id_to_edge)', '=', 'self._build_graph()', 'self._find_loose_ends()', 'self._lane_change_link()'] | 571,337 |
emmanueldufourq/PAM_TransferLearning | PredictionHelper.py | Prediction.create_X_new | create_X_new | Create X input data to apply a model to an audio file. | [
"Create",
"X",
"input",
"data",
"to",
"apply",
"a",
"model",
"to",
"an",
"audio",
"file."
] | def create_X_new(self, mono_data, time_to_extract, sampleRate, start_index, end_index, verbose):
X_frequences = []
sampleRate = sampleRate
duration = end_index - start_index - time_to_extract + 1
if verbose:
print('-----------------------')
print('start (seconds)', start_index)
p... | ['def', 'create_X_new(self,', 'mono_data,', 'time_to_extract,', 'sampleRate,', 'start_index,', 'end_index,', 'verbose):', 'X_frequences', '=', '[]', 'sampleRate', '=', 'sampleRate', 'duration', '=', 'end_index', '-', 'start_index', '-', 'time_to_extract', '+', '1', 'if', 'verbose:', "print('-----------------------')", ... | 778,249 |
atulkum/object_detection | optimizer.py | build_data_parallel_model | build_data_parallel_model | Build a data parallel model given a function that builds the model on a single GPU. | [
"Build",
"a",
"data",
"parallel",
"model",
"given",
"a",
"function",
"that",
"builds",
"the",
"model",
"on",
"a",
"single",
"GPU."
] | def build_data_parallel_model(model, single_gpu_build_func):
if model.only_build_forward_pass:
single_gpu_build_func(model)
elif model.train:
all_loss_gradients = _build_forward_graph(model, single_gpu_build_func)
model.AddGradientOperators(all_loss_gradients)
if cfg.NUM_GPUS > 1... | ['def', 'build_data_parallel_model(model,', 'single_gpu_build_func):', 'if', 'model.only_build_forward_pass:', 'single_gpu_build_func(model)', 'elif', 'model.train:', 'all_loss_gradients', '=', '_build_forward_graph(model,', 'single_gpu_build_func)', 'model.AddGradientOperators(all_loss_gradients)', 'if', 'cfg.NUM_GPUS... | 772,826 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | test_memory.py | test_argument_change | test_argument_change | Check that if a function has a side effect in its arguments, it should use the hash of changing arguments. | [
"Check",
"that",
"if",
"a",
"function",
"has",
"a",
"side",
"effect",
"in",
"its",
"arguments,",
"it",
"should",
"use",
"the",
"hash",
"of",
"changing",
"arguments."
] | def test_argument_change(tmpdir):
memory = Memory(location=tmpdir.strpath, verbose=0)
func = memory.cache(count_and_append)
assert func() == 0
assert func() == 1 | ['def', 'test_argument_change(tmpdir):', 'memory', '=', 'Memory(location=tmpdir.strpath,', 'verbose=0)', 'func', '=', 'memory.cache(count_and_append)', 'assert', 'func()', '==', '0', 'assert', 'func()', '==', '1'] | 449,690 |
weimin17/Object-Detection_HelmetDetection | np_box_ops.py | iou | iou | Computes pairwise intersection-over-union between box collections. | [
"Computes",
"pairwise",
"intersection-over-union",
"between",
"box",
"collections."
] | def iou(boxes1, boxes2):
intersect = intersection(boxes1, boxes2)
area1 = area(boxes1)
area2 = area(boxes2)
union = np.expand_dims(area1, axis=1) + np.expand_dims(area2, axis=0) - intersect
return intersect / union | ['def', 'iou(boxes1,', 'boxes2):', 'intersect', '=', 'intersection(boxes1,', 'boxes2)', 'area1', '=', 'area(boxes1)', 'area2', '=', 'area(boxes2)', 'union', '=', 'np.expand_dims(area1,', 'axis=1)', '+', 'np.expand_dims(area2,', 'axis=0)', '-', 'intersect', 'return', 'intersect', '/', 'union'] | 751,112 |
nicknochnack/RealTimeSignLanguageTFJS | xlnet_modeling.py | RelativeAttention.call | call | Implements call() for the layer. | [
"Implements",
"call()",
"for",
"the",
"layer."
] | def call(self, q_head, k_head_h, v_head_h, k_head_r, seg_embed, seg_mat, r_w_bias, r_r_bias, r_s_bias, attn_mask):
ac = tf.einsum('ibnd,jbnd->ijbn', q_head + r_w_bias, k_head_h)
bd = tf.einsum('ibnd,jbnd->ijbn', q_head + r_r_bias, k_head_r)
bd = rel_shift(bd, klen=tf.shape(ac)[1])
if seg_mat is None:
... | ['def', 'call(self,', 'q_head,', 'k_head_h,', 'v_head_h,', 'k_head_r,', 'seg_embed,', 'seg_mat,', 'r_w_bias,', 'r_r_bias,', 'r_s_bias,', 'attn_mask):', 'ac', '=', "tf.einsum('ibnd,jbnd->ijbn',", 'q_head', '+', 'r_w_bias,', 'k_head_h)', 'bd', '=', "tf.einsum('ibnd,jbnd->ijbn',", 'q_head', '+', 'r_r_bias,', 'k_head_r)', ... | 850,656 |
csjunxu/Noisy-As-Clean-TIP2020 | __init__.py | YAMLObject.from_yaml | from_yaml | Convert a representation node to a Python object. | [
"Convert",
"a",
"representation",
"node",
"to",
"a",
"Python",
"object."
] | def from_yaml(cls, loader, node):
return loader.construct_yaml_object(node, cls) | ['def', 'from_yaml(cls,', 'loader,', 'node):', 'return', 'loader.construct_yaml_object(node,', 'cls)'] | 249,422 |
rnsandeep/ObjectDetection | logger.py | Logger.scalar_summary | scalar_summary | Log a scalar variable. | [
"Log",
"a",
"scalar",
"variable."
] | def scalar_summary(self, tag, value, step):
if USE_TENSORBOARD:
self.writer.add_scalar(tag, value, step) | ['def', 'scalar_summary(self,', 'tag,', 'value,', 'step):', 'if', 'USE_TENSORBOARD:', 'self.writer.add_scalar(tag,', 'value,', 'step)'] | 754,296 |
DLR-RM/stable-baselines3 | dummy_vec_env.py | DummyVecEnv.get_attr | get_attr | Return attribute from vectorized environment (see base class). | [
"Return",
"attribute",
"from",
"vectorized",
"environment",
"(see",
"base",
"class)."
] | def get_attr(self, attr_name: str, indices: VecEnvIndices=None) -> List[Any]:
target_envs = self._get_target_envs(indices)
return [getattr(env_i, attr_name) for env_i in target_envs] | ['def', 'get_attr(self,', 'attr_name:', 'str,', 'indices:', 'VecEnvIndices=None)', '->', 'List[Any]:', 'target_envs', '=', 'self._get_target_envs(indices)', 'return', '[getattr(env_i,', 'attr_name)', 'for', 'env_i', 'in', 'target_envs]'] | 383,189 |
SamsungLabs/fcaf3d | kitti_mono_dataset.py | KittiMonoDataset.convert_valid_bboxes | convert_valid_bboxes | Convert the predicted boxes into valid ones. | [
"Convert",
"the",
"predicted",
"boxes",
"into",
"valid",
"ones."
] | def convert_valid_bboxes(self, box_dict, info):
box_preds = box_dict['boxes_3d']
scores = box_dict['scores_3d']
labels = box_dict['labels_3d']
sample_idx = info['image']['image_idx']
if len(box_preds) == 0:
return dict(bbox=np.zeros([0, 4]), box3d_camera=np.zeros([0, 7]), scores=np.zeros([0]... | ['def', 'convert_valid_bboxes(self,', 'box_dict,', 'info):', 'box_preds', '=', "box_dict['boxes_3d']", 'scores', '=', "box_dict['scores_3d']", 'labels', '=', "box_dict['labels_3d']", 'sample_idx', '=', "info['image']['image_idx']", 'if', 'len(box_preds)', '==', '0:', 'return', 'dict(bbox=np.zeros([0,', '4]),', 'box3d_c... | 560,334 |
aws/sagemaker-python-sdk | accessors.py | JumpStartModelsAccessor.get_jumpstart_content_bucket | get_jumpstart_content_bucket | Returns JumpStart content bucket. | [
"Returns",
"JumpStart",
"content",
"bucket."
] | def get_jumpstart_content_bucket() -> Optional[str]:
return JumpStartModelsAccessor._content_bucket | ['def', 'get_jumpstart_content_bucket()', '->', 'Optional[str]:', 'return', 'JumpStartModelsAccessor._content_bucket'] | 830,144 |
rishab-sharma/object_detection | dataset.py | DataSet.has_next_batch | has_next_batch | Determine whether there is any batch left. | [
"Determine",
"whether",
"there",
"is",
"any",
"batch",
"left."
] | def has_next_batch(self):
return self.current_index + self.batch_size <= self.count | ['def', 'has_next_batch(self):', 'return', 'self.current_index', '+', 'self.batch_size', '<=', 'self.count'] | 744,963 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | _header_value_parser.py | get_extended_attrtext | get_extended_attrtext | attrtext = 1*(any non-ATTRIBUTE_ENDS character plus '%') This is a special parsing routine so that we get a value that includes % escapes as a single string (which we decode as a single string later). | [
"attrtext",
"=",
"1*(any",
"non-ATTRIBUTE_ENDS",
"character",
"plus",
"'%')",
"This",
"is",
"a",
"special",
"parsing",
"routine",
"so",
"that",
"we",
"get",
"a",
"value",
"that",
"includes",
"%",
"escapes",
"as",
"a",
"single",
"string",
"(which",
"we",
"dec... | def get_extended_attrtext(value):
m = _non_extended_attribute_end_matcher(value)
if not m:
raise errors.HeaderParseError('expected extended attrtext but found {!r}'.format(value))
attrtext = m.group()
value = value[len(attrtext):]
attrtext = ValueTerminal(attrtext, 'extended-attrtext')
_... | ['def', 'get_extended_attrtext(value):', 'm', '=', '_non_extended_attribute_end_matcher(value)', 'if', 'not', 'm:', 'raise', "errors.HeaderParseError('expected", 'extended', 'attrtext', 'but', 'found', "{!r}'.format(value))", 'attrtext', '=', 'm.group()', 'value', '=', 'value[len(attrtext):]', 'attrtext', '=', 'ValueTe... | 430,606 |
enlite-ai/maze | inventory.py | Inventory.is_full | is_full | Checks weather all slots in the inventory are in use. | [
"Checks",
"weather",
"all",
"slots",
"in",
"the",
"inventory",
"are",
"in",
"use."
] | def is_full(self) -> bool:
return len(self.pieces) == self.max_pieces_in_inventory | ['def', 'is_full(self)', '->', 'bool:', 'return', 'len(self.pieces)', '==', 'self.max_pieces_in_inventory'] | 647,583 |
SALT-NLP/Adaptive-Compositional-Modules | modeling_tf_utils.py | TFPreTrainedModel.set_bias | set_bias | Set all the bias in the LM head. | [
"Set",
"all",
"the",
"bias",
"in",
"the",
"LM",
"head."
] | def set_bias(self, value):
if self.get_lm_head() is not None:
lm_head = self.get_lm_head()
try:
lm_head.set_bias(value)
except AttributeError:
self(self.dummy_inputs)
lm_head.set_bias(value) | ['def', 'set_bias(self,', 'value):', 'if', 'self.get_lm_head()', 'is', 'not', 'None:', 'lm_head', '=', 'self.get_lm_head()', 'try:', 'lm_head.set_bias(value)', 'except', 'AttributeError:', 'self(self.dummy_inputs)', 'lm_head.set_bias(value)'] | 408,209 |
rifqind/Agent-Programs-3KS1 | iptestcontroller.py | report | report | Return a string with a summary report of test-related variables. | [
"Return",
"a",
"string",
"with",
"a",
"summary",
"report",
"of",
"test-related",
"variables."
] | def report():
inf = get_sys_info()
out = []
def _add(name, value):
out.append((name, value))
_add('IPython version', inf['ipython_version'])
_add('IPython commit', '{} ({})'.format(inf['commit_hash'], inf['commit_source']))
_add('IPython package', compress_user(inf['ipython_path']))
... | ['def', 'report():', 'inf', '=', 'get_sys_info()', 'out', '=', '[]', 'def', '_add(name,', 'value):', 'out.append((name,', 'value))', "_add('IPython", "version',", "inf['ipython_version'])", "_add('IPython", "commit',", "'{}", "({})'.format(inf['commit_hash'],", "inf['commit_source']))", "_add('IPython", "package',", "c... | 41,765 |
mo-cv/pycv | cameo.py | Cameo.run | run | Run the main loop. | [
"Run",
"the",
"main",
"loop."
] | def run(self):
self._windowManager.createWindow()
while self._windowManager.isWindowCreated:
self._captureManager.enterFrame()
frame = self._captureManager.frame
if frame is not None:
self._faceTracker.update(frame)
faces = self._faceTracker.faces
rect... | ['def', 'run(self):', 'self._windowManager.createWindow()', 'while', 'self._windowManager.isWindowCreated:', 'self._captureManager.enterFrame()', 'frame', '=', 'self._captureManager.frame', 'if', 'frame', 'is', 'not', 'None:', 'self._faceTracker.update(frame)', 'faces', '=', 'self._faceTracker.faces', 'rects.swapRects(... | 819,452 |
gunthercox/ChatterBot | srparser_app.py | app | app | Create a shift reduce parser app, using a simple grammar and text. | [
"Create",
"a",
"shift",
"reduce",
"parser",
"app,",
"using",
"a",
"simple",
"grammar",
"and",
"text."
] | def app():
from nltk.grammar import Nonterminal, Production, ContextFreeGrammar
nonterminals = 'S VP NP PP P N Name V Det'
(S, VP, NP, PP, P, N, Name, V, Det) = [Nonterminal(s) for s in nonterminals.split()]
productions = (Production(S, [NP, VP]), Production(NP, [Det, N]), Production(NP, [NP, PP]), Prod... | ['def', 'app():', 'from', 'nltk.grammar', 'import', 'Nonterminal,', 'Production,', 'ContextFreeGrammar', 'nonterminals', '=', "'S", 'VP', 'NP', 'PP', 'P', 'N', 'Name', 'V', "Det'", '(S,', 'VP,', 'NP,', 'PP,', 'P,', 'N,', 'Name,', 'V,', 'Det)', '=', '[Nonterminal(s)', 'for', 's', 'in', 'nonterminals.split()]', 'producti... | 527,361 |
LLNL/Abmarl | super_agent_wrapper.py | SuperAgentWrapper.get_info | get_info | Report the agent's additional info. | [
"Report",
"the",
"agent's",
"additional",
"info."
] | def get_info(self, agent_id, **kwargs):
assert agent_id not in self._covered_agents, 'We cannot get info for an agent that is covered by a super agent.'
if agent_id in self.super_agent_mapping:
return {covered_agent_id: self.sim.get_info(covered_agent_id, **kwargs) for covered_agent_id in self.super_age... | ['def', 'get_info(self,', 'agent_id,', '**kwargs):', 'assert', 'agent_id', 'not', 'in', 'self._covered_agents,', "'We", 'cannot', 'get', 'info', 'for', 'an', 'agent', 'that', 'is', 'covered', 'by', 'a', 'super', "agent.'", 'if', 'agent_id', 'in', 'self.super_agent_mapping:', 'return', '{covered_agent_id:', 'self.sim.ge... | 405,845 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.