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
vturrisi/solo-learn
deepclusterv2.py
DeepClusterV2.update_memory_banks
update_memory_banks
Updates DeepClusterV2's memory banks of indices and features.
[ "Updates", "DeepClusterV2's", "memory", "banks", "of", "indices", "and", "features." ]
def update_memory_banks(self, idxs: torch.Tensor, z: torch.Tensor, batch_idx: int) -> None: (start_idx, end_idx) = (batch_idx * self.batch_size, (batch_idx + 1) * self.batch_size) self.local_memory_index[start_idx:end_idx] = idxs for (c, z_c) in enumerate(z): self.local_memory_embeddings[c][start_id...
['def', 'update_memory_banks(self,', 'idxs:', 'torch.Tensor,', 'z:', 'torch.Tensor,', 'batch_idx:', 'int)', '->', 'None:', '(start_idx,', 'end_idx)', '=', '(batch_idx', '*', 'self.batch_size,', '(batch_idx', '+', '1)', '*', 'self.batch_size)', 'self.local_memory_index[start_idx:end_idx]', '=', 'idxs', 'for', '(c,', 'z_...
393,613
Katja-M/Python_NaturalLanguageProcessing
framenet.py
FramenetCorpusReader.ft_sents
ft_sents
Full-text annotation sentences, optionally filtered by document name.
[ "Full-text", "annotation", "sentences,", "optionally", "filtered", "by", "document", "name." ]
def ft_sents(self, docNamePattern=None): return PrettyLazyIteratorList((sent for d in self.docs(docNamePattern) for sent in d.sentence))
['def', 'ft_sents(self,', 'docNamePattern=None):', 'return', 'PrettyLazyIteratorList((sent', 'for', 'd', 'in', 'self.docs(docNamePattern)', 'for', 'sent', 'in', 'd.sentence))']
866,204
techexpert1611/Natural-Language-Processing
vector_embeddings.py
IMDBMovieReviews.apply_label_map
apply_label_map
Converts string labels to indices.
[ "Converts", "string", "labels", "to", "indices." ]
def apply_label_map(self, data, label_to_idx): for review in data: review[L_LABEL] = label_to_idx[review[L_LABEL]]
['def', 'apply_label_map(self,', 'data,', 'label_to_idx):', 'for', 'review', 'in', 'data:', 'review[L_LABEL]', '=', 'label_to_idx[review[L_LABEL]]']
658,031
gunthercox/ChatterBot
sessions.py
SessionStore.generate_key
generate_key
Simple function that generates a new session key.
[ "Simple", "function", "that", "generates", "a", "new", "session", "key." ]
def generate_key(self, salt=None): return generate_key(salt)
['def', 'generate_key(self,', 'salt=None):', 'return', 'generate_key(salt)']
483,740
vinits5/pc_autoencoder
plyfile.py
PlyData.read
read
Read PLY data from a readable file-like object or filename.
[ "Read", "PLY", "data", "from", "a", "readable", "file-like", "object", "or", "filename." ]
def read(stream): (must_close, stream) = _open_stream(stream, 'read') try: data = PlyData._parse_header(stream) for elt in data: elt._read(stream, data.text, data.byte_order) finally: if must_close: stream.close() return data
['def', 'read(stream):', '(must_close,', 'stream)', '=', '_open_stream(stream,', "'read')", 'try:', 'data', '=', 'PlyData._parse_header(stream)', 'for', 'elt', 'in', 'data:', 'elt._read(stream,', 'data.text,', 'data.byte_order)', 'finally:', 'if', 'must_close:', 'stream.close()', 'return', 'data']
765,799
vwxyzjn/cleanrl
buffers.py
BaseBuffer.add
add
Add elements to the buffer.
[ "Add", "elements", "to", "the", "buffer." ]
def add(self, *args, **kwargs) -> None: raise NotImplementedError()
['def', 'add(self,', '*args,', '**kwargs)', '->', 'None:', 'raise', 'NotImplementedError()']
488,138
43Carrig/recurrent_neural_networks_practice
summaries.py
add_histogram_summaries
add_histogram_summaries
Adds a histogram summary for each of the given tensors.
[ "Adds", "a", "histogram", "summary", "for", "each", "of", "the", "given", "tensors." ]
def add_histogram_summaries(tensors, prefix=None): summary_ops = [] for tensor in tensors: summary_ops.append(add_histogram_summary(tensor, prefix=prefix)) return summary_ops
['def', 'add_histogram_summaries(tensors,', 'prefix=None):', 'summary_ops', '=', '[]', 'for', 'tensor', 'in', 'tensors:', 'summary_ops.append(add_histogram_summary(tensor,', 'prefix=prefix))', 'return', 'summary_ops']
335,205
microsoft/nni
trial_runner.py
TrialRunner.send_heartbeat
send_heartbeat
Send a heartbeat to the other side.
[ "Send", "a", "heartbeat", "to", "the", "other", "side." ]
def send_heartbeat(self) -> float: current_time = time.time() command = ReportAwakeCommand(command_type='awake', time=current_time, idle=not self._processing_trials) self._channel.send(json.dumps(command)) return current_time
['def', 'send_heartbeat(self)', '->', 'float:', 'current_time', '=', 'time.time()', 'command', '=', "ReportAwakeCommand(command_type='awake',", 'time=current_time,', 'idle=not', 'self._processing_trials)', 'self._channel.send(json.dumps(command))', 'return', 'current_time']
728,616
sunishsheth2009/ChatterBot
testing.py
make_test_environ_builder
make_test_environ_builder
Creates a new test builder with some application defaults thrown in.
[ "Creates", "a", "new", "test", "builder", "with", "some", "application", "defaults", "thrown", "in." ]
def make_test_environ_builder(app, path='/', base_url=None, *args, **kwargs): http_host = app.config.get('SERVER_NAME') app_root = app.config.get('APPLICATION_ROOT') if base_url is None: base_url = 'http://%s/' % (http_host or 'localhost') if app_root: base_url += app_root.lstrip...
['def', 'make_test_environ_builder(app,', "path='/',", 'base_url=None,', '*args,', '**kwargs):', 'http_host', '=', "app.config.get('SERVER_NAME')", 'app_root', '=', "app.config.get('APPLICATION_ROOT')", 'if', 'base_url', 'is', 'None:', 'base_url', '=', "'http://%s/'", '%', '(http_host', 'or', "'localhost')", 'if', 'app...
528,987
calico/basenji
basenji_sat_plot2.py
global_align
global_align
Align two 1-hot encoded sequences.
[ "Align", "two", "1-hot", "encoded", "sequences." ]
def global_align(seq1_1hot, seq2_1hot): align_opts = {'gap_open_penalty': 10, 'gap_extend_penalty': 1, 'match_score': 5, 'mismatch_score': -4} seq1_dna = DNA(dna_io.hot1_dna(seq1_1hot)) seq2_dna = DNA(dna_io.hot1_dna(seq2_1hot)) seq_align = global_pairwise_align_nucleotide(seq1_dna, seq2_dna, gap_open_p...
['def', 'global_align(seq1_1hot,', 'seq2_1hot):', 'align_opts', '=', "{'gap_open_penalty':", '10,', "'gap_extend_penalty':", '1,', "'match_score':", '5,', "'mismatch_score':", '-4}', 'seq1_dna', '=', 'DNA(dna_io.hot1_dna(seq1_1hot))', 'seq2_dna', '=', 'DNA(dna_io.hot1_dna(seq2_1hot))', 'seq_align', '=', 'global_pairwis...
94,808
matsu0228/nlp-jp
bulk.py
_Bulk.add_update
add_update
Create an update document and add it to the list of ops.
[ "Create", "an", "update", "document", "and", "add", "it", "to", "the", "list", "of", "ops." ]
def add_update(self, selector, update, multi=False, upsert=False, collation=None): validate_ok_for_update(update) cmd = SON([('q', selector), ('u', update), ('multi', multi), ('upsert', upsert)]) collation = validate_collation_or_none(collation) if collation is not None: self.uses_collation = Tr...
['def', 'add_update(self,', 'selector,', 'update,', 'multi=False,', 'upsert=False,', 'collation=None):', 'validate_ok_for_update(update)', 'cmd', '=', "SON([('q',", 'selector),', "('u',", 'update),', "('multi',", 'multi),', "('upsert',", 'upsert)])', 'collation', '=', 'validate_collation_or_none(collation)', 'if', 'col...
804,719
wandb/wandb
test_vertex.py
mock_aiplatform
mock_aiplatform
Patch the aiplatform module with a mock object and return that object.
[ "Patch", "the", "aiplatform", "module", "with", "a", "mock", "object", "and", "return", "that", "object." ]
def mock_aiplatform(mocker): mock = MagicMock() def _fake_get_module(*args, **kwargs): return mock mocker.patch('wandb.sdk.launch.runner.vertex_runner.get_module', side_effect=_fake_get_module) return mock
['def', 'mock_aiplatform(mocker):', 'mock', '=', 'MagicMock()', 'def', '_fake_get_module(*args,', '**kwargs):', 'return', 'mock', "mocker.patch('wandb.sdk.launch.runner.vertex_runner.get_module',", 'side_effect=_fake_get_module)', 'return', 'mock']
941,308
kianak2002/Sentiment-Emotion-Analysis-project
egg_info.py
get_pkg_info_revision
get_pkg_info_revision
Get a -r### off of PKG-INFO Version in case this is an sdist of a subversion revision.
[ "Get", "a", "-r###", "off", "of", "PKG-INFO", "Version", "in", "case", "this", "is", "an", "sdist", "of", "a", "subversion", "revision." ]
def get_pkg_info_revision(): warnings.warn('get_pkg_info_revision is deprecated.', EggInfoDeprecationWarning) if os.path.exists('PKG-INFO'): with io.open('PKG-INFO') as f: for line in f: match = re.match('Version:.*-r(\\d+)\\s*$', line) if match: ...
['def', 'get_pkg_info_revision():', "warnings.warn('get_pkg_info_revision", 'is', "deprecated.',", 'EggInfoDeprecationWarning)', 'if', "os.path.exists('PKG-INFO'):", 'with', "io.open('PKG-INFO')", 'as', 'f:', 'for', 'line', 'in', 'f:', 'match', '=', "re.match('Version:.*-r(\\\\d+)\\\\s*$',", 'line)', 'if', 'match:', 'r...
875,722
chen742/PiPa
cityscapes.py
CityscapesDataset.evaluate
evaluate
Evaluation in Cityscapes/default protocol.
[ "Evaluation", "in", "Cityscapes/default", "protocol." ]
def evaluate(self, results, metric='mIoU', logger=None, imgfile_prefix=None, efficient_test=False): eval_results = dict() metrics = metric.copy() if isinstance(metric, list) else [metric] if 'cityscapes' in metrics: eval_results.update(self._evaluate_cityscapes(results, logger, imgfile_prefix)) ...
['def', 'evaluate(self,', 'results,', "metric='mIoU',", 'logger=None,', 'imgfile_prefix=None,', 'efficient_test=False):', 'eval_results', '=', 'dict()', 'metrics', '=', 'metric.copy()', 'if', 'isinstance(metric,', 'list)', 'else', '[metric]', 'if', "'cityscapes'", 'in', 'metrics:', 'eval_results.update(self._evaluate_c...
305,091
ArdaGunay99/Key_Detection_Unsupervised_Learning
transforms.py
Bbox.mutatedx
mutatedx
Return whether the x-limits have changed since init.
[ "Return", "whether", "the", "x-limits", "have", "changed", "since", "init." ]
def mutatedx(self): return self._points[0, 0] != self._points_orig[0, 0] or self._points[1, 0] != self._points_orig[1, 0]
['def', 'mutatedx(self):', 'return', 'self._points[0,', '0]', '!=', 'self._points_orig[0,', '0]', 'or', 'self._points[1,', '0]', '!=', 'self._points_orig[1,', '0]']
257,432
kubeflow/pipelines
component.py
bigquery_ml_feature_info_job
bigquery_ml_feature_info_job
Launch a BigQuery feature info job and waits for it to finish.
[ "Launch", "a", "BigQuery", "feature", "info", "job", "and", "waits", "for", "it", "to", "finish." ]
def bigquery_ml_feature_info_job(model: Input[BQMLModel], feature_info: Output[Artifact], gcp_resources: OutputPath(str), location: str='us-central1', query_parameters: List[str]=[], job_configuration_query: Dict[str, str]={}, labels: Dict[str, str]={}, project: str=_placeholders.PROJECT_ID_PLACEHOLDER): return Con...
['def', 'bigquery_ml_feature_info_job(model:', 'Input[BQMLModel],', 'feature_info:', 'Output[Artifact],', 'gcp_resources:', 'OutputPath(str),', 'location:', "str='us-central1',", 'query_parameters:', 'List[str]=[],', 'job_configuration_query:', 'Dict[str,', 'str]={},', 'labels:', 'Dict[str,', 'str]={},', 'project:', 's...
770,931
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
vgslspecs_test.py
VgslspecsTest.ExpectScaledSize
ExpectScaledSize
Tests that the output of the graph of the given spec has target_shape.
[ "Tests", "that", "the", "output", "of", "the", "graph", "of", "the", "given", "spec", "has", "target_shape." ]
def ExpectScaledSize(self, spec, target_shape, factor=1): with tf.Graph().as_default(): with self.test_session() as sess: self.SetupInputs() vgsl = vgslspecs.VGSLSpecs(self.ph_widths, self.ph_heights, True) outputs = vgsl.Build(self.ph_image, spec) target_widt...
['def', 'ExpectScaledSize(self,', 'spec,', 'target_shape,', 'factor=1):', 'with', 'tf.Graph().as_default():', 'with', 'self.test_session()', 'as', 'sess:', 'self.SetupInputs()', 'vgsl', '=', 'vgslspecs.VGSLSpecs(self.ph_widths,', 'self.ph_heights,', 'True)', 'outputs', '=', 'vgsl.Build(self.ph_image,', 'spec)', 'target...
110,657
unixpickle/anyrl-py
test_mpi.py
test_mpi_optimizer
test_mpi_optimizer
Test that the MPIOptimizer is equivalent to its encapsulated optimizer.
[ "Test", "that", "the", "MPIOptimizer", "is", "equivalent", "to", "its", "encapsulated", "optimizer." ]
def test_mpi_optimizer(loss_fn): with tf.Graph().as_default(): x = tf.get_variable('x', shape=[10, 15], dtype=tf.float32, initializer=tf.truncated_normal_initializer()) loss = loss_fn(x) optim = tf.train.AdamOptimizer(learning_rate=0.1) mpi_optim = MPIOptimizer(optim, loss) m...
['def', 'test_mpi_optimizer(loss_fn):', 'with', 'tf.Graph().as_default():', 'x', '=', "tf.get_variable('x',", 'shape=[10,', '15],', 'dtype=tf.float32,', 'initializer=tf.truncated_normal_initializer())', 'loss', '=', 'loss_fn(x)', 'optim', '=', 'tf.train.AdamOptimizer(learning_rate=0.1)', 'mpi_optim', '=', 'MPIOptimizer...
33,716
maheshbhosle/Natural-Language-Processing
data.py
load_vocabulary
load_vocabulary
Loads vocabulary from vocabulary_path.
[ "Loads", "vocabulary", "from", "vocabulary_path." ]
def load_vocabulary(vocabulary_path: str) -> Tuple[Dict[str, int], Dict[int, str]]: vocab_id_to_token = {} vocab_token_to_id = {} with open(vocabulary_path, 'r', encoding='UTF-8') as file: for (index, token) in enumerate(file): token = token.strip() if not token: ...
['def', 'load_vocabulary(vocabulary_path:', 'str)', '->', 'Tuple[Dict[str,', 'int],', 'Dict[int,', 'str]]:', 'vocab_id_to_token', '=', '{}', 'vocab_token_to_id', '=', '{}', 'with', 'open(vocabulary_path,', "'r',", "encoding='UTF-8')", 'as', 'file:', 'for', '(index,', 'token)', 'in', 'enumerate(file):', 'token', '=', 't...
685,236
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform
test_longdouble.py
test_array_and_stringlike_roundtrip
test_array_and_stringlike_roundtrip
Test that string representations of long-double roundtrip both for array casting and scalar coercion, see also gh-15608.
[ "Test", "that", "string", "representations", "of", "long-double", "roundtrip", "both", "for", "array", "casting", "and", "scalar", "coercion,", "see", "also", "gh-15608." ]
def test_array_and_stringlike_roundtrip(strtype): o = 1 + LD_INFO.eps if strtype in (np.bytes_, bytes): o_str = strtype(repr(o).encode('ascii')) else: o_str = strtype(repr(o)) assert o == np.longdouble(o_str) o_strarr = np.asarray([o] * 3, dtype=strtype) assert (o == o_strarr.ast...
['def', 'test_array_and_stringlike_roundtrip(strtype):', 'o', '=', '1', '+', 'LD_INFO.eps', 'if', 'strtype', 'in', '(np.bytes_,', 'bytes):', 'o_str', '=', "strtype(repr(o).encode('ascii'))", 'else:', 'o_str', '=', 'strtype(repr(o))', 'assert', 'o', '==', 'np.longdouble(o_str)', 'o_strarr', '=', 'np.asarray([o]', '*', '...
102,554
AgnostiqHQ/covalent
app_test.py
test_db
test_db
Instantiate and return an in-memory database.
[ "Instantiate", "and", "return", "an", "in-memory", "database." ]
def test_db(): return MockDataStore(db_URL='sqlite+pysqlite:///:memory:')
['def', 'test_db():', 'return', "MockDataStore(db_URL='sqlite+pysqlite:///:memory:')"]
489,754
dengfy/cs224d
utils.py
idxs_to_matrix
idxs_to_matrix
Return a matrix X with each row as a word vector for the corresponding index in idxs.
[ "Return", "a", "matrix", "X", "with", "each", "row", "as", "a", "word", "vector", "for", "the", "corresponding", "index", "in", "idxs." ]
def idxs_to_matrix(idxs, L): return vstack([L[i] for i in idxs])
['def', 'idxs_to_matrix(idxs,', 'L):', 'return', 'vstack([L[i]', 'for', 'i', 'in', 'idxs])']
506,474
openvinotoolkit/training_extensions
shape_drawer.py
Helpers.set_cursor_pos
set_cursor_pos
Move the cursor to a new position.
[ "Move", "the", "cursor", "to", "a", "new", "position." ]
def set_cursor_pos(self, cursor_pos: Optional[Coordinate]=None): if cursor_pos is None: cursor_pos = Coordinate(0, 0) self.cursor_pos = cursor_pos
['def', 'set_cursor_pos(self,', 'cursor_pos:', 'Optional[Coordinate]=None):', 'if', 'cursor_pos', 'is', 'None:', 'cursor_pos', '=', 'Coordinate(0,', '0)', 'self.cursor_pos', '=', 'cursor_pos']
918,892
aivclab/vision
test_video_reader.py
TestVideoReader.test_read_video_from_file_rescale_both_min_max_dimension
test_read_video_from_file_rescale_both_min_max_dimension
Test the case when decoder starts with a video file to decode frames, and video min dimension between height and width is set.
[ "Test", "the", "case", "when", "decoder", "starts", "with", "a", "video", "file", "to", "decode", "frames,", "and", "video", "min", "dimension", "between", "height", "and", "width", "is", "set." ]
def test_read_video_from_file_rescale_both_min_max_dimension(self, test_video): (width, height, min_dimension, max_dimension) = (0, 0, 64, 85) (video_start_pts, video_end_pts) = (0, -1) (video_timebase_num, video_timebase_den) = (0, 1) (samples, channels) = (0, 0) (audio_start_pts, audio_end_pts) = ...
['def', 'test_read_video_from_file_rescale_both_min_max_dimension(self,', 'test_video):', '(width,', 'height,', 'min_dimension,', 'max_dimension)', '=', '(0,', '0,', '64,', '85)', '(video_start_pts,', 'video_end_pts)', '=', '(0,', '-1)', '(video_timebase_num,', 'video_timebase_den)', '=', '(0,', '1)', '(samples,', 'cha...
958,052
Wuziyi616/Artificial_Intelligence_Project1
image_utils.py
show_gray_image
show_gray_image
Show gray scale image.
[ "Show", "gray", "scale", "image." ]
def show_gray_image(image): plt.imshow(image, cmap='gray') plt.show()
['def', 'show_gray_image(image):', 'plt.imshow(image,', "cmap='gray')", 'plt.show()']
92,085
thaines/helit
model.py
DocSample.getInstCount
getInstCount
Returns the number of cluster instances in the documents model.
[ "Returns", "the", "number", "of", "cluster", "instances", "in", "the", "documents", "model." ]
def getInstCount(self): return self.dp.shape[0]
['def', 'getInstCount(self):', 'return', 'self.dp.shape[0]']
591,128
Katja-M/Python_NaturalLanguageProcessing
dates.py
weeks
weeks
Return weeks as days.
[ "Return", "weeks", "as", "days." ]
def weeks(w): return w * DAYS_PER_WEEK
['def', 'weeks(w):', 'return', 'w', '*', 'DAYS_PER_WEEK']
864,488
sony/nnabla-rl
test_ppo.py
TestPPO.test_latest_iteration_state
test_latest_iteration_state
Check that latest iteration state has the keys and values we expected.
[ "Check", "that", "latest", "iteration", "state", "has", "the", "keys", "and", "values", "we", "expected." ]
def test_latest_iteration_state(self): dummy_env = E.DummyContinuous() ppo = A.PPO(dummy_env) ppo._policy_trainer_state = {'pi_loss': 0.0} ppo._v_function_trainer_state = {'v_loss': 1.0} latest_iteration_state = ppo.latest_iteration_state assert 'pi_loss' in latest_iteration_state['scalar'] ...
['def', 'test_latest_iteration_state(self):', 'dummy_env', '=', 'E.DummyContinuous()', 'ppo', '=', 'A.PPO(dummy_env)', 'ppo._policy_trainer_state', '=', "{'pi_loss':", '0.0}', 'ppo._v_function_trainer_state', '=', "{'v_loss':", '1.0}', 'latest_iteration_state', '=', 'ppo.latest_iteration_state', 'assert', "'pi_loss'", ...
727,426
huawei-noah/xingtian
mean_loss.py
MeanLoss.call
call
Compute loss, mean() to average on multi-gpu.
[ "Compute", "loss,", "mean()", "to", "average", "on", "multi-gpu." ]
def call(self, inputs, targets): return inputs.mean()
['def', 'call(self,', 'inputs,', 'targets):', 'return', 'inputs.mean()']
962,719
sek788432/Waymo-2D-Object-Detection
export_model_utils.py
ExtractGlobalFeatures
ExtractGlobalFeatures
Extract global features for input image.
[ "Extract", "global", "features", "for", "input", "image." ]
def ExtractGlobalFeatures(image, image_scales, global_scales_ind, model_fn, multi_scale_pool_type='None', normalize_global_descriptor=False): original_image_shape_float = tf.gather(tf.dtypes.cast(tf.shape(image), tf.float32), [0, 1]) image_tensor = gld.NormalizeImages(image, pixel_value_offset=128.0, pixel_valu...
['def', 'ExtractGlobalFeatures(image,', 'image_scales,', 'global_scales_ind,', 'model_fn,', "multi_scale_pool_type='None',", 'normalize_global_descriptor=False):', 'original_image_shape_float', '=', 'tf.gather(tf.dtypes.cast(tf.shape(image),', 'tf.float32),', '[0,', '1])', 'image_tensor', '=', 'gld.NormalizeImages(imag...
974,301
marcsto/rl
transforms.py
Transform.transform_env_device
transform_env_device
Transforms the device of the parent env.
[ "Transforms", "the", "device", "of", "the", "parent", "env." ]
def transform_env_device(self, device: torch.device): return device
['def', 'transform_env_device(self,', 'device:', 'torch.device):', 'return', 'device']
859,109
myothida/Supervised-Machine-Learning
test_lapack.py
test_tzrzf
test_tzrzf
This test performs an RZ decomposition in which an m x n upper trapezoidal array M (m <= n) is factorized as M = [R 0] * Z where R is upper triangular and Z is unitary.
[ "This", "test", "performs", "an", "RZ", "decomposition", "in", "which", "an", "m", "x", "n", "upper", "trapezoidal", "array", "M", "(m", "<=", "n)", "is", "factorized", "as", "M", "=", "[R", "0]", "*", "Z", "where", "R", "is", "upper", "triangular", ...
def test_tzrzf(): seed(1234) (m, n) = (10, 15) for (ind, dtype) in enumerate(DTYPES): (tzrzf, tzrzf_lw) = get_lapack_funcs(('tzrzf', 'tzrzf_lwork'), dtype=dtype) lwork = _compute_lwork(tzrzf_lw, m, n) if ind < 2: A = triu(rand(m, n).astype(dtype)) else: ...
['def', 'test_tzrzf():', 'seed(1234)', '(m,', 'n)', '=', '(10,', '15)', 'for', '(ind,', 'dtype)', 'in', 'enumerate(DTYPES):', '(tzrzf,', 'tzrzf_lw)', '=', "get_lapack_funcs(('tzrzf',", "'tzrzf_lwork'),", 'dtype=dtype)', 'lwork', '=', '_compute_lwork(tzrzf_lw,', 'm,', 'n)', 'if', 'ind', '<', '2:', 'A', '=', 'triu(rand(m...
445,830
wanyao1992/code_summarization_public
getComments.py
generate_pairs
generate_pairs
Loop through the source code and filter comments and their correspondig code.
[ "Loop", "through", "the", "source", "code", "and", "filter", "comments", "and", "their", "correspondig", "code." ]
def generate_pairs(source, codeFile, commentFile, maxBucket, module='<string>'): if hasattr(source, 'read'): filename = getattr(source, 'name', module) module = splitext(basename(filename))[0] source = source.read() source = source.splitlines() normalComments = 0 inlineComments =...
['def', 'generate_pairs(source,', 'codeFile,', 'commentFile,', 'maxBucket,', "module='<string>'):", 'if', 'hasattr(source,', "'read'):", 'filename', '=', 'getattr(source,', "'name',", 'module)', 'module', '=', 'splitext(basename(filename))[0]', 'source', '=', 'source.read()', 'source', '=', 'source.splitlines()', 'norm...
495,850
devashish-patel/webcam-motion-detector
server.py
BaseHTTPRequestHandler.log_date_time_string
log_date_time_string
Return the current time formatted for logging.
[ "Return", "the", "current", "time", "formatted", "for", "logging." ]
def log_date_time_string(self): now = time.time() (year, month, day, hh, mm, ss, x, y, z) = time.localtime(now) s = '%02d/%3s/%04d %02d:%02d:%02d' % (day, self.monthname[month], year, hh, mm, ss) return s
['def', 'log_date_time_string(self):', 'now', '=', 'time.time()', '(year,', 'month,', 'day,', 'hh,', 'mm,', 'ss,', 'x,', 'y,', 'z)', '=', 'time.localtime(now)', 's', '=', "'%02d/%3s/%04d", "%02d:%02d:%02d'", '%', '(day,', 'self.monthname[month],', 'year,', 'hh,', 'mm,', 'ss)', 'return', 's']
978,084
happinesslz/TANet
fastai_optim.py
OptimWrapper.beta
beta
Set beta (or alpha as makes sense for given optimizer).
[ "Set", "beta", "(or", "alpha", "as", "makes", "sense", "for", "given", "optimizer)." ]
def beta(self, val: float) -> None: if val is None: return if 'betas' in self.opt_keys: self.set_val('betas', (self._mom, listify(val, self._beta))) elif 'alpha' in self.opt_keys: self.set_val('alpha', listify(val, self._beta)) self._beta = listify(val, self._beta)
['def', 'beta(self,', 'val:', 'float)', '->', 'None:', 'if', 'val', 'is', 'None:', 'return', 'if', "'betas'", 'in', 'self.opt_keys:', "self.set_val('betas',", '(self._mom,', 'listify(val,', 'self._beta)))', 'elif', "'alpha'", 'in', 'self.opt_keys:', "self.set_val('alpha',", 'listify(val,', 'self._beta))', 'self._beta',...
907,231
intel/neural-compressor
utility.py
get_serve_log_workspace
get_serve_log_workspace
Get log workspace for service.
[ "Get", "log", "workspace", "for", "service." ]
def get_serve_log_workspace(workspace='./'): return os.path.join(workspace, 'serve_log')
['def', "get_serve_log_workspace(workspace='./'):", 'return', 'os.path.join(workspace,', "'serve_log')"]
721,809
Multhree/Computer-Vision
resneXt.py
resnext101
resnext101
Constructs a ResNeXt-101 model.
[ "Constructs", "a", "ResNeXt-101", "model." ]
def resnext101(**kwargs): model = ResNeXt(Bottleneck, [3, 4, 23, 3], **kwargs) return model
['def', 'resnext101(**kwargs):', 'model', '=', 'ResNeXt(Bottleneck,', '[3,', '4,', '23,', '3],', '**kwargs)', 'return', 'model']
460,061
intel/neural-compressor
test_graph.py
TestGraph.test_empty_graph_has_no_nodes
test_empty_graph_has_no_nodes
Test if empty graph has no nodes.
[ "Test", "if", "empty", "graph", "has", "no", "nodes." ]
def test_empty_graph_has_no_nodes(self) -> None: graph = Graph() self.assertEqual([], graph.nodes)
['def', 'test_empty_graph_has_no_nodes(self)', '->', 'None:', 'graph', '=', 'Graph()', 'self.assertEqual([],', 'graph.nodes)']
721,620
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
pygame_console.py
PyGameConsole.getheightwidth
getheightwidth
Return (height, width) where height and width are the height and width of the terminal window in characters.
[ "Return", "(height,", "width)", "where", "height", "and", "width", "are", "the", "height", "and", "width", "of", "the", "terminal", "window", "in", "characters." ]
def getheightwidth(self): return ((600 - tmargin - bmargin) / self.fh, (800 - lmargin - rmargin) / self.fw)
['def', 'getheightwidth(self):', 'return', '((600', '-', 'tmargin', '-', 'bmargin)', '/', 'self.fh,', '(800', '-', 'lmargin', '-', 'rmargin)', '/', 'self.fw)']
377,435
google-research/batch_rl
logged_prioritized_replay_buffer.py
WrappedLoggedPrioritizedReplayBuffer.tf_get_priority
tf_get_priority
Gets the priorities for the given indices.
[ "Gets", "the", "priorities", "for", "the", "given", "indices." ]
def tf_get_priority(self, indices): return tf.py_func(self.memory.get_priority, [indices], tf.float32, name='prioritized_replay_get_priority_py_func')
['def', 'tf_get_priority(self,', 'indices):', 'return', 'tf.py_func(self.memory.get_priority,', '[indices],', 'tf.float32,', "name='prioritized_replay_get_priority_py_func')"]
105,904
QData/deepWordBug
math2html.py
HybridSize.getsize
getsize
Read the size for a function and parse it.
[ "Read", "the", "size", "for", "a", "function", "and", "parse", "it." ]
def getsize(self, function): sizestring = self.configsizes[function.command] for name in function.params: if name in sizestring: size = function.params[name].value.computesize() sizestring = sizestring.replace(name, str(size)) if '$' in sizestring: Trace.error('Unconv...
['def', 'getsize(self,', 'function):', 'sizestring', '=', 'self.configsizes[function.command]', 'for', 'name', 'in', 'function.params:', 'if', 'name', 'in', 'sizestring:', 'size', '=', 'function.params[name].value.computesize()', 'sizestring', '=', 'sizestring.replace(name,', 'str(size))', 'if', "'$'", 'in', 'sizestrin...
542,647
sunishsheth2009/ChatterBot
serving.py
generate_adhoc_ssl_context
generate_adhoc_ssl_context
Generates an adhoc SSL context for the development server.
[ "Generates", "an", "adhoc", "SSL", "context", "for", "the", "development", "server." ]
def generate_adhoc_ssl_context(): from OpenSSL import SSL (cert, pkey) = generate_adhoc_ssl_pair() ctx = SSL.Context(SSL.SSLv23_METHOD) ctx.use_privatekey(pkey) ctx.use_certificate(cert) return ctx
['def', 'generate_adhoc_ssl_context():', 'from', 'OpenSSL', 'import', 'SSL', '(cert,', 'pkey)', '=', 'generate_adhoc_ssl_pair()', 'ctx', '=', 'SSL.Context(SSL.SSLv23_METHOD)', 'ctx.use_privatekey(pkey)', 'ctx.use_certificate(cert)', 'return', 'ctx']
483,340
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
layers.py
cl_logits_subgraph
cl_logits_subgraph
Construct multiple ReLU layers with dropout and a linear layer.
[ "Construct", "multiple", "ReLU", "layers", "with", "dropout", "and", "a", "linear", "layer." ]
def cl_logits_subgraph(layer_sizes, input_size, num_classes, keep_prob=1.0): subgraph = K.models.Sequential(name='cl_logits') for (i, layer_size) in enumerate(layer_sizes): if i == 0: subgraph.add(K.layers.Dense(layer_size, activation='relu', input_dim=input_size)) else: ...
['def', 'cl_logits_subgraph(layer_sizes,', 'input_size,', 'num_classes,', 'keep_prob=1.0):', 'subgraph', '=', "K.models.Sequential(name='cl_logits')", 'for', '(i,', 'layer_size)', 'in', 'enumerate(layer_sizes):', 'if', 'i', '==', '0:', 'subgraph.add(K.layers.Dense(layer_size,', "activation='relu',", 'input_dim=input_si...
14,268
google-research/fixmatch
ema.py
assign_ema_vars_from_initial_values
assign_ema_vars_from_initial_values
Assign EMA variables from initial values.
[ "Assign", "EMA", "variables", "from", "initial", "values." ]
def assign_ema_vars_from_initial_values(ema_variables, initial_values): def _assign_one_var_fn(ema_var, value): ema_var.assign(value) def _assign_all_in_cross_replica_context_fn(strategy, ema_vars, values): for (ema_var, value) in zip(ema_vars, values): value = strategy.extended.re...
['def', 'assign_ema_vars_from_initial_values(ema_variables,', 'initial_values):', 'def', '_assign_one_var_fn(ema_var,', 'value):', 'ema_var.assign(value)', 'def', '_assign_all_in_cross_replica_context_fn(strategy,', 'ema_vars,', 'values):', 'for', '(ema_var,', 'value)', 'in', 'zip(ema_vars,', 'values):', 'value', '=', ...
211,033
lakshaygoyal425/Computer-Vision
keras_darknet19.py
darknet19
darknet19
Generate Darknet-19 model for Imagenet classification.
[ "Generate", "Darknet-19", "model", "for", "Imagenet", "classification." ]
def darknet19(inputs): body = darknet_body()(inputs) logits = DarknetConv2D(1000, (1, 1), activation='softmax')(body) return Model(inputs, logits)
['def', 'darknet19(inputs):', 'body', '=', 'darknet_body()(inputs)', 'logits', '=', 'DarknetConv2D(1000,', '(1,', '1),', "activation='softmax')(body)", 'return', 'Model(inputs,', 'logits)']
469,675
nicknochnack/RealTimeSignLanguageTFJS
box_ops.py
encode_boxes
encode_boxes
Encode boxes to targets.
[ "Encode", "boxes", "to", "targets." ]
def encode_boxes(boxes, anchors, weights=None): if boxes.shape[-1] != 4: raise ValueError('boxes.shape[-1] is {:d}, but must be 4.'.format(boxes.shape[-1])) with tf.name_scope('encode_boxes'): boxes = tf.cast(boxes, dtype=anchors.dtype) ymin = boxes[..., 0:1] xmin = boxes[..., 1:...
['def', 'encode_boxes(boxes,', 'anchors,', 'weights=None):', 'if', 'boxes.shape[-1]', '!=', '4:', 'raise', "ValueError('boxes.shape[-1]", 'is', '{:d},', 'but', 'must', 'be', "4.'.format(boxes.shape[-1]))", 'with', "tf.name_scope('encode_boxes'):", 'boxes', '=', 'tf.cast(boxes,', 'dtype=anchors.dtype)', 'ymin', '=', 'bo...
850,869
ctogle/chunktagger
util.py
gather
gather
Provide namespace of all run options specified.
[ "Provide", "namespace", "of", "all", "run", "options", "specified." ]
def gather(): cachedir = os.path.join(os.getcwd(), '.cache') vectorcache = os.path.join(cachedir, 'input_vectors.%s.pt') modelcache = os.path.join(cachedir, 'model_snapshot.pt') parser = argparse.ArgumentParser() parser.add_argument('--cachedir', type=str, default=cachedir) parser.add_argument('...
['def', 'gather():', 'cachedir', '=', 'os.path.join(os.getcwd(),', "'.cache')", 'vectorcache', '=', 'os.path.join(cachedir,', "'input_vectors.%s.pt')", 'modelcache', '=', 'os.path.join(cachedir,', "'model_snapshot.pt')", 'parser', '=', 'argparse.ArgumentParser()', "parser.add_argument('--cachedir',", 'type=str,', 'defa...
105,231
myothida/Supervised-Machine-Learning
_win32_console.py
GetConsoleScreenBufferInfo
GetConsoleScreenBufferInfo
Retrieves information about the specified console screen buffer.
[ "Retrieves", "information", "about", "the", "specified", "console", "screen", "buffer." ]
def GetConsoleScreenBufferInfo(std_handle: wintypes.HANDLE) -> CONSOLE_SCREEN_BUFFER_INFO: console_screen_buffer_info = CONSOLE_SCREEN_BUFFER_INFO() _GetConsoleScreenBufferInfo(std_handle, byref(console_screen_buffer_info)) return console_screen_buffer_info
['def', 'GetConsoleScreenBufferInfo(std_handle:', 'wintypes.HANDLE)', '->', 'CONSOLE_SCREEN_BUFFER_INFO:', 'console_screen_buffer_info', '=', 'CONSOLE_SCREEN_BUFFER_INFO()', '_GetConsoleScreenBufferInfo(std_handle,', 'byref(console_screen_buffer_info))', 'return', 'console_screen_buffer_info']
445,166
THU-BPM/PairSCL
losses.py
SupConLoss.forward
forward
Compute loss for model.
[ "Compute", "loss", "for", "model." ]
def forward(self, features, labels=None, mask=None): device = torch.device('cuda') if features.is_cuda else torch.device('cpu') batch_size = features.shape[0] if labels is not None and mask is not None: raise ValueError('Cannot define both `labels` and `mask`') elif labels is not None: l...
['def', 'forward(self,', 'features,', 'labels=None,', 'mask=None):', 'device', '=', "torch.device('cuda')", 'if', 'features.is_cuda', 'else', "torch.device('cpu')", 'batch_size', '=', 'features.shape[0]', 'if', 'labels', 'is', 'not', 'None', 'and', 'mask', 'is', 'not', 'None:', 'raise', "ValueError('Cannot", 'define', ...
277,478
tobegit3hub/deep_image_model
set_ops.py
set_size
set_size
Compute number of unique elements along last dimension of `a`.
[ "Compute", "number", "of", "unique", "elements", "along", "last", "dimension", "of", "`a`." ]
def set_size(a, validate_indices=True): a = tensor_util.convert_to_tensor_or_sparse_tensor(a, name='a') if not isinstance(a, sparse_tensor.SparseTensor): raise TypeError('Expected `SparseTensor`, got %s.' % a) if a.values.dtype.base_dtype not in _VALID_DTYPES: raise TypeError('Invalid dtype ...
['def', 'set_size(a,', 'validate_indices=True):', 'a', '=', 'tensor_util.convert_to_tensor_or_sparse_tensor(a,', "name='a')", 'if', 'not', 'isinstance(a,', 'sparse_tensor.SparseTensor):', 'raise', "TypeError('Expected", '`SparseTensor`,', 'got', "%s.'", '%', 'a)', 'if', 'a.values.dtype.base_dtype', 'not', 'in', '_VALID...
181,959
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
model.py
Model.max_pool_views
max_pool_views
Max pool across all nets in spatial dimensions.
[ "Max", "pool", "across", "all", "nets", "in", "spatial", "dimensions." ]
def max_pool_views(self, nets_list): (batch_size, height, width, num_features) = [d.value for d in nets_list[0].get_shape().dims] xy_flat_shape = (batch_size, 1, height * width, num_features) nets_for_merge = [] with tf.variable_scope('max_pool_views', values=nets_list): for net in nets_list: ...
['def', 'max_pool_views(self,', 'nets_list):', '(batch_size,', 'height,', 'width,', 'num_features)', '=', '[d.value', 'for', 'd', 'in', 'nets_list[0].get_shape().dims]', 'xy_flat_shape', '=', '(batch_size,', '1,', 'height', '*', 'width,', 'num_features)', 'nets_for_merge', '=', '[]', 'with', "tf.variable_scope('max_poo...
14,553
denisyarats/exorl
quadruped.py
Physics.self_to_ball_distance
self_to_ball_distance
Returns horizontal distance from the quadruped workspace to the ball.
[ "Returns", "horizontal", "distance", "from", "the", "quadruped", "workspace", "to", "the", "ball." ]
def self_to_ball_distance(self): self_to_ball = self.named.data.site_xpos['workspace'] - self.named.data.xpos['ball'] return np.linalg.norm(self_to_ball[:2])
['def', 'self_to_ball_distance(self):', 'self_to_ball', '=', "self.named.data.site_xpos['workspace']", '-', "self.named.data.xpos['ball']", 'return', 'np.linalg.norm(self_to_ball[:2])']
563,600
lebrice/Sequoia
setting.py
IncrementalSLSetting.current_task_classes
current_task_classes
Gives back the labels present in the current task.
[ "Gives", "back", "the", "labels", "present", "in", "the", "current", "task." ]
def current_task_classes(self, train: bool) -> List[int]: return self.task_classes(self._current_task_id, train)
['def', 'current_task_classes(self,', 'train:', 'bool)', '->', 'List[int]:', 'return', 'self.task_classes(self._current_task_id,', 'train)']
349,691
LorenzoCassano/TablutChallenge22-23
games.py
Backgammon.compute_utility
compute_utility
If 'W' wins with this move, return 1; if 'B' wins return -1; else return 0.
[ "If", "'W'", "wins", "with", "this", "move,", "return", "1;", "if", "'B'", "wins", "return", "-1;", "else", "return", "0." ]
def compute_utility(self, board, move, player): util = {'W': 1, 'B': -1} for idx in range(0, 24): if board[idx][player] > 0: return 0 return util[player]
['def', 'compute_utility(self,', 'board,', 'move,', 'player):', 'util', '=', "{'W':", '1,', "'B':", '-1}', 'for', 'idx', 'in', 'range(0,', '24):', 'if', 'board[idx][player]', '>', '0:', 'return', '0', 'return', 'util[player]']
365,184
SALT-NLP/Adaptive-Compositional-Modules
model_mixin.py
ModelAdaptersMixin.add_adapter
add_adapter
Adds a new adapter module of the specified type to the model.
[ "Adds", "a", "new", "adapter", "module", "of", "the", "specified", "type", "to", "the", "model." ]
def add_adapter(self, adapter_name: str, config=None): if isinstance(config, dict): config = AdapterConfig.from_dict(config) self.config.adapters.add(adapter_name, config=config) self.base_model._add_adapter(adapter_name)
['def', 'add_adapter(self,', 'adapter_name:', 'str,', 'config=None):', 'if', 'isinstance(config,', 'dict):', 'config', '=', 'AdapterConfig.from_dict(config)', 'self.config.adapters.add(adapter_name,', 'config=config)', 'self.base_model._add_adapter(adapter_name)']
408,500
deepmind/trfl
action_value_ops_test.py
QVTest.testTarget
testTarget
Tests that target value == r_t + pcont_t * q_t[a_t].
[ "Tests", "that", "target", "value", "==", "r_t", "+", "pcont_t", "*", "q_t[a_t]." ]
def testTarget(self): with self.test_session() as sess: self.assertAllClose(sess.run(self.extra_ops.target), [1, 4])
['def', 'testTarget(self):', 'with', 'self.test_session()', 'as', 'sess:', 'self.assertAllClose(sess.run(self.extra_ops.target),', '[1,', '4])']
356,184
caiiiac/Machine-Learning-with-Python
ridge.py
_BaseRidgeCV.fit
fit
Fit Ridge regression model Parameters ---------- X : array-like, shape = [n_samples, n_features] Training data y : array-like, shape = [n_samples] or [n_samples, n_targets] Target values sample_weight : float or array-like of shape [n_samples] Sample weight Returns ------- self : Returns self.
[ "Fit", "Ridge", "regression", "model", "Parameters", "----------", "X", ":", "array-like,", "shape", "=", "[n_samples,", "n_features]", "Training", "data", "y", ":", "array-like,", "shape", "=", "[n_samples]", "or", "[n_samples,", "n_targets]", "Target", "values", ...
def fit(self, X, y, sample_weight=None): if self.cv is None: estimator = _RidgeGCV(self.alphas, fit_intercept=self.fit_intercept, normalize=self.normalize, scoring=self.scoring, gcv_mode=self.gcv_mode, store_cv_values=self.store_cv_values) estimator.fit(X, y, sample_weight=sample_weight) sel...
['def', 'fit(self,', 'X,', 'y,', 'sample_weight=None):', 'if', 'self.cv', 'is', 'None:', 'estimator', '=', '_RidgeGCV(self.alphas,', 'fit_intercept=self.fit_intercept,', 'normalize=self.normalize,', 'scoring=self.scoring,', 'gcv_mode=self.gcv_mode,', 'store_cv_values=self.store_cv_values)', 'estimator.fit(X,', 'y,', 's...
720,899
stefan-rz/udacity-aind
solution.py
naked_twins
naked_twins
Eliminate values using the naked twins strategy.
[ "Eliminate", "values", "using", "the", "naked", "twins", "strategy." ]
def naked_twins(values): naked_twin = dict(((unitlist.index(u), [s for s in u for x in u if s != x and len(values[s]) == 2 and (values[s] == values[x])]) for u in unitlist)) for i in naked_twin: boxes = naked_twin.get(i) if boxes is not None and len(boxes) >= 2: digits = values[boxes...
['def', 'naked_twins(values):', 'naked_twin', '=', 'dict(((unitlist.index(u),', '[s', 'for', 's', 'in', 'u', 'for', 'x', 'in', 'u', 'if', 's', '!=', 'x', 'and', 'len(values[s])', '==', '2', 'and', '(values[s]', '==', 'values[x])])', 'for', 'u', 'in', 'unitlist))', 'for', 'i', 'in', 'naked_twin:', 'boxes', '=', 'naked_t...
427,909
tensorflow/agents
utils.py
SquashToSpecNormal.sample
sample
Generates samples from the wrapped TransformedDistribution.
[ "Generates", "samples", "from", "the", "wrapped", "TransformedDistribution." ]
def sample(self, sample_shape=(), seed=None, name='sample'): return self._squashed_distribution.sample(sample_shape, seed, name)
['def', 'sample(self,', 'sample_shape=(),', 'seed=None,', "name='sample'):", 'return', 'self._squashed_distribution.sample(sample_shape,', 'seed,', 'name)']
22,665
matsu0228/nlp-jp
pyplot.py
get_plot_commands
get_plot_commands
Get a sorted list of all of the plotting commands.
[ "Get", "a", "sorted", "list", "of", "all", "of", "the", "plotting", "commands." ]
def get_plot_commands(): import inspect exclude = {'colormaps', 'colors', 'connect', 'disconnect', 'get_plot_commands', 'get_current_fig_manager', 'ginput', 'plotting', 'waitforbuttonpress'} exclude |= set(colormaps()) this_module = inspect.getmodule(get_plot_commands) commands = set() for (name...
['def', 'get_plot_commands():', 'import', 'inspect', 'exclude', '=', "{'colormaps',", "'colors',", "'connect',", "'disconnect',", "'get_plot_commands',", "'get_current_fig_manager',", "'ginput',", "'plotting',", "'waitforbuttonpress'}", 'exclude', '|=', 'set(colormaps())', 'this_module', '=', 'inspect.getmodule(get_plo...
789,139
Erfanafshar/Principles-and-Applications-of---graph-coloring
plot_directive.py
unescape_doctest
unescape_doctest
Extract code from a piece of text, which contains either Python code or doctests.
[ "Extract", "code", "from", "a", "piece", "of", "text,", "which", "contains", "either", "Python", "code", "or", "doctests." ]
def unescape_doctest(text): if not contains_doctest(text): return text code = '' for line in text.split('\n'): m = re.match('^\\s*(>>>|\\.\\.\\.) (.*)$', line) if m: code += m.group(2) + '\n' elif line.strip(): code += '# ' + line.strip() + '\n' ...
['def', 'unescape_doctest(text):', 'if', 'not', 'contains_doctest(text):', 'return', 'text', 'code', '=', "''", 'for', 'line', 'in', "text.split('\\n'):", 'm', '=', "re.match('^\\\\s*(>>>|\\\\.\\\\.\\\\.)", "(.*)$',", 'line)', 'if', 'm:', 'code', '+=', 'm.group(2)', '+', "'\\n'", 'elif', 'line.strip():', 'code', '+=', ...
307,511
liziwl/AI-Lab
go_solve.py
eat_dead
eat_dead
eat all the specific color chess which is dead :param go_arr: the numpy array contains the chess board :param color_type: -1 is black, 1 is white.
[ "eat", "all", "the", "specific", "color", "chess", "which", "is", "dead", ":param", "go_arr:", "the", "numpy", "array", "contains", "the", "chess", "board", ":param", "color_type:", "-1", "is", "black,", "1", "is", "white." ]
def eat_dead(go_arr, color_type): wait_del = [] optional = np.zeros(go_arr.shape) tmp_indx = np.where(go_arr == color_type) optional[tmp_indx] = 6 for i in range(go_arr.shape[0]): for j in range(go_arr.shape[1]): if optional[i, j] == 6: wait_del = wait_del + which...
['def', 'eat_dead(go_arr,', 'color_type):', 'wait_del', '=', '[]', 'optional', '=', 'np.zeros(go_arr.shape)', 'tmp_indx', '=', 'np.where(go_arr', '==', 'color_type)', 'optional[tmp_indx]', '=', '6', 'for', 'i', 'in', 'range(go_arr.shape[0]):', 'for', 'j', 'in', 'range(go_arr.shape[1]):', 'if', 'optional[i,', 'j]', '=='...
24,619
sunishsheth2009/ChatterBot
sourcedstring.py
SimpleSourcedString.docid
docid
An identifier (such as a filename) that specifies the document where the string was found.
[ "An", "identifier", "(such", "as", "a", "filename)", "that", "specifies", "the", "document", "where", "the", "string", "was", "found." ]
def docid(self): return self.source.docid
['def', 'docid(self):', 'return', 'self.source.docid']
485,121
AboudyKreidieh/h-baselines
humanoid_env.py
mass_center
mass_center
Compute the position of the agent's center of mass.
[ "Compute", "the", "position", "of", "the", "agent's", "center", "of", "mass." ]
def mass_center(model, sim): mass = np.expand_dims(model.body_mass, 1) xpos = sim.data.xipos return (np.sum(mass * xpos, 0) / np.sum(mass))[0]
['def', 'mass_center(model,', 'sim):', 'mass', '=', 'np.expand_dims(model.body_mass,', '1)', 'xpos', '=', 'sim.data.xipos', 'return', '(np.sum(mass', '*', 'xpos,', '0)', '/', 'np.sum(mass))[0]']
573,912
AiIsBetter/computer_vision
sast_process.py
SASTProcessTrain.gen_quad_tbo
gen_quad_tbo
Generate tbo_map for give quad.
[ "Generate", "tbo_map", "for", "give", "quad." ]
def gen_quad_tbo(self, quad, tcl_mask, tbo_map): up_line = self.line_cross_two_point(quad[0], quad[1]) lower_line = self.line_cross_two_point(quad[3], quad[2]) quad_h = 0.5 * (np.linalg.norm(quad[0] - quad[3]) + np.linalg.norm(quad[1] - quad[2])) quad_w = 0.5 * (np.linalg.norm(quad[0] - quad[1]) + np.li...
['def', 'gen_quad_tbo(self,', 'quad,', 'tcl_mask,', 'tbo_map):', 'up_line', '=', 'self.line_cross_two_point(quad[0],', 'quad[1])', 'lower_line', '=', 'self.line_cross_two_point(quad[3],', 'quad[2])', 'quad_h', '=', '0.5', '*', '(np.linalg.norm(quad[0]', '-', 'quad[3])', '+', 'np.linalg.norm(quad[1]', '-', 'quad[2]))', ...
502,212
ifzhang/ByteTrack
metric.py
occupy_mem
occupy_mem
pre-allocate gpu memory for training to avoid memory Fragmentation.
[ "pre-allocate", "gpu", "memory", "for", "training", "to", "avoid", "memory", "Fragmentation." ]
def occupy_mem(cuda_device, mem_ratio=0.95): (total, used) = get_total_and_free_memory_in_Mb(cuda_device) max_mem = int(total * mem_ratio) block_mem = max_mem - used x = torch.cuda.FloatTensor(256, 1024, block_mem) del x time.sleep(5)
['def', 'occupy_mem(cuda_device,', 'mem_ratio=0.95):', '(total,', 'used)', '=', 'get_total_and_free_memory_in_Mb(cuda_device)', 'max_mem', '=', 'int(total', '*', 'mem_ratio)', 'block_mem', '=', 'max_mem', '-', 'used', 'x', '=', 'torch.cuda.FloatTensor(256,', '1024,', 'block_mem)', 'del', 'x', 'time.sleep(5)']
410,720
TrellixVulnTeam/Unsupervised_Learning_HFI7
traitlets.py
Type.info
info
Returns a description of the trait.
[ "Returns", "a", "description", "of", "the", "trait." ]
def info(self): if isinstance(self.klass, str): klass = self.klass else: klass = self.klass.__module__ + '.' + self.klass.__name__ result = "a subclass of '%s'" % klass if self.allow_none: return result + ' or None' return result
['def', 'info(self):', 'if', 'isinstance(self.klass,', 'str):', 'klass', '=', 'self.klass', 'else:', 'klass', '=', 'self.klass.__module__', '+', "'.'", '+', 'self.klass.__name__', 'result', '=', '"a', 'subclass', 'of', '\'%s\'"', '%', 'klass', 'if', 'self.allow_none:', 'return', 'result', '+', "'", 'or', "None'", 'retu...
437,861
weimin17/Object-Detection_HelmetDetection
graphs.py
make_restore_average_vars_dict
make_restore_average_vars_dict
Returns dict mapping moving average names to variables.
[ "Returns", "dict", "mapping", "moving", "average", "names", "to", "variables." ]
def make_restore_average_vars_dict(): var_restore_dict = {} variable_averages = tf.train.ExponentialMovingAverage(0.999) for v in tf.global_variables(): if v in tf.trainable_variables(): name = variable_averages.average_name(v) else: name = v.op.name var_resto...
['def', 'make_restore_average_vars_dict():', 'var_restore_dict', '=', '{}', 'variable_averages', '=', 'tf.train.ExponentialMovingAverage(0.999)', 'for', 'v', 'in', 'tf.global_variables():', 'if', 'v', 'in', 'tf.trainable_variables():', 'name', '=', 'variable_averages.average_name(v)', 'else:', 'name', '=', 'v.op.name',...
761,453
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
model_ptn.py
model_PTN.get_transform_matrix
get_transform_matrix
Get the 4x4 Perspective Transfromation matrix used for PTN.
[ "Get", "the", "4x4", "Perspective", "Transfromation", "matrix", "used", "for", "PTN." ]
def get_transform_matrix(self, view_out): num_views = self._params.num_views focal_length = self._params.focal_length focal_range = self._params.focal_range phi = 30 theta_interval = 360.0 / num_views theta = theta_interval * view_out camera_matrix = np.zeros((4, 4), dtype=np.float32) in...
['def', 'get_transform_matrix(self,', 'view_out):', 'num_views', '=', 'self._params.num_views', 'focal_length', '=', 'self._params.focal_length', 'focal_range', '=', 'self._params.focal_range', 'phi', '=', '30', 'theta_interval', '=', '360.0', '/', 'num_views', 'theta', '=', 'theta_interval', '*', 'view_out', 'camera_m...
109,190
thaines/helit
params_sets.py
ParamsRange.getP2List
getP2List
returns the list of kernel parameters 2, not always used.
[ "returns", "the", "list", "of", "kernel", "parameters", "2,", "not", "always", "used." ]
def getP2List(self): return self.p2
['def', 'getP2List(self):', 'return', 'self.p2']
592,563
pipermerriam/flex
common.py
generate_max_length_validator
generate_max_length_validator
Generates a validator for enforcing the maxLength of a string.
[ "Generates", "a", "validator", "for", "enforcing", "the", "maxLength", "of", "a", "string." ]
def generate_max_length_validator(maxLength, **kwargs): return functools.partial(validate_max_length, maxLength=maxLength)
['def', 'generate_max_length_validator(maxLength,', '**kwargs):', 'return', 'functools.partial(validate_max_length,', 'maxLength=maxLength)']
211,302
BWGZK/ShapePU
inference.py
keep_largest_connected_components
keep_largest_connected_components
Keeps only the largest connected components of each label for a segmentation mask.
[ "Keeps", "only", "the", "largest", "connected", "components", "of", "each", "label", "for", "a", "segmentation", "mask." ]
def keep_largest_connected_components(mask): mask_shape = mask.shape heart_slice = np.where(mask > 0, 1, 0) out_heart = np.zeros(heart_slice.shape, dtype=np.uint8) for struc_id in [1]: binary_img = heart_slice == struc_id blobs = measure.label(binary_img, connectivity=1) props = ...
['def', 'keep_largest_connected_components(mask):', 'mask_shape', '=', 'mask.shape', 'heart_slice', '=', 'np.where(mask', '>', '0,', '1,', '0)', 'out_heart', '=', 'np.zeros(heart_slice.shape,', 'dtype=np.uint8)', 'for', 'struc_id', 'in', '[1]:', 'binary_img', '=', 'heart_slice', '==', 'struc_id', 'blobs', '=', 'measure...
350,226
junliangma/generativeSSL
half_moon_loader.py
load_semi_supervised
load_semi_supervised
Load the half moon dataset with 6 fixed labeled data points.
[ "Load", "the", "half", "moon", "dataset", "with", "6", "fixed", "labeled", "data", "points." ]
def load_semi_supervised(): (train_set, test_set, valid_set) = _download() train_x_l = np.zeros((6, 2)) train_t_l = np.array([0, 0, 0, 1, 1, 1]) train_x_l[0] = [0.7, 1.7] train_x_l[1] = [1.6, 2.6] train_x_l[2] = [2.7, 1.7] train_x_l[3] = [1.6, 2.0] train_x_l[4] = [2.7, 1.1] train_x_l...
['def', 'load_semi_supervised():', '(train_set,', 'test_set,', 'valid_set)', '=', '_download()', 'train_x_l', '=', 'np.zeros((6,', '2))', 'train_t_l', '=', 'np.array([0,', '0,', '0,', '1,', '1,', '1])', 'train_x_l[0]', '=', '[0.7,', '1.7]', 'train_x_l[1]', '=', '[1.6,', '2.6]', 'train_x_l[2]', '=', '[2.7,', '1.7]', 'tr...
202,314
43Carrig/recurrent_neural_networks_practice
inception_v2.py
inception_v2_arg_scope
inception_v2_arg_scope
Defines the default InceptionV2 arg scope.
[ "Defines", "the", "default", "InceptionV2", "arg", "scope." ]
def inception_v2_arg_scope(weight_decay=4e-05, batch_norm_var_collection='moving_vars'): batch_norm_params = {'decay': 0.9997, 'epsilon': 0.001, 'updates_collections': ops.GraphKeys.UPDATE_OPS, 'variables_collections': {'beta': None, 'gamma': None, 'moving_mean': [batch_norm_var_collection], 'moving_variance': [bat...
['def', 'inception_v2_arg_scope(weight_decay=4e-05,', "batch_norm_var_collection='moving_vars'):", 'batch_norm_params', '=', "{'decay':", '0.9997,', "'epsilon':", '0.001,', "'updates_collections':", 'ops.GraphKeys.UPDATE_OPS,', "'variables_collections':", "{'beta':", 'None,', "'gamma':", 'None,', "'moving_mean':", '[ba...
335,233
eora-ai/torchok
resnet.py
resnet101d
resnet101d
Constructs a ResNet-101-D model.
[ "Constructs", "a", "ResNet-101-D", "model." ]
def resnet101d(pretrained=False, **kwargs): model_args = dict(block=Bottleneck, layers=[3, 4, 23, 3], stem_width=32, stem_type='deep', avg_down=True, **kwargs) return _create_resnet('resnet101d', pretrained, **model_args)
['def', 'resnet101d(pretrained=False,', '**kwargs):', 'model_args', '=', 'dict(block=Bottleneck,', 'layers=[3,', '4,', '23,', '3],', 'stem_width=32,', "stem_type='deep',", 'avg_down=True,', '**kwargs)', 'return', "_create_resnet('resnet101d',", 'pretrained,', '**model_args)']
903,192
voxel51/fiftyone
utils.py
ensure_tf
ensure_tf
Verifies that ``tensorflow`` is installed and importable.
[ "Verifies", "that", "``tensorflow``", "is", "installed", "and", "importable." ]
def ensure_tf(eager=False, error_level=None, error_msg=None): if error_level is None: error_level = fo.config.requirement_error_level success = ensure_import('tensorflow', error_level=error_level, error_msg=error_msg) if not success or not eager: return success try: import tensor...
['def', 'ensure_tf(eager=False,', 'error_level=None,', 'error_msg=None):', 'if', 'error_level', 'is', 'None:', 'error_level', '=', 'fo.config.requirement_error_level', 'success', '=', "ensure_import('tensorflow',", 'error_level=error_level,', 'error_msg=error_msg)', 'if', 'not', 'success', 'or', 'not', 'eager:', 'retur...
583,441
microsoft/nni
mnist.py
max_pool
max_pool
max_pool downsamples a feature map by 2X.
[ "max_pool", "downsamples", "a", "feature", "map", "by", "2X." ]
def max_pool(x_input, pool_size): return tf.nn.max_pool(x_input, ksize=[1, pool_size, pool_size, 1], strides=[1, pool_size, pool_size, 1], padding='SAME')
['def', 'max_pool(x_input,', 'pool_size):', 'return', 'tf.nn.max_pool(x_input,', 'ksize=[1,', 'pool_size,', 'pool_size,', '1],', 'strides=[1,', 'pool_size,', 'pool_size,', '1],', "padding='SAME')"]
728,081
pathak22/noreward-rl
inference.py
inference
inference
It only restores LSTMPolicy architecture, and does inference using that.
[ "It", "only", "restores", "LSTMPolicy", "architecture,", "and", "does", "inference", "using", "that." ]
def inference(args): indir = os.path.join(args.log_dir, 'train') outdir = os.path.join(args.log_dir, 'inference') if args.out_dir is None else args.out_dir with open(indir + '/checkpoint', 'r') as f: first_line = f.readline().strip() ckpt = first_line.split(' ')[-1].split('/')[-1][:-1] ckpt ...
['def', 'inference(args):', 'indir', '=', 'os.path.join(args.log_dir,', "'train')", 'outdir', '=', 'os.path.join(args.log_dir,', "'inference')", 'if', 'args.out_dir', 'is', 'None', 'else', 'args.out_dir', 'with', 'open(indir', '+', "'/checkpoint',", "'r')", 'as', 'f:', 'first_line', '=', 'f.readline().strip()', 'ckpt',...
249,508
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
track_perplexity.py
run_once
run_once
Evaluates the latest model checkpoint.
[ "Evaluates", "the", "latest", "model", "checkpoint." ]
def run_once(model, losses, weights, saver, summary_writer, summary_op): model_path = tf.train.latest_checkpoint(FLAGS.checkpoint_dir) if not model_path: tf.logging.info('Skipping evaluation. No checkpoint found in: %s', FLAGS.checkpoint_dir) return with tf.Session() as sess: tf.logg...
['def', 'run_once(model,', 'losses,', 'weights,', 'saver,', 'summary_writer,', 'summary_op):', 'model_path', '=', 'tf.train.latest_checkpoint(FLAGS.checkpoint_dir)', 'if', 'not', 'model_path:', "tf.logging.info('Skipping", 'evaluation.', 'No', 'checkpoint', 'found', 'in:', "%s',", 'FLAGS.checkpoint_dir)', 'return', 'wi...
26,836
JoyHuYY1412/Class_Imbalanced_Semi_Supervised_Learning
data.py
DataSet.memoize
memoize
Call before parsing, since it calls for parse inside.
[ "Call", "before", "parsing,", "since", "it", "calls", "for", "parse", "inside." ]
def memoize(self): data = [] with tf.Session(config=utils.get_config()) as session: it = self.parse().prefetch(16).make_one_shot_iterator().get_next() try: while 1: data.append(session.run(it)) except tf.errors.OutOfRangeError: pass images = np...
['def', 'memoize(self):', 'data', '=', '[]', 'with', 'tf.Session(config=utils.get_config())', 'as', 'session:', 'it', '=', 'self.parse().prefetch(16).make_one_shot_iterator().get_next()', 'try:', 'while', '1:', 'data.append(session.run(it))', 'except', 'tf.errors.OutOfRangeError:', 'pass', 'images', '=', "np.stack([x['...
122,258
43Carrig/recurrent_neural_networks_practice
symbol_database.py
SymbolDatabase.RegisterServiceDescriptor
RegisterServiceDescriptor
Registers the given service descriptor in the local database.
[ "Registers", "the", "given", "service", "descriptor", "in", "the", "local", "database." ]
def RegisterServiceDescriptor(self, service_descriptor): self.pool.AddServiceDescriptor(service_descriptor)
['def', 'RegisterServiceDescriptor(self,', 'service_descriptor):', 'self.pool.AddServiceDescriptor(service_descriptor)']
309,865
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
search.py
Node.path
path
Return a list of nodes forming the path from the root to this node.
[ "Return", "a", "list", "of", "nodes", "forming", "the", "path", "from", "the", "root", "to", "this", "node." ]
def path(self): (node, path_back) = (self, []) while node: path_back.append(node) node = node.parent return list(reversed(path_back))
['def', 'path(self):', '(node,', 'path_back)', '=', '(self,', '[])', 'while', 'node:', 'path_back.append(node)', 'node', '=', 'node.parent', 'return', 'list(reversed(path_back))']
428,100
neardws/Game-Theoretic-Deep-Reinforcement-Learning
agent.py
MAD3PGAgent.make_actor
make_actor
Create an actor instance.
[ "Create", "an", "actor", "instance." ]
def make_actor(self, policy_one_networks: snt.Module, policy_two_networks: snt.Module, adder: Optional[adders.Adder]=None, variable_source: Optional[core.VariableSource]=None): if variable_source: variables = dict() variables['policy_one_network'] = policy_one_networks.variables variables['p...
['def', 'make_actor(self,', 'policy_one_networks:', 'snt.Module,', 'policy_two_networks:', 'snt.Module,', 'adder:', 'Optional[adders.Adder]=None,', 'variable_source:', 'Optional[core.VariableSource]=None):', 'if', 'variable_source:', 'variables', '=', 'dict()', "variables['policy_one_network']", '=', 'policy_one_networ...
199,713
Kvatsx/Artificial-Intelligence-Assignments
nonlin.py
asjacobian
asjacobian
Convert given object to one suitable for use as a Jacobian.
[ "Convert", "given", "object", "to", "one", "suitable", "for", "use", "as", "a", "Jacobian." ]
def asjacobian(J): spsolve = scipy.sparse.linalg.spsolve if isinstance(J, Jacobian): return J elif inspect.isclass(J) and issubclass(J, Jacobian): return J() elif isinstance(J, np.ndarray): if J.ndim > 2: raise ValueError('array must have rank <= 2') J = np.at...
['def', 'asjacobian(J):', 'spsolve', '=', 'scipy.sparse.linalg.spsolve', 'if', 'isinstance(J,', 'Jacobian):', 'return', 'J', 'elif', 'inspect.isclass(J)', 'and', 'issubclass(J,', 'Jacobian):', 'return', 'J()', 'elif', 'isinstance(J,', 'np.ndarray):', 'if', 'J.ndim', '>', '2:', 'raise', "ValueError('array", 'must', 'hav...
77,710
sek788432/Waymo-2D-Object-Detection
context_rcnn_lib.py
project_features
project_features
Projects features to another feature space.
[ "Projects", "features", "to", "another", "feature", "space." ]
def project_features(features, projection_dimension, is_training, normalize): batch_norm_params = {'is_training': is_training, 'decay': 0.97, 'epsilon': 0.001, 'center': True, 'scale': True} (batch_size, _, num_features) = features.shape features = tf.reshape(features, [-1, num_features]) projected_feat...
['def', 'project_features(features,', 'projection_dimension,', 'is_training,', 'normalize):', 'batch_norm_params', '=', "{'is_training':", 'is_training,', "'decay':", '0.97,', "'epsilon':", '0.001,', "'center':", 'True,', "'scale':", 'True}', '(batch_size,', '_,', 'num_features)', '=', 'features.shape', 'features', '='...
975,045
tobegit3hub/deep_image_model
resource_variable_ops.py
ResourceVariable.op
op
The op which reads the value of this variable.
[ "The", "op", "which", "reads", "the", "value", "of", "this", "variable." ]
def op(self): return self._value.op
['def', 'op(self):', 'return', 'self._value.op']
183,038
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
network_units.py
NetworkUnitInterface.get_l2_regularized_weights
get_l2_regularized_weights
Gets the weights that need to be regularized.
[ "Gets", "the", "weights", "that", "need", "to", "be", "regularized." ]
def get_l2_regularized_weights(self): return self.regularized_weights
['def', 'get_l2_regularized_weights(self):', 'return', 'self.regularized_weights']
111,348
tensorflow/data-validation
dashboard_util.py
generate_stats_dashboard_link
generate_stats_dashboard_link
Generate link for stats dashboard.
[ "Generate", "link", "for", "stats", "dashboard." ]
def generate_stats_dashboard_link(): return dashboard_util_impl.generate_stats_dashboard_link()
['def', 'generate_stats_dashboard_link():', 'return', 'dashboard_util_impl.generate_stats_dashboard_link()']
497,597
weimin17/Object-Detection_HelmetDetection
cifar10_input.py
distorted_inputs
distorted_inputs
Construct distorted input for CIFAR training using the Reader ops.
[ "Construct", "distorted", "input", "for", "CIFAR", "training", "using", "the", "Reader", "ops." ]
def distorted_inputs(data_dir, batch_size): filenames = [os.path.join(data_dir, 'data_batch_%d.bin' % i) for i in xrange(1, 6)] for f in filenames: if not tf.gfile.Exists(f): raise ValueError('Failed to find file: ' + f) filename_queue = tf.train.string_input_producer(filenames) with...
['def', 'distorted_inputs(data_dir,', 'batch_size):', 'filenames', '=', '[os.path.join(data_dir,', "'data_batch_%d.bin'", '%', 'i)', 'for', 'i', 'in', 'xrange(1,', '6)]', 'for', 'f', 'in', 'filenames:', 'if', 'not', 'tf.gfile.Exists(f):', 'raise', "ValueError('Failed", 'to', 'find', 'file:', "'", '+', 'f)', 'filename_q...
754,180
SamsungLabs/fcaf3d
sparse_unet.py
SparseUNet.make_encoder_layers
make_encoder_layers
make encoder layers using sparse convs.
[ "make", "encoder", "layers", "using", "sparse", "convs." ]
def make_encoder_layers(self, make_block, norm_cfg, in_channels): self.encoder_layers = spconv.SparseSequential() for (i, blocks) in enumerate(self.encoder_channels): blocks_list = [] for (j, out_channels) in enumerate(tuple(blocks)): padding = tuple(self.encoder_paddings[i])[j] ...
['def', 'make_encoder_layers(self,', 'make_block,', 'norm_cfg,', 'in_channels):', 'self.encoder_layers', '=', 'spconv.SparseSequential()', 'for', '(i,', 'blocks)', 'in', 'enumerate(self.encoder_channels):', 'blocks_list', '=', '[]', 'for', '(j,', 'out_channels)', 'in', 'enumerate(tuple(blocks)):', 'padding', '=', 'tupl...
560,500
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_model_based.py
rl_modelrl_tiny_sv2p
rl_modelrl_tiny_sv2p
Tiny setting with a sv2p model.
[ "Tiny", "setting", "with", "a", "sv2p", "model." ]
def rl_modelrl_tiny_sv2p(): hparams = rl_modelrl_tiny() hparams.generative_model = 'next_frame_sv2p' hparams.generative_model_params = 'next_frame_sv2p_tiny' return hparams
['def', 'rl_modelrl_tiny_sv2p():', 'hparams', '=', 'rl_modelrl_tiny()', 'hparams.generative_model', '=', "'next_frame_sv2p'", 'hparams.generative_model_params', '=', "'next_frame_sv2p_tiny'", 'return', 'hparams']
965,995
zhaocq-nlp/NJUNMT-tf
bridges.py
ZeroBridge.default_params
default_params
Returns a dictionary of default parameters of this bridge.
[ "Returns", "a", "dictionary", "of", "default", "parameters", "of", "this", "bridge." ]
def default_params(): return {}
['def', 'default_params():', 'return', '{}']
782,947
scotthuang1989/object_detection_with_tensorflow
graph_builder_test.py
GraphBuilderTest.testWarmupGetsAndReleasesSession
testWarmupGetsAndReleasesSession
Checks that create_warmup_graph creates Get and ReleaseSession.
[ "Checks", "that", "create_warmup_graph", "creates", "Get", "and", "ReleaseSession." ]
def testWarmupGetsAndReleasesSession(self): test_name = 'warmup-graph-structure' with tf.Graph().as_default(): (builder, _) = self.getBuilderAndTarget(test_name) warmup = builder.build_warmup_graph('foo') self.checkOpOrder('annotations', warmup, ['SetAssetDirectory', 'GetSession', 'Relea...
['def', 'testWarmupGetsAndReleasesSession(self):', 'test_name', '=', "'warmup-graph-structure'", 'with', 'tf.Graph().as_default():', '(builder,', '_)', '=', 'self.getBuilderAndTarget(test_name)', 'warmup', '=', "builder.build_warmup_graph('foo')", "self.checkOpOrder('annotations',", 'warmup,', "['SetAssetDirectory',", ...
739,815
xiaoachen98/DDB
ckd.py
CKD.inference
inference
Inference with slide/whole style.
[ "Inference", "with", "slide/whole", "style." ]
def inference(self, img, img_meta, rescale, name='stu', return_seg_logit=False): return self.get_model(name).inference(img, img_meta, rescale, return_seg_logit)
['def', 'inference(self,', 'img,', 'img_meta,', 'rescale,', "name='stu',", 'return_seg_logit=False):', 'return', 'self.get_model(name).inference(img,', 'img_meta,', 'rescale,', 'return_seg_logit)']
498,908
deepmind/dm_control
cartpole.py
Physics.bounded_position
bounded_position
Returns the state, with pole angle split into sin/cos.
[ "Returns", "the", "state,", "with", "pole", "angle", "split", "into", "sin/cos." ]
def bounded_position(self): return np.hstack((self.cart_position(), self.named.data.xmat[2:, ['zz', 'xz']].ravel()))
['def', 'bounded_position(self):', 'return', 'np.hstack((self.cart_position(),', 'self.named.data.xmat[2:,', "['zz',", "'xz']].ravel()))"]
166,294
rudranil723/mini-main
core.py
enable_diag
enable_diag
Enable a global pyparsing diagnostic flag (see :class:`Diagnostics`).
[ "Enable", "a", "global", "pyparsing", "diagnostic", "flag", "(see", ":class:`Diagnostics`)." ]
def enable_diag(diag_enum: Diagnostics) -> None: __diag__.enable(diag_enum.name)
['def', 'enable_diag(diag_enum:', 'Diagnostics)', '->', 'None:', '__diag__.enable(diag_enum.name)']
268,657
annieyan/PreprocessSatelliteImagery-
get_data_stat.py
parse_args
parse_args
Parse command line arguments passed to script invocation.
[ "Parse", "command", "line", "arguments", "passed", "to", "script", "invocation." ]
def parse_args(): parser = argparse.ArgumentParser(description='Get statistics for training data and test data from geojson and tif images.') parser.add_argument('src_geojson', help='source geojson') return parser.parse_args()
['def', 'parse_args():', 'parser', '=', "argparse.ArgumentParser(description='Get", 'statistics', 'for', 'training', 'data', 'and', 'test', 'data', 'from', 'geojson', 'and', 'tif', "images.')", "parser.add_argument('src_geojson',", "help='source", "geojson')", 'return', 'parser.parse_args()']
824,388
flavioschneider/rl-transfer-
test_functions.py
TestOptimizerInterface.test_tf_make_optimizer_with_type
test_tf_make_optimizer_with_type
Test make_optimizer function with type as first argument.
[ "Test", "make_optimizer", "function", "with", "type", "as", "first", "argument." ]
def test_tf_make_optimizer_with_type(self): optimizer_type = tf.compat.v1.train.AdamOptimizer lr = 0.123 optimizer = make_optimizer(optimizer_type, learning_rate=lr, name='testOptimizer') assert isinstance(optimizer, optimizer_type) self.sess.run(tf.compat.v1.global_variables_initializer()) asse...
['def', 'test_tf_make_optimizer_with_type(self):', 'optimizer_type', '=', 'tf.compat.v1.train.AdamOptimizer', 'lr', '=', '0.123', 'optimizer', '=', 'make_optimizer(optimizer_type,', 'learning_rate=lr,', "name='testOptimizer')", 'assert', 'isinstance(optimizer,', 'optimizer_type)', 'self.sess.run(tf.compat.v1.global_var...
861,705
zihuitang/medical_AI_platform
cookiejar.py
CookieJar.make_cookies
make_cookies
Return sequence of Cookie objects extracted from response object.
[ "Return", "sequence", "of", "Cookie", "objects", "extracted", "from", "response", "object." ]
def make_cookies(self, response, request): headers = response.info() rfc2965_hdrs = headers.get_all('Set-Cookie2', []) ns_hdrs = headers.get_all('Set-Cookie', []) rfc2965 = self._policy.rfc2965 netscape = self._policy.netscape if not rfc2965_hdrs and (not ns_hdrs) or (not ns_hdrs and (not rfc296...
['def', 'make_cookies(self,', 'response,', 'request):', 'headers', '=', 'response.info()', 'rfc2965_hdrs', '=', "headers.get_all('Set-Cookie2',", '[])', 'ns_hdrs', '=', "headers.get_all('Set-Cookie',", '[])', 'rfc2965', '=', 'self._policy.rfc2965', 'netscape', '=', 'self._policy.netscape', 'if', 'not', 'rfc2965_hdrs', ...
282,623
rudranil723/mini-main
axes_rgb.py
make_rgb_axes
make_rgb_axes
Parameters ---------- pad : float Fraction of the axes height.
[ "Parameters", "----------", "pad", ":", "float", "Fraction", "of", "the", "axes", "height." ]
def make_rgb_axes(ax, pad=0.01, axes_class=None, **kwargs): divider = make_axes_locatable(ax) pad_size = pad * Size.AxesY(ax) xsize = (1 - 2 * pad) / 3 * Size.AxesX(ax) ysize = (1 - 2 * pad) / 3 * Size.AxesY(ax) divider.set_horizontal([Size.AxesX(ax), pad_size, xsize]) divider.set_vertical([ysiz...
['def', 'make_rgb_axes(ax,', 'pad=0.01,', 'axes_class=None,', '**kwargs):', 'divider', '=', 'make_axes_locatable(ax)', 'pad_size', '=', 'pad', '*', 'Size.AxesY(ax)', 'xsize', '=', '(1', '-', '2', '*', 'pad)', '/', '3', '*', 'Size.AxesX(ax)', 'ysize', '=', '(1', '-', '2', '*', 'pad)', '/', '3', '*', 'Size.AxesY(ax)', 'd...
320,424