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
intel/neural-compressor
basic.py
KerasBasicPruner.set_global_step
set_global_step
Set global step number.
[ "Set", "global", "step", "number." ]
def set_global_step(self, global_step): self.global_step = global_step
['def', 'set_global_step(self,', 'global_step):', 'self.global_step', '=', 'global_step']
738,205
prakharg24/yoloret
autoaugment_v1.py
rotate_with_bboxes
rotate_with_bboxes
Equivalent of PIL Rotate that rotates the image and bbox.
[ "Equivalent", "of", "PIL", "Rotate", "that", "rotates", "the", "image", "and", "bbox." ]
def rotate_with_bboxes(image, bboxes, degrees, replace): image = rotate(image, degrees, replace) image_height = tf.shape(image)[0] image_width = tf.shape(image)[1] wrapped_rotate_bbox = lambda bbox: _rotate_bbox(bbox, image_height, image_width, degrees) bboxes = tf.map_fn(wrapped_rotate_bbox, bboxes...
['def', 'rotate_with_bboxes(image,', 'bboxes,', 'degrees,', 'replace):', 'image', '=', 'rotate(image,', 'degrees,', 'replace)', 'image_height', '=', 'tf.shape(image)[0]', 'image_width', '=', 'tf.shape(image)[1]', 'wrapped_rotate_bbox', '=', 'lambda', 'bbox:', '_rotate_bbox(bbox,', 'image_height,', 'image_width,', 'degr...
969,414
voxel51/fiftyone
geojson.py
to_geo_json_geometry
to_geo_json_geometry
Returns a GeoJSON ``geometry`` dict representation for the given location.
[ "Returns", "a", "GeoJSON", "``geometry``", "dict", "representation", "for", "the", "given", "location." ]
def to_geo_json_geometry(label): if isinstance(label, fol.GeoLocations): return _to_multi_geo_collection(label) if not isinstance(label, fol.GeoLocation): return None num_shapes = int(label.point is not None) + int(label.line is not None) + int(label.polygon is not None) if num_shapes ==...
['def', 'to_geo_json_geometry(label):', 'if', 'isinstance(label,', 'fol.GeoLocations):', 'return', '_to_multi_geo_collection(label)', 'if', 'not', 'isinstance(label,', 'fol.GeoLocation):', 'return', 'None', 'num_shapes', '=', 'int(label.point', 'is', 'not', 'None)', '+', 'int(label.line', 'is', 'not', 'None)', '+', 'in...
584,049
rudranil723/mini-main
versioncontrol.py
VersionControl.get_src_requirement
get_src_requirement
Return the requirement string to use to redownload the files currently at the given repository directory.
[ "Return", "the", "requirement", "string", "to", "use", "to", "redownload", "the", "files", "currently", "at", "the", "given", "repository", "directory." ]
def get_src_requirement(cls, repo_dir: str, project_name: str) -> str: repo_url = cls.get_remote_url(repo_dir) if cls.should_add_vcs_url_prefix(repo_url): repo_url = f'{cls.name}+{repo_url}' revision = cls.get_requirement_revision(repo_dir) subdir = cls.get_subdirectory(repo_dir) req = make_...
['def', 'get_src_requirement(cls,', 'repo_dir:', 'str,', 'project_name:', 'str)', '->', 'str:', 'repo_url', '=', 'cls.get_remote_url(repo_dir)', 'if', 'cls.should_add_vcs_url_prefix(repo_url):', 'repo_url', '=', "f'{cls.name}+{repo_url}'", 'revision', '=', 'cls.get_requirement_revision(repo_dir)', 'subdir', '=', 'cls.g...
268,233
gibranfp/P300-CNNT
cross_subject_DeepConvNet.py
evaluate_cross_subject_model
evaluate_cross_subject_model
Trains and evaluates DeepConvNet for each subject in the P300 Speller database using random cross validation.
[ "Trains", "and", "evaluates", "DeepConvNet", "for", "each", "subject", "in", "the", "P300", "Speller", "database", "using", "random", "cross", "validation." ]
def evaluate_cross_subject_model(data, labels, modelpath): n_sub = data.shape[0] n_ex_sub = data.shape[1] n_samples = data.shape[2] n_channels = data.shape[3] aucs = np.zeros(n_sub) data = data.reshape((n_sub * n_ex_sub, n_samples, n_channels)) labels = labels.reshape(n_sub * n_ex_sub) g...
['def', 'evaluate_cross_subject_model(data,', 'labels,', 'modelpath):', 'n_sub', '=', 'data.shape[0]', 'n_ex_sub', '=', 'data.shape[1]', 'n_samples', '=', 'data.shape[2]', 'n_channels', '=', 'data.shape[3]', 'aucs', '=', 'np.zeros(n_sub)', 'data', '=', 'data.reshape((n_sub', '*', 'n_ex_sub,', 'n_samples,', 'n_channels)...
253,724
Kvatsx/Artificial-Intelligence-Assignments
server.py
BaseHTTPRequestHandler.version_string
version_string
Return the server software version string.
[ "Return", "the", "server", "software", "version", "string." ]
def version_string(self): return self.server_version + ' ' + self.sys_version
['def', 'version_string(self):', 'return', 'self.server_version', '+', "'", "'", '+', 'self.sys_version']
36,974
voxel51/fiftyone
database.py
cleanup_multiple_config_docs
cleanup_multiple_config_docs
Internal utility that ensures that there is only one :class:`DatabaseConfigDocument` in the database.
[ "Internal", "utility", "that", "ensures", "that", "there", "is", "only", "one", ":class:`DatabaseConfigDocument`", "in", "the", "database." ]
def cleanup_multiple_config_docs(): docs = list(DatabaseConfigDocument.objects) if len(docs) <= 1: return logger.warning("Unexpectedly found %d documents in the 'config' collection; assuming the one with latest 'version' is the correct one", len(docs)) versions = [] for doc in docs: ...
['def', 'cleanup_multiple_config_docs():', 'docs', '=', 'list(DatabaseConfigDocument.objects)', 'if', 'len(docs)', '<=', '1:', 'return', 'logger.warning("Unexpectedly', 'found', '%d', 'documents', 'in', 'the', "'config'", 'collection;', 'assuming', 'the', 'one', 'with', 'latest', "'version'", 'is', 'the', 'correct', 'o...
583,519
UWARG/computer-vision-python
test_data_merge_worker.py
simulate_detect_target_worker
simulate_detect_target_worker
Place the detection into the queue.
[ "Place", "the", "detection", "into", "the", "queue." ]
def simulate_detect_target_worker(timestamp: float, detections_queue: queue_proxy_wrapper.QueueProxyWrapper): detections = detections_and_time.DetectionsAndTime(timestamp) detections_queue.queue.put(detections)
['def', 'simulate_detect_target_worker(timestamp:', 'float,', 'detections_queue:', 'queue_proxy_wrapper.QueueProxyWrapper):', 'detections', '=', 'detections_and_time.DetectionsAndTime(timestamp)', 'detections_queue.queue.put(detections)']
470,486
RasaHQ/rasa
spacy_featurizer.py
SpacyFeaturizer.required_components
required_components
Components that should be included in the pipeline before this component.
[ "Components", "that", "should", "be", "included", "in", "the", "pipeline", "before", "this", "component." ]
def required_components(cls) -> List[Type]: return [SpacyTokenizer]
['def', 'required_components(cls)', '->', 'List[Type]:', 'return', '[SpacyTokenizer]']
837,263
pykale/pykale
multiomics_datasets.py
MultiomicsDataset.len
len
Returns the number of graphs stored in the dataset.
[ "Returns", "the", "number", "of", "graphs", "stored", "in", "the", "dataset." ]
def len(self) -> int: return self.num_modalities
['def', 'len(self)', '->', 'int:', 'return', 'self.num_modalities']
819,690
PaddlePaddle/PARL
communication.py
loads_argument
loads_argument
Restore bytes data to their initial data formats.
[ "Restore", "bytes", "data", "to", "their", "initial", "data", "formats." ]
def loads_argument(data): try: ret = deserialize(data) except Exception as e: raise DeserializeError(e) return ret
['def', 'loads_argument(data):', 'try:', 'ret', '=', 'deserialize(data)', 'except', 'Exception', 'as', 'e:', 'raise', 'DeserializeError(e)', 'return', 'ret']
278,089
rudranil723/mini-main
defaultfilters.py
ljust
ljust
Left-align the value in a field of a given width.
[ "Left-align", "the", "value", "in", "a", "field", "of", "a", "given", "width." ]
def ljust(value, arg): return value.ljust(int(arg))
['def', 'ljust(value,', 'arg):', 'return', 'value.ljust(int(arg))']
316,407
devashish-patel/webcam-motion-detector
security.py
persist_config
persist_config
Context manager that can be used to modify a config object On exit of the context manager, the config will be written back to disk, by default with user-only (600) permissions.
[ "Context", "manager", "that", "can", "be", "used", "to", "modify", "a", "config", "object", "On", "exit", "of", "the", "context", "manager,", "the", "config", "will", "be", "written", "back", "to", "disk,", "by", "default", "with", "user-only", "(600)", "p...
def persist_config(config_file=None, mode=384): if config_file is None: config_file = os.path.join(jupyter_config_dir(), 'jupyter_notebook_config.json') loader = JSONFileConfigLoader(os.path.basename(config_file), os.path.dirname(config_file)) try: config = loader.load_config() except Co...
['def', 'persist_config(config_file=None,', 'mode=384):', 'if', 'config_file', 'is', 'None:', 'config_file', '=', 'os.path.join(jupyter_config_dir(),', "'jupyter_notebook_config.json')", 'loader', '=', 'JSONFileConfigLoader(os.path.basename(config_file),', 'os.path.dirname(config_file))', 'try:', 'config', '=', 'loader...
980,624
carranza96/cnn-landcover
CNNModel_2D.py
bias_variable
bias_variable
bias_variable generates a bias variable of a given shape.
[ "bias_variable", "generates", "a", "bias", "variable", "of", "a", "given", "shape." ]
def bias_variable(shape): return tf.Variable(tf.constant(0.1, shape=shape), name='B')
['def', 'bias_variable(shape):', 'return', 'tf.Variable(tf.constant(0.1,', 'shape=shape),', "name='B')"]
123,623
greydanus/mr_london
datastructures.py
Headers.popitem
popitem
Removes a key or index and returns a (key, value) item.
[ "Removes", "a", "key", "or", "index", "and", "returns", "a", "(key,", "value)", "item." ]
def popitem(self): return self.pop()
['def', 'popitem(self):', 'return', 'self.pop()']
264,009
pasus/Reinforcement-Learning-Book
gmm.py
GMM.estep
estep
Compute log observation probabilities under GMM.
[ "Compute", "log", "observation", "probabilities", "under", "GMM." ]
def estep(self, data): (N, D) = data.shape K = self.sigma.shape[0] logobs = -0.5 * np.ones((N, K)) * D * np.log(2 * np.pi) for i in range(K): (mu, sigma) = (self.mu[i], self.sigma[i]) L = scipy.linalg.cholesky(sigma, lower=True) logobs[:, i] -= np.sum(np.log(np.diag(L))) ...
['def', 'estep(self,', 'data):', '(N,', 'D)', '=', 'data.shape', 'K', '=', 'self.sigma.shape[0]', 'logobs', '=', '-0.5', '*', 'np.ones((N,', 'K))', '*', 'D', '*', 'np.log(2', '*', 'np.pi)', 'for', 'i', 'in', 'range(K):', '(mu,', 'sigma)', '=', '(self.mu[i],', 'self.sigma[i])', 'L', '=', 'scipy.linalg.cholesky(sigma,', ...
340,732
liang-hou/slimgan
cgan_pd_128.py
CGANPDGenerator128.forward
forward
Feedforwards a batch of noise vectors into a batch of fake images, also conditioning the batch norm with labels of the images to be produced.
[ "Feedforwards", "a", "batch", "of", "noise", "vectors", "into", "a", "batch", "of", "fake", "images,", "also", "conditioning", "the", "batch", "norm", "with", "labels", "of", "the", "images", "to", "be", "produced." ]
def forward(self, x, y=None): if y is None: y = torch.randint(low=0, high=self.num_classes, size=(x.shape[0],), device=x.device) h = self.l1(x) h = h.view(x.shape[0], -1, self.bottom_width, self.bottom_width) h = self.block2(h, y) h = self.block3(h, y) h = self.block4(h, y) h = self....
['def', 'forward(self,', 'x,', 'y=None):', 'if', 'y', 'is', 'None:', 'y', '=', 'torch.randint(low=0,', 'high=self.num_classes,', 'size=(x.shape[0],),', 'device=x.device)', 'h', '=', 'self.l1(x)', 'h', '=', 'h.view(x.shape[0],', '-1,', 'self.bottom_width,', 'self.bottom_width)', 'h', '=', 'self.block2(h,', 'y)', 'h', '=...
878,289
rudranil723/mini-main
edit.py
FormMixin.get_form_kwargs
get_form_kwargs
Return the keyword arguments for instantiating the form.
[ "Return", "the", "keyword", "arguments", "for", "instantiating", "the", "form." ]
def get_form_kwargs(self): kwargs = {'initial': self.get_initial(), 'prefix': self.get_prefix()} if self.request.method in ('POST', 'PUT'): kwargs.update({'data': self.request.POST, 'files': self.request.FILES}) return kwargs
['def', 'get_form_kwargs(self):', 'kwargs', '=', "{'initial':", 'self.get_initial(),', "'prefix':", 'self.get_prefix()}', 'if', 'self.request.method', 'in', "('POST',", "'PUT'):", "kwargs.update({'data':", 'self.request.POST,', "'files':", 'self.request.FILES})', 'return', 'kwargs']
316,915
pathak22/noreward-rl
demo.py
inference
inference
It restore policy weights, and does inference.
[ "It", "restore", "policy", "weights,", "and", "does", "inference." ]
def inference(args): env = create_env(args.env_id, client_id='0', remotes=None, envWrap=True, acRepeat=1, record=args.record, outdir=args.outdir) numaction = env.action_space.n with tf.device('/cpu:0'): config = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False) with tf.Se...
['def', 'inference(args):', 'env', '=', 'create_env(args.env_id,', "client_id='0',", 'remotes=None,', 'envWrap=True,', 'acRepeat=1,', 'record=args.record,', 'outdir=args.outdir)', 'numaction', '=', 'env.action_space.n', 'with', "tf.device('/cpu:0'):", 'config', '=', 'tf.ConfigProto(allow_soft_placement=True,', 'log_dev...
249,507
aeon-toolkit/aeon
test_general.py
test_z_normalise_series
test_z_normalise_series
Test the function z_normalise_series.
[ "Test", "the", "function", "z_normalise_series." ]
def test_z_normalise_series(type): a = np.array([2, 2, 2], dtype=type) a_expected = np.array([0, 0, 0], dtype=type) a_result = z_normalise_series(a) assert_array_equal(a_result, a_expected)
['def', 'test_z_normalise_series(type):', 'a', '=', 'np.array([2,', '2,', '2],', 'dtype=type)', 'a_expected', '=', 'np.array([0,', '0,', '0],', 'dtype=type)', 'a_result', '=', 'z_normalise_series(a)', 'assert_array_equal(a_result,', 'a_expected)']
400,213
nicknochnack/RealTimeSignLanguageTFJS
spatial_transform_ops.py
crop_mask_in_target_box
crop_mask_in_target_box
Crop masks in target boxes.
[ "Crop", "masks", "in", "target", "boxes." ]
def crop_mask_in_target_box(masks, boxes, target_boxes, output_size, sample_offset=0, use_einsum=True): with tf.name_scope('crop_mask_in_target_box'): (batch_size, num_masks, height, width) = masks.get_shape().as_list() if batch_size is None: batch_size = tf.shape(masks)[0] masks...
['def', 'crop_mask_in_target_box(masks,', 'boxes,', 'target_boxes,', 'output_size,', 'sample_offset=0,', 'use_einsum=True):', 'with', "tf.name_scope('crop_mask_in_target_box'):", '(batch_size,', 'num_masks,', 'height,', 'width)', '=', 'masks.get_shape().as_list()', 'if', 'batch_size', 'is', 'None:', 'batch_size', '=', ...
850,903
google-research/scenic
detr_sinkhorn_config.py
get_config
get_config
Returns the configuration for COCO detection using DETR.
[ "Returns", "the", "configuration", "for", "COCO", "detection", "using", "DETR." ]
def get_config(): config = ml_collections.ConfigDict() config.experiment_name = 'coco_detection_detr' config.dataset_name = 'coco_detr_detection' config.dataset_configs = ml_collections.ConfigDict() config.dataset_configs.prefetch_to_device = 2 config.dataset_configs.shuffle_buffer_size = 10000 ...
['def', 'get_config():', 'config', '=', 'ml_collections.ConfigDict()', 'config.experiment_name', '=', "'coco_detection_detr'", 'config.dataset_name', '=', "'coco_detr_detection'", 'config.dataset_configs', '=', 'ml_collections.ConfigDict()', 'config.dataset_configs.prefetch_to_device', '=', '2', 'config.dataset_configs...
846,665
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
_bootstrap.py
module_from_spec
module_from_spec
Create a module based on the provided spec.
[ "Create", "a", "module", "based", "on", "the", "provided", "spec." ]
def module_from_spec(spec): module = None if hasattr(spec.loader, 'create_module'): module = spec.loader.create_module(spec) elif hasattr(spec.loader, 'exec_module'): _warnings.warn('starting in Python 3.6, loaders defining exec_module() must also define create_module()', DeprecationWarning,...
['def', 'module_from_spec(spec):', 'module', '=', 'None', 'if', 'hasattr(spec.loader,', "'create_module'):", 'module', '=', 'spec.loader.create_module(spec)', 'elif', 'hasattr(spec.loader,', "'exec_module'):", "_warnings.warn('starting", 'in', 'Python', '3.6,', 'loaders', 'defining', 'exec_module()', 'must', 'also', 'd...
430,990
openvinotoolkit/training_extensions
create_mvtec_ad_json_annotations.py
create_polygons_from_mask
create_polygons_from_mask
Create polygons from binary mask.
[ "Create", "polygons", "from", "binary", "mask." ]
def create_polygons_from_mask(mask_path: str) -> List[List[List[float]]]: mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE) (height, width) = mask.shape polygons = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[0] polygons = [[[point[0][0] / width, point[0][1] / height] for point in pol...
['def', 'create_polygons_from_mask(mask_path:', 'str)', '->', 'List[List[List[float]]]:', 'mask', '=', 'cv2.imread(mask_path,', 'cv2.IMREAD_GRAYSCALE)', '(height,', 'width)', '=', 'mask.shape', 'polygons', '=', 'cv2.findContours(mask,', 'cv2.RETR_TREE,', 'cv2.CHAIN_APPROX_SIMPLE)[0]', 'polygons', '=', '[[[point[0][0]',...
903,916
zichunhao/lgn-autoencoder
cg_dict.py
CGDict.transpose
transpose
Use "transposed" version of CG coefficients.
[ "Use", "\"transposed\"", "version", "of", "CG", "coefficients." ]
def transpose(self): return self._transpose
['def', 'transpose(self):', 'return', 'self._transpose']
600,191
Kvatsx/Artificial-Intelligence-Assignments
_tifffile.py
TiffPage.is_fei
is_fei
Page contains SFEG or HELIOS metadata.
[ "Page", "contains", "SFEG", "or", "HELIOS", "metadata." ]
def is_fei(self): return 'FEI_SFEG' in self.tags or 'FEI_HELIOS' in self.tags
['def', 'is_fei(self):', 'return', "'FEI_SFEG'", 'in', 'self.tags', 'or', "'FEI_HELIOS'", 'in', 'self.tags']
37,631
nancheng58/Self-supervised-learning-for-Sequential-Recommender-Systems
collector.py
Collector.data_collect
data_collect
Collect the evaluation resource from training data.
[ "Collect", "the", "evaluation", "resource", "from", "training", "data." ]
def data_collect(self, train_data): if self.register.need('data.num_items'): item_id = self.config['ITEM_ID_FIELD'] self.data_struct.set('data.num_items', train_data.dataset.num(item_id)) if self.register.need('data.num_users'): user_id = self.config['USER_ID_FIELD'] self.data_st...
['def', 'data_collect(self,', 'train_data):', 'if', "self.register.need('data.num_items'):", 'item_id', '=', "self.config['ITEM_ID_FIELD']", "self.data_struct.set('data.num_items',", 'train_data.dataset.num(item_id))', 'if', "self.register.need('data.num_users'):", 'user_id', '=', "self.config['USER_ID_FIELD']", "self....
341,840
sintel-dev/Orion
point.py
point_accuracy
point_accuracy
Compute an accuracy score between the ground truth and the detected anomalies.
[ "Compute", "an", "accuracy", "score", "between", "the", "ground", "truth", "and", "the", "detected", "anomalies." ]
def point_accuracy(expected, observed, data=None, start=None, end=None): return _accuracy(expected, observed, data, start, end, cm=point_confusion_matrix)
['def', 'point_accuracy(expected,', 'observed,', 'data=None,', 'start=None,', 'end=None):', 'return', '_accuracy(expected,', 'observed,', 'data,', 'start,', 'end,', 'cm=point_confusion_matrix)']
776,635
rudranil723/mini-main
test_texmanager.py
test_fontconfig_preamble
test_fontconfig_preamble
Test that the preamble is included in the source.
[ "Test", "that", "the", "preamble", "is", "included", "in", "the", "source." ]
def test_fontconfig_preamble(): plt.rcParams['text.usetex'] = True src1 = TexManager()._get_tex_source('', fontsize=12) plt.rcParams['text.latex.preamble'] = '\\usepackage{txfonts}' src2 = TexManager()._get_tex_source('', fontsize=12) assert src1 != src2
['def', 'test_fontconfig_preamble():', "plt.rcParams['text.usetex']", '=', 'True', 'src1', '=', "TexManager()._get_tex_source('',", 'fontsize=12)', "plt.rcParams['text.latex.preamble']", '=', "'\\\\usepackage{txfonts}'", 'src2', '=', "TexManager()._get_tex_source('',", 'fontsize=12)', 'assert', 'src1', '!=', 'src2']
320,330
Farama-Foundation/Gymnasium-Robotics
mujoco_multi.py
MultiAgentMujocoEnv.reset
reset
Resets the the `single_agent_env`.
[ "Resets", "the", "the", "`single_agent_env`." ]
def reset(self, seed: int | None=None, options=None): (_, info_n) = self.single_agent_env.reset(seed=seed) info = {} for agent in self.possible_agents: info[agent] = info_n self.agents = self.possible_agents return (self._get_obs(), info)
['def', 'reset(self,', 'seed:', 'int', '|', 'None=None,', 'options=None):', '(_,', 'info_n)', '=', 'self.single_agent_env.reset(seed=seed)', 'info', '=', '{}', 'for', 'agent', 'in', 'self.possible_agents:', 'info[agent]', '=', 'info_n', 'self.agents', '=', 'self.possible_agents', 'return', '(self._get_obs(),', 'info)']
573,734
sklearn-theano/sklearn-theano
descriptor_pool.py
DescriptorPool.Add
Add
Adds the FileDescriptorProto and its types to this pool.
[ "Adds", "the", "FileDescriptorProto", "and", "its", "types", "to", "this", "pool." ]
def Add(self, file_desc_proto): self._internal_db.Add(file_desc_proto)
['def', 'Add(self,', 'file_desc_proto):', 'self._internal_db.Add(file_desc_proto)']
351,056
facebookresearch/fvcore
transform.py
Transform.register_type
register_type
Register the given function as a handler that this transform will use for a specific data type.
[ "Register", "the", "given", "function", "as", "a", "handler", "that", "this", "transform", "will", "use", "for", "a", "specific", "data", "type." ]
def register_type(cls, data_type: str, func: Optional[Callable]=None): if func is None: def wrapper(decorated_func): assert decorated_func is not None cls.register_type(data_type, decorated_func) return decorated_func return wrapper assert callable(func), 'Yo...
['def', 'register_type(cls,', 'data_type:', 'str,', 'func:', 'Optional[Callable]=None):', 'if', 'func', 'is', 'None:', 'def', 'wrapper(decorated_func):', 'assert', 'decorated_func', 'is', 'not', 'None', 'cls.register_type(data_type,', 'decorated_func)', 'return', 'decorated_func', 'return', 'wrapper', 'assert', 'callab...
565,930
rudranil723/mini-main
axis.py
Axis.get_minor_locator
get_minor_locator
Get the locator of the minor ticker.
[ "Get", "the", "locator", "of", "the", "minor", "ticker." ]
def get_minor_locator(self): return self.minor.locator
['def', 'get_minor_locator(self):', 'return', 'self.minor.locator']
319,029
deepmind/acme
base.py
ReverbAdder.add
add
Record an action and the following timestep.
[ "Record", "an", "action", "and", "the", "following", "timestep." ]
def add(self, action: types.NestedArray, next_timestep: dm_env.TimeStep, extras: types.NestedArray=()): if not self._add_first_called: raise ValueError('adder.add_first must be called before adder.add.') has_extras = len(extras) > 0 if isinstance(extras, Sized) else extras is not None current_step =...
['def', 'add(self,', 'action:', 'types.NestedArray,', 'next_timestep:', 'dm_env.TimeStep,', 'extras:', 'types.NestedArray=()):', 'if', 'not', 'self._add_first_called:', 'raise', "ValueError('adder.add_first", 'must', 'be', 'called', 'before', "adder.add.')", 'has_extras', '=', 'len(extras)', '>', '0', 'if', 'isinstance...
8,021
autonlab/weasel
VGG.py
VGG.get_decision_thresh
get_decision_thresh
Get the model's decision threshold for hard predictions in binary classification.
[ "Get", "the", "model's", "decision", "threshold", "for", "hard", "predictions", "in", "binary", "classification." ]
def get_decision_thresh(self) -> Optional[float]: return self.classifier.get_decision_thresh()
['def', 'get_decision_thresh(self)', '->', 'Optional[float]:', 'return', 'self.classifier.get_decision_thresh()']
373,375
jingjingli01/TGLS
inputter.py
collect_features
collect_features
Collect features from Field object.
[ "Collect", "features", "from", "Field", "object." ]
def collect_features(fields, side='src'): assert side in ['src', 'tgt'] feats = [] for j in count(): key = side + '_feat_' + str(j) if key not in fields: break feats.append(key) return feats
['def', 'collect_features(fields,', "side='src'):", 'assert', 'side', 'in', "['src',", "'tgt']", 'feats', '=', '[]', 'for', 'j', 'in', 'count():', 'key', '=', 'side', '+', "'_feat_'", '+', 'str(j)', 'if', 'key', 'not', 'in', 'fields:', 'break', 'feats.append(key)', 'return', 'feats']
367,276
eddylau328/fyp-artificial-intelligence-ac-control-device
client_info.py
ClientInfo.to_grpc_metadata
to_grpc_metadata
Returns the gRPC metadata for this client info.
[ "Returns", "the", "gRPC", "metadata", "for", "this", "client", "info." ]
def to_grpc_metadata(self): return (METRICS_METADATA_KEY, self.to_user_agent())
['def', 'to_grpc_metadata(self):', 'return', '(METRICS_METADATA_KEY,', 'self.to_user_agent())']
214,519
eliben/deep-learning-samples
assign6.py
characters
characters
Turn a 1-hot encoding or a probability distribution over the possible characters back into its (most likely) character representation.
[ "Turn", "a", "1-hot", "encoding", "or", "a", "probability", "distribution", "over", "the", "possible", "characters", "back", "into", "its", "(most", "likely)", "character", "representation." ]
def characters(probabilities): return [id2char(c) for c in np.argmax(probabilities, 1)]
['def', 'characters(probabilities):', 'return', '[id2char(c)', 'for', 'c', 'in', 'np.argmax(probabilities,', '1)]']
519,048
utiasASRL/hero_radar_odometry
monitor.py
SteamMonitor.vis
vis
Visualizes the output from a single batch.
[ "Visualizes", "the", "output", "from", "a", "single", "batch." ]
def vis(self, batchi, batch, out): (score_img, match_img, error_img) = draw_batch_steam(batch, out, self.config) self.writer.add_image('val/score_img/{}'.format(batchi), score_img, global_step=self.counter) self.writer.add_image('val/match_img/{}'.format(batchi), match_img, global_step=self.counter) sel...
['def', 'vis(self,', 'batchi,', 'batch,', 'out):', '(score_img,', 'match_img,', 'error_img)', '=', 'draw_batch_steam(batch,', 'out,', 'self.config)', "self.writer.add_image('val/score_img/{}'.format(batchi),", 'score_img,', 'global_step=self.counter)', "self.writer.add_image('val/match_img/{}'.format(batchi),", 'match_...
205,952
tensorflow/quantum
controlled_pqc_test.py
ControlledPQCTest.test_controlled_pqc_noisy_error
test_controlled_pqc_noisy_error
Ensure error refers to alternate layer.
[ "Ensure", "error", "refers", "to", "alternate", "layer." ]
def test_controlled_pqc_noisy_error(self): symbol = sympy.Symbol('alpha') qubit = cirq.GridQubit(0, 0) learnable_flip = cirq.Circuit(cirq.X(qubit) ** symbol) with self.assertRaisesRegex(ValueError, expected_regex='tfq.layers.NoisyControlledPQC'): controlled_pqc.ControlledPQC(learnable_flip, cirq...
['def', 'test_controlled_pqc_noisy_error(self):', 'symbol', '=', "sympy.Symbol('alpha')", 'qubit', '=', 'cirq.GridQubit(0,', '0)', 'learnable_flip', '=', 'cirq.Circuit(cirq.X(qubit)', '**', 'symbol)', 'with', 'self.assertRaisesRegex(ValueError,', "expected_regex='tfq.layers.NoisyControlledPQC'):", 'controlled_pqc.Contr...
835,381
Ikomia-dev/IkomiaApi
workflow.py
Workflow.root
root
Get workflow root node.
[ "Get", "workflow", "root", "node." ]
def root(self): return self.get_task(self.get_root_id())
['def', 'root(self):', 'return', 'self.get_task(self.get_root_id())']
598,681
sktime/sktime
test_conformal.py
test_conformal_with_gscv
test_conformal_with_gscv
With ForecastingGridSearchCV and parameter plugin.
[ "With", "ForecastingGridSearchCV", "and", "parameter", "plugin." ]
def test_conformal_with_gscv(): from sktime.forecasting.model_selection import ForecastingGridSearchCV from sktime.param_est.plugin import PluginParamsForecaster from sktime.split import ExpandingWindowSplitter y = load_airline() cv = ExpandingWindowSplitter(fh=[1, 2, 3]) forecaster = NaiveForec...
['def', 'test_conformal_with_gscv():', 'from', 'sktime.forecasting.model_selection', 'import', 'ForecastingGridSearchCV', 'from', 'sktime.param_est.plugin', 'import', 'PluginParamsForecaster', 'from', 'sktime.split', 'import', 'ExpandingWindowSplitter', 'y', '=', 'load_airline()', 'cv', '=', 'ExpandingWindowSplitter(fh...
877,308
nicknochnack/RealTimeSignLanguageTFJS
pnasnet.py
build_pnasnet_mobile
build_pnasnet_mobile
Build PNASNet Mobile model for the ImageNet Dataset.
[ "Build", "PNASNet", "Mobile", "model", "for", "the", "ImageNet", "Dataset." ]
def build_pnasnet_mobile(images, num_classes, is_training=True, final_endpoint=None, config=None): hparams = copy.deepcopy(config) if config else mobile_imagenet_config() nasnet._update_hparams(hparams, is_training) if tf.test.is_gpu_available() and hparams.data_format == 'NHWC': tf.logging.info('A ...
['def', 'build_pnasnet_mobile(images,', 'num_classes,', 'is_training=True,', 'final_endpoint=None,', 'config=None):', 'hparams', '=', 'copy.deepcopy(config)', 'if', 'config', 'else', 'mobile_imagenet_config()', 'nasnet._update_hparams(hparams,', 'is_training)', 'if', 'tf.test.is_gpu_available()', 'and', 'hparams.data_f...
831,343
suhaspillai/HandwritingRecognition-with-MultiDimensional
lstm_net_cythonic.py
LSTM_net_cythonic.MDLSTM_lstm_conv_feed_layer_backward
MDLSTM_lstm_conv_feed_layer_backward
The method is used for backpropagation of MDLSTM and Convolutional subsampling layers.
[ "The", "method", "is", "used", "for", "backpropagation", "of", "MDLSTM", "and", "Convolutional", "subsampling", "layers." ]
def MDLSTM_lstm_conv_feed_layer_backward(self, dscores, cache): lstm_layer_obj = Layer() (cache_lstm_frwd, cache_lstm_bckd, cache_lstm_frwd_flip, cache_lstm_bckd_flip, cache_conv_frwd, cache_conv_bckd, cache_conv_frwd_flip, cache_conv_bckd_flip, dout_conv_frwd) = cache (N, C, W, H) = dout_conv_frwd.shape ...
['def', 'MDLSTM_lstm_conv_feed_layer_backward(self,', 'dscores,', 'cache):', 'lstm_layer_obj', '=', 'Layer()', '(cache_lstm_frwd,', 'cache_lstm_bckd,', 'cache_lstm_frwd_flip,', 'cache_lstm_bckd_flip,', 'cache_conv_frwd,', 'cache_conv_bckd,', 'cache_conv_frwd_flip,', 'cache_conv_bckd_flip,', 'dout_conv_frwd)', '=', 'cac...
205,423
aisingapore/PeekingDuck
track.py
BaseTrack.mark_lost
mark_lost
Marks the Track as lost.
[ "Marks", "the", "Track", "as", "lost." ]
def mark_lost(self) -> None: self.state = TrackState.LOST
['def', 'mark_lost(self)', '->', 'None:', 'self.state', '=', 'TrackState.LOST']
766,967
weimin17/Object-Detection_HelmetDetection
rdp_bucketized.py
compute_expected_answered_per_bin
compute_expected_answered_per_bin
Computes expected number of answers per bin.
[ "Computes", "expected", "number", "of", "answers", "per", "bin." ]
def compute_expected_answered_per_bin(bin_num, votes, threshold, sigma1): n = votes.shape[0] bin_answered = np.zeros(bin_num) for i in xrange(n): v = votes[i,] p = math.exp(pate.compute_logpr_answered(threshold, sigma1, v)) bin_idx = int(math.floor(max(v) * bin_num / sum(v))) ...
['def', 'compute_expected_answered_per_bin(bin_num,', 'votes,', 'threshold,', 'sigma1):', 'n', '=', 'votes.shape[0]', 'bin_answered', '=', 'np.zeros(bin_num)', 'for', 'i', 'in', 'xrange(n):', 'v', '=', 'votes[i,]', 'p', '=', 'math.exp(pate.compute_logpr_answered(threshold,', 'sigma1,', 'v))', 'bin_idx', '=', 'int(math....
749,806
Yuting-Gao/DisCo-pytorch
gluon_resnet.py
gluon_senet154
gluon_senet154
Constructs an SENet-154 model.
[ "Constructs", "an", "SENet-154", "model." ]
def gluon_senet154(pretrained=False, **kwargs): model_args = dict(block=Bottleneck, layers=[3, 8, 36, 3], cardinality=64, base_width=4, stem_type='deep', down_kernel_size=3, block_reduce_first=2, block_args=dict(attn_layer=SEModule), **kwargs) return _create_resnet('gluon_senet154', pretrained, **model_args)
['def', 'gluon_senet154(pretrained=False,', '**kwargs):', 'model_args', '=', 'dict(block=Bottleneck,', 'layers=[3,', '8,', '36,', '3],', 'cardinality=64,', 'base_width=4,', "stem_type='deep',", 'down_kernel_size=3,', 'block_reduce_first=2,', 'block_args=dict(attn_layer=SEModule),', '**kwargs)', 'return', "_create_resne...
187,400
opendilab/DI-star
lib.py
RunConfig.map_data
map_data
Return the map data for a map by name or path.
[ "Return", "the", "map", "data", "for", "a", "map", "by", "name", "or", "path." ]
def map_data(self, map_name, players=None): map_names = [map_name] if players: map_names.append(os.path.join(os.path.dirname(map_name), '(%s)%s' % (players, os.path.basename(map_name)))) for name in map_names: path = os.path.join(self.data_dir, 'Maps', name) if gfile.Exists(path): ...
['def', 'map_data(self,', 'map_name,', 'players=None):', 'map_names', '=', '[map_name]', 'if', 'players:', 'map_names.append(os.path.join(os.path.dirname(map_name),', "'(%s)%s'", '%', '(players,', 'os.path.basename(map_name))))', 'for', 'name', 'in', 'map_names:', 'path', '=', 'os.path.join(self.data_dir,', "'Maps',", ...
184,815
dibyaghosh/gcsl
mjpy_sim_scene.py
MjPySimScene.get_mjlib
get_mjlib
Returns an interface to the low-level MuJoCo API.
[ "Returns", "an", "interface", "to", "the", "low-level", "MuJoCo", "API." ]
def get_mjlib(self) -> Any: return _MjlibWrapper(mujoco_py.cymj)
['def', 'get_mjlib(self)', '->', 'Any:', 'return', '_MjlibWrapper(mujoco_py.cymj)']
202,026
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
test_venv.py
BasicTest.test_overwrite_existing
test_overwrite_existing
Test creating environment in an existing directory.
[ "Test", "creating", "environment", "in", "an", "existing", "directory." ]
def test_overwrite_existing(self): self.create_contents(self.ENV_SUBDIRS, 'foo') venv.create(self.env_dir) for subdirs in self.ENV_SUBDIRS: fn = os.path.join(self.env_dir, *subdirs + ('foo',)) self.assertTrue(os.path.exists(fn)) with open(fn, 'rb') as f: self.assertEqual(...
['def', 'test_overwrite_existing(self):', 'self.create_contents(self.ENV_SUBDIRS,', "'foo')", 'venv.create(self.env_dir)', 'for', 'subdirs', 'in', 'self.ENV_SUBDIRS:', 'fn', '=', 'os.path.join(self.env_dir,', '*subdirs', '+', "('foo',))", 'self.assertTrue(os.path.exists(fn))', 'with', 'open(fn,', "'rb')", 'as', 'f:', '...
376,467
tinyvision/DAMO-YOLO
base.py
parse_config
parse_config
get config object by file.
[ "get", "config", "object", "by", "file." ]
def parse_config(config_file): assert config_file is not None, 'plz provide config file' if config_file is not None: return get_config_by_file(config_file)
['def', 'parse_config(config_file):', 'assert', 'config_file', 'is', 'not', 'None,', "'plz", 'provide', 'config', "file'", 'if', 'config_file', 'is', 'not', 'None:', 'return', 'get_config_by_file(config_file)']
496,979
PacktPublishing/Hands-On-Artificial--for-Banking
gradient_boosting.py
VerboseReporter.update
update
Update reporter with new iteration.
[ "Update", "reporter", "with", "new", "iteration." ]
def update(self, j, est): do_oob = est.subsample < 1 i = j - self.begin_at_stage if (i + 1) % self.verbose_mod == 0: oob_impr = est.oob_improvement_[j] if do_oob else 0 remaining_time = (est.n_estimators - (j + 1)) * (time() - self.start_time) / float(i + 1) if remaining_time > 60: ...
['def', 'update(self,', 'j,', 'est):', 'do_oob', '=', 'est.subsample', '<', '1', 'i', '=', 'j', '-', 'self.begin_at_stage', 'if', '(i', '+', '1)', '%', 'self.verbose_mod', '==', '0:', 'oob_impr', '=', 'est.oob_improvement_[j]', 'if', 'do_oob', 'else', '0', 'remaining_time', '=', '(est.n_estimators', '-', '(j', '+', '1)...
204,173
tobegit3hub/deep_image_model
gmm.py
GMM.predict
predict
Predict cluster id for each element in x.
[ "Predict", "cluster", "id", "for", "each", "element", "in", "x." ]
def predict(self, x, batch_size=None): return np.array([prediction[GMM.ASSIGNMENTS] for prediction in super(GMM, self).predict(x=x, batch_size=batch_size, as_iterable=True)])
['def', 'predict(self,', 'x,', 'batch_size=None):', 'return', 'np.array([prediction[GMM.ASSIGNMENTS]', 'for', 'prediction', 'in', 'super(GMM,', 'self).predict(x=x,', 'batch_size=batch_size,', 'as_iterable=True)])']
181,266
triaquae/triaquae
geometry.py
GEOSGeometry.relate_pattern
relate_pattern
Returns true if the elements in the DE-9IM intersection matrix for the two Geometries match the elements in pattern.
[ "Returns", "true", "if", "the", "elements", "in", "the", "DE-9IM", "intersection", "matrix", "for", "the", "two", "Geometries", "match", "the", "elements", "in", "pattern." ]
def relate_pattern(self, other, pattern): if not isinstance(pattern, six.string_types) or len(pattern) > 9: raise GEOSException('invalid intersection matrix pattern') return capi.geos_relatepattern(self.ptr, other.ptr, force_bytes(pattern))
['def', 'relate_pattern(self,', 'other,', 'pattern):', 'if', 'not', 'isinstance(pattern,', 'six.string_types)', 'or', 'len(pattern)', '>', '9:', 'raise', "GEOSException('invalid", 'intersection', 'matrix', "pattern')", 'return', 'capi.geos_relatepattern(self.ptr,', 'other.ptr,', 'force_bytes(pattern))']
357,781
myothida/Supervised-Machine-Learning
test_plot.py
test_learning_curve_display_score_type
test_learning_curve_display_score_type
Check the behaviour of setting the `score_type` parameter.
[ "Check", "the", "behaviour", "of", "setting", "the", "`score_type`", "parameter." ]
def test_learning_curve_display_score_type(pyplot, data, std_display_style): (X, y) = data estimator = DecisionTreeClassifier(random_state=0) train_sizes = [0.3, 0.6, 0.9] (train_sizes_abs, train_scores, test_scores) = learning_curve(estimator, X, y, train_sizes=train_sizes) score_type = 'train' ...
['def', 'test_learning_curve_display_score_type(pyplot,', 'data,', 'std_display_style):', '(X,', 'y)', '=', 'data', 'estimator', '=', 'DecisionTreeClassifier(random_state=0)', 'train_sizes', '=', '[0.3,', '0.6,', '0.9]', '(train_sizes_abs,', 'train_scores,', 'test_scores)', '=', 'learning_curve(estimator,', 'X,', 'y,',...
364,354
edwardlib/observations
util.py
get_file_size
get_file_size
Get file size from a given URL in bytes.
[ "Get", "file", "size", "from", "a", "given", "URL", "in", "bytes." ]
def get_file_size(url, params, timeout=10): try: response = requests.get(url, params={}, stream=True) except requests.exceptions.HTTPError as e: print(e) return 0 try: file_size = int(response.headers['Content-Length']) except (IndexError, KeyError, TypeError): re...
['def', 'get_file_size(url,', 'params,', 'timeout=10):', 'try:', 'response', '=', 'requests.get(url,', 'params={},', 'stream=True)', 'except', 'requests.exceptions.HTTPError', 'as', 'e:', 'print(e)', 'return', '0', 'try:', 'file_size', '=', "int(response.headers['Content-Length'])", 'except', '(IndexError,', 'KeyError,...
740,018
dustin/twitty-twister
test_streaming.py
TwitterStreamTest.test_badJSON
test_badJSON
Datagrams with invalid JSON are logged and ignored.
[ "Datagrams", "with", "invalid", "JSON", "are", "logged", "and", "ignored." ]
def test_badJSON(self): data = 'blah\n\r' self.protocol.datagramReceived(data) self.assertEquals(0, len(self.objects)) loggedErrors = self.flushLoggedErrors(ValueError) self.assertEquals(1, len(loggedErrors))
['def', 'test_badJSON(self):', 'data', '=', "'blah\\n\\r'", 'self.protocol.datagramReceived(data)', 'self.assertEquals(0,', 'len(self.objects))', 'loggedErrors', '=', 'self.flushLoggedErrors(ValueError)', 'self.assertEquals(1,', 'len(loggedErrors))']
426,492
devashish-patel/webcam-motion-detector
lexers.py
PygmentsLexer.from_filename
from_filename
Create a `Lexer` from a filename.
[ "Create", "a", "`Lexer`", "from", "a", "filename." ]
def from_filename(cls, filename, sync_from_start=True): from pygments.util import ClassNotFound from pygments.lexers import get_lexer_for_filename try: pygments_lexer = get_lexer_for_filename(filename) except ClassNotFound: return SimpleLexer() else: return cls(pygments_lexer...
['def', 'from_filename(cls,', 'filename,', 'sync_from_start=True):', 'from', 'pygments.util', 'import', 'ClassNotFound', 'from', 'pygments.lexers', 'import', 'get_lexer_for_filename', 'try:', 'pygments_lexer', '=', 'get_lexer_for_filename(filename)', 'except', 'ClassNotFound:', 'return', 'SimpleLexer()', 'else:', 'retu...
984,018
deepmind/dm_control
control.py
Environment.reset
reset
Starts a new episode and returns the first `TimeStep`.
[ "Starts", "a", "new", "episode", "and", "returns", "the", "first", "`TimeStep`." ]
def reset(self): self._reset_next_step = False self._step_count = 0 with self._physics.reset_context(): self._task.initialize_episode(self._physics) observation = self._task.get_observation(self._physics) if self._flat_observation: observation = flatten_observation(observation) r...
['def', 'reset(self):', 'self._reset_next_step', '=', 'False', 'self._step_count', '=', '0', 'with', 'self._physics.reset_context():', 'self._task.initialize_episode(self._physics)', 'observation', '=', 'self._task.get_observation(self._physics)', 'if', 'self._flat_observation:', 'observation', '=', 'flatten_observatio...
165,344
enlite-ai/maze
torch_model.py
TorchModel.num_params
num_params
Returns overall number of network parameters.
[ "Returns", "overall", "number", "of", "network", "parameters." ]
def num_params(self) -> int: return sum((t.numel() for t in self.parameters()))
['def', 'num_params(self)', '->', 'int:', 'return', 'sum((t.numel()', 'for', 't', 'in', 'self.parameters()))']
646,525
google/ml-compiler-opt
data_reader.py
create_sequence_example_dataset_fn
create_sequence_example_dataset_fn
Get a function that creates a dataset from serialized sequence examples.
[ "Get", "a", "function", "that", "creates", "a", "dataset", "from", "serialized", "sequence", "examples." ]
def create_sequence_example_dataset_fn(agent_cfg: agent_config.AgentConfig, batch_size: int, train_sequence_length: int) -> Callable[[List[str]], tf.data.Dataset]: trajectory_shuffle_buffer_size = 1024 flat_sequence_example_dataset_fn = create_flat_sequence_example_dataset_fn(agent_cfg) def _sequence_examp...
['def', 'create_sequence_example_dataset_fn(agent_cfg:', 'agent_config.AgentConfig,', 'batch_size:', 'int,', 'train_sequence_length:', 'int)', '->', 'Callable[[List[str]],', 'tf.data.Dataset]:', 'trajectory_shuffle_buffer_size', '=', '1024', 'flat_sequence_example_dataset_fn', '=', 'create_flat_sequence_example_dataset...
671,193
calico/basenji
seqnn.py
SeqNN.gradients
gradients
Compute input gradients for sequences (GPU-friendly).
[ "Compute", "input", "gradients", "for", "sequences", "(GPU-friendly)." ]
def gradients(self, seq_1hot, head_i=None, target_slice=None, pos_slice=None, pos_mask=None, pos_slice_denom=None, pos_mask_denom=None, chunk_size=None, batch_size=1, track_scale=1.0, track_transform=1.0, clip_soft=None, pseudo_count=0.0, no_transform=False, use_mean=False, use_ratio=False, use_logodds=False, subtract_...
['def', 'gradients(self,', 'seq_1hot,', 'head_i=None,', 'target_slice=None,', 'pos_slice=None,', 'pos_mask=None,', 'pos_slice_denom=None,', 'pos_mask_denom=None,', 'chunk_size=None,', 'batch_size=1,', 'track_scale=1.0,', 'track_transform=1.0,', 'clip_soft=None,', 'pseudo_count=0.0,', 'no_transform=False,', 'use_mean=Fa...
94,604
weimin17/Object-Detection_HelmetDetection
model_helpers_test.py
PastStopThresholdTest.test_past_stop_threshold
test_past_stop_threshold
Tests for normal operating conditions.
[ "Tests", "for", "normal", "operating", "conditions." ]
def test_past_stop_threshold(self): self.assertTrue(model_helpers.past_stop_threshold(0.54, 1)) self.assertTrue(model_helpers.past_stop_threshold(54, 100)) self.assertFalse(model_helpers.past_stop_threshold(0.54, 0.1)) self.assertFalse(model_helpers.past_stop_threshold(-0.54, -1.5)) self.assertTrue(...
['def', 'test_past_stop_threshold(self):', 'self.assertTrue(model_helpers.past_stop_threshold(0.54,', '1))', 'self.assertTrue(model_helpers.past_stop_threshold(54,', '100))', 'self.assertFalse(model_helpers.past_stop_threshold(0.54,', '0.1))', 'self.assertFalse(model_helpers.past_stop_threshold(-0.54,', '-1.5))', 'self...
748,841
Katja-M/Python_NaturalLanguageProcessing
featstruct.py
Feature.name
name
The name of this feature.
[ "The", "name", "of", "this", "feature." ]
def name(self): return self._name
['def', 'name(self):', 'return', 'self._name']
865,771
DevanshuSave/Pacman-and-Ghostbusters
inference.py
MarginalInference.elapseTime
elapseTime
Update beliefs for a time step elapsing from a gameState.
[ "Update", "beliefs", "for", "a", "time", "step", "elapsing", "from", "a", "gameState." ]
def elapseTime(self, gameState): if self.index == 1: jointInference.elapseTime(gameState)
['def', 'elapseTime(self,', 'gameState):', 'if', 'self.index', '==', '1:', 'jointInference.elapseTime(gameState)']
254,035
myothida/Supervised-Machine-Learning
colors.py
Colormap.get_under
get_under
Get the color for low out-of-range values.
[ "Get", "the", "color", "for", "low", "out-of-range", "values." ]
def get_under(self): if not self._isinit: self._init() return np.array(self._lut[self._i_under])
['def', 'get_under(self):', 'if', 'not', 'self._isinit:', 'self._init()', 'return', 'np.array(self._lut[self._i_under])']
361,904
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
test_strptime.py
StrptimeTests.helper
helper
Helper fxn in testing.
[ "Helper", "fxn", "in", "testing." ]
def helper(self, directive, position): strf_output = time.strftime('%' + directive, self.time_tuple) strp_output = _strptime._strptime_time(strf_output, '%' + directive) self.assertTrue(strp_output[position] == self.time_tuple[position], "testing of '%s' directive failed; '%s' -> %s != %s" % (directive, str...
['def', 'helper(self,', 'directive,', 'position):', 'strf_output', '=', "time.strftime('%'", '+', 'directive,', 'self.time_tuple)', 'strp_output', '=', '_strptime._strptime_time(strf_output,', "'%'", '+', 'directive)', 'self.assertTrue(strp_output[position]', '==', 'self.time_tuple[position],', '"testing', 'of', "'%s'"...
376,399
devashish-patel/webcam-motion-detector
interface.py
CommandLineInterface.push_focus
push_focus
Push to the focus stack.
[ "Push", "to", "the", "focus", "stack." ]
def push_focus(self, buffer_name): self.buffers.push_focus(self, buffer_name)
['def', 'push_focus(self,', 'buffer_name):', 'self.buffers.push_focus(self,', 'buffer_name)']
983,765
robmarkcole/HASS-Deepstack-
image_processing.py
ObjectClassifyEntity.unit_of_measurement
unit_of_measurement
Return the unit of measurement.
[ "Return", "the", "unit", "of", "measurement." ]
def unit_of_measurement(self): return 'targets'
['def', 'unit_of_measurement(self):', 'return', "'targets'"]
588,905
thaines/helit
corpus.py
Corpus.add
add
Adds a document to the corpus.
[ "Adds", "a", "document", "to", "the", "corpus." ]
def add(self, doc): doc.ident = len(self.docs) self.docs.append(doc) maxDocIdent = int(doc.words[-1, 0]) if maxDocIdent > self.maxWordIdentifier: self.maxWordIdentifier = maxDocIdent self.totalWords += doc.dupWords()
['def', 'add(self,', 'doc):', 'doc.ident', '=', 'len(self.docs)', 'self.docs.append(doc)', 'maxDocIdent', '=', 'int(doc.words[-1,', '0])', 'if', 'maxDocIdent', '>', 'self.maxWordIdentifier:', 'self.maxWordIdentifier', '=', 'maxDocIdent', 'self.totalWords', '+=', 'doc.dupWords()']
592,071
MLBazaar/MLPrimitives
utils.py
import_object
import_object
Import an object from its Fully Qualified Name.
[ "Import", "an", "object", "from", "its", "Fully", "Qualified", "Name." ]
def import_object(object_name): if isinstance(object_name, str): (parent_name, attribute) = object_name.rsplit('.', 1) try: parent = importlib.import_module(parent_name) except ImportError: (grand_parent_name, parent_name) = parent_name.rsplit('.', 1) gran...
['def', 'import_object(object_name):', 'if', 'isinstance(object_name,', 'str):', '(parent_name,', 'attribute)', '=', "object_name.rsplit('.',", '1)', 'try:', 'parent', '=', 'importlib.import_module(parent_name)', 'except', 'ImportError:', '(grand_parent_name,', 'parent_name)', '=', "parent_name.rsplit('.',", '1)', 'gra...
630,642
CEA-LIST/SCE
checkpoints.py
get_last_ckpt_in_path_or_dir
get_last_ckpt_in_path_or_dir
Get checkpoint from file or from last checkpoint in directory following a sorting function.
[ "Get", "checkpoint", "from", "file", "or", "from", "last", "checkpoint", "in", "directory", "following", "a", "sorting", "function." ]
def get_last_ckpt_in_path_or_dir(checkpoint_file: Optional[str]=None, checkpoint_dir: Optional[str]=None, ckpt_pattern: str='*.ckpt', key_sort: Callable=lambda x: x.stat().st_mtime) -> Optional[Path]: if checkpoint_file is not None: checkpoint_file_path = Path(checkpoint_file) if checkpoint_file_pat...
['def', 'get_last_ckpt_in_path_or_dir(checkpoint_file:', 'Optional[str]=None,', 'checkpoint_dir:', 'Optional[str]=None,', 'ckpt_pattern:', "str='*.ckpt',", 'key_sort:', 'Callable=lambda', 'x:', 'x.stat().st_mtime)', '->', 'Optional[Path]:', 'if', 'checkpoint_file', 'is', 'not', 'None:', 'checkpoint_file_path', '=', 'Pa...
329,481
zion-king/Graph-to-Sequence-Model-for-Natural-Question-
model.py
dev_batch
dev_batch
Test the `network` on the `batch`, return the ROUGE score and the loss.
[ "Test", "the", "`network`", "on", "the", "`batch`,", "return", "the", "ROUGE", "score", "and", "the", "loss." ]
def dev_batch(batch, network, vocab, criterion=None, show_cover_loss=False): network.train(False) (decoded_batch, out) = eval_decode_batch(batch, network, vocab, criterion=criterion, show_cover_loss=show_cover_loss) metrics = evaluate_predictions(batch['target_src'], decoded_batch) return (decoded_batch...
['def', 'dev_batch(batch,', 'network,', 'vocab,', 'criterion=None,', 'show_cover_loss=False):', 'network.train(False)', '(decoded_batch,', 'out)', '=', 'eval_decode_batch(batch,', 'network,', 'vocab,', 'criterion=criterion,', 'show_cover_loss=show_cover_loss)', 'metrics', '=', "evaluate_predictions(batch['target_src'],...
580,412
eddylau328/fyp-artificial-intelligence-ac-control-device
_messaging_encoder.py
_Validators.check_string_dict
check_string_dict
Checks if the given value is a dictionary comprised only of string keys and values.
[ "Checks", "if", "the", "given", "value", "is", "a", "dictionary", "comprised", "only", "of", "string", "keys", "and", "values." ]
def check_string_dict(cls, label, value): if value is None or value == {}: return None if not isinstance(value, dict): raise ValueError('{0} must be a dictionary.'.format(label)) non_str = [k for k in value if not isinstance(k, six.string_types)] if non_str: raise ValueError('{0}...
['def', 'check_string_dict(cls,', 'label,', 'value):', 'if', 'value', 'is', 'None', 'or', 'value', '==', '{}:', 'return', 'None', 'if', 'not', 'isinstance(value,', 'dict):', 'raise', "ValueError('{0}", 'must', 'be', 'a', "dictionary.'.format(label))", 'non_str', '=', '[k', 'for', 'k', 'in', 'value', 'if', 'not', 'isins...
214,339
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
webcam.py
get_cameras
get_cameras
Opens cameras using cv2, ensures they can take images.
[ "Opens", "cameras", "using", "cv2,", "ensures", "they", "can", "take", "images." ]
def get_cameras(): if FLAGS.webcam_ports: ports = map(int, FLAGS.webcam_ports.split(',')) else: ports = range(FLAGS.num_views) cameras = [cv2.VideoCapture(i) for i in ports] if not all([i.isOpened() for i in cameras]): try: output = subprocess.check_output(['lsof -t /...
['def', 'get_cameras():', 'if', 'FLAGS.webcam_ports:', 'ports', '=', 'map(int,', "FLAGS.webcam_ports.split(','))", 'else:', 'ports', '=', 'range(FLAGS.num_views)', 'cameras', '=', '[cv2.VideoCapture(i)', 'for', 'i', 'in', 'ports]', 'if', 'not', 'all([i.isOpened()', 'for', 'i', 'in', 'cameras]):', 'try:', 'output', '=',...
112,506
tobegit3hub/deep_image_model
curses_ui_test.py
CursesTest.testRegexSearchWithInvalidRegex
testRegexSearchWithInvalidRegex
Test using invalid regex to search.
[ "Test", "using", "invalid", "regex", "to", "search." ]
def testRegexSearchWithInvalidRegex(self): ui = MockCursesUI(40, 80, command_sequence=[string_to_codes('babble -n 3\n'), string_to_codes('/[\n'), self._EXIT]) ui.register_command_handler('babble', self._babble, 'babble some', prefix_aliases=['b']) ui.run_ui() self.assertEqual(1, len(ui.unwrapped_outputs...
['def', 'testRegexSearchWithInvalidRegex(self):', 'ui', '=', 'MockCursesUI(40,', '80,', "command_sequence=[string_to_codes('babble", '-n', "3\\n'),", "string_to_codes('/[\\n'),", 'self._EXIT])', "ui.register_command_handler('babble',", 'self._babble,', "'babble", "some',", "prefix_aliases=['b'])", 'ui.run_ui()', 'self....
182,397
Xianpeng919/MonoCon
monocon_head.py
MonoConHead.angle2class
angle2class
Convert continuous angle to discrete class and residual.
[ "Convert", "continuous", "angle", "to", "discrete", "class", "and", "residual." ]
def angle2class(self, angle): angle = angle % (2 * PI) assert angle >= 0 and angle <= 2 * PI angle_per_class = 2 * PI / float(self.num_alpha_bins) shifted_angle = (angle + angle_per_class / 2) % (2 * PI) class_id = int(shifted_angle / angle_per_class) residual_angle = shifted_angle - (class_id *...
['def', 'angle2class(self,', 'angle):', 'angle', '=', 'angle', '%', '(2', '*', 'PI)', 'assert', 'angle', '>=', '0', 'and', 'angle', '<=', '2', '*', 'PI', 'angle_per_class', '=', '2', '*', 'PI', '/', 'float(self.num_alpha_bins)', 'shifted_angle', '=', '(angle', '+', 'angle_per_class', '/', '2)', '%', '(2', '*', 'PI)', '...
654,787
microsoft/maro
abs_net.py
AbsNet.step
step
Run a training step to update the net's parameters according to the given loss.
[ "Run", "a", "training", "step", "to", "update", "the", "net's", "parameters", "according", "to", "the", "given", "loss." ]
def step(self, loss: torch.Tensor) -> None: self.optim.zero_grad() loss.backward() self.optim.step()
['def', 'step(self,', 'loss:', 'torch.Tensor)', '->', 'None:', 'self.optim.zero_grad()', 'loss.backward()', 'self.optim.step()']
628,465
Samjith888/Keras-retinanet-Training-on-custom-datasets-for---
debug.py
make_output_path
make_output_path
Compute the output path for a debug image.
[ "Compute", "the", "output", "path", "for", "a", "debug", "image." ]
def make_output_path(output_dir, image_path, flatten=False): if flatten: path = os.path.basename(image_path) else: (_, path) = os.path.splitdrive(image_path) if os.path.isabs(path): path = os.path.relpath(path, '/') (base, extension) = os.path.splitext(path) path = ba...
['def', 'make_output_path(output_dir,', 'image_path,', 'flatten=False):', 'if', 'flatten:', 'path', '=', 'os.path.basename(image_path)', 'else:', '(_,', 'path)', '=', 'os.path.splitdrive(image_path)', 'if', 'os.path.isabs(path):', 'path', '=', 'os.path.relpath(path,', "'/')", '(base,', 'extension)', '=', 'os.path.split...
595,872
AtlantixJJ/LinearGAN
visualizer.py
HtmlPageVisualizer.set_headers
set_headers
Sets the contents of all headers.
[ "Sets", "the", "contents", "of", "all", "headers." ]
def set_headers(self, contents): if isinstance(contents, str): contents = [contents] assert isinstance(contents, (list, tuple)) assert len(contents) == self.num_cols for (col_idx, content) in enumerate(contents): self.set_header(col_idx, content)
['def', 'set_headers(self,', 'contents):', 'if', 'isinstance(contents,', 'str):', 'contents', '=', '[contents]', 'assert', 'isinstance(contents,', '(list,', 'tuple))', 'assert', 'len(contents)', '==', 'self.num_cols', 'for', '(col_idx,', 'content)', 'in', 'enumerate(contents):', 'self.set_header(col_idx,', 'content)']
602,585
apeterswu/RL4NMT
common_attention_test.py
CommonAttentionTest.test2dGather
test2dGather
Testing 2d index gather and block gather functions.
[ "Testing", "2d", "index", "gather", "and", "block", "gather", "functions." ]
def test2dGather(self): batch_size = 2 num_heads = 2 height = 4 width = 6 depth = 8 query_shape = (2, 3) x = np.random.rand(batch_size, num_heads, height, width, depth) y = np.reshape(x, (batch_size, num_heads, -1, depth)) correct_indices = [[0, 1, 2, 6, 7, 8], [3, 4, 5, 9, 10, 11], ...
['def', 'test2dGather(self):', 'batch_size', '=', '2', 'num_heads', '=', '2', 'height', '=', '4', 'width', '=', '6', 'depth', '=', '8', 'query_shape', '=', '(2,', '3)', 'x', '=', 'np.random.rand(batch_size,', 'num_heads,', 'height,', 'width,', 'depth)', 'y', '=', 'np.reshape(x,', '(batch_size,', 'num_heads,', '-1,', 'd...
331,495
instadeepai/jumanji
utils.py
MoveCarry.target
target
Tile at target index of row.
[ "Tile", "at", "target", "index", "of", "row." ]
def target(self) -> chex.Numeric: return self.row[self.target_idx]
['def', 'target(self)', '->', 'chex.Numeric:', 'return', 'self.row[self.target_idx]']
594,026
dibyaghosh/gcsl
scripted_reset.py
add_groups_for_reset
add_groups_for_reset
Defines groups required to perform the reset.
[ "Defines", "groups", "required", "to", "perform", "the", "reset." ]
def add_groups_for_reset(builder: RobotComponentBuilder): builder.add_group('dclaw_top', motor_ids=[10, 20, 30]) builder.add_group('dclaw_middle', motor_ids=[11, 21, 31]) builder.add_group('dclaw_bottom', motor_ids=[12, 22, 32])
['def', 'add_groups_for_reset(builder:', 'RobotComponentBuilder):', "builder.add_group('dclaw_top',", 'motor_ids=[10,', '20,', '30])', "builder.add_group('dclaw_middle',", 'motor_ids=[11,', '21,', '31])', "builder.add_group('dclaw_bottom',", 'motor_ids=[12,', '22,', '32])']
201,877
matsu0228/nlp-jp
filecheckpoints.py
GenericFileCheckpoints.get_file_checkpoint
get_file_checkpoint
Get a checkpoint for a file.
[ "Get", "a", "checkpoint", "for", "a", "file." ]
def get_file_checkpoint(self, checkpoint_id, path): path = path.strip('/') self.log.info('restoring %s from checkpoint %s', path, checkpoint_id) os_checkpoint_path = self.checkpoint_path(checkpoint_id, path) if not os.path.isfile(os_checkpoint_path): self.no_such_checkpoint(path, checkpoint_id) ...
['def', 'get_file_checkpoint(self,', 'checkpoint_id,', 'path):', 'path', '=', "path.strip('/')", "self.log.info('restoring", '%s', 'from', 'checkpoint', "%s',", 'path,', 'checkpoint_id)', 'os_checkpoint_path', '=', 'self.checkpoint_path(checkpoint_id,', 'path)', 'if', 'not', 'os.path.isfile(os_checkpoint_path):', 'self...
790,641
locationlabs/mockredis
test_factories.py
test_mock_strict_redis_client_from_url
test_mock_strict_redis_client_from_url
Test that we can pass kwargs to the StrictRedis from_url mock/patch target.
[ "Test", "that", "we", "can", "pass", "kwargs", "to", "the", "StrictRedis", "from_url", "mock/patch", "target." ]
def test_mock_strict_redis_client_from_url(): ok_(mock_strict_redis_client.from_url(host='localhost', port=6379).strict)
['def', 'test_mock_strict_redis_client_from_url():', "ok_(mock_strict_redis_client.from_url(host='localhost',", 'port=6379).strict)']
240,648
clips/pattern
__init__.py
Table.search
search
Returns a Query object that can be used to construct complex table queries.
[ "Returns", "a", "Query", "object", "that", "can", "be", "used", "to", "construct", "complex", "table", "queries." ]
def search(self, *args, **kwargs): return Query(self, *args, **kwargs)
['def', 'search(self,', '*args,', '**kwargs):', 'return', 'Query(self,', '*args,', '**kwargs)']
764,581
shengchen-liu/Computer-Vision
audio_conv_utils.py
preprocess_input
preprocess_input
Reads an audio file and outputs a Mel-spectrogram.
[ "Reads", "an", "audio", "file", "and", "outputs", "a", "Mel-spectrogram." ]
def preprocess_input(audio_path, dim_ordering='default'): if dim_ordering == 'default': dim_ordering = K.image_dim_ordering() assert dim_ordering in {'tf', 'th'} if librosa_exists(): import librosa else: raise RuntimeError('Librosa is required to process audio files.\n' + 'Instal...
['def', 'preprocess_input(audio_path,', "dim_ordering='default'):", 'if', 'dim_ordering', '==', "'default':", 'dim_ordering', '=', 'K.image_dim_ordering()', 'assert', 'dim_ordering', 'in', "{'tf',", "'th'}", 'if', 'librosa_exists():', 'import', 'librosa', 'else:', 'raise', "RuntimeError('Librosa", 'is', 'required', 'to...
458,237
wandb/wandb
utils.py
cleanup_deployment
cleanup_deployment
Delete a k8s deployment and all pods in the same namespace.
[ "Delete", "a", "k8s", "deployment", "and", "all", "pods", "in", "the", "same", "namespace." ]
def cleanup_deployment(namespace: str): config.load_kube_config() apps_api = client.AppsV1Api() core_api = client.CoreV1Api() apps_api.delete_namespaced_deployment(name='launch-agent-release-testing', namespace=namespace) pods = core_api.list_namespaced_pod(namespace=namespace).items for pod in ...
['def', 'cleanup_deployment(namespace:', 'str):', 'config.load_kube_config()', 'apps_api', '=', 'client.AppsV1Api()', 'core_api', '=', 'client.CoreV1Api()', "apps_api.delete_namespaced_deployment(name='launch-agent-release-testing',", 'namespace=namespace)', 'pods', '=', 'core_api.list_namespaced_pod(namespace=namespac...
941,335
angeladai/ScanComplete
util.py
export_labeled_scene
export_labeled_scene
Saves colored point cloud for semantics.
[ "Saves", "colored", "point", "cloud", "for", "semantics." ]
def export_labeled_scene(pred_df, pred_sem, output_path, df_thresh=1): with open(output_path + '.obj', 'w') as output_file: for z in range(0, pred_df.shape[0]): for y in range(0, pred_df.shape[1]): for x in range(0, pred_df.shape[2]): if pred_df[z, y, x] > df_...
['def', 'export_labeled_scene(pred_df,', 'pred_sem,', 'output_path,', 'df_thresh=1):', 'with', 'open(output_path', '+', "'.obj',", "'w')", 'as', 'output_file:', 'for', 'z', 'in', 'range(0,', 'pred_df.shape[0]):', 'for', 'y', 'in', 'range(0,', 'pred_df.shape[1]):', 'for', 'x', 'in', 'range(0,', 'pred_df.shape[2]):', 'if...
845,870
jxhe/unify-parameter-efficient-tuning
check_inits.py
check_all_inits
check_all_inits
Check all inits in the transformers repo and raise an error if at least one does not define the same objects in both halves.
[ "Check", "all", "inits", "in", "the", "transformers", "repo", "and", "raise", "an", "error", "if", "at", "least", "one", "does", "not", "define", "the", "same", "objects", "in", "both", "halves." ]
def check_all_inits(): failures = [] for (root, _, files) in os.walk(PATH_TO_TRANSFORMERS): if '__init__.py' in files: fname = os.path.join(root, '__init__.py') objects = parse_init(fname) if objects is not None: errors = analyze_results(*objects) ...
['def', 'check_all_inits():', 'failures', '=', '[]', 'for', '(root,', '_,', 'files)', 'in', 'os.walk(PATH_TO_TRANSFORMERS):', 'if', "'__init__.py'", 'in', 'files:', 'fname', '=', 'os.path.join(root,', "'__init__.py')", 'objects', '=', 'parse_init(fname)', 'if', 'objects', 'is', 'not', 'None:', 'errors', '=', 'analyze_r...
949,566
anantm95/Pose-Guided-Dance-Sequence-
nn_compat.py
residual_block
residual_block
Slight variation of original.
[ "Slight", "variation", "of", "original." ]
def residual_block(x, a=None, conv=conv2d, init=False, dropout_p=0.0, gated=False, **kwargs): xs = int_shape(x) num_filters = xs[-1] residual = x if a is not None: a = nin(activate(a), num_filters) residual = tf.concat([residual, a], axis=-1) residual = activate(residual) residua...
['def', 'residual_block(x,', 'a=None,', 'conv=conv2d,', 'init=False,', 'dropout_p=0.0,', 'gated=False,', '**kwargs):', 'xs', '=', 'int_shape(x)', 'num_filters', '=', 'xs[-1]', 'residual', '=', 'x', 'if', 'a', 'is', 'not', 'None:', 'a', '=', 'nin(activate(a),', 'num_filters)', 'residual', '=', 'tf.concat([residual,', 'a...
821,036
arshpreetsingh/quantopian-machinelearning
magic.py
Magics.format_latex
format_latex
Format a string for latex inclusion.
[ "Format", "a", "string", "for", "latex", "inclusion." ]
def format_latex(self, strng): escape_re = re.compile('(%|_|\\$|#|&)', re.MULTILINE) cmd_name_re = re.compile('^(%s.*?):' % ESC_MAGIC, re.MULTILINE) cmd_re = re.compile('(?P<cmd>%s.+?\\b)(?!\\}\\}:)' % ESC_MAGIC, re.MULTILINE) par_re = re.compile('\\\\$', re.MULTILINE) newline_re = re.compile('\\\\n...
['def', 'format_latex(self,', 'strng):', 'escape_re', '=', "re.compile('(%|_|\\\\$|#|&)',", 're.MULTILINE)', 'cmd_name_re', '=', "re.compile('^(%s.*?):'", '%', 'ESC_MAGIC,', 're.MULTILINE)', 'cmd_re', '=', "re.compile('(?P<cmd>%s.+?\\\\b)(?!\\\\}\\\\}:)'", '%', 'ESC_MAGIC,', 're.MULTILINE)', 'par_re', '=', "re.compile(...
886,378
SimingYan/IAE
training.py
Trainer.train_step
train_step
Performs a training step.
[ "Performs", "a", "training", "step." ]
def train_step(self, data): self.model.train() self.optimizer.zero_grad() loss = self.compute_loss(data) loss.backward() self.optimizer.step() return loss.item()
['def', 'train_step(self,', 'data):', 'self.model.train()', 'self.optimizer.zero_grad()', 'loss', '=', 'self.compute_loss(data)', 'loss.backward()', 'self.optimizer.step()', 'return', 'loss.item()']
228,265
DeepX-inc/machina
distributed_epi_sampler.py
DistributedEpiSampler.sample
sample
This method should be called in master node.
[ "This", "method", "should", "be", "called", "in", "master", "node." ]
def sample(self, pol, max_epis=None, max_steps=None, deterministic=False): self.pol = pol self.max_epis = max_epis // self.world_size if max_epis is not None else None self.max_steps = max_steps // self.world_size if max_steps is not None else None self.deterministic = deterministic self.scatter_fro...
['def', 'sample(self,', 'pol,', 'max_epis=None,', 'max_steps=None,', 'deterministic=False):', 'self.pol', '=', 'pol', 'self.max_epis', '=', 'max_epis', '//', 'self.world_size', 'if', 'max_epis', 'is', 'not', 'None', 'else', 'None', 'self.max_steps', '=', 'max_steps', '//', 'self.world_size', 'if', 'max_steps', 'is', 'n...
218,973
cleanlab/cleanlab
datalab.py
Datalab.issues
issues
Issues found in each example from the dataset.
[ "Issues", "found", "in", "each", "example", "from", "the", "dataset." ]
def issues(self) -> pd.DataFrame: return self.data_issues.issues
['def', 'issues(self)', '->', 'pd.DataFrame:', 'return', 'self.data_issues.issues']
487,945
rifqind/Agent-Programs-3KS1
test_regexremove.py
TestRegexRemove.test_nosource_with_output
test_nosource_with_output
Test that the check_conditions returns true when given a code-cell that has non-empty outputs but no source.
[ "Test", "that", "the", "check_conditions", "returns", "true", "when", "given", "a", "code-cell", "that", "has", "non-empty", "outputs", "but", "no", "source." ]
def test_nosource_with_output(self): cell = {'cell_type': 'code', 'execution_count': 2, 'metadata': {}, 'outputs': [{'name': 'stdout', 'output_type': 'stream', 'text': 'I exist.\n'}], 'source': ''} preprocessor = self.build_preprocessor() node = from_dict(cell) assert preprocessor.check_conditions(node)
['def', 'test_nosource_with_output(self):', 'cell', '=', "{'cell_type':", "'code',", "'execution_count':", '2,', "'metadata':", '{},', "'outputs':", "[{'name':", "'stdout',", "'output_type':", "'stream',", "'text':", "'I", "exist.\\n'}],", "'source':", "''}", 'preprocessor', '=', 'self.build_preprocessor()', 'node', '=...
42,827
nasimrahaman/antipasti-tf
core.py
get
get
Get attribute from framework.
[ "Get", "attribute", "from", "framework." ]
def get(attr): assert isinstance(attr, str), 'Attribute to get must be a string, got {} instead.'.format(attr.__class__.__name__) return getattr(tf, attr)
['def', 'get(attr):', 'assert', 'isinstance(attr,', 'str),', "'Attribute", 'to', 'get', 'must', 'be', 'a', 'string,', 'got', '{}', "instead.'.format(attr.__class__.__name__)", 'return', 'getattr(tf,', 'attr)']
33,456
rudranil723/mini-main
edit.py
ProcessFormView.get
get
Handle GET requests: instantiate a blank version of the form.
[ "Handle", "GET", "requests:", "instantiate", "a", "blank", "version", "of", "the", "form." ]
def get(self, request, *args, **kwargs): return self.render_to_response(self.get_context_data())
['def', 'get(self,', 'request,', '*args,', '**kwargs):', 'return', 'self.render_to_response(self.get_context_data())']
316,924
asyml/texar
tf_helpers.py
InferenceHelper.next_inputs
next_inputs
Gets the outputs for next step.
[ "Gets", "the", "outputs", "for", "next", "step." ]
def next_inputs(self, time, outputs, state, sample_ids, name=None): del time, outputs if self._next_inputs_fn is None: next_inputs = sample_ids else: next_inputs = self._next_inputs_fn(sample_ids) finished = self._end_fn(sample_ids) return (finished, next_inputs, state)
['def', 'next_inputs(self,', 'time,', 'outputs,', 'state,', 'sample_ids,', 'name=None):', 'del', 'time,', 'outputs', 'if', 'self._next_inputs_fn', 'is', 'None:', 'next_inputs', '=', 'sample_ids', 'else:', 'next_inputs', '=', 'self._next_inputs_fn(sample_ids)', 'finished', '=', 'self._end_fn(sample_ids)', 'return', '(fi...
924,697
tensorflow/privacy
advanced_mia.py
replace_nan_with_column_mean
replace_nan_with_column_mean
Replaces each NaN with the mean of the corresponding column.
[ "Replaces", "each", "NaN", "with", "the", "mean", "of", "the", "corresponding", "column." ]
def replace_nan_with_column_mean(a: np.ndarray): mean = np.nanmean(a, axis=0) for i in range(a.shape[1]): np.nan_to_num(a[:, i], copy=False, nan=mean[i])
['def', 'replace_nan_with_column_mean(a:', 'np.ndarray):', 'mean', '=', 'np.nanmean(a,', 'axis=0)', 'for', 'i', 'in', 'range(a.shape[1]):', 'np.nan_to_num(a[:,', 'i],', 'copy=False,', 'nan=mean[i])']
824,857