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
myothida/Supervised-Machine-Learning
test_to_latex.py
TestToLatexCaptionLabel.caption_table
caption_table
Caption for table/tabular LaTeX environment.
[ "Caption", "for", "table/tabular", "LaTeX", "environment." ]
def caption_table(self): return 'a table in a \\texttt{table/tabular} environment'
['def', 'caption_table(self):', 'return', "'a", 'table', 'in', 'a', '\\\\texttt{table/tabular}', "environment'"]
443,768
nicknochnack/RealTimeSignLanguageTFJS
model.py
Model.build_depth_test_graph
build_depth_test_graph
Builds depth model reading from placeholders.
[ "Builds", "depth", "model", "reading", "from", "placeholders." ]
def build_depth_test_graph(self): with tf.name_scope('depth_prediction'): with tf.variable_scope('depth_prediction'): input_uint8 = tf.placeholder(tf.uint8, [self.batch_size, self.img_height, self.img_width, 3], name='raw_input') input_float = tf.image.convert_image_dtype(input_uint8...
['def', 'build_depth_test_graph(self):', 'with', "tf.name_scope('depth_prediction'):", 'with', "tf.variable_scope('depth_prediction'):", 'input_uint8', '=', 'tf.placeholder(tf.uint8,', '[self.batch_size,', 'self.img_height,', 'self.img_width,', '3],', "name='raw_input')", 'input_float', '=', 'tf.image.convert_image_dty...
831,365
hankcs/HanLP
torch_component.py
TorchComponent.load
load
Load from a local/remote component.
[ "Load", "from", "a", "local/remote", "component." ]
def load(self, save_dir: str, devices=None, verbose=HANLP_VERBOSE, **kwargs): save_dir = get_resource(save_dir) if devices is None and self.model: devices = self.devices self.load_config(save_dir, **kwargs) self.load_vocabs(save_dir) if verbose: flash('Building model [blink][yellow]....
['def', 'load(self,', 'save_dir:', 'str,', 'devices=None,', 'verbose=HANLP_VERBOSE,', '**kwargs):', 'save_dir', '=', 'get_resource(save_dir)', 'if', 'devices', 'is', 'None', 'and', 'self.model:', 'devices', '=', 'self.devices', 'self.load_config(save_dir,', '**kwargs)', 'self.load_vocabs(save_dir)', 'if', 'verbose:', "...
575,695
deepmind/dm_control
renderer.py
SceneCamera.new_perturbation
new_perturbation
Creates a proxy that allows to manipulate the specified object.
[ "Creates", "a", "proxy", "that", "allows", "to", "manipulate", "the", "specified", "object." ]
def new_perturbation(self, body_id): return Perturbation(body_id, self._model, self._data, self._scene)
['def', 'new_perturbation(self,', 'body_id):', 'return', 'Perturbation(body_id,', 'self._model,', 'self._data,', 'self._scene)']
166,573
arshpreetsingh/quantopian-machinelearning
iostream.py
BaseIOStream.writing
writing
Returns ``True`` if we are currently writing to the stream.
[ "Returns", "``True``", "if", "we", "are", "currently", "writing", "to", "the", "stream." ]
def writing(self) -> bool: return bool(self._write_buffer)
['def', 'writing(self)', '->', 'bool:', 'return', 'bool(self._write_buffer)']
893,508
zihuitang/medical_AI_platform
pathlib.py
Path.owner
owner
Return the login name of the file owner.
[ "Return", "the", "login", "name", "of", "the", "file", "owner." ]
def owner(self): import pwd return pwd.getpwuid(self.stat().st_uid).pw_name
['def', 'owner(self):', 'import', 'pwd', 'return', 'pwd.getpwuid(self.stat().st_uid).pw_name']
280,978
Trusted-AI/AIF360
test_datasets.py
test_adult_matches_old
test_adult_matches_old
Tests Adult Income dataset matches original version.
[ "Tests", "Adult", "Income", "dataset", "matches", "original", "version." ]
def test_adult_matches_old(): (X, y, _) = fetch_adult() X.race = X.race.cat.set_categories(['Non-white', 'White']).fillna('Non-white') adult = AdultDataset() adult = adult.convert_to_dataframe(de_dummy_code=True)[0].drop(columns=adult.label_names) assert_frame_equal(X.reset_index(drop=True), adult.r...
['def', 'test_adult_matches_old():', '(X,', 'y,', '_)', '=', 'fetch_adult()', 'X.race', '=', "X.race.cat.set_categories(['Non-white',", "'White']).fillna('Non-white')", 'adult', '=', 'AdultDataset()', 'adult', '=', 'adult.convert_to_dataframe(de_dummy_code=True)[0].drop(columns=adult.label_names)', 'assert_frame_equal(...
412,510
huawei-noah/xingtian
timm_trainer_callback.py
TimmTrainerCallback.after_epoch
after_epoch
Be called after each epoch.
[ "Be", "called", "after", "each", "epoch." ]
def after_epoch(self, epoch, logs=None): if self.use_ema: self.trainer.model = self.model self.trainer.lr_scheduler.step(epoch=epoch + 1) if self.trainer.is_chief: self.trainer._backup()
['def', 'after_epoch(self,', 'epoch,', 'logs=None):', 'if', 'self.use_ema:', 'self.trainer.model', '=', 'self.model', 'self.trainer.lr_scheduler.step(epoch=epoch', '+', '1)', 'if', 'self.trainer.is_chief:', 'self.trainer._backup()']
968,393
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
translate.py
TranslateDistillProblem.get_or_create_vocab
get_or_create_vocab
Get vocab for distill problems.
[ "Get", "vocab", "for", "distill", "problems." ]
def get_or_create_vocab(self, data_dir, tmp_dir, force_get=False): vocab_filepath = os.path.join(data_dir, self.vocab_filename) encoder = text_encoder.SubwordTextEncoder(vocab_filepath) return encoder
['def', 'get_or_create_vocab(self,', 'data_dir,', 'tmp_dir,', 'force_get=False):', 'vocab_filepath', '=', 'os.path.join(data_dir,', 'self.vocab_filename)', 'encoder', '=', 'text_encoder.SubwordTextEncoder(vocab_filepath)', 'return', 'encoder']
965,057
rudranil723/mini-main
query.py
Query.get_initial_alias
get_initial_alias
Return the first alias for this query, after increasing its reference count.
[ "Return", "the", "first", "alias", "for", "this", "query,", "after", "increasing", "its", "reference", "count." ]
def get_initial_alias(self): if self.alias_map: alias = self.base_table self.ref_alias(alias) else: alias = self.join(BaseTable(self.get_meta().db_table, None)) return alias
['def', 'get_initial_alias(self):', 'if', 'self.alias_map:', 'alias', '=', 'self.base_table', 'self.ref_alias(alias)', 'else:', 'alias', '=', 'self.join(BaseTable(self.get_meta().db_table,', 'None))', 'return', 'alias']
316,149
43Carrig/recurrent_neural_networks_practice
device_assignment.py
DeviceAssignment.tpu_device
tpu_device
Returns the name of the TPU device assigned to a logical core.
[ "Returns", "the", "name", "of", "the", "TPU", "device", "assigned", "to", "a", "logical", "core." ]
def tpu_device(self, replica=0, logical_core=None, job=None): coordinates = self._coordinates(replica, logical_core) return _tpu_device_name(job, self._topology_tasks[coordinates], self._topology_devices[coordinates])
['def', 'tpu_device(self,', 'replica=0,', 'logical_core=None,', 'job=None):', 'coordinates', '=', 'self._coordinates(replica,', 'logical_core)', 'return', '_tpu_device_name(job,', 'self._topology_tasks[coordinates],', 'self._topology_devices[coordinates])']
335,553
awslabs/mxnet-lambda
utils.py
OSUtils.remove_file
remove_file
Remove a file, noop if file does not exist.
[ "Remove", "a", "file,", "noop", "if", "file", "does", "not", "exist." ]
def remove_file(self, filename): try: os.remove(filename) except OSError: pass
['def', 'remove_file(self,', 'filename):', 'try:', 'os.remove(filename)', 'except', 'OSError:', 'pass']
289,001
rudranil723/mini-main
api.py
debug
debug
Add a message with the ``DEBUG`` level.
[ "Add", "a", "message", "with", "the", "``DEBUG``", "level." ]
def debug(request, message, extra_tags='', fail_silently=False): add_message(request, constants.DEBUG, message, extra_tags=extra_tags, fail_silently=fail_silently)
['def', 'debug(request,', 'message,', "extra_tags='',", 'fail_silently=False):', 'add_message(request,', 'constants.DEBUG,', 'message,', 'extra_tags=extra_tags,', 'fail_silently=fail_silently)']
315,406
zihuitang/medical_AI_platform
smtplib.py
SMTP.quit
quit
Terminate the SMTP session.
[ "Terminate", "the", "SMTP", "session." ]
def quit(self): res = self.docmd('quit') self.ehlo_resp = self.helo_resp = None self.esmtp_features = {} self.does_esmtp = False self.close() return res
['def', 'quit(self):', 'res', '=', "self.docmd('quit')", 'self.ehlo_resp', '=', 'self.helo_resp', '=', 'None', 'self.esmtp_features', '=', '{}', 'self.does_esmtp', '=', 'False', 'self.close()', 'return', 'res']
281,387
43Carrig/recurrent_neural_networks_practice
converter.py
string_to_standard
string_to_standard
Converts a string level to standard logging level value.
[ "Converts", "a", "string", "level", "to", "standard", "logging", "level", "value." ]
def string_to_standard(level): return absl_to_standard(ABSL_NAMES.get(level.upper()))
['def', 'string_to_standard(level):', 'return', 'absl_to_standard(ABSL_NAMES.get(level.upper()))']
309,670
Kvatsx/Artificial-Intelligence-Assignments
console_widget.py
is_whitespace
is_whitespace
Check whether a given char counts as white space.
[ "Check", "whether", "a", "given", "char", "counts", "as", "white", "space." ]
def is_whitespace(char): return category(char).startswith('Z')
['def', 'is_whitespace(char):', 'return', "category(char).startswith('Z')"]
77,235
ViTAE-Transformer/ViTDet
mask_point_head.py
MaskPointHead.get_roi_rel_points_test
get_roi_rel_points_test
Get ``num_points`` most uncertain points during test.
[ "Get", "``num_points``", "most", "uncertain", "points", "during", "test." ]
def get_roi_rel_points_test(self, mask_pred, pred_label, cfg): num_points = cfg.subdivision_num_points uncertainty_map = self._get_uncertainty(mask_pred, pred_label) (num_rois, _, mask_height, mask_width) = uncertainty_map.shape if isinstance(mask_height, torch.Tensor): h_step = 1.0 / mask_heigh...
['def', 'get_roi_rel_points_test(self,', 'mask_pred,', 'pred_label,', 'cfg):', 'num_points', '=', 'cfg.subdivision_num_points', 'uncertainty_map', '=', 'self._get_uncertainty(mask_pred,', 'pred_label)', '(num_rois,', '_,', 'mask_height,', 'mask_width)', '=', 'uncertainty_map.shape', 'if', 'isinstance(mask_height,', 'to...
945,786
RasaHQ/rasa
test_telemetry.py
patch_telemetry_context
patch_telemetry_context
Use a new telemetry context for each test to avoid tests influencing each other.
[ "Use", "a", "new", "telemetry", "context", "for", "each", "test", "to", "avoid", "tests", "influencing", "each", "other." ]
def patch_telemetry_context() -> Generator[None, None, None]: defaut_context = telemetry.TELEMETRY_CONTEXT telemetry.TELEMETRY_CONTEXT = None yield telemetry.TELEMETRY_CONTEXT = defaut_context
['def', 'patch_telemetry_context()', '->', 'Generator[None,', 'None,', 'None]:', 'defaut_context', '=', 'telemetry.TELEMETRY_CONTEXT', 'telemetry.TELEMETRY_CONTEXT', '=', 'None', 'yield', 'telemetry.TELEMETRY_CONTEXT', '=', 'defaut_context']
838,023
Ruturaj123/Flowchart-Detection
model_ops.py
tree_ensemble_variable
tree_ensemble_variable
Creates a tree ensemble model and returns a handle to it.
[ "Creates", "a", "tree", "ensemble", "model", "and", "returns", "a", "handle", "to", "it." ]
def tree_ensemble_variable(stamp_token, tree_ensemble_config, name, container=None): with ops.name_scope(name, 'TreeEnsembleVariable') as name: resource_handle = gen_model_ops.decision_tree_ensemble_resource_handle_op(container, shared_name=name, name=name) create_op = gen_model_ops.create_tree_ense...
['def', 'tree_ensemble_variable(stamp_token,', 'tree_ensemble_config,', 'name,', 'container=None):', 'with', 'ops.name_scope(name,', "'TreeEnsembleVariable')", 'as', 'name:', 'resource_handle', '=', 'gen_model_ops.decision_tree_ensemble_resource_handle_op(container,', 'shared_name=name,', 'name=name)', 'create_op', '='...
586,879
rlworkgroup/garage
test_cnn_module.py
TestCNNModule.test_is_pickleable
test_is_pickleable
Check CNNModule is pickeable.
[ "Check", "CNNModule", "is", "pickeable." ]
def test_is_pickleable(self, hidden_channels, kernel_sizes, strides): model = CNNModule(self.input_spec, image_format='NCHW', hidden_channels=hidden_channels, kernel_sizes=kernel_sizes, strides=strides) output1 = model(self.input) h = pickle.dumps(model) model_pickled = pickle.loads(h) output2 = mod...
['def', 'test_is_pickleable(self,', 'hidden_channels,', 'kernel_sizes,', 'strides):', 'model', '=', 'CNNModule(self.input_spec,', "image_format='NCHW',", 'hidden_channels=hidden_channels,', 'kernel_sizes=kernel_sizes,', 'strides=strides)', 'output1', '=', 'model(self.input)', 'h', '=', 'pickle.dumps(model)', 'model_pic...
201,030
morpheus-project/morpheus
helpers.py
LabelHelper.finalize_rank_vote
finalize_rank_vote
Finalize the rank vote by dividing by n.
[ "Finalize", "the", "rank", "vote", "by", "dividing", "by", "n." ]
def finalize_rank_vote(data: dict) -> None: n = data['n'] for morph in LabelHelper.MORPHOLOGIES: m = data[morph].copy() m = np.divide(m, n, out=np.zeros_like(m, dtype=np.float32), where=n != 0) data[morph][:, :] = m[:, :]
['def', 'finalize_rank_vote(data:', 'dict)', '->', 'None:', 'n', '=', "data['n']", 'for', 'morph', 'in', 'LabelHelper.MORPHOLOGIES:', 'm', '=', 'data[morph].copy()', 'm', '=', 'np.divide(m,', 'n,', 'out=np.zeros_like(m,', 'dtype=np.float32),', 'where=n', '!=', '0)', 'data[morph][:,', ':]', '=', 'm[:,', ':]']
655,983
alpecli/predlig
wrapper.py
WrapperFeatureSelection.reached_stopping_criteria
reached_stopping_criteria
Returns if the algorithm has reached the stopping criteria of the strategy.
[ "Returns", "if", "the", "algorithm", "has", "reached", "the", "stopping", "criteria", "of", "the", "strategy." ]
def reached_stopping_criteria(self): raise NotImplementedError('Need to override this method')
['def', 'reached_stopping_criteria(self):', 'raise', "NotImplementedError('Need", 'to', 'override', 'this', "method')"]
305,941
TonyLianLong/VAI-ReinforcementLearning
engine.py
MovableCamera.set_pose
set_pose
Sets the pose of the camera.
[ "Sets", "the", "pose", "of", "the", "camera." ]
def set_pose(self, lookat, distance, azimuth, elevation): np.copyto(self._render_camera.lookat, lookat) self._render_camera.distance = distance self._render_camera.azimuth = azimuth self._render_camera.elevation = elevation
['def', 'set_pose(self,', 'lookat,', 'distance,', 'azimuth,', 'elevation):', 'np.copyto(self._render_camera.lookat,', 'lookat)', 'self._render_camera.distance', '=', 'distance', 'self._render_camera.azimuth', '=', 'azimuth', 'self._render_camera.elevation', '=', 'elevation']
440,085
DavidDiazGuerra/Cross3D
acousticTrackingLearners.py
OneSourceTrackingLearner.train_epoch
train_epoch
Train the model with an epoch of the dataset.
[ "Train", "the", "model", "with", "an", "epoch", "of", "the", "dataset." ]
def train_epoch(self, dataset, trajectories_per_batch, trajectories_per_gpu_call=5, lr=0.0001, epoch=None): assert trajectories_per_batch % trajectories_per_gpu_call == 0 avg_loss = 0 avg_beta = 0.99 self.model.train() optimizer = optim.Adam(self.model.parameters(), lr=lr) n_trajectories = len(d...
['def', 'train_epoch(self,', 'dataset,', 'trajectories_per_batch,', 'trajectories_per_gpu_call=5,', 'lr=0.0001,', 'epoch=None):', 'assert', 'trajectories_per_batch', '%', 'trajectories_per_gpu_call', '==', '0', 'avg_loss', '=', '0', 'avg_beta', '=', '0.99', 'self.model.train()', 'optimizer', '=', 'optim.Adam(self.model...
138,762
kubeflow/pipelines
import_evaluated_annotation.py
read_gcs_uri_as_text
read_gcs_uri_as_text
Reads the contents of a file in Google Cloud Storage as text.
[ "Reads", "the", "contents", "of", "a", "file", "in", "Google", "Cloud", "Storage", "as", "text." ]
def read_gcs_uri_as_text(gcs_uri: str) -> str: if not gcs_uri.startswith('gs://'): raise ValueError(f'Invalid GCS URI: {gcs_uri}') (bucket_name, file_path) = gcs_uri.split('//')[1].split('/', 1) storage_client = storage.Client() bucket = storage_client.bucket(bucket_name) blob = bucket.blob(...
['def', 'read_gcs_uri_as_text(gcs_uri:', 'str)', '->', 'str:', 'if', 'not', "gcs_uri.startswith('gs://'):", 'raise', "ValueError(f'Invalid", 'GCS', 'URI:', "{gcs_uri}')", '(bucket_name,', 'file_path)', '=', "gcs_uri.split('//')[1].split('/',", '1)', 'storage_client', '=', 'storage.Client()', 'bucket', '=', 'storage_cli...
770,832
netket/netket
planar.py
rectangle
rectangle
The symmetry group of a rectangle aligned with the Cartesian axes (Vierergruppe).
[ "The", "symmetry", "group", "of", "a", "rectangle", "aligned", "with", "the", "Cartesian", "axes", "(Vierergruppe)." ]
def rectangle() -> PointGroup: return D(2)
['def', 'rectangle()', '->', 'PointGroup:', 'return', 'D(2)']
736,291
pranjaldatta/PyVision
testsuite.py
test
test
Run the face test suite.
[ "Run", "the", "face", "test", "suite." ]
def test(): pv.disableCommercialUseWarnings() normalize_suite = unittest.TestLoader().loadTestsFromTestCase(_TestNormalize) surf_suite = unittest.TestLoader().loadTestsFromTestCase(_TestSURF) dist_suite = unittest.TestLoader().loadTestsFromTestCase(_TestDistance) test_suites = [normalize_suite, surf...
['def', 'test():', 'pv.disableCommercialUseWarnings()', 'normalize_suite', '=', 'unittest.TestLoader().loadTestsFromTestCase(_TestNormalize)', 'surf_suite', '=', 'unittest.TestLoader().loadTestsFromTestCase(_TestSURF)', 'dist_suite', '=', 'unittest.TestLoader().loadTestsFromTestCase(_TestDistance)', 'test_suites', '=',...
815,858
ChandlerBang/awesome-self-supervised-gnn
scholar.py
ScholarQuerier.apply_settings
apply_settings
Applies settings as provided by a ScholarSettings instance.
[ "Applies", "settings", "as", "provided", "by", "a", "ScholarSettings", "instance." ]
def apply_settings(self, settings): if settings is None or not settings.is_configured(): return True self.settings = settings html = self._get_http_response(url=self.GET_SETTINGS_URL, log_msg='dump of settings form HTML', err_msg='requesting settings failed') if html is None: return Fals...
['def', 'apply_settings(self,', 'settings):', 'if', 'settings', 'is', 'None', 'or', 'not', 'settings.is_configured():', 'return', 'True', 'self.settings', '=', 'settings', 'html', '=', 'self._get_http_response(url=self.GET_SETTINGS_URL,', "log_msg='dump", 'of', 'settings', 'form', "HTML',", "err_msg='requesting", 'sett...
93,864
lebrice/Sequoia
pl_dqn.py
Agent.get_action
get_action
Using the given network, decide what action to carry out using an epsilon-greedy policy.
[ "Using", "the", "given", "network,", "decide", "what", "action", "to", "carry", "out", "using", "an", "epsilon-greedy", "policy." ]
def get_action(self, state: Tensor, net: nn.Module, epsilon: float) -> int: if np.random.random() < epsilon: action = self.env.action_space.sample() else: q_values = net(state) (_, action) = torch.max(q_values, dim=-1) action = int(action.item()) return action
['def', 'get_action(self,', 'state:', 'Tensor,', 'net:', 'nn.Module,', 'epsilon:', 'float)', '->', 'int:', 'if', 'np.random.random()', '<', 'epsilon:', 'action', '=', 'self.env.action_space.sample()', 'else:', 'q_values', '=', 'net(state)', '(_,', 'action)', '=', 'torch.max(q_values,', 'dim=-1)', 'action', '=', 'int(ac...
344,272
deephyper/deephyper
_redis_storage.py
RedisStorage.store_job_out
store_job_out
Stores the output value of the executed job.
[ "Stores", "the", "output", "value", "of", "the", "executed", "job." ]
def store_job_out(self, job_id: Hashable, value: Any) -> None: if isinstance(value, Number) and math.isnan(value): value = 'NaN' logging.info(f'Storing output for job:{job_id} with value:{value}') self.store_job(job_id, key='out', value=value)
['def', 'store_job_out(self,', 'job_id:', 'Hashable,', 'value:', 'Any)', '->', 'None:', 'if', 'isinstance(value,', 'Number)', 'and', 'math.isnan(value):', 'value', '=', "'NaN'", "logging.info(f'Storing", 'output', 'for', 'job:{job_id}', 'with', "value:{value}')", 'self.store_job(job_id,', "key='out',", 'value=value)']
520,850
ZumoLabs/zpy
objects.py
rotate
rotate
Rotate the given object with Euler angles.
[ "Rotate", "the", "given", "object", "with", "Euler", "angles." ]
def rotate(obj: Union[bpy.types.Object, str], rotation: Union[Tuple[float], mathutils.Euler]=(0.0, 0.0, 0.0), axis_order: str='XYZ') -> None: obj = verify(obj) view_layer = zpy.blender.verify_view_layer() select(obj) log.info(f'Rotating object {obj.name} by {rotation} radians in {axis_order}. ') log...
['def', 'rotate(obj:', 'Union[bpy.types.Object,', 'str],', 'rotation:', 'Union[Tuple[float],', 'mathutils.Euler]=(0.0,', '0.0,', '0.0),', 'axis_order:', "str='XYZ')", '->', 'None:', 'obj', '=', 'verify(obj)', 'view_layer', '=', 'zpy.blender.verify_view_layer()', 'select(obj)', "log.info(f'Rotating", 'object', '{obj.nam...
972,085
prakharg24/yoloret
autoaugment_v1.py
translate_y
translate_y
Equivalent of PIL Translate in Y dimension.
[ "Equivalent", "of", "PIL", "Translate", "in", "Y", "dimension." ]
def translate_y(image, pixels, replace): image = tf.contrib.image.translate(wrap(image), [0, -pixels]) return unwrap(image, replace)
['def', 'translate_y(image,', 'pixels,', 'replace):', 'image', '=', 'tf.contrib.image.translate(wrap(image),', '[0,', '-pixels])', 'return', 'unwrap(image,', 'replace)']
969,416
tobegit3hub/deep_image_model
operator_pd_vdvt_update.py
OperatorPDSqrtVDVTUpdate.name
name
String name identifying this `Operator`.
[ "String", "name", "identifying", "this", "`Operator`." ]
def name(self): return self._name
['def', 'name(self):', 'return', 'self._name']
181,218
asyml/texar-pytorch
vocabulary.py
Vocab.bos_token_id
bos_token_id
The `int` index of the special token indicating the beginning of sequence.
[ "The", "`int`", "index", "of", "the", "special", "token", "indicating", "the", "beginning", "of", "sequence." ]
def bos_token_id(self) -> int: return self.token_to_id_map_py[self._bos_token]
['def', 'bos_token_id(self)', '->', 'int:', 'return', 'self.token_to_id_map_py[self._bos_token]']
925,024
nilearn/nilearn
test_canica.py
test_threshold_bound_error
test_threshold_bound_error
Test that an error is raised when the threshold is higher than the number of components.
[ "Test", "that", "an", "error", "is", "raised", "when", "the", "threshold", "is", "higher", "than", "the", "number", "of", "components." ]
def test_threshold_bound_error(): with pytest.raises(ValueError, match='Threshold must not be higher'): CanICA(n_components=4, threshold=5.0)
['def', 'test_threshold_bound_error():', 'with', 'pytest.raises(ValueError,', "match='Threshold", 'must', 'not', 'be', "higher'):", 'CanICA(n_components=4,', 'threshold=5.0)']
723,741
thallada/nlp
rc_model.py
RCModel.create_shared_params
create_shared_params
Creates parameter objects that shared by multiple layers.
[ "Creates", "parameter", "objects", "that", "shared", "by", "multiple", "layers." ]
def create_shared_params(self): self.emb_param = Attr.Param(name=self.name + '.embs', is_static=self.static_emb, initial_std=math.sqrt(1.0 / self.emb_dim))
['def', 'create_shared_params(self):', 'self.emb_param', '=', 'Attr.Param(name=self.name', '+', "'.embs',", 'is_static=self.static_emb,', 'initial_std=math.sqrt(1.0', '/', 'self.emb_dim))']
808,490
ludwig-ai/ludwig
scheduler.py
BaseSchedulerConfig.dependencies_installed
dependencies_installed
Some search algorithms require additional packages to be installed, check that they are available.
[ "Some", "search", "algorithms", "require", "additional", "packages", "to", "be", "installed,", "check", "that", "they", "are", "available." ]
def dependencies_installed(self): missing_packages = [] missing_installs = [] for (package_name, install_name) in hyperopt_utils.get_scheduler_dependencies(self.type): try: import_module(package_name) except ImportError: missing_packages.append(package_name) ...
['def', 'dependencies_installed(self):', 'missing_packages', '=', '[]', 'missing_installs', '=', '[]', 'for', '(package_name,', 'install_name)', 'in', 'hyperopt_utils.get_scheduler_dependencies(self.type):', 'try:', 'import_module(package_name)', 'except', 'ImportError:', 'missing_packages.append(package_name)', 'missi...
616,982
yihui-he/KL-Loss
ResNet.py
bottleneck_gn_transformation
bottleneck_gn_transformation
Add a bottleneck transformation with GroupNorm to the model.
[ "Add", "a", "bottleneck", "transformation", "with", "GroupNorm", "to", "the", "model." ]
def bottleneck_gn_transformation(model, blob_in, dim_in, dim_out, stride, prefix, dim_inner, dilation=1, group=1): (str1x1, str3x3) = (stride, 1) if cfg.RESNETS.STRIDE_1X1 else (1, stride) cur = model.ConvGN(blob_in, prefix + '_branch2a', dim_in, dim_inner, kernel=1, group_gn=get_group_gn(dim_inner), stride=str...
['def', 'bottleneck_gn_transformation(model,', 'blob_in,', 'dim_in,', 'dim_out,', 'stride,', 'prefix,', 'dim_inner,', 'dilation=1,', 'group=1):', '(str1x1,', 'str3x3)', '=', '(stride,', '1)', 'if', 'cfg.RESNETS.STRIDE_1X1', 'else', '(1,', 'stride)', 'cur', '=', 'model.ConvGN(blob_in,', 'prefix', '+', "'_branch2a',", 'd...
596,556
devashish-patel/webcam-motion-detector
test_magic.py
test_whos
test_whos
Check that whos is protected against objects where repr() fails.
[ "Check", "that", "whos", "is", "protected", "against", "objects", "where", "repr()", "fails." ]
def test_whos(): class A(object): def __repr__(self): raise Exception() _ip.user_ns['a'] = A() _ip.magic('whos')
['def', 'test_whos():', 'class', 'A(object):', 'def', '__repr__(self):', 'raise', 'Exception()', "_ip.user_ns['a']", '=', 'A()', "_ip.magic('whos')"]
979,032
Bismarrck/kcon
bx.py
get_usr_features
get_usr_features
Return the USR feature vector.
[ "Return", "the", "USR", "feature", "vector." ]
def get_usr_features(cart_coords): def get_vector(v1, v2, v3, v4, coords): vector = np.zeros(12) k = 0 for v in [v1, v2, v3, v4]: di = np.linalg.norm(v - coords, axis=1) vector[k:k + 3] = (np.mean(di), np.std(di), skewness(di)) k += 3 return vecto...
['def', 'get_usr_features(cart_coords):', 'def', 'get_vector(v1,', 'v2,', 'v3,', 'v4,', 'coords):', 'vector', '=', 'np.zeros(12)', 'k', '=', '0', 'for', 'v', 'in', '[v1,', 'v2,', 'v3,', 'v4]:', 'di', '=', 'np.linalg.norm(v', '-', 'coords,', 'axis=1)', 'vector[k:k', '+', '3]', '=', '(np.mean(di),', 'np.std(di),', 'skewn...
247,623
juliancervos/stdp-nmnist
nodes.py
PassThroughNodes.reset_state_variables
reset_state_variables
Resets relevant state variables.
[ "Resets", "relevant", "state", "variables." ]
def reset_state_variables(self) -> None: self.s.zero_()
['def', 'reset_state_variables(self)', '->', 'None:', 'self.s.zero_()']
383,953
avril-affine/cs224d
utils.py
prune_wv
prune_wv
Prune word vectors to vocabulary.
[ "Prune", "word", "vectors", "to", "vocabulary." ]
def prune_wv(df, vocab, extra=['UUUNKKK']): items = set(vocab).union(set(extra)) return df.filter(items=items, axis='index')
['def', 'prune_wv(df,', 'vocab,', "extra=['UUUNKKK']):", 'items', '=', 'set(vocab).union(set(extra))', 'return', 'df.filter(items=items,', "axis='index')"]
506,469
ThomasBrouwer/HMF
statistics.py
all_statistics_list
all_statistics_list
Return tuple (MSE,R2,Rp), for all 1 entries in M.
[ "Return", "tuple", "(MSE,R2,Rp),", "for", "all", "1", "entries", "in", "M." ]
def all_statistics_list(R, R_pred): return (MSE_list(R, R_pred), R2_list(R, R_pred), Rp_list(R, R_pred))
['def', 'all_statistics_list(R,', 'R_pred):', 'return', '(MSE_list(R,', 'R_pred),', 'R2_list(R,', 'R_pred),', 'Rp_list(R,', 'R_pred))']
206,722
Katja-M/Python_NaturalLanguageProcessing
core.py
MaskedArray.flat
flat
Return a flat iterator, or set a flattened version of self to value.
[ "Return", "a", "flat", "iterator,", "or", "set", "a", "flattened", "version", "of", "self", "to", "value." ]
def flat(self): return MaskedIterator(self)
['def', 'flat(self):', 'return', 'MaskedIterator(self)']
867,881
sek788432/Waymo-2D-Object-Detection
get_dataset_colormap_test.py
VisualizationUtilTest.testBitGet
testBitGet
Test that if the returned bit value is correct.
[ "Test", "that", "if", "the", "returned", "bit", "value", "is", "correct." ]
def testBitGet(self): self.assertEqual(1, get_dataset_colormap.bit_get(9, 0)) self.assertEqual(0, get_dataset_colormap.bit_get(9, 1)) self.assertEqual(0, get_dataset_colormap.bit_get(9, 2)) self.assertEqual(1, get_dataset_colormap.bit_get(9, 3))
['def', 'testBitGet(self):', 'self.assertEqual(1,', 'get_dataset_colormap.bit_get(9,', '0))', 'self.assertEqual(0,', 'get_dataset_colormap.bit_get(9,', '1))', 'self.assertEqual(0,', 'get_dataset_colormap.bit_get(9,', '2))', 'self.assertEqual(1,', 'get_dataset_colormap.bit_get(9,', '3))']
974,185
gunthercox/ChatterBot
unitofwork.py
UOWTransaction.is_deleted
is_deleted
return true if the given state is marked as deleted within this uowtransaction.
[ "return", "true", "if", "the", "given", "state", "is", "marked", "as", "deleted", "within", "this", "uowtransaction." ]
def is_deleted(self, state): return state in self.states and self.states[state][0]
['def', 'is_deleted(self,', 'state):', 'return', 'state', 'in', 'self.states', 'and', 'self.states[state][0]']
481,508
clvrai/spirl
block_stacking_env.py
BlockStackEnv.unflatten_block_obs
unflatten_block_obs
Unflattens observation vector into dict.
[ "Unflattens", "observation", "vector", "into", "dict." ]
def unflatten_block_obs(obs_vector, include_quat=True, include_vel=False): n_gripper_dims = 8 if include_vel else 5 if include_quat: n_blocks = (obs_vector.shape[0] - n_gripper_dims) // 7 else: n_blocks = (obs_vector.shape[0] - n_gripper_dims) // 3 if include_quat: block_quat = o...
['def', 'unflatten_block_obs(obs_vector,', 'include_quat=True,', 'include_vel=False):', 'n_gripper_dims', '=', '8', 'if', 'include_vel', 'else', '5', 'if', 'include_quat:', 'n_blocks', '=', '(obs_vector.shape[0]', '-', 'n_gripper_dims)', '//', '7', 'else:', 'n_blocks', '=', '(obs_vector.shape[0]', '-', 'n_gripper_dims)...
896,753
Eric3911/OpenAGI
model_utils.py
unique_names_check
unique_names_check
Performs a uniqueness check on the name list resolved, so that it can warn users about non-unique keys.
[ "Performs", "a", "uniqueness", "check", "on", "the", "name", "list", "resolved,", "so", "that", "it", "can", "warn", "users", "about", "non-unique", "keys." ]
def unique_names_check(name_list: Optional[List[str]]): if name_list is None: return names = set() for name in name_list: if name in names: logging.warning(f'Name resolution has found more than one data loader having the same name !\nIn such cases, logs will nor be properly gener...
['def', 'unique_names_check(name_list:', 'Optional[List[str]]):', 'if', 'name_list', 'is', 'None:', 'return', 'names', '=', 'set()', 'for', 'name', 'in', 'name_list:', 'if', 'name', 'in', 'names:', "logging.warning(f'Name", 'resolution', 'has', 'found', 'more', 'than', 'one', 'data', 'loader', 'having', 'the', 'same', ...
274,218
yinyunie/ScenePriors
test_render_meshes.py
TestRenderMeshes.test_batch_uvs
test_batch_uvs
Test that two random tori with TexturesUV render the same as each individually.
[ "Test", "that", "two", "random", "tori", "with", "TexturesUV", "render", "the", "same", "as", "each", "individually." ]
def test_batch_uvs(self): torch.manual_seed(1) device = torch.device('cuda:0') plain_torus = torus(r=1, R=4, sides=10, rings=10, device=device) [verts] = plain_torus.verts_list() [faces] = plain_torus.faces_list() nocolor = torch.zeros((100, 100), device=device) color_gradient = torch.linspa...
['def', 'test_batch_uvs(self):', 'torch.manual_seed(1)', 'device', '=', "torch.device('cuda:0')", 'plain_torus', '=', 'torus(r=1,', 'R=4,', 'sides=10,', 'rings=10,', 'device=device)', '[verts]', '=', 'plain_torus.verts_list()', '[faces]', '=', 'plain_torus.faces_list()', 'nocolor', '=', 'torch.zeros((100,', '100),', 'd...
330,115
rudranil723/mini-main
debug.py
ExceptionReporter.get_traceback_html
get_traceback_html
Return HTML version of debug 500 HTTP error page.
[ "Return", "HTML", "version", "of", "debug", "500", "HTTP", "error", "page." ]
def get_traceback_html(self): with Path(CURRENT_DIR, 'templates', 'technical_500.html').open() as fh: t = DEBUG_ENGINE.from_string(fh.read()) c = Context(self.get_traceback_data(), use_l10n=False) return t.render(c)
['def', 'get_traceback_html(self):', 'with', 'Path(CURRENT_DIR,', "'templates',", "'technical_500.html').open()", 'as', 'fh:', 't', '=', 'DEBUG_ENGINE.from_string(fh.read())', 'c', '=', 'Context(self.get_traceback_data(),', 'use_l10n=False)', 'return', 't.render(c)']
316,845
ouwei-guo/mit-6.034
lab4.py
all_different
all_different
Returns a list of constraints, with one difference constraint between each pair of variables.
[ "Returns", "a", "list", "of", "constraints,", "with", "one", "difference", "constraint", "between", "each", "pair", "of", "variables." ]
def all_different(variables): con = [] for i in range(len(variables) - 1): for j in range(len(variables) - i - 1): con.append(Constraint(variables[i], variables[i + j + 1], constraint_different)) return con
['def', 'all_different(variables):', 'con', '=', '[]', 'for', 'i', 'in', 'range(len(variables)', '-', '1):', 'for', 'j', 'in', 'range(len(variables)', '-', 'i', '-', '1):', 'con.append(Constraint(variables[i],', 'variables[i', '+', 'j', '+', '1],', 'constraint_different))', 'return', 'con']
238,737
weimin17/Object-Detection_HelmetDetection
data_utils.py
get_batch
get_batch
Get a batch of data, training or testing.
[ "Get", "a", "batch", "of", "data,", "training", "or", "testing." ]
def get_batch(bin_id, batch_size, data_set, height, offset=None, preset=None): (inputs, targets) = ([], []) pad_length = bins[bin_id] for b in xrange(batch_size): if preset is None: elem = random.choice(data_set[bin_id]) if offset is not None and offset + b < len(data_set[bin...
['def', 'get_batch(bin_id,', 'batch_size,', 'data_set,', 'height,', 'offset=None,', 'preset=None):', '(inputs,', 'targets)', '=', '([],', '[])', 'pad_length', '=', 'bins[bin_id]', 'for', 'b', 'in', 'xrange(batch_size):', 'if', 'preset', 'is', 'None:', 'elem', '=', 'random.choice(data_set[bin_id])', 'if', 'offset', 'is'...
758,280
ayush94582/CS236_Project
model.py
TemporalModelBase.receptive_field
receptive_field
Return the total receptive field of this model as # of frames.
[ "Return", "the", "total", "receptive", "field", "of", "this", "model", "as", "#", "of", "frames." ]
def receptive_field(self): frames = 0 for f in self.pad: frames += f return 1 + 2 * frames
['def', 'receptive_field(self):', 'frames', '=', '0', 'for', 'f', 'in', 'self.pad:', 'frames', '+=', 'f', 'return', '1', '+', '2', '*', 'frames']
507,954
caiiiac/Machine-Learning-with-Python
artist.py
Artist.format_cursor_data
format_cursor_data
Return *cursor data* string formatted.
[ "Return", "*cursor", "data*", "string", "formatted." ]
def format_cursor_data(self, data): try: data[0] except (TypeError, IndexError): data = [data] return ', '.join(('{:0.3g}'.format(item) for item in data if isinstance(item, (np.floating, np.integer, int, float))))
['def', 'format_cursor_data(self,', 'data):', 'try:', 'data[0]', 'except', '(TypeError,', 'IndexError):', 'data', '=', '[data]', 'return', "',", "'.join(('{:0.3g}'.format(item)", 'for', 'item', 'in', 'data', 'if', 'isinstance(item,', '(np.floating,', 'np.integer,', 'int,', 'float))))']
714,936
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
network_units.py
NetworkUnitInterface.get_logits
get_logits
Pulls out the logits from the tensors produced by this unit.
[ "Pulls", "out", "the", "logits", "from", "the", "tensors", "produced", "by", "this", "unit." ]
def get_logits(self, network_tensors): raise NotImplementedError()
['def', 'get_logits(self,', 'network_tensors):', 'raise', 'NotImplementedError()']
111,239
PaddlePaddle/PaddleSpeech
utility.py
read_manifest
read_manifest
Load and parse manifest file.
[ "Load", "and", "parse", "manifest", "file." ]
def read_manifest(manifest_path, max_input_len=float('inf'), min_input_len=0.0, max_output_len=float('inf'), min_output_len=0.0, max_output_input_ratio=float('inf'), min_output_input_ratio=0.0): manifest = [] with jsonlines.open(manifest_path, 'r') as reader: for json_data in reader: feat_le...
['def', 'read_manifest(manifest_path,', "max_input_len=float('inf'),", 'min_input_len=0.0,', "max_output_len=float('inf'),", 'min_output_len=0.0,', "max_output_input_ratio=float('inf'),", 'min_output_input_ratio=0.0):', 'manifest', '=', '[]', 'with', 'jsonlines.open(manifest_path,', "'r')", 'as', 'reader:', 'for', 'jso...
276,694
google/deepvariant
realigner.py
window_selector_config
window_selector_config
Creates a WindowSelectorOptions proto based on input and default settings.
[ "Creates", "a", "WindowSelectorOptions", "proto", "based", "on", "input", "and", "default", "settings." ]
def window_selector_config(flags_obj): if not flags_obj.ws_use_window_selector_model: if flags_obj.ws_window_selector_model is not None: raise ValueError('Cannot specify a ws_window_selector_model if ws_use_window_selector_model is False.') min_num_supporting_reads = _DEFAULT_MIN_SUPPORT...
['def', 'window_selector_config(flags_obj):', 'if', 'not', 'flags_obj.ws_use_window_selector_model:', 'if', 'flags_obj.ws_window_selector_model', 'is', 'not', 'None:', 'raise', "ValueError('Cannot", 'specify', 'a', 'ws_window_selector_model', 'if', 'ws_use_window_selector_model', 'is', "False.')", 'min_num_supporting_r...
540,473
neurospin/pylearn-parsimony
estimators.py
LogisticRegressionL1L2GraphNet.get_params
get_params
Return a dictionary containing all the estimator's parameters.
[ "Return", "a", "dictionary", "containing", "all", "the", "estimator's", "parameters." ]
def get_params(self): return {'l1': self.l1, 'l2': self.l2, 'gn': self.gn, 'A': self.A, 'mu': self.mu, 'class_weight': self.class_weight, 'penalty_start': self.penalty_start, 'mean': self.mean}
['def', 'get_params(self):', 'return', "{'l1':", 'self.l1,', "'l2':", 'self.l2,', "'gn':", 'self.gn,', "'A':", 'self.A,', "'mu':", 'self.mu,', "'class_weight':", 'self.class_weight,', "'penalty_start':", 'self.penalty_start,', "'mean':", 'self.mean}']
819,900
zhexxian/SUTD-Artificial-Intelligence
nnet2e_studentversion_convolution.py
do_eval
do_eval
Runs one evaluation against the full epoch of data.
[ "Runs", "one", "evaluation", "against", "the", "full", "epoch", "of", "data." ]
def do_eval(sess, eval_correct, images_placeholder, labels_placeholder, keep_prob, data_set): true_count = 0 steps_per_epoch = data_set.num_examples // FLAGS.batch_size num_examples = steps_per_epoch * FLAGS.batch_size for step in xrange(steps_per_epoch): feed_dict = fill_feed_dict(data_set, ima...
['def', 'do_eval(sess,', 'eval_correct,', 'images_placeholder,', 'labels_placeholder,', 'keep_prob,', 'data_set):', 'true_count', '=', '0', 'steps_per_epoch', '=', 'data_set.num_examples', '//', 'FLAGS.batch_size', 'num_examples', '=', 'steps_per_epoch', '*', 'FLAGS.batch_size', 'for', 'step', 'in', 'xrange(steps_per_e...
365,020
omarmhaimdat/twitter_nlp_native_swift
utils.py
make_str
make_str
Converts a value into a valid string.
[ "Converts", "a", "value", "into", "a", "valid", "string." ]
def make_str(value): if isinstance(value, bytes): try: return value.decode(get_filesystem_encoding()) except UnicodeError: return value.decode('utf-8', 'replace') return text_type(value)
['def', 'make_str(value):', 'if', 'isinstance(value,', 'bytes):', 'try:', 'return', 'value.decode(get_filesystem_encoding())', 'except', 'UnicodeError:', 'return', "value.decode('utf-8',", "'replace')", 'return', 'text_type(value)']
953,002
rudranil723/mini-main
backend_bases.py
NavigationToolbar2.release_pan
release_pan
Callback for mouse button release in pan/zoom mode.
[ "Callback", "for", "mouse", "button", "release", "in", "pan/zoom", "mode." ]
def release_pan(self, event): if self._pan_info is None: return self.canvas.mpl_disconnect(self._pan_info.cid) self._id_drag = self.canvas.mpl_connect('motion_notify_event', self.mouse_move) for ax in self._pan_info.axes: ax.end_pan() self.canvas.draw_idle() self._pan_info = None...
['def', 'release_pan(self,', 'event):', 'if', 'self._pan_info', 'is', 'None:', 'return', 'self.canvas.mpl_disconnect(self._pan_info.cid)', 'self._id_drag', '=', "self.canvas.mpl_connect('motion_notify_event',", 'self.mouse_move)', 'for', 'ax', 'in', 'self._pan_info.axes:', 'ax.end_pan()', 'self.canvas.draw_idle()', 'se...
319,168
devashish-patel/webcam-motion-detector
data.py
YamlLexer.parse_block_scalar_empty_line
parse_block_scalar_empty_line
Process an empty line in a block scalar.
[ "Process", "an", "empty", "line", "in", "a", "block", "scalar." ]
def parse_block_scalar_empty_line(indent_token_class, content_token_class): def callback(lexer, match, context): text = match.group() if context.block_scalar_indent is None or len(text) <= context.block_scalar_indent: if text: yield (match.start(), indent_token_class, te...
['def', 'parse_block_scalar_empty_line(indent_token_class,', 'content_token_class):', 'def', 'callback(lexer,', 'match,', 'context):', 'text', '=', 'match.group()', 'if', 'context.block_scalar_indent', 'is', 'None', 'or', 'len(text)', '<=', 'context.block_scalar_indent:', 'if', 'text:', 'yield', '(match.start(),', 'ind...
984,166
aeon-toolkit/aeon
test_mlflow_aeon_model_export.py
test_signature_and_examples_saved_correctly
test_signature_and_examples_saved_correctly
Test saving of mlflow signature and example for native aeon predict method.
[ "Test", "saving", "of", "mlflow", "signature", "and", "example", "for", "native", "aeon", "predict", "method." ]
def test_signature_and_examples_saved_correctly(auto_arima_model, test_data_airline, model_path, use_signature, use_example): from mlflow.models import Model, infer_signature from mlflow.models.utils import _read_example from aeon.utils import mlflow_aeon prediction = auto_arima_model.predict() sign...
['def', 'test_signature_and_examples_saved_correctly(auto_arima_model,', 'test_data_airline,', 'model_path,', 'use_signature,', 'use_example):', 'from', 'mlflow.models', 'import', 'Model,', 'infer_signature', 'from', 'mlflow.models.utils', 'import', '_read_example', 'from', 'aeon.utils', 'import', 'mlflow_aeon', 'predi...
400,232
googleapis/python-aiplatform
test_ray_prediction.py
TestPredictionFunctionality.test_convert_checkpoint_to_pytorch_model_succeed
test_convert_checkpoint_to_pytorch_model_succeed
Test if a TorchCheckpoint conversion is successful.
[ "Test", "if", "a", "TorchCheckpoint", "conversion", "is", "successful." ]
def test_convert_checkpoint_to_pytorch_model_succeed(self, ray_torch_checkpoint) -> None: model = prediction_torch.register.get_pytorch_model_from(ray_torch_checkpoint) assert model is not None values = model(torch.tensor([10000], dtype=torch.float)) print(values[0]) assert values[0] is not None
['def', 'test_convert_checkpoint_to_pytorch_model_succeed(self,', 'ray_torch_checkpoint)', '->', 'None:', 'model', '=', 'prediction_torch.register.get_pytorch_model_from(ray_torch_checkpoint)', 'assert', 'model', 'is', 'not', 'None', 'values', '=', 'model(torch.tensor([10000],', 'dtype=torch.float))', 'print(values[0])...
863,119
thaines/helit
mask_stats.py
MaskStats.getFMeasureTotal
getFMeasureTotal
Returns the f-measure by summing the confusion matrix over the entire range and then calculating.
[ "Returns", "the", "f-measure", "by", "summing", "the", "confusion", "matrix", "over", "the", "entire", "range", "and", "then", "calculating." ]
def getFMeasureTotal(self, start, end): con = self.getConfusionTotal(start, end) recall = float(con[1, 1]) / float(con[1, 0] + con[1, 1]) prec = float(con[1, 1]) / float(con[0, 1] + con[1, 1]) return 2.0 * recall * prec / (recall + prec)
['def', 'getFMeasureTotal(self,', 'start,', 'end):', 'con', '=', 'self.getConfusionTotal(start,', 'end)', 'recall', '=', 'float(con[1,', '1])', '/', 'float(con[1,', '0]', '+', 'con[1,', '1])', 'prec', '=', 'float(con[1,', '1])', '/', 'float(con[0,', '1]', '+', 'con[1,', '1])', 'return', '2.0', '*', 'recall', '*', 'prec...
592,783
wangjin0818/Artificial_Intelligence_2022
imdb_stacked_lstm.py
make_idx_data
make_idx_data
Transforms sentences into a 2-d matrix.
[ "Transforms", "sentences", "into", "a", "2-d", "matrix." ]
def make_idx_data(revs, word_idx_map, maxlen=60): (X_train, X_test, X_dev, y_train, y_dev) = ([], [], [], [], []) for rev in revs: sent = get_idx_from_sent(rev['text'], word_idx_map) y = rev['y'] if rev['split'] == 1: X_train.append(sent) y_train.append(y) ...
['def', 'make_idx_data(revs,', 'word_idx_map,', 'maxlen=60):', '(X_train,', 'X_test,', 'X_dev,', 'y_train,', 'y_dev)', '=', '([],', '[],', '[],', '[],', '[])', 'for', 'rev', 'in', 'revs:', 'sent', '=', "get_idx_from_sent(rev['text'],", 'word_idx_map)', 'y', '=', "rev['y']", 'if', "rev['split']", '==', '1:', 'X_train.ap...
146,700
jbwang1997/CrossKD
analyze_results.py
ResultVisualizer.detection_evaluate
detection_evaluate
Evaluation for object detection.
[ "Evaluation", "for", "object", "detection." ]
def detection_evaluate(self, dataset, results, topk=20, eval_fn=None): if eval_fn is None: eval_fn = bbox_map_eval else: assert callable(eval_fn) prog_bar = ProgressBar(len(results)) _mAPs = {} data_info = {} for (i, (result,)) in enumerate(zip(results)): data_info = data...
['def', 'detection_evaluate(self,', 'dataset,', 'results,', 'topk=20,', 'eval_fn=None):', 'if', 'eval_fn', 'is', 'None:', 'eval_fn', '=', 'bbox_map_eval', 'else:', 'assert', 'callable(eval_fn)', 'prog_bar', '=', 'ProgressBar(len(results))', '_mAPs', '=', '{}', 'data_info', '=', '{}', 'for', '(i,', '(result,))', 'in', '...
491,976
sktime/sktime
test_panel.py
test_check_X_bad_input_args
test_check_X_bad_input_args
Test for the correct reaction for bad input in check_X.
[ "Test", "for", "the", "correct", "reaction", "for", "bad", "input", "in", "check_X." ]
def test_check_X_bad_input_args(X): with pytest.raises(ValueError): check_X(X) with pytest.raises(ValueError): check_X_y(X, y)
['def', 'test_check_X_bad_input_args(X):', 'with', 'pytest.raises(ValueError):', 'check_X(X)', 'with', 'pytest.raises(ValueError):', 'check_X_y(X,', 'y)']
878,133
triaquae/triaquae
query.py
QuerySet.update
update
Updates all elements in the current QuerySet, setting all the given fields to the appropriate values.
[ "Updates", "all", "elements", "in", "the", "current", "QuerySet,", "setting", "all", "the", "given", "fields", "to", "the", "appropriate", "values." ]
def update(self, **kwargs): assert self.query.can_filter(), 'Cannot update a query once a slice has been taken.' self._for_write = True query = self.query.clone(sql.UpdateQuery) query.add_update_values(kwargs) if not transaction.is_managed(using=self.db): transaction.enter_transaction_manage...
['def', 'update(self,', '**kwargs):', 'assert', 'self.query.can_filter(),', "'Cannot", 'update', 'a', 'query', 'once', 'a', 'slice', 'has', 'been', "taken.'", 'self._for_write', '=', 'True', 'query', '=', 'self.query.clone(sql.UpdateQuery)', 'query.add_update_values(kwargs)', 'if', 'not', 'transaction.is_managed(using=...
423,478
tryolabs/luminoth
rcnn_target_test.py
RCNNTargetTest.testMultipleGtBoxes
testMultipleGtBoxes
Tests we're getting the right labels when there's several gt_boxes.
[ "Tests", "we're", "getting", "the", "right", "labels", "when", "there's", "several", "gt_boxes." ]
def testMultipleGtBoxes(self): num_classes = 3 config = EasyDict({'foreground_threshold': 0.5, 'background_threshold_high': 0.5, 'background_threshold_low': 0.1, 'foreground_fraction': 0.5, 'minibatch_size': 18}) model = RCNNTarget(num_classes, config, seed=0) gt_boxes = tf.constant([(10, 0, 398, 399, 0...
['def', 'testMultipleGtBoxes(self):', 'num_classes', '=', '3', 'config', '=', "EasyDict({'foreground_threshold':", '0.5,', "'background_threshold_high':", '0.5,', "'background_threshold_low':", '0.1,', "'foreground_fraction':", '0.5,', "'minibatch_size':", '18})', 'model', '=', 'RCNNTarget(num_classes,', 'config,', 'se...
617,487
bnpy/bnpy
TestFromFixedCountsToRhoOmega.py
evalELBOandPrint
evalELBOandPrint
Check on the objective.
[ "Check", "on", "the", "objective." ]
def evalELBOandPrint(DocTopicCount=None, alpha=None, gamma=None, rho=None, omega=None, msg=''): L = calcELBO_FixedDocTopicCountIgnoreEntropy(DocTopicCount=DocTopicCount, alpha=alpha, gamma=gamma, rho=rho, omega=omega) nDoc = DocTopicCount.shape[0] betaK = rho2beta(rho, returnSize='K') betastr = np2flats...
['def', 'evalELBOandPrint(DocTopicCount=None,', 'alpha=None,', 'gamma=None,', 'rho=None,', 'omega=None,', "msg=''):", 'L', '=', 'calcELBO_FixedDocTopicCountIgnoreEntropy(DocTopicCount=DocTopicCount,', 'alpha=alpha,', 'gamma=gamma,', 'rho=rho,', 'omega=omega)', 'nDoc', '=', 'DocTopicCount.shape[0]', 'betaK', '=', 'rho2b...
465,344
ludwig-ai/ludwig
sst.py
get_sentence_idcs_in_split
get_sentence_idcs_in_split
Given a dataset split is (1 for train, 2 for test, 3 for dev), returns the set of corresponding sentence indices in sentences_df.
[ "Given", "a", "dataset", "split", "is", "(1", "for", "train,", "2", "for", "test,", "3", "for", "dev),", "returns", "the", "set", "of", "corresponding", "sentence", "indices", "in", "sentences_df." ]
def get_sentence_idcs_in_split(datasplit: pd.DataFrame, split_id: int): return set(datasplit[datasplit['splitset_label'] == split_id]['sentence_index'])
['def', 'get_sentence_idcs_in_split(datasplit:', 'pd.DataFrame,', 'split_id:', 'int):', 'return', "set(datasplit[datasplit['splitset_label']", '==', "split_id]['sentence_index'])"]
616,712
sarnsdev/social-alignment-data-mining
_tstutils.py
f4
f4
Piecewise linear, left and right discontinuous at x=1, the root.
[ "Piecewise", "linear,", "left", "and", "right", "discontinuous", "at", "x=1,", "the", "root." ]
def f4(x): if x > 1: return 1.0 + 0.1 * x if x < 1: return -1.0 + 0.1 * x return 0
['def', 'f4(x):', 'if', 'x', '>', '1:', 'return', '1.0', '+', '0.1', '*', 'x', 'if', 'x', '<', '1:', 'return', '-1.0', '+', '0.1', '*', 'x', 'return', '0']
390,990
bhateharsh/computer_vision
cpp_lint.py
PrintUsage
PrintUsage
Prints a brief usage string and exits, optionally with an error message.
[ "Prints", "a", "brief", "usage", "string", "and", "exits,", "optionally", "with", "an", "error", "message." ]
def PrintUsage(message): sys.stderr.write(_USAGE) if message: sys.exit('\nFATAL ERROR: ' + message) else: sys.exit(1)
['def', 'PrintUsage(message):', 'sys.stderr.write(_USAGE)', 'if', 'message:', "sys.exit('\\nFATAL", 'ERROR:', "'", '+', 'message)', 'else:', 'sys.exit(1)']
473,353
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
gym_problems.py
GymSimulatedDiscreteProblem.video_num_target_frames
video_num_target_frames
Number of frames on input for real environment.
[ "Number", "of", "frames", "on", "input", "for", "real", "environment." ]
def video_num_target_frames(self): return 1
['def', 'video_num_target_frames(self):', 'return', '1']
964,883
google-research/scenic
adatape_trainer.py
representation_fn
representation_fn
Feeds the inputs to the model and returns their representations.
[ "Feeds", "the", "inputs", "to", "the", "model", "and", "returns", "their", "representations." ]
def representation_fn(train_state: train_utils.TrainState, batch: Batch, *, flax_model: nn.Module, representation_layer: str, gather_to_host: bool=True) -> Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray]: variables = {'params': train_state.params, **train_state.model_state} representation_layer_parts = representat...
['def', 'representation_fn(train_state:', 'train_utils.TrainState,', 'batch:', 'Batch,', '*,', 'flax_model:', 'nn.Module,', 'representation_layer:', 'str,', 'gather_to_host:', 'bool=True)', '->', 'Tuple[jnp.ndarray,', 'jnp.ndarray,', 'jnp.ndarray]:', 'variables', '=', "{'params':", 'train_state.params,', '**train_state...
846,318
tensorflow/agents
actor.py
Actor.write_metric_summaries
write_metric_summaries
Generates scalar summaries for the actor metrics.
[ "Generates", "scalar", "summaries", "for", "the", "actor", "metrics." ]
def write_metric_summaries(self): if self._metrics is None: return with self._summary_writer.as_default(), common.soft_device_placement(), tf.summary.record_if(lambda : True): for m in self._metrics: tag = m.name try: tf.summary.scalar(name=os.path.join('M...
['def', 'write_metric_summaries(self):', 'if', 'self._metrics', 'is', 'None:', 'return', 'with', 'self._summary_writer.as_default(),', 'common.soft_device_placement(),', 'tf.summary.record_if(lambda', ':', 'True):', 'for', 'm', 'in', 'self._metrics:', 'tag', '=', 'm.name', 'try:', "tf.summary.scalar(name=os.path.join('...
23,719
amartya-k/vision
datasets_utils.py
create_image_or_video_tensor
create_image_or_video_tensor
Create a random uint8 tensor.
[ "Create", "a", "random", "uint8", "tensor." ]
def create_image_or_video_tensor(size: Sequence[int]) -> torch.Tensor: return torch.randint(0, 256, size, dtype=torch.uint8)
['def', 'create_image_or_video_tensor(size:', 'Sequence[int])', '->', 'torch.Tensor:', 'return', 'torch.randint(0,', '256,', 'size,', 'dtype=torch.uint8)']
957,888
quantumiracle/Benchmark-Efficient-Reinforcement--with-Demonstrations
test_vec_env.py
test_vec_env
test_vec_env
Test that a vectorized environment is equivalent to DummyVecEnv, since DummyVecEnv is less likely to be error prone.
[ "Test", "that", "a", "vectorized", "environment", "is", "equivalent", "to", "DummyVecEnv,", "since", "DummyVecEnv", "is", "less", "likely", "to", "be", "error", "prone." ]
def test_vec_env(klass, dtype): num_envs = 3 num_steps = 100 shape = (3, 8) def make_fn(seed): return lambda : SimpleEnv(seed, shape, dtype) fns = [make_fn(i) for i in range(num_envs)] env1 = DummyVecEnv(fns) env2 = klass(fns) assert_envs_equal(env1, env2, num_steps=num_steps)
['def', 'test_vec_env(klass,', 'dtype):', 'num_envs', '=', '3', 'num_steps', '=', '100', 'shape', '=', '(3,', '8)', 'def', 'make_fn(seed):', 'return', 'lambda', ':', 'SimpleEnv(seed,', 'shape,', 'dtype)', 'fns', '=', '[make_fn(i)', 'for', 'i', 'in', 'range(num_envs)]', 'env1', '=', 'DummyVecEnv(fns)', 'env2', '=', 'kla...
433,893
PacktPublishing/Hands-On-Artificial--for-Banking
test_lobpcg.py
test_verbosity
test_verbosity
Check that nonzero verbosity level code runs.
[ "Check", "that", "nonzero", "verbosity", "level", "code", "runs." ]
def test_verbosity(tmpdir): (A, B) = ElasticRod(100) n = A.shape[0] m = 20 np.random.seed(0) V = rand(n, m) X = orth(V) (_, _) = lobpcg(A, X, B=B, tol=1e-05, maxiter=30, largest=False, verbosityLevel=9)
['def', 'test_verbosity(tmpdir):', '(A,', 'B)', '=', 'ElasticRod(100)', 'n', '=', 'A.shape[0]', 'm', '=', '20', 'np.random.seed(0)', 'V', '=', 'rand(n,', 'm)', 'X', '=', 'orth(V)', '(_,', '_)', '=', 'lobpcg(A,', 'X,', 'B=B,', 'tol=1e-05,', 'maxiter=30,', 'largest=False,', 'verbosityLevel=9)']
203,462
nasimrahaman/antipasti-tf
core.py
TFSession.get
get
Get current Tensorflow session.
[ "Get", "current", "Tensorflow", "session." ]
def get(self): return self.session
['def', 'get(self):', 'return', 'self.session']
33,496
google/deepvariant
realigner.py
Realigner.call_debruijn_graph
call_debruijn_graph
Helper function to call debruijn_graph module.
[ "Helper", "function", "to", "call", "debruijn_graph", "module." ]
def call_debruijn_graph(self, windows, reads): windows_haplotypes = [] sam_reader = sam.InMemorySamReader(reads) for window in windows: if window.end - window.start > self.config.ws_config.max_window_size: continue if not self.ref_reader.is_valid(window): continue ...
['def', 'call_debruijn_graph(self,', 'windows,', 'reads):', 'windows_haplotypes', '=', '[]', 'sam_reader', '=', 'sam.InMemorySamReader(reads)', 'for', 'window', 'in', 'windows:', 'if', 'window.end', '-', 'window.start', '>', 'self.config.ws_config.max_window_size:', 'continue', 'if', 'not', 'self.ref_reader.is_valid(wi...
540,483
TonyLianLong/VAI-ReinforcementLearning
wrappers.py
MjrContextWrapper.rangeHField
rangeHField
all hfields from model.
[ "all", "hfields", "from", "model." ]
def rangeHField(self): return self._ptr.contents.rangeHField
['def', 'rangeHField(self):', 'return', 'self._ptr.contents.rangeHField']
440,650
weimin17/Object-Detection_HelmetDetection
benchmark_uploader.py
BigQueryUploader.insert_run_status
insert_run_status
Insert the run status in to Bigquery run status table.
[ "Insert", "the", "run", "status", "in", "to", "Bigquery", "run", "status", "table." ]
def insert_run_status(self, dataset_name, table_name, run_id, run_status): query = "INSERT {ds}.{tb} (run_id, status) VALUES('{rid}', '{status}')".format(ds=dataset_name, tb=table_name, rid=run_id, status=run_status) try: self._bq_client.query(query=query).result() except exceptions.GoogleCloudError...
['def', 'insert_run_status(self,', 'dataset_name,', 'table_name,', 'run_id,', 'run_status):', 'query', '=', '"INSERT', '{ds}.{tb}', '(run_id,', 'status)', "VALUES('{rid}',", '\'{status}\')".format(ds=dataset_name,', 'tb=table_name,', 'rid=run_id,', 'status=run_status)', 'try:', 'self._bq_client.query(query=query).resul...
761,001
DPerrySvendsen/COS30002
box_world.py
BoxWorld.set_target
set_target
Set the target box based on its index idx value.
[ "Set", "the", "target", "box", "based", "on", "its", "index", "idx", "value." ]
def set_target(self, idx): if self.start == self.boxes[idx]: print("Can't have the same start and end boxes!") return if self.target is not None: self.target.marker = None self.target = self.boxes[idx] self.target.marker = 'T'
['def', 'set_target(self,', 'idx):', 'if', 'self.start', '==', 'self.boxes[idx]:', 'print("Can\'t', 'have', 'the', 'same', 'start', 'and', 'end', 'boxes!")', 'return', 'if', 'self.target', 'is', 'not', 'None:', 'self.target.marker', '=', 'None', 'self.target', '=', 'self.boxes[idx]', 'self.target.marker', '=', "'T'"]
137,491
datature/portal
predict.py
tf_predict
tf_predict
Prediction function for TensorFlow models.
[ "Prediction", "function", "for", "TensorFlow", "models." ]
def tf_predict(model, model_format, output_name, image_array): detections_output = model(inputs=image_array) if model_format == 'instance': bboxes = detections_output['output_3'].numpy() masks = detections_output['output_4'].numpy() scores = detections_output['output_1'].numpy() ...
['def', 'tf_predict(model,', 'model_format,', 'output_name,', 'image_array):', 'detections_output', '=', 'model(inputs=image_array)', 'if', 'model_format', '==', "'instance':", 'bboxes', '=', "detections_output['output_3'].numpy()", 'masks', '=', "detections_output['output_4'].numpy()", 'scores', '=', "detections_outpu...
820,905
BMW-InnovationLab/BMW-Semantic--Training-GUI
model_zoo.py
get_model
get_model
Returns a pre-defined model by name Returns ------- The model.
[ "Returns", "a", "pre-defined", "model", "by", "name", "Returns", "-------", "The", "model." ]
def get_model(cfg): name = cfg.CONFIG.MODEL.NAME.lower() if name not in _models: err_str = '"%s" is not among the following model list:\n\t' % name err_str += '%s' % '\n\t'.join(sorted(_models.keys())) raise ValueError(err_str) net = _models[name](cfg) return net
['def', 'get_model(cfg):', 'name', '=', 'cfg.CONFIG.MODEL.NAME.lower()', 'if', 'name', 'not', 'in', '_models:', 'err_str', '=', '\'"%s"', 'is', 'not', 'among', 'the', 'following', 'model', "list:\\n\\t'", '%', 'name', 'err_str', '+=', "'%s'", '%', "'\\n\\t'.join(sorted(_models.keys()))", 'raise', 'ValueError(err_str)',...
462,961
deepmind/meltingpot
commons_harvest__closed.py
get_config
get_config
Default configuration for training on the commons_harvest level.
[ "Default", "configuration", "for", "training", "on", "the", "commons_harvest", "level." ]
def get_config(): config = config_dict.ConfigDict() config.action_set = ACTION_SET config.individual_observation_names = ['RGB', 'READY_TO_SHOOT'] config.global_observation_names = ['WORLD.RGB'] config.action_spec = specs.action(len(ACTION_SET)) config.timestep_spec = specs.timestep({'RGB': spec...
['def', 'get_config():', 'config', '=', 'config_dict.ConfigDict()', 'config.action_set', '=', 'ACTION_SET', 'config.individual_observation_names', '=', "['RGB',", "'READY_TO_SHOOT']", 'config.global_observation_names', '=', "['WORLD.RGB']", 'config.action_spec', '=', 'specs.action(len(ACTION_SET))', 'config.timestep_sp...
285,328
neardws/Game-Theoretic-Deep-Reinforcement-Learning
gradient.py
record_gradient
record_gradient
Explicitly record the gradient for a given op.
[ "Explicitly", "record", "the", "gradient", "for", "a", "given", "op." ]
def record_gradient(op_name, inputs, attrs, outputs): pywrap_tfe.TFE_Py_RecordGradient(op_name, inputs, attrs, outputs, ops.get_name_scope())
['def', 'record_gradient(op_name,', 'inputs,', 'attrs,', 'outputs):', 'pywrap_tfe.TFE_Py_RecordGradient(op_name,', 'inputs,', 'attrs,', 'outputs,', 'ops.get_name_scope())']
199,847
akshitsarin/Udacity-AI-Nanodegree
logic.py
dpll
dpll
See if the clauses are true in a partial model.
[ "See", "if", "the", "clauses", "are", "true", "in", "a", "partial", "model." ]
def dpll(clauses, symbols, model): unknown_clauses = [] for c in clauses: val = pl_true(c, model) if val is False: return False if val is not True: unknown_clauses.append(c) if not unknown_clauses: return model (P, value) = find_pure_symbol(symbols...
['def', 'dpll(clauses,', 'symbols,', 'model):', 'unknown_clauses', '=', '[]', 'for', 'c', 'in', 'clauses:', 'val', '=', 'pl_true(c,', 'model)', 'if', 'val', 'is', 'False:', 'return', 'False', 'if', 'val', 'is', 'not', 'True:', 'unknown_clauses.append(c)', 'if', 'not', 'unknown_clauses:', 'return', 'model', '(P,', 'valu...
427,385
chribsen/simple-machine-learning-examples
array3d.py
create_array
create_array
Creates a simple 3D numpy array with unique values at each location in the matrix.
[ "Creates", "a", "simple", "3D", "numpy", "array", "with", "unique", "values", "at", "each", "location", "in", "the", "matrix." ]
def create_array(): (rows, cols, depth) = (2, 3, 4) arr = numpy.zeros((rows, cols, depth), 'i') count = 0 for i in range(rows): for j in range(cols): for k in range(depth): arr[i, j, k] = count count += 1 return arr
['def', 'create_array():', '(rows,', 'cols,', 'depth)', '=', '(2,', '3,', '4)', 'arr', '=', 'numpy.zeros((rows,', 'cols,', 'depth),', "'i')", 'count', '=', '0', 'for', 'i', 'in', 'range(rows):', 'for', 'j', 'in', 'range(cols):', 'for', 'k', 'in', 'range(depth):', 'arr[i,', 'j,', 'k]', '=', 'count', 'count', '+=', '1', ...
938,674
matsu0228/nlp-jp
connection.py
MWSConnection.list_orders_by_next_token
list_orders_by_next_token
Returns the next page of orders using the NextToken value that was returned by your previous request to either ListOrders or ListOrdersByNextToken.
[ "Returns", "the", "next", "page", "of", "orders", "using", "the", "NextToken", "value", "that", "was", "returned", "by", "your", "previous", "request", "to", "either", "ListOrders", "or", "ListOrdersByNextToken." ]
def list_orders_by_next_token(self, request, response, **kw): return self._post_request(request, kw, response)
['def', 'list_orders_by_next_token(self,', 'request,', 'response,', '**kw):', 'return', 'self._post_request(request,', 'kw,', 'response)']
784,965
rahlk/Bellwether
hsic.py
normalize
normalize
Normalize each dimension of the data separately to zero mean and unit standard deviation.
[ "Normalize", "each", "dimension", "of", "the", "data", "separately", "to", "zero", "mean", "and", "unit", "standard", "deviation." ]
def normalize(data): m = data.mean(axis=0) s = data.std(axis=0) data.__isub__(m).__itruediv__(s)
['def', 'normalize(data):', 'm', '=', 'data.mean(axis=0)', 's', '=', 'data.std(axis=0)', 'data.__isub__(m).__itruediv__(s)']
431,718
flavioschneider/rl-transfer-
_environment.py
Wrapper.spec
spec
EnvSpec: The environment specification.
[ "EnvSpec:", "The", "environment", "specification." ]
def spec(self): return self._env.spec
['def', 'spec(self):', 'return', 'self._env.spec']
860,984
StepNeverStop/RLs
policy.py
Policy.resume
resume
check whether chekpoint and model be within cp_dir, if in it, restore otherwise initialize randomly.
[ "check", "whether", "chekpoint", "and", "model", "be", "within", "cp_dir,", "if", "in", "it,", "restore", "otherwise", "initialize", "randomly." ]
def resume(self, base_dir: Optional[str]=None): cp_dir = os.path.join(base_dir or self._base_dir, 'model') if self._save2single_file: ckpt_path = os.path.join(cp_dir, 'checkpoint.pth') if os.path.exists(ckpt_path): checkpoint = th.load(ckpt_path, map_location=self.device) ...
['def', 'resume(self,', 'base_dir:', 'Optional[str]=None):', 'cp_dir', '=', 'os.path.join(base_dir', 'or', 'self._base_dir,', "'model')", 'if', 'self._save2single_file:', 'ckpt_path', '=', 'os.path.join(cp_dir,', "'checkpoint.pth')", 'if', 'os.path.exists(ckpt_path):', 'checkpoint', '=', 'th.load(ckpt_path,', 'map_loca...
334,827
michaelhush/M-LOOP
interfaces.py
ShellInterface.get_next_cost_dict
get_next_cost_dict
Implementation of running a command with parameters on the command line and reading the result.
[ "Implementation", "of", "running", "a", "command", "with", "parameters", "on", "the", "command", "line", "and", "reading", "the", "result." ]
def get_next_cost_dict(self, params_dict): self.command_count += 1 self.log.debug('Running command count' + repr(self.command_count)) self.last_params_dict = params_dict params = params_dict['params'] param_names = self.param_names if param_names == None: param_names = [] for (in...
['def', 'get_next_cost_dict(self,', 'params_dict):', 'self.command_count', '+=', '1', "self.log.debug('Running", 'command', "count'", '+', 'repr(self.command_count))', 'self.last_params_dict', '=', 'params_dict', 'params', '=', "params_dict['params']", 'param_names', '=', 'self.param_names', 'if', 'param_names', '==', ...
619,871
santhoshkolloju/Abstractive-Summarization-With-Transfer-
mono_text_data_test.py
VarUttMonoTextDataTest.test_default_setting
test_default_setting
Tests the logics of the text data.
[ "Tests", "the", "logics", "of", "the", "text", "data." ]
def test_default_setting(self): self._run_and_test(self._hparams)
['def', 'test_default_setting(self):', 'self._run_and_test(self._hparams)']
406,092
hamza-murad/AALU
discovery_v2.py
QueryHistogramAggregationResult.from_dict
from_dict
Initialize a QueryHistogramAggregationResult object from a json dictionary.
[ "Initialize", "a", "QueryHistogramAggregationResult", "object", "from", "a", "json", "dictionary." ]
def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregationResult': args = {} valid_keys = ['key', 'matching_results', 'aggregations'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError('Unrecognized keys detected in dictionary for class QueryHistogramAggregationResul...
['def', 'from_dict(cls,', '_dict:', 'Dict)', '->', "'QueryHistogramAggregationResult':", 'args', '=', '{}', 'valid_keys', '=', "['key',", "'matching_results',", "'aggregations']", 'bad_keys', '=', 'set(_dict.keys())', '-', 'set(valid_keys)', 'if', 'bad_keys:', 'raise', "ValueError('Unrecognized", 'keys', 'detected', 'i...
5,758
arnomoonens/yarll
async_knowledge_transfer.py
AKTThread.learn_REINFORCE
learn_REINFORCE
Learn using updates like in the REINFORCE algorithm.
[ "Learn", "using", "updates", "like", "in", "the", "REINFORCE", "algorithm." ]
def learn_REINFORCE(self): reporter = Reporter() total_n_trajectories = 0 iteration = self.start_at_iter while iteration < self.n_iter and (not self.master.stop_requested): iteration += 1 trajectories = self.task_runner.get_trajectories() total_n_trajectories += len(trajectories)...
['def', 'learn_REINFORCE(self):', 'reporter', '=', 'Reporter()', 'total_n_trajectories', '=', '0', 'iteration', '=', 'self.start_at_iter', 'while', 'iteration', '<', 'self.n_iter', 'and', '(not', 'self.master.stop_requested):', 'iteration', '+=', '1', 'trajectories', '=', 'self.task_runner.get_trajectories()', 'total_n...
374,666
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
multimodel.py
multimodel_base
multimodel_base
Base parameters for MultiModel.
[ "Base", "parameters", "for", "MultiModel." ]
def multimodel_base(): hparams = common_hparams.basic_params1() hparams.hidden_size = 512 hparams.batch_size = 2048 hparams.num_hidden_layers = 4 hparams.learning_rate_decay_scheme = 'noam' hparams.learning_rate = 0.1 hparams.learning_rate_warmup_steps = 4000 hparams.initializer_gain = 1...
['def', 'multimodel_base():', 'hparams', '=', 'common_hparams.basic_params1()', 'hparams.hidden_size', '=', '512', 'hparams.batch_size', '=', '2048', 'hparams.num_hidden_layers', '=', '4', 'hparams.learning_rate_decay_scheme', '=', "'noam'", 'hparams.learning_rate', '=', '0.1', 'hparams.learning_rate_warmup_steps', '='...
965,843