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
rudranil723/mini-main
autopep8.py
ReformattedLines.previous_item
previous_item
Return the previous non-whitespace item.
[ "Return", "the", "previous", "non-whitespace", "item." ]
def previous_item(self): return self._prev_item
['def', 'previous_item(self):', 'return', 'self._prev_item']
313,929
zplizzi/fusedprop
tf_fid_score.py
check_or_download_inception
check_or_download_inception
Checks if the path to the inception file is valid, or downloads the file if it is not present.
[ "Checks", "if", "the", "path", "to", "the", "inception", "file", "is", "valid,", "or", "downloads", "the", "file", "if", "it", "is", "not", "present." ]
def check_or_download_inception(inception_path): INCEPTION_URL = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz' if inception_path is None: inception_path = '/tmp' inception_path = pathlib.Path(inception_path) model_file = inception_path / 'classify_image_graph_de...
['def', 'check_or_download_inception(inception_path):', 'INCEPTION_URL', '=', "'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz'", 'if', 'inception_path', 'is', 'None:', 'inception_path', '=', "'/tmp'", 'inception_path', '=', 'pathlib.Path(inception_path)', 'model_file', '=', 'inception_pa...
565,690
weimin17/Object-Detection_HelmetDetection
helper.py
recursive_length
recursive_length
Recursively determine the total number of elements in nested list.
[ "Recursively", "determine", "the", "total", "number", "of", "elements", "in", "nested", "list." ]
def recursive_length(item): if type(item) == list: return sum((recursive_length(subitem) for subitem in item)) else: return 1.0
['def', 'recursive_length(item):', 'if', 'type(item)', '==', 'list:', 'return', 'sum((recursive_length(subitem)', 'for', 'subitem', 'in', 'item))', 'else:', 'return', '1.0']
763,740
aws/sagemaker-python-sdk
utils.py
construct_container_object
construct_container_object
Function to construct container object.
[ "Function", "to", "construct", "container", "object." ]
def construct_container_object(obj, data_input_configuration, framework, framework_version, nearest_model_name): if framework is not None: obj.update({'Framework': framework}) if framework_version is not None: obj.update({'FrameworkVersion': framework_version}) if nearest_model_name is not N...
['def', 'construct_container_object(obj,', 'data_input_configuration,', 'framework,', 'framework_version,', 'nearest_model_name):', 'if', 'framework', 'is', 'not', 'None:', "obj.update({'Framework':", 'framework})', 'if', 'framework_version', 'is', 'not', 'None:', "obj.update({'FrameworkVersion':", 'framework_version})...
829,733
facebookresearch/salina
ant.py
Ant.step
step
Run one timestep of the environment's dynamics.
[ "Run", "one", "timestep", "of", "the", "environment's", "dynamics." ]
def step(self, state: _env.State, action: jp.ndarray) -> _env.State: action = action * self.action_mask (qp, info) = self.sys.step(state.qp, action) velocity = (qp.pos[0] - state.qp.pos[0]) / self.sys.config.dt forward_reward = velocity[0] (min_z, max_z) = self._healthy_z_range is_healthy = jp.w...
['def', 'step(self,', 'state:', '_env.State,', 'action:', 'jp.ndarray)', '->', '_env.State:', 'action', '=', 'action', '*', 'self.action_mask', '(qp,', 'info)', '=', 'self.sys.step(state.qp,', 'action)', 'velocity', '=', '(qp.pos[0]', '-', 'state.qp.pos[0])', '/', 'self.sys.config.dt', 'forward_reward', '=', 'velocity[...
328,601
jonathanking/sidechainnet
errors.py
ProteinErrors.write_summary_files
write_summary_files
For all counted errors, writes the list of pnids with each error to the errors/ directory.
[ "For", "all", "counted", "errors,", "writes", "the", "list", "of", "pnids", "with", "each", "error", "to", "the", "errors/", "directory." ]
def write_summary_files(self): os.makedirs('errors/', exist_ok=True) for e in self.get_error_names(): if len(self.get_pnids_with_error_name(e)) > 0: with open(f'errors/{e}.txt', 'w') as f: f.write('\n'.join(self.get_pnids_with_error_name(e)) + '\n')
['def', 'write_summary_files(self):', "os.makedirs('errors/',", 'exist_ok=True)', 'for', 'e', 'in', 'self.get_error_names():', 'if', 'len(self.get_pnids_with_error_name(e))', '>', '0:', 'with', "open(f'errors/{e}.txt',", "'w')", 'as', 'f:', "f.write('\\n'.join(self.get_pnids_with_error_name(e))", '+', "'\\n')"]
934,110
clovaai/assembled-cnn
hooks.py
ExamplesPerSecondHook.after_run
after_run
Called after each call to run().
[ "Called", "after", "each", "call", "to", "run()." ]
def after_run(self, run_context, run_values): global_step = run_values.results if self._timer.should_trigger_for_step(global_step) and global_step > self._warm_steps: (elapsed_time, elapsed_steps) = self._timer.update_last_triggered_step(global_step) if elapsed_time is not None: self...
['def', 'after_run(self,', 'run_context,', 'run_values):', 'global_step', '=', 'run_values.results', 'if', 'self._timer.should_trigger_for_step(global_step)', 'and', 'global_step', '>', 'self._warm_steps:', '(elapsed_time,', 'elapsed_steps)', '=', 'self._timer.update_last_triggered_step(global_step)', 'if', 'elapsed_ti...
92,445
facebookresearch/CompilerGym
compiler_env_state.py
CompilerEnvState.has_reward
has_reward
Return whether the state has a reward value.
[ "Return", "whether", "the", "state", "has", "a", "reward", "value." ]
def has_reward(self) -> bool: return self.reward is not None
['def', 'has_reward(self)', '->', 'bool:', 'return', 'self.reward', 'is', 'not', 'None']
125,335
TheCurryMan/MedicAI
tests.py
test_string
test_string
Return true if the object is a string.
[ "Return", "true", "if", "the", "object", "is", "a", "string." ]
def test_string(value): return isinstance(value, string_types)
['def', 'test_string(value):', 'return', 'isinstance(value,', 'string_types)']
648,503
augmentedstartups/AS-One
distance.py
euclidean_squared_distance
euclidean_squared_distance
Computes euclidean squared distance.
[ "Computes", "euclidean", "squared", "distance." ]
def euclidean_squared_distance(input1, input2): (m, n) = (input1.size(0), input2.size(0)) mat1 = torch.pow(input1, 2).sum(dim=1, keepdim=True).expand(m, n) mat2 = torch.pow(input2, 2).sum(dim=1, keepdim=True).expand(n, m).t() distmat = mat1 + mat2 distmat.addmm_(input1, input2.t(), beta=1, alpha=-2)...
['def', 'euclidean_squared_distance(input1,', 'input2):', '(m,', 'n)', '=', '(input1.size(0),', 'input2.size(0))', 'mat1', '=', 'torch.pow(input1,', '2).sum(dim=1,', 'keepdim=True).expand(m,', 'n)', 'mat2', '=', 'torch.pow(input2,', '2).sum(dim=1,', 'keepdim=True).expand(n,', 'm).t()', 'distmat', '=', 'mat1', '+', 'mat...
402,429
rifqind/Agent-Programs-3KS1
transform_test.py
TransformModuleTest.test_average_surfaces__subclassed_surfaces
test_average_surfaces__subclassed_surfaces
Ensure average_surfaces accepts subclassed surfaces.
[ "Ensure", "average_surfaces", "accepts", "subclassed", "surfaces." ]
def test_average_surfaces__subclassed_surfaces(self): expected_size = (23, 17) expected_flags = 0 expected_depth = 32 expected_color = (50, 50, 50, 255) surfaces = [] for color in ((40, 60, 40), (60, 40, 60)): s = test_utils.SurfaceSubclass(expected_size, expected_flags, expected_depth) ...
['def', 'test_average_surfaces__subclassed_surfaces(self):', 'expected_size', '=', '(23,', '17)', 'expected_flags', '=', '0', 'expected_depth', '=', '32', 'expected_color', '=', '(50,', '50,', '50,', '255)', 'surfaces', '=', '[]', 'for', 'color', 'in', '((40,', '60,', '40),', '(60,', '40,', '60)):', 's', '=', 'test_uti...
46,009
sek788432/Waymo-2D-Object-Detection
replay_buffer.py
PrioritizedReplayBuffer.get_batch
get_batch
Get batch of episodes to train on.
[ "Get", "batch", "of", "episodes", "to", "train", "on." ]
def get_batch(self, n): p = self.sampling_distribution() idxs = np.random.choice(self.cur_size, size=int(n), replace=False, p=p) self.last_batch = idxs return ([self.buffer[idx] for idx in idxs], p[idxs])
['def', 'get_batch(self,', 'n):', 'p', '=', 'self.sampling_distribution()', 'idxs', '=', 'np.random.choice(self.cur_size,', 'size=int(n),', 'replace=False,', 'p=p)', 'self.last_batch', '=', 'idxs', 'return', '([self.buffer[idx]', 'for', 'idx', 'in', 'idxs],', 'p[idxs])']
975,674
zzndream/ShipRSImageNet
auto_augment.py
enhance_level_to_value
enhance_level_to_value
Map from level to values.
[ "Map", "from", "level", "to", "values." ]
def enhance_level_to_value(level, a=1.8, b=0.1): return level / _MAX_LEVEL * a + b
['def', 'enhance_level_to_value(level,', 'a=1.8,', 'b=0.1):', 'return', 'level', '/', '_MAX_LEVEL', '*', 'a', '+', 'b']
901,258
myothida/Supervised-Machine-Learning
test_polynomial.py
test_spline_transformer_periodic_splines_smoothness
test_spline_transformer_periodic_splines_smoothness
Test that spline transformation is smooth at first / last knot.
[ "Test", "that", "spline", "transformation", "is", "smooth", "at", "first", "/", "last", "knot." ]
def test_spline_transformer_periodic_splines_smoothness(degree): X = np.linspace(-2, 10, 10000)[:, None] transformer = SplineTransformer(degree=degree, extrapolation='periodic', knots=[[0.0], [1.0], [3.0], [4.0], [5.0], [8.0]]) Xt = transformer.fit_transform(X) delta = (X.max() - X.min()) / len(X) t...
['def', 'test_spline_transformer_periodic_splines_smoothness(degree):', 'X', '=', 'np.linspace(-2,', '10,', '10000)[:,', 'None]', 'transformer', '=', 'SplineTransformer(degree=degree,', "extrapolation='periodic',", 'knots=[[0.0],', '[1.0],', '[3.0],', '[4.0],', '[5.0],', '[8.0]])', 'Xt', '=', 'transformer.fit_transform...
364,576
TrellixVulnTeam/Unsupervised_Learning_HFI7
info.py
TableBuilderAbstract.memory_usage_string
memory_usage_string
Memory usage string with proper size qualifier.
[ "Memory", "usage", "string", "with", "proper", "size", "qualifier." ]
def memory_usage_string(self) -> str: return self.info.memory_usage_string
['def', 'memory_usage_string(self)', '->', 'str:', 'return', 'self.info.memory_usage_string']
453,544
avisingh599/reward-learning-rl
gym_adapter.py
GymAdapter.active_observation_shape
active_observation_shape
Shape for the active observation based on observation_keys.
[ "Shape", "for", "the", "active", "observation", "based", "on", "observation_keys." ]
def active_observation_shape(self): if not isinstance(self._env.observation_space, spaces.Dict): return super(GymAdapter, self).active_observation_shape active_size = sum((np.prod(self._env.observation_space.spaces[key].shape) for key in self.observation_keys)) active_observation_shape = (active_siz...
['def', 'active_observation_shape(self):', 'if', 'not', 'isinstance(self._env.observation_space,', 'spaces.Dict):', 'return', 'super(GymAdapter,', 'self).active_observation_shape', 'active_size', '=', 'sum((np.prod(self._env.observation_space.spaces[key].shape)', 'for', 'key', 'in', 'self.observation_keys))', 'active_o...
348,734
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
lstm.py
lstm_seq2seq_internal_attention_bid_encoder
lstm_seq2seq_internal_attention_bid_encoder
LSTM seq2seq model with attention, main step used for training.
[ "LSTM", "seq2seq", "model", "with", "attention,", "main", "step", "used", "for", "training." ]
def lstm_seq2seq_internal_attention_bid_encoder(inputs, targets, hparams, train): with tf.variable_scope('lstm_seq2seq_attention_bid_encoder'): inputs_length = common_layers.length_from_embedding(inputs) inputs = common_layers.flatten4d3d(inputs) (encoder_outputs, final_encoder_state) = lstm...
['def', 'lstm_seq2seq_internal_attention_bid_encoder(inputs,', 'targets,', 'hparams,', 'train):', 'with', "tf.variable_scope('lstm_seq2seq_attention_bid_encoder'):", 'inputs_length', '=', 'common_layers.length_from_embedding(inputs)', 'inputs', '=', 'common_layers.flatten4d3d(inputs)', '(encoder_outputs,', 'final_encod...
965,646
caiiiac/Machine-Learning-with-Python
axis_artist.py
Ticks.get_ticksize
get_ticksize
Return length of the ticks in points.
[ "Return", "length", "of", "the", "ticks", "in", "points." ]
def get_ticksize(self): return self._ticksize
['def', 'get_ticksize(self):', 'return', 'self._ticksize']
716,802
ludwig-ai/ludwig
mnist.py
MNISTLoader.load_unprocessed_dataframe
load_unprocessed_dataframe
Load dataset files into a dataframe.
[ "Load", "dataset", "files", "into", "a", "dataframe." ]
def load_unprocessed_dataframe(self, file_paths: List[str]) -> pd.DataFrame: return self.output_training_and_test_data()
['def', 'load_unprocessed_dataframe(self,', 'file_paths:', 'List[str])', '->', 'pd.DataFrame:', 'return', 'self.output_training_and_test_data()']
616,701
ashwanitanwar/nmt-transfer-learning-xlm-r
test_noising.py
TestDataNoising.assert_word_shuffle_matches_expected
assert_word_shuffle_matches_expected
This verifies that with a given x, x_len, max_shuffle_distance, and vocab, we get the expected shuffle result.
[ "This", "verifies", "that", "with", "a", "given", "x,", "x_len,", "max_shuffle_distance,", "and", "vocab,", "we", "get", "the", "expected", "shuffle", "result." ]
def assert_word_shuffle_matches_expected(self, x, x_len, max_shuffle_distance: int, vocab: Dictionary, expected_shufle_maps: List[Dict[int, int]], expect_eos_at_end: bool, bpe_end_marker=None): bpe_cont_marker = None if bpe_end_marker is None: bpe_cont_marker = '@@' with data_utils.numpy_seed(1234):...
['def', 'assert_word_shuffle_matches_expected(self,', 'x,', 'x_len,', 'max_shuffle_distance:', 'int,', 'vocab:', 'Dictionary,', 'expected_shufle_maps:', 'List[Dict[int,', 'int]],', 'expect_eos_at_end:', 'bool,', 'bpe_end_marker=None):', 'bpe_cont_marker', '=', 'None', 'if', 'bpe_end_marker', 'is', 'None:', 'bpe_cont_ma...
732,809
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
__init__.py
PhotoImage.cget
cget
Return the value of OPTION.
[ "Return", "the", "value", "of", "OPTION." ]
def cget(self, option): return self.tk.call(self.name, 'cget', '-' + option)
['def', 'cget(self,', 'option):', 'return', 'self.tk.call(self.name,', "'cget',", "'-'", '+', 'option)']
377,099
clips/pattern
metrics.py
cdf
cdf
Returns the cumulative distribution function at x.
[ "Returns", "the", "cumulative", "distribution", "function", "at", "x." ]
def cdf(x, mean=0.0, stdev=1.0): return min(1.0, 0.5 * erfc((-x + mean) / (stdev * 2 ** 0.5)))
['def', 'cdf(x,', 'mean=0.0,', 'stdev=1.0):', 'return', 'min(1.0,', '0.5', '*', 'erfc((-x', '+', 'mean)', '/', '(stdev', '*', '2', '**', '0.5)))']
764,533
ryu-ed/SpaceInvaders_Ros
test_print.py
test_complex_inf_nan
test_complex_inf_nan
Check inf/nan formatting of complex types.
[ "Check", "inf/nan", "formatting", "of", "complex", "types." ]
def test_complex_inf_nan(dtype): TESTS = {complex(np.inf, 0): '(inf+0j)', complex(0, np.inf): 'infj', complex(-np.inf, 0): '(-inf+0j)', complex(0, -np.inf): '-infj', complex(np.inf, 1): '(inf+1j)', complex(1, np.inf): '(1+infj)', complex(-np.inf, 1): '(-inf+1j)', complex(1, -np.inf): '(1-infj)', complex(np.nan, 0):...
['def', 'test_complex_inf_nan(dtype):', 'TESTS', '=', '{complex(np.inf,', '0):', "'(inf+0j)',", 'complex(0,', 'np.inf):', "'infj',", 'complex(-np.inf,', '0):', "'(-inf+0j)',", 'complex(0,', '-np.inf):', "'-infj',", 'complex(np.inf,', '1):', "'(inf+1j)',", 'complex(1,', 'np.inf):', "'(1+infj)',", 'complex(-np.inf,', '1)...
396,397
zihuitang/medical_AI_platform
test_main.py
TestMain.setup_test_source_trees
setup_test_source_trees
Setup a test source tree and output destination tree.
[ "Setup", "a", "test", "source", "tree", "and", "output", "destination", "tree." ]
def setup_test_source_trees(self): self.temp_dir = tempfile.mkdtemp() self.py2_src_dir = os.path.join(self.temp_dir, 'python2_project') self.py3_dest_dir = os.path.join(self.temp_dir, 'python3_project') os.mkdir(self.py2_src_dir) os.mkdir(self.py3_dest_dir) self.setup_files = [] open(os.path...
['def', 'setup_test_source_trees(self):', 'self.temp_dir', '=', 'tempfile.mkdtemp()', 'self.py2_src_dir', '=', 'os.path.join(self.temp_dir,', "'python2_project')", 'self.py3_dest_dir', '=', 'os.path.join(self.temp_dir,', "'python3_project')", 'os.mkdir(self.py2_src_dir)', 'os.mkdir(self.py3_dest_dir)', 'self.setup_file...
283,019
thu-ml/tianshou
base.py
BasePolicy.soft_update
soft_update
Softly update the parameters of target module towards the parameters of source module.
[ "Softly", "update", "the", "parameters", "of", "target", "module", "towards", "the", "parameters", "of", "source", "module." ]
def soft_update(self, tgt: nn.Module, src: nn.Module, tau: float) -> None: for (tgt_param, src_param) in zip(tgt.parameters(), src.parameters()): tgt_param.data.copy_(tau * src_param.data + (1 - tau) * tgt_param.data)
['def', 'soft_update(self,', 'tgt:', 'nn.Module,', 'src:', 'nn.Module,', 'tau:', 'float)', '->', 'None:', 'for', '(tgt_param,', 'src_param)', 'in', 'zip(tgt.parameters(),', 'src.parameters()):', 'tgt_param.data.copy_(tau', '*', 'src_param.data', '+', '(1', '-', 'tau)', '*', 'tgt_param.data)']
355,246
intra2net/guibot
test_calibrator.py
CalibratorTest.test_benchmark_text
test_benchmark_text
Check that benchmarking of OCR backends produces correct results.
[ "Check", "that", "benchmarking", "of", "OCR", "backends", "produces", "correct", "results." ]
def test_benchmark_text(self): self.benchmark_setUp() calibrator = Calibrator(Text('Text'), Image('all_shapes')) for (calibration, random_starts) in [(False, 0), (False, 1), (True, 0), (True, 1)]: finder = TextFinder() finder.algorithms['threshold_filters2'] = ('adaptive',) finder.al...
['def', 'test_benchmark_text(self):', 'self.benchmark_setUp()', 'calibrator', '=', "Calibrator(Text('Text'),", "Image('all_shapes'))", 'for', '(calibration,', 'random_starts)', 'in', '[(False,', '0),', '(False,', '1),', '(True,', '0),', '(True,', '1)]:', 'finder', '=', 'TextFinder()', "finder.algorithms['threshold_filt...
572,607
paniabhisek/AlexNet
model.py
AlexNet.get_summary_writer
get_summary_writer
Get summary writer for training and validation Responsible for creating summary writer so it can write summaries to a file so it can be read by tensorboard later.
[ "Get", "summary", "writer", "for", "training", "and", "validation", "Responsible", "for", "creating", "summary", "writer", "so", "it", "can", "write", "summaries", "to", "a", "file", "so", "it", "can", "be", "read", "by", "tensorboard", "later." ]
def get_summary_writer(self, sess): if not os.path.exists(os.path.join('summary', 'train')): os.makedirs(os.path.join('summary', 'train')) if not os.path.exists(os.path.join('summary', 'val')): os.makedirs(os.path.join('summary', 'val')) return (tf.summary.FileWriter(os.path.join(os.getcwd()...
['def', 'get_summary_writer(self,', 'sess):', 'if', 'not', "os.path.exists(os.path.join('summary',", "'train')):", "os.makedirs(os.path.join('summary',", "'train'))", 'if', 'not', "os.path.exists(os.path.join('summary',", "'val')):", "os.makedirs(os.path.join('summary',", "'val'))", 'return', '(tf.summary.FileWriter(os...
32,902
43Carrig/recurrent_neural_networks_practice
distribute_coordinator.py
_Barrier.wait
wait
Waits until all other callers reach the same wait call.
[ "Waits", "until", "all", "other", "callers", "reach", "the", "same", "wait", "call." ]
def wait(self): if not hasattr(self._local_sense, 'value'): self._local_sense.value = False self._local_sense.value = not self._flag with self._lock: self._counter += 1 if self._counter == self._num_participants: self._counter = 0 self._flag = self._local_sens...
['def', 'wait(self):', 'if', 'not', 'hasattr(self._local_sense,', "'value'):", 'self._local_sense.value', '=', 'False', 'self._local_sense.value', '=', 'not', 'self._flag', 'with', 'self._lock:', 'self._counter', '+=', '1', 'if', 'self._counter', '==', 'self._num_participants:', 'self._counter', '=', '0', 'self._flag',...
336,051
ArtificialIntelligenceToolkit/aitk.robots
compass.py
Compass.from_json
from_json
Set the settings from a device config.
[ "Set", "the", "settings", "from", "a", "device", "config." ]
def from_json(self, config): valid_keys = set(['position', 'name', 'class']) self.verify_config(valid_keys, config) if 'name' in config: self.name = config['name'] if 'position' in config: self.position = config['position'] self.dist_from_center = distance(0, 0, self.position[0],...
['def', 'from_json(self,', 'config):', 'valid_keys', '=', "set(['position',", "'name',", "'class'])", 'self.verify_config(valid_keys,', 'config)', 'if', "'name'", 'in', 'config:', 'self.name', '=', "config['name']", 'if', "'position'", 'in', 'config:', 'self.position', '=', "config['position']", 'self.dist_from_center'...
86,744
muhanzhang/D-VAE
test_basic.py
copymod
copymod
Return dct but with the keys named by args removed, and with kwargs added.
[ "Return", "dct", "but", "with", "the", "keys", "named", "by", "args", "removed,", "and", "with", "kwargs", "added." ]
def copymod(dct, without=None, **kwargs): if without is None: without = [] rval = copy(dct) for a in without: if a in rval: del rval[a] for (kw, val) in iteritems(kwargs): rval[kw] = val return rval
['def', 'copymod(dct,', 'without=None,', '**kwargs):', 'if', 'without', 'is', 'None:', 'without', '=', '[]', 'rval', '=', 'copy(dct)', 'for', 'a', 'in', 'without:', 'if', 'a', 'in', 'rval:', 'del', 'rval[a]', 'for', '(kw,', 'val)', 'in', 'iteritems(kwargs):', 'rval[kw]', '=', 'val', 'return', 'rval']
525,785
Farama-Foundation/Gymnasium
test_order_enforcing.py
test_order_enforcing
test_order_enforcing
Checks that the order enforcing works as expected, raising an error before reset is called and not after.
[ "Checks", "that", "the", "order", "enforcing", "works", "as", "expected,", "raising", "an", "error", "before", "reset", "is", "called", "and", "not", "after." ]
def test_order_enforcing(): env = CartPoleEnv(render_mode='rgb_array_list') assert not has_wrapper(env, OrderEnforcing) order_enforced_env = OrderEnforcing(env) assert order_enforced_env.has_reset is False with pytest.raises(ResetNeeded): order_enforced_env.step(0) with pytest.raises(Res...
['def', 'test_order_enforcing():', 'env', '=', "CartPoleEnv(render_mode='rgb_array_list')", 'assert', 'not', 'has_wrapper(env,', 'OrderEnforcing)', 'order_enforced_env', '=', 'OrderEnforcing(env)', 'assert', 'order_enforced_env.has_reset', 'is', 'False', 'with', 'pytest.raises(ResetNeeded):', 'order_enforced_env.step(0...
573,679
deepmind/meltingpot
chemistry__two_metabolic_cycles_with_distractors.py
make_graph
make_graph
User defined graph construction function using networkx.
[ "User", "defined", "graph", "construction", "function", "using", "networkx." ]
def make_graph(): g = nx.MultiDiGraph() graph_utils.add_system_nodes(g) cycle(g, 'R', intermediates=['ax', 'bx', 'cx'], product='x', secondary_product='iy', food='food1') cycle(g, 'R', intermediates=['ay', 'by', 'cy'], product='y', secondary_product='ix', food='food2') null(g, 'Holding', 'distractor...
['def', 'make_graph():', 'g', '=', 'nx.MultiDiGraph()', 'graph_utils.add_system_nodes(g)', 'cycle(g,', "'R',", "intermediates=['ax',", "'bx',", "'cx'],", "product='x',", "secondary_product='iy',", "food='food1')", 'cycle(g,', "'R',", "intermediates=['ay',", "'by',", "'cy'],", "product='y',", "secondary_product='ix',", ...
285,282
ludwig-ai/ludwig
llm.py
LLM.get_target_ids
get_target_ids
Returns the output ids for the text feature output.
[ "Returns", "the", "output", "ids", "for", "the", "text", "feature", "output." ]
def get_target_ids(self, outputs: Dict[str, torch.Tensor]) -> torch.Tensor: return outputs[self.config_obj.output_features[0].name].type(torch.int32)
['def', 'get_target_ids(self,', 'outputs:', 'Dict[str,', 'torch.Tensor])', '->', 'torch.Tensor:', 'return', 'outputs[self.config_obj.output_features[0].name].type(torch.int32)']
616,873
RasaHQ/rasa
test_common.py
test_cli_missing_log_level_env_var_used
test_cli_missing_log_level_env_var_used
Test CLI without log level uses env var for both rasa and libraries.
[ "Test", "CLI", "without", "log", "level", "uses", "env", "var", "for", "both", "rasa", "and", "libraries." ]
def test_cli_missing_log_level_env_var_used(): configure_logging_and_warnings() rasa_logger = logging.getLogger('rasa') assert rasa_logger.level == logging.WARNING matplotlib_logger = logging.getLogger('matplotlib') assert matplotlib_logger.level == logging.INFO
['def', 'test_cli_missing_log_level_env_var_used():', 'configure_logging_and_warnings()', 'rasa_logger', '=', "logging.getLogger('rasa')", 'assert', 'rasa_logger.level', '==', 'logging.WARNING', 'matplotlib_logger', '=', "logging.getLogger('matplotlib')", 'assert', 'matplotlib_logger.level', '==', 'logging.INFO']
838,106
tobegit3hub/deep_image_model
svm.py
SVM.predict
predict
Runs inference to determine the predicted class.
[ "Runs", "inference", "to", "determine", "the", "predicted", "class." ]
def predict(self, x=None, input_fn=None, batch_size=None, as_iterable=True): key = prediction_key.PredictionKey.CLASSES preds = self._estimator.predict(x=x, input_fn=input_fn, batch_size=batch_size, outputs=[key], as_iterable=as_iterable) if as_iterable: return _as_iterable(preds, output=key) re...
['def', 'predict(self,', 'x=None,', 'input_fn=None,', 'batch_size=None,', 'as_iterable=True):', 'key', '=', 'prediction_key.PredictionKey.CLASSES', 'preds', '=', 'self._estimator.predict(x=x,', 'input_fn=input_fn,', 'batch_size=batch_size,', 'outputs=[key],', 'as_iterable=as_iterable)', 'if', 'as_iterable:', 'return', ...
181,804
instadeepai/jumanji
conftest.py
cvrp_sparse_reward
cvrp_sparse_reward
Instantiates a CVRP environment with sparse rewards and 5 nodes, maximum capacity of 3 and maximum demand of 2.
[ "Instantiates", "a", "CVRP", "environment", "with", "sparse", "rewards", "and", "5", "nodes,", "maximum", "capacity", "of", "3", "and", "maximum", "demand", "of", "2." ]
def cvrp_sparse_reward(sparse_reward: SparseReward) -> CVRP: return CVRP(generator=UniformGenerator(num_nodes=5, max_capacity=3, max_demand=2), reward_fn=sparse_reward)
['def', 'cvrp_sparse_reward(sparse_reward:', 'SparseReward)', '->', 'CVRP:', 'return', 'CVRP(generator=UniformGenerator(num_nodes=5,', 'max_capacity=3,', 'max_demand=2),', 'reward_fn=sparse_reward)']
594,345
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
mesh_tensorflow.py
parallel
parallel
Call a function once on each device.
[ "Call", "a", "function", "once", "on", "each", "device." ]
def parallel(devices, fn, *args, **kwargs): if not isinstance(devices, list): raise ValueError('devices must be a list') for x in list(args) + list(six.itervalues(kwargs)): if not isinstance(x, list) or len(x) != len(devices): raise ValueError('Argument not a list with same length as...
['def', 'parallel(devices,', 'fn,', '*args,', '**kwargs):', 'if', 'not', 'isinstance(devices,', 'list):', 'raise', "ValueError('devices", 'must', 'be', 'a', "list')", 'for', 'x', 'in', 'list(args)', '+', 'list(six.itervalues(kwargs)):', 'if', 'not', 'isinstance(x,', 'list)', 'or', 'len(x)', '!=', 'len(devices):', 'rais...
965,481
open-mmlab/mmsegmentation
clip_model.py
ResidualAttentionBlock.forward_dense
forward_dense
Reinplementation of forward function for dense prediction of image encoder in CLIP model.
[ "Reinplementation", "of", "forward", "function", "for", "dense", "prediction", "of", "image", "encoder", "in", "CLIP", "model." ]
def forward_dense(self, x: torch.Tensor): y = self.ln_1(x) y = F.linear(y, self.attn.in_proj_weight, self.attn.in_proj_bias) (L, N, D) = y.shape y = y.reshape(L, N, 3, D // 3).permute(2, 1, 0, 3).reshape(3 * N, L, D // 3) y = F.linear(y, self.attn.out_proj.weight, self.attn.out_proj.bias) (q, k,...
['def', 'forward_dense(self,', 'x:', 'torch.Tensor):', 'y', '=', 'self.ln_1(x)', 'y', '=', 'F.linear(y,', 'self.attn.in_proj_weight,', 'self.attn.in_proj_bias)', '(L,', 'N,', 'D)', '=', 'y.shape', 'y', '=', 'y.reshape(L,', 'N,', '3,', 'D', '//', '3).permute(2,', '1,', '0,', '3).reshape(3', '*', 'N,', 'L,', 'D', '//', '...
625,538
myothida/Supervised-Machine-Learning
backend_bases.py
GraphicsContextBase.copy_properties
copy_properties
Copy properties from *gc* to self.
[ "Copy", "properties", "from", "*gc*", "to", "self." ]
def copy_properties(self, gc): self._alpha = gc._alpha self._forced_alpha = gc._forced_alpha self._antialiased = gc._antialiased self._capstyle = gc._capstyle self._cliprect = gc._cliprect self._clippath = gc._clippath self._dashes = gc._dashes self._joinstyle = gc._joinstyle self._l...
['def', 'copy_properties(self,', 'gc):', 'self._alpha', '=', 'gc._alpha', 'self._forced_alpha', '=', 'gc._forced_alpha', 'self._antialiased', '=', 'gc._antialiased', 'self._capstyle', '=', 'gc._capstyle', 'self._cliprect', '=', 'gc._cliprect', 'self._clippath', '=', 'gc._clippath', 'self._dashes', '=', 'gc._dashes', 's...
361,704
yuantn/MI-AOD
mask_scoring_roi_head.py
MaskScoringRoIHead.simple_test_mask
simple_test_mask
Obtain mask prediction without augmentation.
[ "Obtain", "mask", "prediction", "without", "augmentation." ]
def simple_test_mask(self, x, img_metas, det_bboxes, det_labels, rescale=False): ori_shape = img_metas[0]['ori_shape'] scale_factor = img_metas[0]['scale_factor'] if det_bboxes.shape[0] == 0: segm_result = [[] for _ in range(self.mask_head.num_classes)] mask_scores = [[] for _ in range(self....
['def', 'simple_test_mask(self,', 'x,', 'img_metas,', 'det_bboxes,', 'det_labels,', 'rescale=False):', 'ori_shape', '=', "img_metas[0]['ori_shape']", 'scale_factor', '=', "img_metas[0]['scale_factor']", 'if', 'det_bboxes.shape[0]', '==', '0:', 'segm_result', '=', '[[]', 'for', '_', 'in', 'range(self.mask_head.num_class...
635,313
eddylau328/fyp-artificial-intelligence-ac-control-device
face.py
StreamStreamMultiCallable.event
event
Asynchronously invokes the underlying RPC.
[ "Asynchronously", "invokes", "the", "underlying", "RPC." ]
def event(self, receiver, abortion_callback, timeout, metadata=None, protocol_options=None): raise NotImplementedError()
['def', 'event(self,', 'receiver,', 'abortion_callback,', 'timeout,', 'metadata=None,', 'protocol_options=None):', 'raise', 'NotImplementedError()']
215,699
instadeepai/jumanji
utils_test.py
test_board_size_6
test_board_size_6
Validate that various actions can be performed on a 6x6 game board.
[ "Validate", "that", "various", "actions", "can", "be", "performed", "on", "a", "6x6", "game", "board." ]
def test_board_size_6(board6x6: Board) -> None: (board_up, reward) = move_up(board6x6) expected_board = jnp.array([[3, 1, 2, 3, 1, 2], [3, 4, 1, 0, 4, 6], [3, 4, 0, 0, 1, 1], [0, 3, 0, 0, 0, 2], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]) assert jnp.array_equal(expected_board, board_up) assert reward == 14...
['def', 'test_board_size_6(board6x6:', 'Board)', '->', 'None:', '(board_up,', 'reward)', '=', 'move_up(board6x6)', 'expected_board', '=', 'jnp.array([[3,', '1,', '2,', '3,', '1,', '2],', '[3,', '4,', '1,', '0,', '4,', '6],', '[3,', '4,', '0,', '0,', '1,', '1],', '[0,', '3,', '0,', '0,', '0,', '2],', '[0,', '0,', '0,', ...
594,039
megvii-research/MSCL
download.py
create_video_folders
create_video_folders
Creates a directory for each label name in the dataset.
[ "Creates", "a", "directory", "for", "each", "label", "name", "in", "the", "dataset." ]
def create_video_folders(dataset, output_dir, tmp_dir): if 'label-name' not in dataset.columns: this_dir = os.path.join(output_dir, 'test') if not os.path.exists(this_dir): os.makedirs(this_dir) return this_dir if not os.path.exists(output_dir): os.makedirs(output_dir...
['def', 'create_video_folders(dataset,', 'output_dir,', 'tmp_dir):', 'if', "'label-name'", 'not', 'in', 'dataset.columns:', 'this_dir', '=', 'os.path.join(output_dir,', "'test')", 'if', 'not', 'os.path.exists(this_dir):', 'os.makedirs(this_dir)', 'return', 'this_dir', 'if', 'not', 'os.path.exists(output_dir):', 'os.mak...
265,049
deepmind/meltingpot
paintball__capture_the_flag.py
build
build
Build substrate definition given player roles.
[ "Build", "substrate", "definition", "given", "player", "roles." ]
def build(roles: Sequence[str], config: config_dict.ConfigDict) -> Mapping[str, Any]: num_players = len(roles) substrate_definition = dict(levelName='paintball__capture_the_flag', levelDirectory='meltingpot/lua/levels', numPlayers=num_players, maxEpisodeLengthFrames=1000, spriteSize=8, topology='BOUNDED', simul...
['def', 'build(roles:', 'Sequence[str],', 'config:', 'config_dict.ConfigDict)', '->', 'Mapping[str,', 'Any]:', 'num_players', '=', 'len(roles)', 'substrate_definition', '=', "dict(levelName='paintball__capture_the_flag',", "levelDirectory='meltingpot/lua/levels',", 'numPlayers=num_players,', 'maxEpisodeLengthFrames=100...
285,770
yihui-he/KL-Loss
config.py
cache_cfg_urls
cache_cfg_urls
Download URLs in the config, cache them locally, and rewrite cfg to make use of the locally cached file.
[ "Download", "URLs", "in", "the", "config,", "cache", "them", "locally,", "and", "rewrite", "cfg", "to", "make", "use", "of", "the", "locally", "cached", "file." ]
def cache_cfg_urls(): __C.TRAIN.WEIGHTS = cache_url(__C.TRAIN.WEIGHTS, __C.DOWNLOAD_CACHE) __C.TEST.WEIGHTS = cache_url(__C.TEST.WEIGHTS, __C.DOWNLOAD_CACHE) __C.TRAIN.PROPOSAL_FILES = tuple((cache_url(f, __C.DOWNLOAD_CACHE) for f in __C.TRAIN.PROPOSAL_FILES)) __C.TEST.PROPOSAL_FILES = tuple((cache_url(...
['def', 'cache_cfg_urls():', '__C.TRAIN.WEIGHTS', '=', 'cache_url(__C.TRAIN.WEIGHTS,', '__C.DOWNLOAD_CACHE)', '__C.TEST.WEIGHTS', '=', 'cache_url(__C.TEST.WEIGHTS,', '__C.DOWNLOAD_CACHE)', '__C.TRAIN.PROPOSAL_FILES', '=', 'tuple((cache_url(f,', '__C.DOWNLOAD_CACHE)', 'for', 'f', 'in', '__C.TRAIN.PROPOSAL_FILES))', '__C...
596,437
sony/nnabla-rl
test_icml2015_trpo.py
TestICML2015TRPO.test_run_online_training
test_run_online_training
Check that no error occurs when calling online training.
[ "Check", "that", "no", "error", "occurs", "when", "calling", "online", "training." ]
def test_run_online_training(self): dummy_env = E.DummyDiscreteImg() dummy_env = EpisodicEnv(dummy_env, min_episode_length=3) config = A.ICML2015TRPOConfig(batch_size=5, gpu_batch_size=2, num_steps_per_iteration=5, sigma_kl_divergence_constraint=10.0, maximum_backtrack_numbers=2) trpo = A.ICML2015TRPO(d...
['def', 'test_run_online_training(self):', 'dummy_env', '=', 'E.DummyDiscreteImg()', 'dummy_env', '=', 'EpisodicEnv(dummy_env,', 'min_episode_length=3)', 'config', '=', 'A.ICML2015TRPOConfig(batch_size=5,', 'gpu_batch_size=2,', 'num_steps_per_iteration=5,', 'sigma_kl_divergence_constraint=10.0,', 'maximum_backtrack_num...
727,378
Ruturaj123/Flowchart-Detection
vgslspecs_test.py
VgslspecsTest.testScalingOps
testScalingOps
Test a heterogeneous series with scaling.
[ "Test", "a", "heterogeneous", "series", "with", "scaling." ]
def testScalingOps(self): self.ExpectScaledSize('[Cs5,5,16 Mp{MyPool}2,2 Ct3,3,32 Mp3,3 Lfx32 Lry64]', (self.batch_size, self.max_height / 6, self.max_width / 6, 64), 6)
['def', 'testScalingOps(self):', "self.ExpectScaledSize('[Cs5,5,16", 'Mp{MyPool}2,2', 'Ct3,3,32', 'Mp3,3', 'Lfx32', "Lry64]',", '(self.batch_size,', 'self.max_height', '/', '6,', 'self.max_width', '/', '6,', '64),', '6)']
586,530
ryu-ed/SpaceInvaders_Ros
_constraints.py
strict_bounds
strict_bounds
Remove bounds which are not asked to be kept feasible.
[ "Remove", "bounds", "which", "are", "not", "asked", "to", "be", "kept", "feasible." ]
def strict_bounds(lb, ub, keep_feasible, n_vars): strict_lb = np.resize(lb, n_vars).astype(float) strict_ub = np.resize(ub, n_vars).astype(float) keep_feasible = np.resize(keep_feasible, n_vars) strict_lb[~keep_feasible] = -np.inf strict_ub[~keep_feasible] = np.inf return (strict_lb, strict_ub)
['def', 'strict_bounds(lb,', 'ub,', 'keep_feasible,', 'n_vars):', 'strict_lb', '=', 'np.resize(lb,', 'n_vars).astype(float)', 'strict_ub', '=', 'np.resize(ub,', 'n_vars).astype(float)', 'keep_feasible', '=', 'np.resize(keep_feasible,', 'n_vars)', 'strict_lb[~keep_feasible]', '=', '-np.inf', 'strict_ub[~keep_feasible]',...
370,615
enuguru/artificial_intelligence_and_machine_learning
searching.py
Searcher.doc_count
doc_count
Returns the number of UNDELETED documents in the index.
[ "Returns", "the", "number", "of", "UNDELETED", "documents", "in", "the", "index." ]
def doc_count(self): return self.ixreader.doc_count()
['def', 'doc_count(self):', 'return', 'self.ixreader.doc_count()']
162,198
suarez12138/AI-Reversi_IMP_TextDichotomy
canonical_constraint.py
CanonicalConstraint.from_PreparedConstraint
from_PreparedConstraint
Create an instance from `PreparedConstrained` object.
[ "Create", "an", "instance", "from", "`PreparedConstrained`", "object." ]
def from_PreparedConstraint(cls, constraint): (lb, ub) = constraint.bounds cfun = constraint.fun keep_feasible = constraint.keep_feasible if np.all(lb == -np.inf) and np.all(ub == np.inf): return cls.empty(cfun.n) if np.all(lb == -np.inf) and np.all(ub == np.inf): return cls.empty(cf...
['def', 'from_PreparedConstraint(cls,', 'constraint):', '(lb,', 'ub)', '=', 'constraint.bounds', 'cfun', '=', 'constraint.fun', 'keep_feasible', '=', 'constraint.keep_feasible', 'if', 'np.all(lb', '==', '-np.inf)', 'and', 'np.all(ub', '==', 'np.inf):', 'return', 'cls.empty(cfun.n)', 'if', 'np.all(lb', '==', '-np.inf)',...
99,940
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
sysconfig_cpython.py
get_makefile_filename
get_makefile_filename
Return full pathname of installed Makefile from the Python build.
[ "Return", "full", "pathname", "of", "installed", "Makefile", "from", "the", "Python", "build." ]
def get_makefile_filename(): if python_build: return os.path.join(_sys_home or project_base, 'Makefile') lib_dir = get_python_lib(plat_specific=0, standard_lib=1) config_file = 'config-{}{}'.format(get_python_version(), build_flags) return os.path.join(lib_dir, config_file, 'Makefile')
['def', 'get_makefile_filename():', 'if', 'python_build:', 'return', 'os.path.join(_sys_home', 'or', 'project_base,', "'Makefile')", 'lib_dir', '=', 'get_python_lib(plat_specific=0,', 'standard_lib=1)', 'config_file', '=', "'config-{}{}'.format(get_python_version(),", 'build_flags)', 'return', 'os.path.join(lib_dir,', ...
430,361
devashish-patel/webcam-motion-detector
surrogateescape.py
replace_surrogate_encode
replace_surrogate_encode
Returns a (unicode) string, not the more logical bytes, because the codecs register_error functionality expects this.
[ "Returns", "a", "(unicode)", "string,", "not", "the", "more", "logical", "bytes,", "because", "the", "codecs", "register_error", "functionality", "expects", "this." ]
def replace_surrogate_encode(mystring): decoded = [] for ch in mystring: code = ord(ch) if not 55296 <= code <= 56575: raise exc if 56320 <= code <= 56447: decoded.append(_unichr(code - 56320)) elif code <= 56575: decoded.append(_unichr(code - ...
['def', 'replace_surrogate_encode(mystring):', 'decoded', '=', '[]', 'for', 'ch', 'in', 'mystring:', 'code', '=', 'ord(ch)', 'if', 'not', '55296', '<=', 'code', '<=', '56575:', 'raise', 'exc', 'if', '56320', '<=', 'code', '<=', '56447:', 'decoded.append(_unichr(code', '-', '56320))', 'elif', 'code', '<=', '56575:', 'de...
978,253
RasaHQ/rasa
common.py
clean_duplicates
clean_duplicates
Removes keys for empty values.
[ "Removes", "keys", "for", "empty", "values." ]
def clean_duplicates(dupes: Dict[Text, Any]) -> Dict[Text, Any]: duplicates = dupes.copy() for k in dupes: if not dupes[k]: duplicates.pop(k) return duplicates
['def', 'clean_duplicates(dupes:', 'Dict[Text,', 'Any])', '->', 'Dict[Text,', 'Any]:', 'duplicates', '=', 'dupes.copy()', 'for', 'k', 'in', 'dupes:', 'if', 'not', 'dupes[k]:', 'duplicates.pop(k)', 'return', 'duplicates']
837,786
tensorflow/quantum
serializer_test.py
SerializerTest.test_serialize_deserialize_circuit_consistency
test_serialize_deserialize_circuit_consistency
Ensure that serializing followed by deserializing works.
[ "Ensure", "that", "serializing", "followed", "by", "deserializing", "works." ]
def test_serialize_deserialize_circuit_consistency(self, circ_proto_pair): self.assertProtoEquals(serializer.serialize_circuit(serializer.deserialize_circuit(circ_proto_pair[1])), circ_proto_pair[1]) self.assertEqual(serializer.deserialize_circuit(serializer.serialize_circuit(circ_proto_pair[0])), circ_proto_pa...
['def', 'test_serialize_deserialize_circuit_consistency(self,', 'circ_proto_pair):', 'self.assertProtoEquals(serializer.serialize_circuit(serializer.deserialize_circuit(circ_proto_pair[1])),', 'circ_proto_pair[1])', 'self.assertEqual(serializer.deserialize_circuit(serializer.serialize_circuit(circ_proto_pair[0])),', 'c...
835,020
weimin17/Object-Detection_HelmetDetection
data_download.py
compile_files
compile_files
Compile raw files into a single file for each language.
[ "Compile", "raw", "files", "into", "a", "single", "file", "for", "each", "language." ]
def compile_files(raw_dir, raw_files, tag): tf.logging.info('Compiling files with tag %s.' % tag) filename = '%s-%s' % (_PREFIX, tag) input_compiled_file = os.path.join(raw_dir, filename + '.lang1') target_compiled_file = os.path.join(raw_dir, filename + '.lang2') with tf.gfile.Open(input_compiled_f...
['def', 'compile_files(raw_dir,', 'raw_files,', 'tag):', "tf.logging.info('Compiling", 'files', 'with', 'tag', "%s.'", '%', 'tag)', 'filename', '=', "'%s-%s'", '%', '(_PREFIX,', 'tag)', 'input_compiled_file', '=', 'os.path.join(raw_dir,', 'filename', '+', "'.lang1')", 'target_compiled_file', '=', 'os.path.join(raw_dir,...
761,149
apeterswu/RL4NMT
common_layers.py
smoothing_cross_entropy
smoothing_cross_entropy
Cross entropy with label smoothing to limit over-confidence.
[ "Cross", "entropy", "with", "label", "smoothing", "to", "limit", "over-confidence." ]
def smoothing_cross_entropy(logits, labels, vocab_size, confidence, use_focal_loss=False, focal_loss_gamma=0.0, gaussian=False): with tf.name_scope('smoothing_cross_entropy', [logits, labels]): low_confidence = (1.0 - confidence) / tf.to_float(vocab_size - 1) normalizing = -(confidence * tf.log(conf...
['def', 'smoothing_cross_entropy(logits,', 'labels,', 'vocab_size,', 'confidence,', 'use_focal_loss=False,', 'focal_loss_gamma=0.0,', 'gaussian=False):', 'with', "tf.name_scope('smoothing_cross_entropy',", '[logits,', 'labels]):', 'low_confidence', '=', '(1.0', '-', 'confidence)', '/', 'tf.to_float(vocab_size', '-', '1...
331,068
AgnostiqHQ/covalent
transport_test.py
test_transport_graph_get_dependencies
test_transport_graph_get_dependencies
Test the graph node retrieval method in the transport graph.
[ "Test", "the", "graph", "node", "retrieval", "method", "in", "the", "transport", "graph." ]
def test_transport_graph_get_dependencies(workflow_transport_graph): wtg = workflow_transport_graph assert not list(wtg.get_dependencies(node_key=0)) assert not list(wtg.get_dependencies(node_key=1)) wtg.add_edge(x=0, y=1, edge_name='apples') assert not list(wtg.get_dependencies(node_key=0)) ass...
['def', 'test_transport_graph_get_dependencies(workflow_transport_graph):', 'wtg', '=', 'workflow_transport_graph', 'assert', 'not', 'list(wtg.get_dependencies(node_key=0))', 'assert', 'not', 'list(wtg.get_dependencies(node_key=1))', 'wtg.add_edge(x=0,', 'y=1,', "edge_name='apples')", 'assert', 'not', 'list(wtg.get_dep...
489,949
edsonbollis/Weakly-Supervised-Learning-Citrus-Pest-Benchmark
instance-database-generator.py
guided_backprop
guided_backprop
Guided Backpropagation method for visualizing input saliency.
[ "Guided", "Backpropagation", "method", "for", "visualizing", "input", "saliency." ]
def guided_backprop(input_model, images): input_imgs = input_model.input layer_output = input_model.get_layer(layer_name).output grads = K.gradients(layer_output, input_imgs)[0] backprop_fn = K.function([input_imgs, K.learning_phase()], [grads]) grads_val = backprop_fn([images, 0])[0] return gra...
['def', 'guided_backprop(input_model,', 'images):', 'input_imgs', '=', 'input_model.input', 'layer_output', '=', 'input_model.get_layer(layer_name).output', 'grads', '=', 'K.gradients(layer_output,', 'input_imgs)[0]', 'backprop_fn', '=', 'K.function([input_imgs,', 'K.learning_phase()],', '[grads])', 'grads_val', '=', '...
373,321
TonyLianLong/VAI-ReinforcementLearning
wrappers.py
MjrContextWrapper.rangeFont
rangeFont
all characters in font.
[ "all", "characters", "in", "font." ]
def rangeFont(self): return self._ptr.contents.rangeFont
['def', 'rangeFont(self):', 'return', 'self._ptr.contents.rangeFont']
440,652
sunishsheth2009/ChatterBot
schema.py
ChangesetColumn.alter
alter
Makes a call to :func:`alter_column` for the column this method is called on.
[ "Makes", "a", "call", "to", ":func:`alter_column`", "for", "the", "column", "this", "method", "is", "called", "on." ]
def alter(self, *p, **k): if 'table' not in k: k['table'] = self.table if 'engine' not in k: k['engine'] = k['table'].bind return alter_column(self, *p, **k)
['def', 'alter(self,', '*p,', '**k):', 'if', "'table'", 'not', 'in', 'k:', "k['table']", '=', 'self.table', 'if', "'engine'", 'not', 'in', 'k:', "k['engine']", '=', "k['table'].bind", 'return', 'alter_column(self,', '*p,', '**k)']
529,650
openvinotoolkit/training_extensions
scored_label.py
ScoredLabel.get_label
get_label
Gets the label that the ScoredLabel object was initialized with.
[ "Gets", "the", "label", "that", "the", "ScoredLabel", "object", "was", "initialized", "with." ]
def get_label(self) -> LabelEntity: return self.label
['def', 'get_label(self)', '->', 'LabelEntity:', 'return', 'self.label']
918,670
NifTK/NiftyNet
grid_warper.py
AffineWarpConstraints.shear_2d
shear_2d
Assigns constraints on shear components of affine transform in 2d.
[ "Assigns", "constraints", "on", "shear", "components", "of", "affine", "transform", "in", "2d." ]
def shear_2d(cls, x=None, y=None): return cls([[None, x, None], [y, None, None]])
['def', 'shear_2d(cls,', 'x=None,', 'y=None):', 'return', 'cls([[None,', 'x,', 'None],', '[y,', 'None,', 'None]])']
294,172
rtlee9/recipe-summarization
vocabulary-embedding.py
build_word_to_glove
build_word_to_glove
Map full vocabulary to glove based on cosine distance.
[ "Map", "full", "vocabulary", "to", "glove", "based", "on", "cosine", "distance." ]
def build_word_to_glove(embedding, word2idx, idx2word, glove_index_dict, glove_embedding_weights): glove_thr = 0.5 word2glove = {} for w in word2idx: if w in glove_index_dict: g = w elif w.lower() in glove_index_dict: g = w.lower() elif w.startswith('#') and w...
['def', 'build_word_to_glove(embedding,', 'word2idx,', 'idx2word,', 'glove_index_dict,', 'glove_embedding_weights):', 'glove_thr', '=', '0.5', 'word2glove', '=', '{}', 'for', 'w', 'in', 'word2idx:', 'if', 'w', 'in', 'glove_index_dict:', 'g', '=', 'w', 'elif', 'w.lower()', 'in', 'glove_index_dict:', 'g', '=', 'w.lower()...
309,102
replit-archive/empythoned
inspect.py
trace
trace
Return a list of records for the stack below the current exception.
[ "Return", "a", "list", "of", "records", "for", "the", "stack", "below", "the", "current", "exception." ]
def trace(context=1): return getinnerframes(sys.exc_info()[2], context)
['def', 'trace(context=1):', 'return', 'getinnerframes(sys.exc_info()[2],', 'context)']
176,369
bhateharsh/computer_vision
tps.py
GridGenerator.forward
forward
Generate the grid for the grid_sampler.
[ "Generate", "the", "grid", "for", "the", "grid_sampler." ]
def forward(self, batch_C_prime, I_r_size): C = self.build_C_paddle() P = self.build_P_paddle(I_r_size) inv_delta_C_tensor = self.build_inv_delta_C_paddle(C).astype('float32') P_hat_tensor = self.build_P_hat_paddle(C, paddle.to_tensor(P)).astype('float32') inv_delta_C_tensor.stop_gradient = True ...
['def', 'forward(self,', 'batch_C_prime,', 'I_r_size):', 'C', '=', 'self.build_C_paddle()', 'P', '=', 'self.build_P_paddle(I_r_size)', 'inv_delta_C_tensor', '=', "self.build_inv_delta_C_paddle(C).astype('float32')", 'P_hat_tensor', '=', 'self.build_P_hat_paddle(C,', "paddle.to_tensor(P)).astype('float32')", 'inv_delta_...
502,307
devashish-patel/webcam-motion-detector
test_decorators.py
test_deliberately_broken2
test_deliberately_broken2
Another deliberately broken test - we want to skip this one.
[ "Another", "deliberately", "broken", "test", "-", "we", "want", "to", "skip", "this", "one." ]
def test_deliberately_broken2(): 1 / 0
['def', 'test_deliberately_broken2():', '1', '/', '0']
979,358
Oporto/CS4341_Artificial_Inteligence
mask.py
Sprite.collide
collide
Test if the sprites are colliding and resolve the collision in this case.
[ "Test", "if", "the", "sprites", "are", "colliding", "and", "resolve", "the", "collision", "in", "this", "case." ]
def collide(self, s): offset = [int(x) for x in vsub(s.pos, self.pos)] overlap = self.mask.overlap_area(s.mask, offset) if overlap == 0: return 'Calculate collision normal' nx = self.mask.overlap_area(s.mask, (offset[0] + 1, offset[1])) - self.mask.overlap_area(s.mask, (offset[0] - 1, offset...
['def', 'collide(self,', 's):', 'offset', '=', '[int(x)', 'for', 'x', 'in', 'vsub(s.pos,', 'self.pos)]', 'overlap', '=', 'self.mask.overlap_area(s.mask,', 'offset)', 'if', 'overlap', '==', '0:', 'return', "'Calculate", 'collision', "normal'", 'nx', '=', 'self.mask.overlap_area(s.mask,', '(offset[0]', '+', '1,', 'offset...
191,656
DeepGraphLearning/torchdrug
graph.py
Graph.node
node
Context manager for node attributes.
[ "Context", "manager", "for", "node", "attributes." ]
def node(self): return self.context('node')
['def', 'node(self):', 'return', "self.context('node')"]
902,689
suarez12138/AI-Reversi_IMP_TextDichotomy
figure.py
_AxesStack.remove
remove
Remove the axes from the stack.
[ "Remove", "the", "axes", "from", "the", "stack." ]
def remove(self, a): super().remove(self._entry_from_axes(a))
['def', 'remove(self,', 'a):', 'super().remove(self._entry_from_axes(a))']
96,437
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
scan_ex2_solution.py
set_p_to_zero
set_p_to_zero
Provided utility function: given a symbolic vector of probabilities and an index 'i', set the probability of the i-th element to 0 and renormalize the probabilities so they sum to 1.
[ "Provided", "utility", "function:", "given", "a", "symbolic", "vector", "of", "probabilities", "and", "an", "index", "'i',", "set", "the", "probability", "of", "the", "i-th", "element", "to", "0", "and", "renormalize", "the", "probabilities", "so", "they", "su...
def set_p_to_zero(pvect, i): new_pvect = T.set_subtensor(pvect[i], 0.0) new_pvect = new_pvect / new_pvect.sum() return new_pvect
['def', 'set_p_to_zero(pvect,', 'i):', 'new_pvect', '=', 'T.set_subtensor(pvect[i],', '0.0)', 'new_pvect', '=', 'new_pvect', '/', 'new_pvect.sum()', 'return', 'new_pvect']
15,225
weimin17/Object-Detection_HelmetDetection
seq2seq_vd.py
discriminator
discriminator
Define the Discriminator graph.
[ "Define", "the", "Discriminator", "graph." ]
def discriminator(hparams, inputs, targets_present, sequence, is_training, reuse=None): if FLAGS.dis_share_embedding: assert hparams.dis_rnn_size == hparams.gen_rnn_size, 'If you wish to share Discriminator/Generator embeddings, they must be same dimension.' with tf.variable_scope('gen/decoder/rnn',...
['def', 'discriminator(hparams,', 'inputs,', 'targets_present,', 'sequence,', 'is_training,', 'reuse=None):', 'if', 'FLAGS.dis_share_embedding:', 'assert', 'hparams.dis_rnn_size', '==', 'hparams.gen_rnn_size,', "'If", 'you', 'wish', 'to', 'share', 'Discriminator/Generator', 'embeddings,', 'they', 'must', 'be', 'same', ...
763,723
CosmiQ/solaris
test_mask.py
TestBoundaryMask.test_make_inner_mask_from_fp
test_make_inner_mask_from_fp
test creating a boundary mask using an existing footprint mask.
[ "test", "creating", "a", "boundary", "mask", "using", "an", "existing", "footprint", "mask." ]
def test_make_inner_mask_from_fp(self): fp_mask = skimage.io.imread(os.path.join(data_dir, 'sample_fp_mask.tif')) output_mask = boundary_mask(fp_mask) truth_mask = skimage.io.imread(os.path.join(data_dir, 'sample_b_mask_inner.tif')) assert np.array_equal(output_mask, truth_mask)
['def', 'test_make_inner_mask_from_fp(self):', 'fp_mask', '=', 'skimage.io.imread(os.path.join(data_dir,', "'sample_fp_mask.tif'))", 'output_mask', '=', 'boundary_mask(fp_mask)', 'truth_mask', '=', 'skimage.io.imread(os.path.join(data_dir,', "'sample_b_mask_inner.tif'))", 'assert', 'np.array_equal(output_mask,', 'truth...
879,455
trenton3983/Programming_Computer__with_Python
hcluster.py
ClusterNode.get_depth
get_depth
Return the depth of a node, depth is max of each child plus own distance.
[ "Return", "the", "depth", "of", "a", "node,", "depth", "is", "max", "of", "each", "child", "plus", "own", "distance." ]
def get_depth(self): return max(self.left.get_depth(), self.right.get_depth()) + self.distance
['def', 'get_depth(self):', 'return', 'max(self.left.get_depth(),', 'self.right.get_depth())', '+', 'self.distance']
817,373
shengwenliang/lpcvc2020_water
export_model.py
representative_dataset_gen
representative_dataset_gen
Gets a python generator of image numpy arrays for ImageNet.
[ "Gets", "a", "python", "generator", "of", "image", "numpy", "arrays", "for", "ImageNet." ]
def representative_dataset_gen(): params = dict(batch_size=FLAGS.batch_size) imagenet_eval = imagenet_input.ImageNetInput(is_training=False, data_dir=FLAGS.data_dir, transpose_input=False, cache=False, image_size=FLAGS.image_size, num_parallel_calls=1, use_bfloat16=False, include_background_label=True) data...
['def', 'representative_dataset_gen():', 'params', '=', 'dict(batch_size=FLAGS.batch_size)', 'imagenet_eval', '=', 'imagenet_input.ImageNetInput(is_training=False,', 'data_dir=FLAGS.data_dir,', 'transpose_input=False,', 'cache=False,', 'image_size=FLAGS.image_size,', 'num_parallel_calls=1,', 'use_bfloat16=False,', 'inc...
615,859
tobegit3hub/deep_image_model
exporter.py
regression_signature
regression_signature
Creates a regression signature.
[ "Creates", "a", "regression", "signature." ]
def regression_signature(input_tensor, output_tensor): signature = manifest_pb2.Signature() signature.regression_signature.input.tensor_name = input_tensor.name signature.regression_signature.output.tensor_name = output_tensor.name return signature
['def', 'regression_signature(input_tensor,', 'output_tensor):', 'signature', '=', 'manifest_pb2.Signature()', 'signature.regression_signature.input.tensor_name', '=', 'input_tensor.name', 'signature.regression_signature.output.tensor_name', '=', 'output_tensor.name', 'return', 'signature']
181,991
brijeshiitg/XuNet-Structural-Design-of---Networksfor-Steganalysis
options.py
arguments
arguments
This function returns arguments.
[ "This", "function", "returns", "arguments." ]
def arguments() -> str: parser = argparse.ArgumentParser() parser.add_argument('--cover_path', default='D:\\Github\\Toy-Bossbase-dataset\\bossbase_toy_dataset\\train\\cover') parser.add_argument('--stego_path', default='D:\\Github\\Toy-Bossbase-dataset\\bossbase_toy_dataset\\train\\stego') parser.add_ar...
['def', 'arguments()', '->', 'str:', 'parser', '=', 'argparse.ArgumentParser()', "parser.add_argument('--cover_path',", "default='D:\\\\Github\\\\Toy-Bossbase-dataset\\\\bossbase_toy_dataset\\\\train\\\\cover')", "parser.add_argument('--stego_path',", "default='D:\\\\Github\\\\Toy-Bossbase-dataset\\\\bossbase_toy_datas...
374,640
xiaoaleiBLUE/computer_vision
sast_process.py
SASTProcessTrain.shrink_poly_along_width
shrink_poly_along_width
shrink poly with given length.
[ "shrink", "poly", "with", "given", "length." ]
def shrink_poly_along_width(self, quads, shrink_ratio_of_width, expand_height_ratio=1.0): upper_edge_list = [] def get_cut_info(edge_len_list, cut_len): for (idx, edge_len) in enumerate(edge_len_list): cut_len -= edge_len if cut_len <= 1e-06: ratio = (cut_len + e...
['def', 'shrink_poly_along_width(self,', 'quads,', 'shrink_ratio_of_width,', 'expand_height_ratio=1.0):', 'upper_edge_list', '=', '[]', 'def', 'get_cut_info(edge_len_list,', 'cut_len):', 'for', '(idx,', 'edge_len)', 'in', 'enumerate(edge_len_list):', 'cut_len', '-=', 'edge_len', 'if', 'cut_len', '<=', '1e-06:', 'ratio'...
502,156
ThomasBrouwer/HMF
updates_Gibbs.py
column_tau_individual_mtf
column_tau_individual_mtf
Return the component of the tau update for an individual matrix, for matrix tri-factorisation.
[ "Return", "the", "component", "of", "the", "tau", "update", "for", "an", "individual", "matrix,", "for", "matrix", "tri-factorisation." ]
def column_tau_individual_mtf(dataset, mask, F, S, G, tau, alpha, k): return tau * alpha * (mask * numpy.dot(S[k, :], G.T) ** 2).sum(axis=1)
['def', 'column_tau_individual_mtf(dataset,', 'mask,', 'F,', 'S,', 'G,', 'tau,', 'alpha,', 'k):', 'return', 'tau', '*', 'alpha', '*', '(mask', '*', 'numpy.dot(S[k,', ':],', 'G.T)', '**', '2).sum(axis=1)']
206,695
rudranil723/mini-main
conftest.py
series
series
Make mocked series as fixture.
[ "Make", "mocked", "series", "as", "fixture." ]
def series(): arr = np.random.randn(100) locs = np.arange(20, 40) arr[locs] = np.NaN series = Series(arr, index=bdate_range(datetime(2009, 1, 1), periods=100)) return series
['def', 'series():', 'arr', '=', 'np.random.randn(100)', 'locs', '=', 'np.arange(20,', '40)', 'arr[locs]', '=', 'np.NaN', 'series', '=', 'Series(arr,', 'index=bdate_range(datetime(2009,', '1,', '1),', 'periods=100))', 'return', 'series']
267,724
ljw-struggle/Bioinfor-DeepATT
utils.py
write_json
write_json
Write dict to json file.
[ "Write", "dict", "to", "json", "file." ]
def write_json(content, file_path): with open(file_path, 'wt') as f: json.dump(content, f, indent=4, sort_keys=False)
['def', 'write_json(content,', 'file_path):', 'with', 'open(file_path,', "'wt')", 'as', 'f:', 'json.dump(content,', 'f,', 'indent=4,', 'sort_keys=False)']
461,042
noambassat/SpeechTrainer
cmd.py
Command.ensure_string
ensure_string
Ensure that 'option' is a string; if not defined, set it to 'default'.
[ "Ensure", "that", "'option'", "is", "a", "string;", "if", "not", "defined,", "set", "it", "to", "'default'." ]
def ensure_string(self, option, default=None): self._ensure_stringlike(option, 'string', default)
['def', 'ensure_string(self,', 'option,', 'default=None):', 'self._ensure_stringlike(option,', "'string',", 'default)']
896,199
f-dangel/cockpit
test_bin_adaptation.py
test_grad_hist1d_adapted
test_grad_hist1d_adapted
Compare the 1d histogram with bin adaptation versus autograd.
[ "Compare", "the", "1d", "histogram", "with", "bin", "adaptation", "versus", "autograd." ]
def test_grad_hist1d_adapted(problem, q_kwargs): def adapt_schedule(global_step): return global_step in [1, 2] q1 = GradHist1d(**q_kwargs, adapt=GradAbsMax(adapt_schedule, verbose=True)) output1 = run_harness_get_output(problem, [q1])[0] q2 = AutogradGradHist1d(**q_kwargs, adapt=AutogradGradAbs...
['def', 'test_grad_hist1d_adapted(problem,', 'q_kwargs):', 'def', 'adapt_schedule(global_step):', 'return', 'global_step', 'in', '[1,', '2]', 'q1', '=', 'GradHist1d(**q_kwargs,', 'adapt=GradAbsMax(adapt_schedule,', 'verbose=True))', 'output1', '=', 'run_harness_get_output(problem,', '[q1])[0]', 'q2', '=', 'AutogradGrad...
492,783
arshpreetsingh/quantopian-machinelearning
document.py
Document.cursor_position
cursor_position
The document cursor position.
[ "The", "document", "cursor", "position." ]
def cursor_position(self): return self._cursor_position
['def', 'cursor_position(self):', 'return', 'self._cursor_position']
892,015
triaquae/triaquae
forms.py
PasswordChangeForm.clean_old_password
clean_old_password
Validates that the old_password field is correct.
[ "Validates", "that", "the", "old_password", "field", "is", "correct." ]
def clean_old_password(self): old_password = self.cleaned_data['old_password'] if not self.user.check_password(old_password): raise forms.ValidationError(self.error_messages['password_incorrect']) return old_password
['def', 'clean_old_password(self):', 'old_password', '=', "self.cleaned_data['old_password']", 'if', 'not', 'self.user.check_password(old_password):', 'raise', "forms.ValidationError(self.error_messages['password_incorrect'])", 'return', 'old_password']
357,070
opendilab/DI-star
point.py
Point.scale
scale
Scale the vector to have the target length.
[ "Scale", "the", "vector", "to", "have", "the", "target", "length." ]
def scale(self, target_len): return self * (target_len / self.len())
['def', 'scale(self,', 'target_len):', 'return', 'self', '*', '(target_len', '/', 'self.len())']
184,714
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
registry_test.py
RegistryTest.testCannotCreateNonSubclass
testCannotCreateNonSubclass
Tests that Create fails if the class is not a subclass of Base.
[ "Tests", "that", "Create", "fails", "if", "the", "class", "is", "not", "a", "subclass", "of", "Base." ]
def testCannotCreateNonSubclass(self): with self.assertRaisesRegexp(ValueError, 'Failed to create'): registry_test_base.Base.Create(PATH + 'registry_test_impl.NonSubclass', 'hello world')
['def', 'testCannotCreateNonSubclass(self):', 'with', 'self.assertRaisesRegexp(ValueError,', "'Failed", 'to', "create'):", 'registry_test_base.Base.Create(PATH', '+', "'registry_test_impl.NonSubclass',", "'hello", "world')"]
111,937
43Carrig/recurrent_neural_networks_practice
mvn_linear_operator.py
MultivariateNormalLinearOperator.loc
loc
The `loc` `Tensor` in `Y = scale @ X + loc`.
[ "The", "`loc`", "`Tensor`", "in", "`Y", "=", "scale", "@", "X", "+", "loc`." ]
def loc(self): return self.bijector.shift
['def', 'loc(self):', 'return', 'self.bijector.shift']
312,837
erfaneshrati/meta-transfer-learning
args.py
argument_parser
argument_parser
Get an argument parser for a training script.
[ "Get", "an", "argument", "parser", "for", "a", "training", "script." ]
def argument_parser(): parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--pretrained', help='evaluate a pre-trained model', action='store_true', default=False) parser.add_argument('--seed', help='random seed', default=0, type=int) parser.add_a...
['def', 'argument_parser():', 'parser', '=', 'argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)', "parser.add_argument('--pretrained',", "help='evaluate", 'a', 'pre-trained', "model',", "action='store_true',", 'default=False)', "parser.add_argument('--seed',", "help='random", "seed',", 'de...
633,373
LucasAlegre/morl-baselines
networks.py
NatureCNN.forward
forward
Predicts the features from the observations.
[ "Predicts", "the", "features", "from", "the", "observations." ]
def forward(self, observations: th.Tensor) -> th.Tensor: if observations.dim() == 3: observations = observations.unsqueeze(0) return self.linear(self.cnn(observations / 255.0))
['def', 'forward(self,', 'observations:', 'th.Tensor)', '->', 'th.Tensor:', 'if', 'observations.dim()', '==', '3:', 'observations', '=', 'observations.unsqueeze(0)', 'return', 'self.linear(self.cnn(observations', '/', '255.0))']
655,817
hamza-murad/AALU
visual_recognition_v3.py
ClassifierResult.from_dict
from_dict
Initialize a ClassifierResult object from a json dictionary.
[ "Initialize", "a", "ClassifierResult", "object", "from", "a", "json", "dictionary." ]
def from_dict(cls, _dict: Dict) -> 'ClassifierResult': args = {} valid_keys = ['name', 'classifier_id', 'classes'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError('Unrecognized keys detected in dictionary for class ClassifierResult: ' + ', '.join(bad_keys)) if 'n...
['def', 'from_dict(cls,', '_dict:', 'Dict)', '->', "'ClassifierResult':", 'args', '=', '{}', 'valid_keys', '=', "['name',", "'classifier_id',", "'classes']", 'bad_keys', '=', 'set(_dict.keys())', '-', 'set(valid_keys)', 'if', 'bad_keys:', 'raise', "ValueError('Unrecognized", 'keys', 'detected', 'in', 'dictionary', 'for...
6,147
ashwanitanwar/nmt-transfer-learning-xlm-r
hub_interface.py
RobertaHubInterface.extract_features_aligned_to_words
extract_features_aligned_to_words
Extract RoBERTa features, aligned to spaCy's word-level tokenizer.
[ "Extract", "RoBERTa", "features,", "aligned", "to", "spaCy's", "word-level", "tokenizer." ]
def extract_features_aligned_to_words(self, sentence: str, return_all_hiddens: bool=False) -> torch.Tensor: from fairseq.models.roberta import alignment_utils from spacy.tokens import Doc nlp = alignment_utils.spacy_nlp() tokenizer = alignment_utils.spacy_tokenizer() bpe_toks = self.encode(sentence)...
['def', 'extract_features_aligned_to_words(self,', 'sentence:', 'str,', 'return_all_hiddens:', 'bool=False)', '->', 'torch.Tensor:', 'from', 'fairseq.models.roberta', 'import', 'alignment_utils', 'from', 'spacy.tokens', 'import', 'Doc', 'nlp', '=', 'alignment_utils.spacy_nlp()', 'tokenizer', '=', 'alignment_utils.spacy...
732,124
ChenhongyiYang/PPAL
test_mask_head.py
test_mask_head_loss
test_mask_head_loss
Test mask head loss when mask target is empty.
[ "Test", "mask", "head", "loss", "when", "mask", "target", "is", "empty." ]
def test_mask_head_loss(): self = FCNMaskHead(num_convs=1, roi_feat_size=6, in_channels=8, conv_out_channels=8, num_classes=8) proposal_list = [torch.Tensor([[23.6667, 23.8757, 228.6326, 153.8874]])] gt_bboxes = [torch.Tensor([[23.6667, 23.8757, 238.6326, 151.8874]])] gt_labels = [torch.LongTensor([2])]...
['def', 'test_mask_head_loss():', 'self', '=', 'FCNMaskHead(num_convs=1,', 'roi_feat_size=6,', 'in_channels=8,', 'conv_out_channels=8,', 'num_classes=8)', 'proposal_list', '=', '[torch.Tensor([[23.6667,', '23.8757,', '228.6326,', '153.8874]])]', 'gt_bboxes', '=', '[torch.Tensor([[23.6667,', '23.8757,', '238.6326,', '15...
821,888
Kvatsx/Artificial-Intelligence-Assignments
_tifffile.py
TiffPage.is_tvips
is_tvips
Page contains TVIPS metadata.
[ "Page", "contains", "TVIPS", "metadata." ]
def is_tvips(self): return 'TVIPS' in self.tags
['def', 'is_tvips(self):', 'return', "'TVIPS'", 'in', 'self.tags']
37,630
enuguru/artificial_intelligence_and_machine_
acore.py
entoken
entoken
Takes a sequence of unicode strings and yields a series of Token objects (actually the same Token object over and over, for performance reasons), with the attributes filled in with reasonable values (for example, if ``positions`` or ``chars`` is True, the function assumes each token was separated by one space).
[ "Takes", "a", "sequence", "of", "unicode", "strings", "and", "yields", "a", "series", "of", "Token", "objects", "(actually", "the", "same", "Token", "object", "over", "and", "over,", "for", "performance", "reasons),", "with", "the", "attributes", "filled", "in...
def entoken(textstream, positions=False, chars=False, start_pos=0, start_char=0, **kwargs): pos = start_pos char = start_char t = Token(positions=positions, chars=chars, **kwargs) for text in textstream: t.text = text if positions: t.pos = pos pos += 1 if ...
['def', 'entoken(textstream,', 'positions=False,', 'chars=False,', 'start_pos=0,', 'start_char=0,', '**kwargs):', 'pos', '=', 'start_pos', 'char', '=', 'start_char', 't', '=', 'Token(positions=positions,', 'chars=chars,', '**kwargs)', 'for', 'text', 'in', 'textstream:', 't.text', '=', 'text', 'if', 'positions:', 't.pos...
133,241
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
vqa_attention.py
question_encoder
question_encoder
Question encoder, run LSTM encoder and get the last output as encoding.
[ "Question", "encoder,", "run", "LSTM", "encoder", "and", "get", "the", "last", "output", "as", "encoding." ]
def question_encoder(question, hparams, name='encoder'): with tf.variable_scope(name, 'encoder', values=[question]): question = common_layers.flatten4d3d(question) padding = common_attention.embedding_to_padding(question) length = common_attention.padding_to_length(padding) max_quest...
['def', 'question_encoder(question,', 'hparams,', "name='encoder'):", 'with', 'tf.variable_scope(name,', "'encoder',", 'values=[question]):', 'question', '=', 'common_layers.flatten4d3d(question)', 'padding', '=', 'common_attention.embedding_to_padding(question)', 'length', '=', 'common_attention.padding_to_length(padd...
965,923
spollok/magfield-prediction
create_data.py
ProgressBarActor.update
update
Updates the ProgressBar with the incremental number of items that were just completed.
[ "Updates", "the", "ProgressBar", "with", "the", "incremental", "number", "of", "items", "that", "were", "just", "completed." ]
def update(self, num_items_completed: int) -> None: self.counter += num_items_completed self.delta += num_items_completed self.event.set()
['def', 'update(self,', 'num_items_completed:', 'int)', '->', 'None:', 'self.counter', '+=', 'num_items_completed', 'self.delta', '+=', 'num_items_completed', 'self.event.set()']
627,183
QData/deepWordBug
__init__.py
LaTeXTranslator.duclass_close
duclass_close
Close a group of class declarations.
[ "Close", "a", "group", "of", "class", "declarations." ]
def duclass_close(self, node): for cls in reversed(node['classes']): if cls.startswith('language-'): language = self.babel.language_name(cls[9:]) if language: self.babel.otherlanguages[language] = True self.out.append('\\end{selectlanguage}\n') ...
['def', 'duclass_close(self,', 'node):', 'for', 'cls', 'in', "reversed(node['classes']):", 'if', "cls.startswith('language-'):", 'language', '=', 'self.babel.language_name(cls[9:])', 'if', 'language:', 'self.babel.otherlanguages[language]', '=', 'True', "self.out.append('\\\\end{selectlanguage}\\n')", 'else:', "self.fa...
542,721
linkedin/lambda-learner
functions.py
flatten
flatten
Flatten a list of lists into a shallow list.
[ "Flatten", "a", "list", "of", "lists", "into", "a", "shallow", "list." ]
def flatten(list_of_lists: Iterable[Iterable[Any]]) -> Iterable[Any]: return list(chain.from_iterable(list_of_lists))
['def', 'flatten(list_of_lists:', 'Iterable[Iterable[Any]])', '->', 'Iterable[Any]:', 'return', 'list(chain.from_iterable(list_of_lists))']
261,841
facebookresearch/CompilerGym
observation_test.py
test_observation_when_raw_step_returns_incorrect_no_of_observations
test_observation_when_raw_step_returns_incorrect_no_of_observations
Test that a ServiceError is propagated when raw_step() returns unexpected number of observations.
[ "Test", "that", "a", "ServiceError", "is", "propagated", "when", "raw_step()", "returns", "unexpected", "number", "of", "observations." ]
def test_observation_when_raw_step_returns_incorrect_no_of_observations(): def make_failing_raw_step(n: int): def failing_raw_step(*args, **kwargs): del args del kwargs return (['ir'] * n, None, False, {}) return failing_raw_step spaces = [ObservationSpace(n...
['def', 'test_observation_when_raw_step_returns_incorrect_no_of_observations():', 'def', 'make_failing_raw_step(n:', 'int):', 'def', 'failing_raw_step(*args,', '**kwargs):', 'del', 'args', 'del', 'kwargs', 'return', "(['ir']", '*', 'n,', 'None,', 'False,', '{})', 'return', 'failing_raw_step', 'spaces', '=', "[Observati...
135,931
google-research/rigl
imagenet_train_eval.py
resnet_model_fn_w_pruning
resnet_model_fn_w_pruning
The model_fn for ResNet-50 with pruning.
[ "The", "model_fn", "for", "ResNet-50", "with", "pruning." ]
def resnet_model_fn_w_pruning(features, labels, mode, params): width = 1.0 if FLAGS.width <= 0 else FLAGS.width if isinstance(features, dict): features = features['feature'] if FLAGS.data_format == 'channels_first': assert not FLAGS.transpose_input features = tf.transpose(features, [...
['def', 'resnet_model_fn_w_pruning(features,', 'labels,', 'mode,', 'params):', 'width', '=', '1.0', 'if', 'FLAGS.width', '<=', '0', 'else', 'FLAGS.width', 'if', 'isinstance(features,', 'dict):', 'features', '=', "features['feature']", 'if', 'FLAGS.data_format', '==', "'channels_first':", 'assert', 'not', 'FLAGS.transpo...
841,577