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
_json.py
JsonReader.read
read
Read the whole JSON input into a pandas object.
[ "Read", "the", "whole", "JSON", "input", "into", "a", "pandas", "object." ]
def read(self) -> DataFrame | Series: obj: DataFrame | Series with self: if self.engine == 'pyarrow': pyarrow_json = import_optional_dependency('pyarrow.json') pa_table = pyarrow_json.read_json(self.data) mapping: type[ArrowDtype] | None | Callable if self...
['def', 'read(self)', '->', 'DataFrame', '|', 'Series:', 'obj:', 'DataFrame', '|', 'Series', 'with', 'self:', 'if', 'self.engine', '==', "'pyarrow':", 'pyarrow_json', '=', "import_optional_dependency('pyarrow.json')", 'pa_table', '=', 'pyarrow_json.read_json(self.data)', 'mapping:', 'type[ArrowDtype]', '|', 'None', '|'...
443,447
TonyLianLong/VAI-ReinforcementLearning
wrappers.py
MjModelWrapper.body_subtreemass
body_subtreemass
mass of subtree starting at this body (nbody x 1).
[ "mass", "of", "subtree", "starting", "at", "this", "body", "(nbody", "x", "1)." ]
def body_subtreemass(self): return util.buf_to_npy(self._ptr.contents.body_subtreemass, (self.nbody,))
['def', 'body_subtreemass(self):', 'return', 'util.buf_to_npy(self._ptr.contents.body_subtreemass,', '(self.nbody,))']
440,252
UWARG/computer-vision-python
test_landing_pad_tracking.py
TestMarkFalsePositive.test_mark_multiple_false_positive
test_mark_multiple_false_positive
Test if marking false positive adds detection to list of false positives.
[ "Test", "if", "marking", "false", "positive", "adds", "detection", "to", "list", "of", "false", "positives." ]
def test_mark_multiple_false_positive(self, tracker: landing_pad_tracking.LandingPadTracking, detections_1: 'list[object_in_world.ObjectInWorld]'): (_, false_positive_1) = object_in_world.ObjectInWorld.create(0, 0, 1) assert false_positive_1 is not None (_, false_positive_2) = object_in_world.ObjectInWorld....
['def', 'test_mark_multiple_false_positive(self,', 'tracker:', 'landing_pad_tracking.LandingPadTracking,', 'detections_1:', "'list[object_in_world.ObjectInWorld]'):", '(_,', 'false_positive_1)', '=', 'object_in_world.ObjectInWorld.create(0,', '0,', '1)', 'assert', 'false_positive_1', 'is', 'not', 'None', '(_,', 'false_...
470,515
OpenMDAO/OpenMDAO-Framework
query_hdf5.py
QueryHDF5.parent_case
parent_case
Filter the cases to only include this case and its children.
[ "Filter", "the", "cases", "to", "only", "include", "this", "case", "and", "its", "children." ]
def parent_case(self, parent_case_id): self.parent_id = parent_case_id self.parent_itername = parent_case_id self.case_id = None return self
['def', 'parent_case(self,', 'parent_case_id):', 'self.parent_id', '=', 'parent_case_id', 'self.parent_itername', '=', 'parent_case_id', 'self.case_id', '=', 'None', 'return', 'self']
275,405
lijian-ml/CS373-Programming-a-Robotic-Car
Parameter Optimization.py
Robot.set_noise
set_noise
Sets the noise parameters.
[ "Sets", "the", "noise", "parameters." ]
def set_noise(self, steering_noise, distance_noise): self.steering_noise = steering_noise self.distance_noise = distance_noise
['def', 'set_noise(self,', 'steering_noise,', 'distance_noise):', 'self.steering_noise', '=', 'steering_noise', 'self.distance_noise', '=', 'distance_noise']
228,050
deepmind/dm_control
inverse_kinematics_test.py
InverseKinematicsTest.testNamedJointsWithMultipleDOFs
testNamedJointsWithMultipleDOFs
Regression test for b/77506142.
[ "Regression", "test", "for", "b/77506142." ]
def testNamedJointsWithMultipleDOFs(self): physics = mujoco.Physics.from_xml_string(_MODEL_WITH_BALL_JOINTS_XML) site_name = 'gripsite' joint_names = ['joint_1', 'joint_2'] target_pos = (0.05, 0.05, 0) result = ik.qpos_from_site_pose(physics=physics, site_name=site_name, target_pos=target_pos, joint...
['def', 'testNamedJointsWithMultipleDOFs(self):', 'physics', '=', 'mujoco.Physics.from_xml_string(_MODEL_WITH_BALL_JOINTS_XML)', 'site_name', '=', "'gripsite'", 'joint_names', '=', "['joint_1',", "'joint_2']", 'target_pos', '=', '(0.05,', '0.05,', '0)', 'result', '=', 'ik.qpos_from_site_pose(physics=physics,', 'site_na...
165,615
sunishsheth2009/ChatterBot
ma.py
masked_equal
masked_equal
masked_equal(x, value) = x masked where x == value For floating point consider masked_values(x, value) instead.
[ "masked_equal(x,", "value)", "=", "x", "masked", "where", "x", "==", "value", "For", "floating", "point", "consider", "masked_values(x,", "value)", "instead." ]
def masked_equal(x, value, copy=1): d = filled(x, 0) c = umath.equal(d, value) m = mask_or(c, getmask(x)) return array(d, mask=m, copy=copy)
['def', 'masked_equal(x,', 'value,', 'copy=1):', 'd', '=', 'filled(x,', '0)', 'c', '=', 'umath.equal(d,', 'value)', 'm', '=', 'mask_or(c,', 'getmask(x))', 'return', 'array(d,', 'mask=m,', 'copy=copy)']
532,315
yinyunie/ScenePriors
eval_demo.py
evaluate_dbir_for_category
evaluate_dbir_for_category
Evaluates new view synthesis metrics of a simple depth-based image rendering (DBIR) model for a given task, category, and sequence (in case task=='singlesequence').
[ "Evaluates", "new", "view", "synthesis", "metrics", "of", "a", "simple", "depth-based", "image", "rendering", "(DBIR)", "model", "for", "a", "given", "task,", "category,", "and", "sequence", "(in", "case", "task=='singlesequence')." ]
def evaluate_dbir_for_category(category: str, task: Task, bg_color: Tuple[float, float, float]=(0.0, 0.0, 0.0), single_sequence_id: Optional[int]=None, num_workers: int=16): single_sequence_id = single_sequence_id if single_sequence_id is not None else -1 torch.manual_seed(42) dataset_map_provider_args = {'...
['def', 'evaluate_dbir_for_category(category:', 'str,', 'task:', 'Task,', 'bg_color:', 'Tuple[float,', 'float,', 'float]=(0.0,', '0.0,', '0.0),', 'single_sequence_id:', 'Optional[int]=None,', 'num_workers:', 'int=16):', 'single_sequence_id', '=', 'single_sequence_id', 'if', 'single_sequence_id', 'is', 'not', 'None', 'e...
329,627
tensorflow/agents
eval_job_test.py
EvalJobTest.test_eval_job
test_eval_job
Tests the eval job doing an eval every 5 steps for 10 train steps.
[ "Tests", "the", "eval", "job", "doing", "an", "eval", "every", "5", "steps", "for", "10", "train", "steps." ]
def test_eval_job(self): summary_dir = self.create_tempdir().full_path environment = test_envs.CountingEnv(steps_per_episode=4) action_tensor_spec = tensor_spec.from_spec(environment.action_spec()) time_step_tensor_spec = tensor_spec.from_spec(environment.time_step_spec()) policy = py_tf_eager_polic...
['def', 'test_eval_job(self):', 'summary_dir', '=', 'self.create_tempdir().full_path', 'environment', '=', 'test_envs.CountingEnv(steps_per_episode=4)', 'action_tensor_spec', '=', 'tensor_spec.from_spec(environment.action_spec())', 'time_step_tensor_spec', '=', 'tensor_spec.from_spec(environment.time_step_spec())', 'po...
22,771
kornia/kornia
sepia.py
sepia_from_rgb
sepia_from_rgb
Apply to a tensor the sepia filter.
[ "Apply", "to", "a", "tensor", "the", "sepia", "filter." ]
def sepia_from_rgb(input: Tensor, rescale: bool=True, eps: float=1e-06) -> Tensor: if len(input.shape) < 3 or input.shape[-3] != 3: raise ValueError(f'Input size must have a shape of (*, 3, H, W). Got {input.shape}') r = input[..., 0, :, :] g = input[..., 1, :, :] b = input[..., 2, :, :] r_o...
['def', 'sepia_from_rgb(input:', 'Tensor,', 'rescale:', 'bool=True,', 'eps:', 'float=1e-06)', '->', 'Tensor:', 'if', 'len(input.shape)', '<', '3', 'or', 'input.shape[-3]', '!=', '3:', 'raise', "ValueError(f'Input", 'size', 'must', 'have', 'a', 'shape', 'of', '(*,', '3,', 'H,', 'W).', 'Got', "{input.shape}')", 'r', '=',...
621,567
dgseten/bad-cv-tfm
inputs.py
eval_input
eval_input
Returns `features` and `labels` tensor dictionaries for evaluation.
[ "Returns", "`features`", "and", "`labels`", "tensor", "dictionaries", "for", "evaluation." ]
def eval_input(eval_config, eval_input_config, model_config, model=None, params=None): params = params or {} if not isinstance(eval_config, eval_pb2.EvalConfig): raise TypeError('For eval mode, the `eval_config` must be a train_pb2.EvalConfig.') if not isinstance(eval_input_config, input_reader_pb2....
['def', 'eval_input(eval_config,', 'eval_input_config,', 'model_config,', 'model=None,', 'params=None):', 'params', '=', 'params', 'or', '{}', 'if', 'not', 'isinstance(eval_config,', 'eval_pb2.EvalConfig):', 'raise', "TypeError('For", 'eval', 'mode,', 'the', '`eval_config`', 'must', 'be', 'a', "train_pb2.EvalConfig.')"...
421,336
Farama-Foundation/Minigrid
mission.py
MissionSpace.sample
sample
Sample a random mission string.
[ "Sample", "a", "random", "mission", "string." ]
def sample(self) -> str: if self.ordered_placeholders is not None: placeholders = [] for rand_var_list in self.ordered_placeholders: idx = self.np_random.integers(0, len(rand_var_list)) placeholders.append(rand_var_list[idx]) return self.mission_func(*placeholders) ...
['def', 'sample(self)', '->', 'str:', 'if', 'self.ordered_placeholders', 'is', 'not', 'None:', 'placeholders', '=', '[]', 'for', 'rand_var_list', 'in', 'self.ordered_placeholders:', 'idx', '=', 'self.np_random.integers(0,', 'len(rand_var_list))', 'placeholders.append(rand_var_list[idx])', 'return', 'self.mission_func(*...
271,584
deepmind/meltingpot
play_fruit_market.py
get_offer_apple_pressed
get_offer_apple_pressed
Sets apple offer to either -1, 0, or 1.
[ "Sets", "apple", "offer", "to", "either", "-1,", "0,", "or", "1." ]
def get_offer_apple_pressed() -> int: key_pressed = pygame.key.get_pressed() if key_pressed[pygame.K_1]: return -1 if key_pressed[pygame.K_2]: return 1 return 0
['def', 'get_offer_apple_pressed()', '->', 'int:', 'key_pressed', '=', 'pygame.key.get_pressed()', 'if', 'key_pressed[pygame.K_1]:', 'return', '-1', 'if', 'key_pressed[pygame.K_2]:', 'return', '1', 'return', '0']
285,504
43Carrig/recurrent_neural_networks_practice
ops.py
cast
cast
Casts a labeled tensor to a new type.
[ "Casts", "a", "labeled", "tensor", "to", "a", "new", "type." ]
def cast(labeled_tensor, dtype=None, name=None): with ops.name_scope(name, 'lt_cast', [labeled_tensor]) as scope: labeled_tensor = core.convert_to_labeled_tensor(labeled_tensor) op = math_ops.cast(labeled_tensor.tensor, dtype=dtype, name=scope) return core.LabeledTensor(op, labeled_tensor.ax...
['def', 'cast(labeled_tensor,', 'dtype=None,', 'name=None):', 'with', 'ops.name_scope(name,', "'lt_cast',", '[labeled_tensor])', 'as', 'scope:', 'labeled_tensor', '=', 'core.convert_to_labeled_tensor(labeled_tensor)', 'op', '=', 'math_ops.cast(labeled_tensor.tensor,', 'dtype=dtype,', 'name=scope)', 'return', 'core.Labe...
313,372
myothida/Supervised-Machine-Learning
categorical.py
_BoxPlotter.restyle_boxplot
restyle_boxplot
Take a drawn matplotlib boxplot and make it look nice.
[ "Take", "a", "drawn", "matplotlib", "boxplot", "and", "make", "it", "look", "nice." ]
def restyle_boxplot(self, artist_dict, color, props): for box in artist_dict['boxes']: box.update(dict(facecolor=color, zorder=0.9, edgecolor=self.gray, linewidth=self.linewidth)) box.update(props['box']) for whisk in artist_dict['whiskers']: whisk.update(dict(color=self.gray, linewidth=...
['def', 'restyle_boxplot(self,', 'artist_dict,', 'color,', 'props):', 'for', 'box', 'in', "artist_dict['boxes']:", 'box.update(dict(facecolor=color,', 'zorder=0.9,', 'edgecolor=self.gray,', 'linewidth=self.linewidth))', "box.update(props['box'])", 'for', 'whisk', 'in', "artist_dict['whiskers']:", 'whisk.update(dict(col...
446,668
intel/neural-compressor
utility.py
show_memory_info
show_memory_info
Show process full memory.
[ "Show", "process", "full", "memory." ]
def show_memory_info(hint): pid = os.getpid() p = psutil.Process(pid) info = p.memory_full_info() memory = info.uss / 1024.0 / 1024 print('{} memory used: {} MB'.format(hint, memory))
['def', 'show_memory_info(hint):', 'pid', '=', 'os.getpid()', 'p', '=', 'psutil.Process(pid)', 'info', '=', 'p.memory_full_info()', 'memory', '=', 'info.uss', '/', '1024.0', '/', '1024', "print('{}", 'memory', 'used:', '{}', "MB'.format(hint,", 'memory))']
721,505
bwhite/hadoop_vision
wordcount.py
Mapper.map
map
Take in a byte offset and a document, emit terms with count of 1.
[ "Take", "in", "a", "byte", "offset", "and", "a", "document,", "emit", "terms", "with", "count", "of", "1." ]
def map(self, unused_docid, doc): for term in doc.split(): yield (term, 1)
['def', 'map(self,', 'unused_docid,', 'doc):', 'for', 'term', 'in', 'doc.split():', 'yield', '(term,', '1)']
574,247
cnr-isti-vclab/TagLab
Blob.py
Blob.setupForDrawing
setupForDrawing
Create the QPolygon and the QPainterPath according to the blob's contours.
[ "Create", "the", "QPolygon", "and", "the", "QPainterPath", "according", "to", "the", "blob's", "contours." ]
def setupForDrawing(self): qpolygon = QPolygonF() for i in range(self.contour.shape[0]): qpolygon << QPointF(self.contour[i, 0] + 0.5, self.contour[i, 1] + 0.5) self.qpath = QPainterPath() self.qpath.addPolygon(qpolygon) for inner_contour in self.inner_contours: qpoly_inner = QPolygo...
['def', 'setupForDrawing(self):', 'qpolygon', '=', 'QPolygonF()', 'for', 'i', 'in', 'range(self.contour.shape[0]):', 'qpolygon', '<<', 'QPointF(self.contour[i,', '0]', '+', '0.5,', 'self.contour[i,', '1]', '+', '0.5)', 'self.qpath', '=', 'QPainterPath()', 'self.qpath.addPolygon(qpolygon)', 'for', 'inner_contour', 'in',...
906,691
salesforce/CodeRL
utils_multiple_choice.py
DataProcessor.get_test_examples
get_test_examples
Gets a collection of `InputExample`s for the test set.
[ "Gets", "a", "collection", "of", "`InputExample`s", "for", "the", "test", "set." ]
def get_test_examples(self, data_dir): raise NotImplementedError()
['def', 'get_test_examples(self,', 'data_dir):', 'raise', 'NotImplementedError()']
493,683
deepmind/dm_alchemy
helpers.py
partial_perm_from_index
partial_perm_from_index
Converts int to permutation of length 3 with potentially unknown values.
[ "Converts", "int", "to", "permutation", "of", "length", "3", "with", "potentially", "unknown", "values." ]
def partial_perm_from_index(ind: int, num_elements: int, index_to_perm_index: np.ndarray) -> List[int]: num_simple_perms = math.factorial(num_elements) if ind < num_simple_perms: return perm_from_index(ind, num_elements, index_to_perm_index) none_known = [UNKNOWN for _ in range(num_elements)] if...
['def', 'partial_perm_from_index(ind:', 'int,', 'num_elements:', 'int,', 'index_to_perm_index:', 'np.ndarray)', '->', 'List[int]:', 'num_simple_perms', '=', 'math.factorial(num_elements)', 'if', 'ind', '<', 'num_simple_perms:', 'return', 'perm_from_index(ind,', 'num_elements,', 'index_to_perm_index)', 'none_known', '='...
522,263
greydanus/mr_london
mingw32ccompiler.py
msvc_manifest_xml
msvc_manifest_xml
Given a major and minor version of the MSVCR, returns the corresponding XML file.
[ "Given", "a", "major", "and", "minor", "version", "of", "the", "MSVCR,", "returns", "the", "corresponding", "XML", "file." ]
def msvc_manifest_xml(maj, min): try: fullver = _MSVCRVER_TO_FULLVER[str(maj * 10 + min)] except KeyError: raise ValueError('Version %d,%d of MSVCRT not supported yet' % (maj, min)) template = '<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">\n <trustInfo xmlns="urn...
['def', 'msvc_manifest_xml(maj,', 'min):', 'try:', 'fullver', '=', '_MSVCRVER_TO_FULLVER[str(maj', '*', '10', '+', 'min)]', 'except', 'KeyError:', 'raise', "ValueError('Version", '%d,%d', 'of', 'MSVCRT', 'not', 'supported', "yet'", '%', '(maj,', 'min))', 'template', '=', "'<assembly", 'xmlns="urn:schemas-microsoft-com:...
262,706
akandykeller/NeuralWaveMachines
phase_space.py
poisson_bracket_with_q_and_p
poisson_bracket_with_q_and_p
Returns a function that computes the Poisson brackets {q,f} and {p,f}.
[ "Returns", "a", "function", "that", "computes", "the", "Poisson", "brackets", "{q,f}", "and", "{p,f}." ]
def poisson_bracket_with_q_and_p(f: HamiltonianFunction) -> SymplecticTangentFunction: def bracket(t: jnp.ndarray, y: PhaseSpace) -> TangentPhaseSpace: grad = jax.grad(lambda *args: jnp.sum(f(*args)), argnums=1)(t, y) return TangentPhaseSpace(position=grad.p, momentum=-grad.q) return bracket
['def', 'poisson_bracket_with_q_and_p(f:', 'HamiltonianFunction)', '->', 'SymplecticTangentFunction:', 'def', 'bracket(t:', 'jnp.ndarray,', 'y:', 'PhaseSpace)', '->', 'TangentPhaseSpace:', 'grad', '=', 'jax.grad(lambda', '*args:', 'jnp.sum(f(*args)),', 'argnums=1)(t,', 'y)', 'return', 'TangentPhaseSpace(position=grad.p...
293,577
TrellixVulnTeam/Unsupervised_Learning_HFI7
_statistics.py
Histogram.define_bin_edges
define_bin_edges
Given data, return the edges of the histogram bins.
[ "Given", "data,", "return", "the", "edges", "of", "the", "histogram", "bins." ]
def define_bin_edges(self, x1, x2=None, weights=None, cache=True): if x2 is None: bin_edges = self._define_bin_edges(x1, weights, self.bins, self.binwidth, self.binrange, self.discrete) else: bin_edges = [] for (i, x) in enumerate([x1, x2]): bins = self.bins if no...
['def', 'define_bin_edges(self,', 'x1,', 'x2=None,', 'weights=None,', 'cache=True):', 'if', 'x2', 'is', 'None:', 'bin_edges', '=', 'self._define_bin_edges(x1,', 'weights,', 'self.bins,', 'self.binwidth,', 'self.binrange,', 'self.discrete)', 'else:', 'bin_edges', '=', '[]', 'for', '(i,', 'x)', 'in', 'enumerate([x1,', 'x...
436,030
tobegit3hub/deep_image_model
summary_iterator.py
SummaryWriterCache.get
get
Returns the SummaryWriter for the specified directory.
[ "Returns", "the", "SummaryWriter", "for", "the", "specified", "directory." ]
def get(logdir): with SummaryWriterCache._lock: if logdir not in SummaryWriterCache._cache: SummaryWriterCache._cache[logdir] = SummaryWriter(logdir, graph=ops.get_default_graph()) return SummaryWriterCache._cache[logdir]
['def', 'get(logdir):', 'with', 'SummaryWriterCache._lock:', 'if', 'logdir', 'not', 'in', 'SummaryWriterCache._cache:', 'SummaryWriterCache._cache[logdir]', '=', 'SummaryWriter(logdir,', 'graph=ops.get_default_graph())', 'return', 'SummaryWriterCache._cache[logdir]']
183,250
greydanus/mr_london
files.py
relative_directory
relative_directory
Return the directory that `relative_filename` is relative to.
[ "Return", "the", "directory", "that", "`relative_filename`", "is", "relative", "to." ]
def relative_directory(): return RELATIVE_DIR
['def', 'relative_directory():', 'return', 'RELATIVE_DIR']
242,153
apple/ml-cvnets
__init__.py
get_test_dataset
get_test_dataset
Helper function to build a dataset for testing.
[ "Helper", "function", "to", "build", "a", "dataset", "for", "testing." ]
def get_test_dataset(opts: argparse.Namespace, *args, **kwargs) -> BaseDataset: test_dataset = build_dataset_from_registry(opts, *args, is_training=False, is_evaluation=True, **kwargs) if is_master(opts): logger.log('Evaluation dataset details: ') print('{}'.format(test_dataset)) return test...
['def', 'get_test_dataset(opts:', 'argparse.Namespace,', '*args,', '**kwargs)', '->', 'BaseDataset:', 'test_dataset', '=', 'build_dataset_from_registry(opts,', '*args,', 'is_training=False,', 'is_evaluation=True,', '**kwargs)', 'if', 'is_master(opts):', "logger.log('Evaluation", 'dataset', 'details:', "')", "print('{}'...
671,403
snudatalab/BPN
main.py
select_seeds
select_seeds
Select randomly a list of random seeds.
[ "Select", "randomly", "a", "list", "of", "random", "seeds." ]
def select_seeds(seed: int, size: int): np.random.seed(seed) return np.random.randint(1000000, size=size)
['def', 'select_seeds(seed:', 'int,', 'size:', 'int):', 'np.random.seed(seed)', 'return', 'np.random.randint(1000000,', 'size=size)']
107,945
rudranil723/mini-main
common.py
outf_writer_compat
outf_writer_compat
Get a CSV writer with optional compression.
[ "Get", "a", "CSV", "writer", "with", "optional", "compression." ]
def outf_writer_compat(outfile, encoding, errors, gzip_compress=False): return _outf_writer(outfile, encoding, errors, gzip_compress)
['def', 'outf_writer_compat(outfile,', 'encoding,', 'errors,', 'gzip_compress=False):', 'return', '_outf_writer(outfile,', 'encoding,', 'errors,', 'gzip_compress)']
322,044
ermongroup/MetaIRL
glfw.py
_GLFWvidmode.unwrap
unwrap
Returns a nested python sequence.
[ "Returns", "a", "nested", "python", "sequence." ]
def unwrap(self): size = (self.width, self.height) bits = (self.red_bits, self.green_bits, self.blue_bits) return (size, bits, self.refresh_rate)
['def', 'unwrap(self):', 'size', '=', '(self.width,', 'self.height)', 'bits', '=', '(self.red_bits,', 'self.green_bits,', 'self.blue_bits)', 'return', '(size,', 'bits,', 'self.refresh_rate)']
634,745
joao-montanari/artificial_intelligence
selectors.py
BaseSelector.modify
modify
Change a registered file object monitored events and data.
[ "Change", "a", "registered", "file", "object", "monitored", "events", "and", "data." ]
def modify(self, fileobj, events, data=None): try: key = self._fd_to_key[self._fileobj_lookup(fileobj)] except KeyError: raise KeyError('{0!r} is not registered'.format(fileobj)) if events != key.events: self.unregister(fileobj) key = self.register(fileobj, events, data) ...
['def', 'modify(self,', 'fileobj,', 'events,', 'data=None):', 'try:', 'key', '=', 'self._fd_to_key[self._fileobj_lookup(fileobj)]', 'except', 'KeyError:', 'raise', "KeyError('{0!r}", 'is', 'not', "registered'.format(fileobj))", 'if', 'events', '!=', 'key.events:', 'self.unregister(fileobj)', 'key', '=', 'self.register(...
146,443
loicmarie/hands-detection
visualization.py
InteractiveVisualization.initial_html
initial_html
Returns HTML for a container, which will be populated later.
[ "Returns", "HTML", "for", "a", "container,", "which", "will", "be", "populated", "later." ]
def initial_html(self, height='700px', script=None, init_message=None): if script is None: script = _load_viz_script() if init_message is None: init_message = 'Type a sentence and press (enter) to see the trace.' (self.elt_id, div_html) = _container_div(height=height, contents='<strong>{}</s...
['def', 'initial_html(self,', "height='700px',", 'script=None,', 'init_message=None):', 'if', 'script', 'is', 'None:', 'script', '=', '_load_viz_script()', 'if', 'init_message', 'is', 'None:', 'init_message', '=', "'Type", 'a', 'sentence', 'and', 'press', '(enter)', 'to', 'see', 'the', "trace.'", '(self.elt_id,', 'div_...
575,468
cesium-ml/cesium
periodic_model.py
get_max_delta_mags
get_max_delta_mags
Largest value minus second largest value of fitted Lomb Scargle model.
[ "Largest", "value", "minus", "second", "largest", "value", "of", "fitted", "Lomb", "Scargle", "model." ]
def get_max_delta_mags(model): return model['max_delta_mags']
['def', 'get_max_delta_mags(model):', 'return', "model['max_delta_mags']"]
476,644
danamyu/hedgehog_detector
pixelda_model.py
residual_interpretation_block
residual_interpretation_block
Learns a residual image which is added to the incoming image.
[ "Learns", "a", "residual", "image", "which", "is", "added", "to", "the", "incoming", "image." ]
def residual_interpretation_block(images, hparams, scope): with tf.variable_scope(scope): with slim.arg_scope([slim.conv2d], normalizer_fn=None, kernel_size=[hparams.generator_kernel_size] * 2): net = images for _ in range(hparams.res_int_convs): net = slim.conv2d(net...
['def', 'residual_interpretation_block(images,', 'hparams,', 'scope):', 'with', 'tf.variable_scope(scope):', 'with', 'slim.arg_scope([slim.conv2d],', 'normalizer_fn=None,', 'kernel_size=[hparams.generator_kernel_size]', '*', '2):', 'net', '=', 'images', 'for', '_', 'in', 'range(hparams.res_int_convs):', 'net', '=', 'sl...
589,560
tencent-ailab/TriNet
iterators.py
CountingIterator.skip
skip
Fast-forward the iterator by skipping n elements.
[ "Fast-forward", "the", "iterator", "by", "skipping", "n", "elements." ]
def skip(self, n): for _ in range(n): next(self) return self
['def', 'skip(self,', 'n):', 'for', '_', 'in', 'range(n):', 'next(self)', 'return', 'self']
425,155
keras-team/keras-cv
mlp_mixer.py
MLPMixerL16
MLPMixerL16
Instantiates the MLPMixerL16 architecture.
[ "Instantiates", "the", "MLPMixerL16", "architecture." ]
def MLPMixerL16(input_shape, *, include_rescaling, include_top, num_classes=None, input_tensor=None, weights=None, pooling=None, name='MLPMixerL16', **kwargs): return MLPMixer(input_shape=input_shape, patch_size=MODEL_CONFIGS['MLPMixerL16']['patch_size'], num_blocks=MODEL_CONFIGS['MLPMixerL16']['num_blocks'], hidde...
['def', 'MLPMixerL16(input_shape,', '*,', 'include_rescaling,', 'include_top,', 'num_classes=None,', 'input_tensor=None,', 'weights=None,', 'pooling=None,', "name='MLPMixerL16',", '**kwargs):', 'return', 'MLPMixer(input_shape=input_shape,', "patch_size=MODEL_CONFIGS['MLPMixerL16']['patch_size'],", "num_blocks=MODEL_CON...
595,283
intel/neural-compressor
model.py
Model.get_tensors_info
get_tensors_info
Get information about tensors.
[ "Get", "information", "about", "tensors." ]
def get_tensors_info(self) -> dict: raise NotImplementedError(f'Getting tensors informarmation for model {self.path} is not supported.')
['def', 'get_tensors_info(self)', '->', 'dict:', 'raise', "NotImplementedError(f'Getting", 'tensors', 'informarmation', 'for', 'model', '{self.path}', 'is', 'not', "supported.')"]
721,556
lspvic/CopyNet
model_helper.py
avg_checkpoints
avg_checkpoints
Average the last N checkpoints in the model_dir.
[ "Average", "the", "last", "N", "checkpoints", "in", "the", "model_dir." ]
def avg_checkpoints(model_dir, num_last_checkpoints, global_step, global_step_name): checkpoint_state = tf.train.get_checkpoint_state(model_dir) if not checkpoint_state: utils.print_out('# No checkpoint file found in directory: %s' % model_dir) return None checkpoints = checkpoint_state.all_...
['def', 'avg_checkpoints(model_dir,', 'num_last_checkpoints,', 'global_step,', 'global_step_name):', 'checkpoint_state', '=', 'tf.train.get_checkpoint_state(model_dir)', 'if', 'not', 'checkpoint_state:', "utils.print_out('#", 'No', 'checkpoint', 'file', 'found', 'in', 'directory:', "%s'", '%', 'model_dir)', 'return', '...
137,197
xvjiarui/VFS
bmn.py
BMN.forward_test
forward_test
Define the computation performed at every call when testing.
[ "Define", "the", "computation", "performed", "at", "every", "call", "when", "testing." ]
def forward_test(self, raw_feature, video_meta): (confidence_map, start, end) = self._forward(raw_feature) start_scores = start[0].cpu().numpy() end_scores = end[0].cpu().numpy() cls_confidence = confidence_map[0][1].cpu().numpy() reg_confidence = confidence_map[0][0].cpu().numpy() max_start = m...
['def', 'forward_test(self,', 'raw_feature,', 'video_meta):', '(confidence_map,', 'start,', 'end)', '=', 'self._forward(raw_feature)', 'start_scores', '=', 'start[0].cpu().numpy()', 'end_scores', '=', 'end[0].cpu().numpy()', 'cls_confidence', '=', 'confidence_map[0][1].cpu().numpy()', 'reg_confidence', '=', 'confidence...
379,660
openvinotoolkit/training_extensions
dataloader.py
ActionOVDetDataLoader.add_prediction
add_prediction
Add prediction results to key frame.
[ "Add", "prediction", "results", "to", "key", "frame." ]
def add_prediction(self, data: List[DatasetItemEntity], prediction: AnnotationSceneEntity): dataset_item = data[len(data) // 2] dataset_item.append_annotations(prediction.annotations)
['def', 'add_prediction(self,', 'data:', 'List[DatasetItemEntity],', 'prediction:', 'AnnotationSceneEntity):', 'dataset_item', '=', 'data[len(data)', '//', '2]', 'dataset_item.append_annotations(prediction.annotations)']
903,879
deepmind/meltingpot
reaction_graph_utils.py
create_scene
create_scene
Construct the global scene prefab.
[ "Construct", "the", "global", "scene", "prefab." ]
def create_scene(reactions, stochastic_episode_ending=False): scene = {'name': 'scene', 'components': [{'component': 'StateManager', 'kwargs': {'initialState': 'scene', 'stateConfigs': [{'state': 'scene'}]}}, {'component': 'Transform'}, {'component': 'ReactionAlgebra', 'kwargs': {'reactions': reactions}}, {'compone...
['def', 'create_scene(reactions,', 'stochastic_episode_ending=False):', 'scene', '=', "{'name':", "'scene',", "'components':", "[{'component':", "'StateManager',", "'kwargs':", "{'initialState':", "'scene',", "'stateConfigs':", "[{'state':", "'scene'}]}},", "{'component':", "'Transform'},", "{'component':", "'ReactionA...
285,828
43Carrig/recurrent_neural_networks_practice
convert_saved_model.py
get_tensors_from_tensor_names
get_tensors_from_tensor_names
Gets the Tensors associated with the `tensor_names` in the provided graph.
[ "Gets", "the", "Tensors", "associated", "with", "the", "`tensor_names`", "in", "the", "provided", "graph." ]
def get_tensors_from_tensor_names(graph, tensor_names): tensor_name_to_tensor = {tensor_name(tensor): tensor for op in graph.get_operations() for tensor in op.values()} tensors = [] invalid_tensors = [] for name in tensor_names: tensor = tensor_name_to_tensor.get(name) if tensor is None:...
['def', 'get_tensors_from_tensor_names(graph,', 'tensor_names):', 'tensor_name_to_tensor', '=', '{tensor_name(tensor):', 'tensor', 'for', 'op', 'in', 'graph.get_operations()', 'for', 'tensor', 'in', 'op.values()}', 'tensors', '=', '[]', 'invalid_tensors', '=', '[]', 'for', 'name', 'in', 'tensor_names:', 'tensor', '=', ...
313,779
PKU-Alignment/safe-rlhf
rl_trainer.py
RLTrainer.rollout
rollout
Rollout a batch of experiences.
[ "Rollout", "a", "batch", "of", "experiences." ]
def rollout(self, prompt_only_batch: PromptOnlyBatch) -> list[dict[str, Any]]: input_ids = prompt_only_batch['input_ids'] sequences = self.actor_model.module.generate(input_ids=input_ids, attention_mask=prompt_only_batch['attention_mask'], generation_config=self.generation_config, synced_gpus=True, do_sample=Tr...
['def', 'rollout(self,', 'prompt_only_batch:', 'PromptOnlyBatch)', '->', 'list[dict[str,', 'Any]]:', 'input_ids', '=', "prompt_only_batch['input_ids']", 'sequences', '=', 'self.actor_model.module.generate(input_ids=input_ids,', "attention_mask=prompt_only_batch['attention_mask'],", 'generation_config=self.generation_co...
829,197
weimin17/Object-Detection_HelmetDetection
kepler_spline.py
fit_kepler_spline
fit_kepler_spline
Fits a Kepler spline with logarithmically-sampled breakpoint spacings.
[ "Fits", "a", "Kepler", "spline", "with", "logarithmically-sampled", "breakpoint", "spacings." ]
def fit_kepler_spline(all_time, all_flux, bkspace_min=0.5, bkspace_max=20, bkspace_num=20, maxiter=5, penalty_coeff=1.0, verbose=True): bkspaces = np.logspace(np.log10(bkspace_min), np.log10(bkspace_max), num=bkspace_num) return choose_kepler_spline(all_time, all_flux, bkspaces, maxiter=maxiter, penalty_coeff=p...
['def', 'fit_kepler_spline(all_time,', 'all_flux,', 'bkspace_min=0.5,', 'bkspace_max=20,', 'bkspace_num=20,', 'maxiter=5,', 'penalty_coeff=1.0,', 'verbose=True):', 'bkspaces', '=', 'np.logspace(np.log10(bkspace_min),', 'np.log10(bkspace_max),', 'num=bkspace_num)', 'return', 'choose_kepler_spline(all_time,', 'all_flux,'...
761,684
HighnessAtharva/VocabCLI
Study.py
revise_favorite
revise_favorite
Revise words in favorite list.
[ "Revise", "words", "in", "favorite", "list." ]
def revise_favorite(number: Optional[int]=None) -> None: conn = createConnection() c = conn.cursor() with contextlib.suppress(NoWordsInFavoriteListException): if count_favorite() == 0: raise NoWordsInFavoriteListException() if not number: c.execute('SELECT DISTINCT word FROM ...
['def', 'revise_favorite(number:', 'Optional[int]=None)', '->', 'None:', 'conn', '=', 'createConnection()', 'c', '=', 'conn.cursor()', 'with', 'contextlib.suppress(NoWordsInFavoriteListException):', 'if', 'count_favorite()', '==', '0:', 'raise', 'NoWordsInFavoriteListException()', 'if', 'not', 'number:', "c.execute('SE...
946,299
weimin17/Object-Detection_HelmetDetection
tensorrt.py
get_trt_graph
get_trt_graph
Create and save inference graph using the TensorRT library.
[ "Create", "and", "save", "inference", "graph", "using", "the", "TensorRT", "library." ]
def get_trt_graph(graph_name, graph_def, precision_mode, output_dir, output_node, batch_size=128, workspace_size=2 << 10): trt_graph = trt.create_inference_graph(graph_def, [output_node], max_batch_size=batch_size, max_workspace_size_bytes=workspace_size << 20, precision_mode=precision_mode) write_graph_to_file...
['def', 'get_trt_graph(graph_name,', 'graph_def,', 'precision_mode,', 'output_dir,', 'output_node,', 'batch_size=128,', 'workspace_size=2', '<<', '10):', 'trt_graph', '=', 'trt.create_inference_graph(graph_def,', '[output_node],', 'max_batch_size=batch_size,', 'max_workspace_size_bytes=workspace_size', '<<', '20,', 'pr...
760,764
juaml/julearn
available_searchers.py
reset_searcher_register
reset_searcher_register
Reset the searcher register to its initial state.
[ "Reset", "the", "searcher", "register", "to", "its", "initial", "state." ]
def reset_searcher_register() -> None: global _available_searchers _available_searchers = deepcopy(_available_searchers_reset)
['def', 'reset_searcher_register()', '->', 'None:', 'global', '_available_searchers', '_available_searchers', '=', 'deepcopy(_available_searchers_reset)']
593,650
gopinath-balu/computer_vision
sys_funcs.py
check_gpu
check_gpu
Log error and exit when set use_gpu=true in paddlepaddle cpu version.
[ "Log", "error", "and", "exit", "when", "set", "use_gpu=true", "in", "paddlepaddle", "cpu", "version." ]
def check_gpu(use_gpu): err = 'Config use_gpu cannot be set as true while you are using paddlepaddle cpu version ! \nPlease try: \n\t1. Install paddlepaddle-gpu to run model on GPU \n\t2. Set use_gpu as false in config file to run model on CPU' if use_gpu: try: if not paddle.is_compiled_with...
['def', 'check_gpu(use_gpu):', 'err', '=', "'Config", 'use_gpu', 'cannot', 'be', 'set', 'as', 'true', 'while', 'you', 'are', 'using', 'paddlepaddle', 'cpu', 'version', '!', '\\nPlease', 'try:', '\\n\\t1.', 'Install', 'paddlepaddle-gpu', 'to', 'run', 'model', 'on', 'GPU', '\\n\\t2.', 'Set', 'use_gpu', 'as', 'false', 'in...
474,735
palVikram/Machine-Learning-using-Python
op.py
Op.make_py_thunk
make_py_thunk
Like make_thunk() but only makes python thunks.
[ "Like", "make_thunk()", "but", "only", "makes", "python", "thunks." ]
def make_py_thunk(self, node, storage_map, compute_map, no_recycling, debug=False): node_input_storage = [storage_map[r] for r in node.inputs] node_output_storage = [storage_map[r] for r in node.outputs] if debug: p = node.op.debug_perform else: p = node.op.perform params = node.run_...
['def', 'make_py_thunk(self,', 'node,', 'storage_map,', 'compute_map,', 'no_recycling,', 'debug=False):', 'node_input_storage', '=', '[storage_map[r]', 'for', 'r', 'in', 'node.inputs]', 'node_output_storage', '=', '[storage_map[r]', 'for', 'r', 'in', 'node.outputs]', 'if', 'debug:', 'p', '=', 'node.op.debug_perform', '...
621,386
huawei-noah/xingtian
serializable.py
Serializable.md5
md5
MD5 value of network description.
[ "MD5", "value", "of", "network", "description." ]
def md5(self): return self.get_md5(self.to_desc(1))
['def', 'md5(self):', 'return', 'self.get_md5(self.to_desc(1))']
962,819
mayuelala/SimVTP
metric.py
v2t_metrics
v2t_metrics
Compute retrieval metrics from a similarity matrix.
[ "Compute", "retrieval", "metrics", "from", "a", "similarity", "matrix." ]
def v2t_metrics(sims, query_masks=None): sims = sims.T if False: sims = np.ones((3, 3)) sims[0, 0] = 2 sims[1, 1:2] = 2 sims[2, :] = 2 query_masks = None assert sims.ndim == 2, 'expected a matrix' (num_queries, num_caps) = sims.shape dists = -sims caps_per...
['def', 'v2t_metrics(sims,', 'query_masks=None):', 'sims', '=', 'sims.T', 'if', 'False:', 'sims', '=', 'np.ones((3,', '3))', 'sims[0,', '0]', '=', '2', 'sims[1,', '1:2]', '=', '2', 'sims[2,', ':]', '=', '2', 'query_masks', '=', 'None', 'assert', 'sims.ndim', '==', '2,', "'expected", 'a', "matrix'", '(num_queries,', 'nu...
884,279
bm777/object_detection
keypoints.py
scores_to_probs
scores_to_probs
Transforms CxHxW of scores to probabilities spatially.
[ "Transforms", "CxHxW", "of", "scores", "to", "probabilities", "spatially." ]
def scores_to_probs(scores): channels = scores.shape[0] for c in range(channels): temp = scores[c, :, :] max_score = temp.max() temp = np.exp(temp - max_score) / np.sum(np.exp(temp - max_score)) scores[c, :, :] = temp return scores
['def', 'scores_to_probs(scores):', 'channels', '=', 'scores.shape[0]', 'for', 'c', 'in', 'range(channels):', 'temp', '=', 'scores[c,', ':,', ':]', 'max_score', '=', 'temp.max()', 'temp', '=', 'np.exp(temp', '-', 'max_score)', '/', 'np.sum(np.exp(temp', '-', 'max_score))', 'scores[c,', ':,', ':]', '=', 'temp', 'return'...
773,422
viko-3/DiffSeqMol
utils.py
_PeriodicTimer.cancel
cancel
Stop the timer at the next opportunity.
[ "Stop", "the", "timer", "at", "the", "next", "opportunity." ]
def cancel(self) -> None: if self._finalizer: self._finalizer()
['def', 'cancel(self)', '->', 'None:', 'if', 'self._finalizer:', 'self._finalizer()']
551,457
suarez12138/AI-Reversi_IMP_TextDichotomy
test_image.py
test_image_array_alpha
test_image_array_alpha
Per-pixel alpha channel test.
[ "Per-pixel", "alpha", "channel", "test." ]
def test_image_array_alpha(fig_test, fig_ref): x = np.linspace(0, 1) (xx, yy) = np.meshgrid(x, x) zz = np.exp(-3 * (xx - 0.5) ** 2 + (yy - 0.7 ** 2)) alpha = zz / zz.max() cmap = plt.get_cmap('viridis') ax = fig_test.add_subplot(111) ax.imshow(zz, alpha=alpha, cmap=cmap, interpolation='neare...
['def', 'test_image_array_alpha(fig_test,', 'fig_ref):', 'x', '=', 'np.linspace(0,', '1)', '(xx,', 'yy)', '=', 'np.meshgrid(x,', 'x)', 'zz', '=', 'np.exp(-3', '*', '(xx', '-', '0.5)', '**', '2', '+', '(yy', '-', '0.7', '**', '2))', 'alpha', '=', 'zz', '/', 'zz.max()', 'cmap', '=', "plt.get_cmap('viridis')", 'ax', '=', ...
97,353
TrellixVulnTeam/Unsupervised_Learning_HFI7
checkpoints.py
Checkpoints.rename_checkpoint
rename_checkpoint
Rename a single checkpoint from old_path to new_path.
[ "Rename", "a", "single", "checkpoint", "from", "old_path", "to", "new_path." ]
def rename_checkpoint(self, checkpoint_id, old_path, new_path): raise NotImplementedError('must be implemented in a subclass')
['def', 'rename_checkpoint(self,', 'checkpoint_id,', 'old_path,', 'new_path):', 'raise', "NotImplementedError('must", 'be', 'implemented', 'in', 'a', "subclass')"]
452,215
nancheng58/Self-supervised-learning-for-Sequential-Recommender-Systems
trainer.py
Trainer.evaluate
evaluate
Evaluate the model based on the eval data.
[ "Evaluate", "the", "model", "based", "on", "the", "eval", "data." ]
def evaluate(self, eval_data, train_data, load_best_model=True, model_file=None, show_progress=False): if not eval_data: return if load_best_model: checkpoint_file = model_file or self.saved_model_file checkpoint = torch.load(checkpoint_file) self.model.load_state_dict(checkpoint...
['def', 'evaluate(self,', 'eval_data,', 'train_data,', 'load_best_model=True,', 'model_file=None,', 'show_progress=False):', 'if', 'not', 'eval_data:', 'return', 'if', 'load_best_model:', 'checkpoint_file', '=', 'model_file', 'or', 'self.saved_model_file', 'checkpoint', '=', 'torch.load(checkpoint_file)', "self.model.l...
342,025
deepmind/dm_control
transformations.py
quat_rotate
quat_rotate
Rotate a vector by a quaternion.
[ "Rotate", "a", "vector", "by", "a", "quaternion." ]
def quat_rotate(quat, vec): qvec = np.hstack([[0], vec]) return quat_mul(quat_mul(quat, qvec), quat_conj(quat))[1:]
['def', 'quat_rotate(quat,', 'vec):', 'qvec', '=', 'np.hstack([[0],', 'vec])', 'return', 'quat_mul(quat_mul(quat,', 'qvec),', 'quat_conj(quat))[1:]']
165,626
intelligent-environments-lab/CityLearn
citylearn.py
CityLearnEnv.render
render
Rendering function for The CityLearn Challenge 2023.
[ "Rendering", "function", "for", "The", "CityLearn", "Challenge", "2023." ]
def render(self): (canvas, canvas_size, draw_obj, color) = get_background() num_buildings = len(self.buildings) profile_time_steps = 24 (norm_min, norm_max) = (0.0, 1.0) space_limits = [] for (i, b) in enumerate(self.buildings): energy = b.net_electricity_consumption[b.time_step] / b.non...
['def', 'render(self):', '(canvas,', 'canvas_size,', 'draw_obj,', 'color)', '=', 'get_background()', 'num_buildings', '=', 'len(self.buildings)', 'profile_time_steps', '=', '24', '(norm_min,', 'norm_max)', '=', '(0.0,', '1.0)', 'space_limits', '=', '[]', 'for', '(i,', 'b)', 'in', 'enumerate(self.buildings):', 'energy',...
105,706
Ruturaj123/Flowchart-Detection
input_data.py
load_wav_file
load_wav_file
Loads an audio file and returns a float PCM-encoded array of samples.
[ "Loads", "an", "audio", "file", "and", "returns", "a", "float", "PCM-encoded", "array", "of", "samples." ]
def load_wav_file(filename): with tf.Session(graph=tf.Graph()) as sess: wav_filename_placeholder = tf.placeholder(tf.string, []) wav_loader = io_ops.read_file(wav_filename_placeholder) wav_decoder = contrib_audio.decode_wav(wav_loader, desired_channels=1) return sess.run(wav_decoder,...
['def', 'load_wav_file(filename):', 'with', 'tf.Session(graph=tf.Graph())', 'as', 'sess:', 'wav_filename_placeholder', '=', 'tf.placeholder(tf.string,', '[])', 'wav_loader', '=', 'io_ops.read_file(wav_filename_placeholder)', 'wav_decoder', '=', 'contrib_audio.decode_wav(wav_loader,', 'desired_channels=1)', 'return', 's...
604,893
0xangelo/raylab
info.py
list_
list_
Retrieve and echo a help text for the given agent's config.
[ "Retrieve", "and", "echo", "a", "help", "text", "for", "the", "given", "agent's", "config." ]
def list_(ctx, agent, key, separator, rllib): from raylab.agents.registry import AGENTS from raylab.options import UnknownOptionError cls = AGENTS[agent]() try: msg = cls.options.help(key, separator, with_rllib=rllib) except UnknownOptionError as err: click.echo(err) click.ec...
['def', 'list_(ctx,', 'agent,', 'key,', 'separator,', 'rllib):', 'from', 'raylab.agents.registry', 'import', 'AGENTS', 'from', 'raylab.options', 'import', 'UnknownOptionError', 'cls', '=', 'AGENTS[agent]()', 'try:', 'msg', '=', 'cls.options.help(key,', 'separator,', 'with_rllib=rllib)', 'except', 'UnknownOptionError', ...
848,271
ADLab3Ds/TiG-BEV
open3d_vis.py
show_pts_index_boxes
show_pts_index_boxes
Draw bbox and points on visualizer with indices that indicate which bbox3d that each point lies in.
[ "Draw", "bbox", "and", "points", "on", "visualizer", "with", "indices", "that", "indicate", "which", "bbox3d", "that", "each", "point", "lies", "in." ]
def show_pts_index_boxes(points, bbox3d=None, show=True, indices=None, save_path=None, points_size=2, point_color=(0.5, 0.5, 0.5), bbox_color=(0, 1, 0), points_in_box_color=(1, 0, 0), rot_axis=2, center_mode='lidar_bottom', mode='xyz'): assert 0 <= rot_axis <= 2 vis = o3d.visualization.Visualizer() vis.crea...
['def', 'show_pts_index_boxes(points,', 'bbox3d=None,', 'show=True,', 'indices=None,', 'save_path=None,', 'points_size=2,', 'point_color=(0.5,', '0.5,', '0.5),', 'bbox_color=(0,', '1,', '0),', 'points_in_box_color=(1,', '0,', '0),', 'rot_axis=2,', "center_mode='lidar_bottom',", "mode='xyz'):", 'assert', '0', '<=', 'rot...
916,866
keras-team/keras-nlp
data.py
prepare_tokenizer
prepare_tokenizer
Preapare English and Spanish tokenizer.
[ "Preapare", "English", "and", "Spanish", "tokenizer." ]
def prepare_tokenizer(train_pairs, sequence_length, vocab_size): eng_tokenizer = keras.layers.TextVectorization(max_tokens=vocab_size, output_mode='int', output_sequence_length=sequence_length) spa_tokenizer = keras.layers.TextVectorization(max_tokens=vocab_size, output_mode='int', output_sequence_length=sequen...
['def', 'prepare_tokenizer(train_pairs,', 'sequence_length,', 'vocab_size):', 'eng_tokenizer', '=', 'keras.layers.TextVectorization(max_tokens=vocab_size,', "output_mode='int',", 'output_sequence_length=sequence_length)', 'spa_tokenizer', '=', 'keras.layers.TextVectorization(max_tokens=vocab_size,', "output_mode='int',...
595,596
dtransposed/Reinforcement-Learning-With-Unity-G.E.A.R
meta_curriculum.py
MetaCurriculum.set_all_curriculums_to_lesson_num
set_all_curriculums_to_lesson_num
Sets all the curriculums in this meta curriculum to a specified lesson number.
[ "Sets", "all", "the", "curriculums", "in", "this", "meta", "curriculum", "to", "a", "specified", "lesson", "number." ]
def set_all_curriculums_to_lesson_num(self, lesson_num): for (_, curriculum) in self.brains_to_curriculums.items(): curriculum.lesson_num = lesson_num
['def', 'set_all_curriculums_to_lesson_num(self,', 'lesson_num):', 'for', '(_,', 'curriculum)', 'in', 'self.brains_to_curriculums.items():', 'curriculum.lesson_num', '=', 'lesson_num']
833,744
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
register.py
register.verify_metadata
verify_metadata
Send the metadata to the package index server to be checked.
[ "Send", "the", "metadata", "to", "the", "package", "index", "server", "to", "be", "checked." ]
def verify_metadata(self): (code, result) = self.post_to_server(self.build_post_data('verify')) log.info('Server response (%s): %s' % (code, result))
['def', 'verify_metadata(self):', '(code,', 'result)', '=', "self.post_to_server(self.build_post_data('verify'))", "log.info('Server", 'response', '(%s):', "%s'", '%', '(code,', 'result))']
430,451
seltzerfish/guardyn
gtest_filter_unittest.py
GTestFilterUnitTest.testThreePatterns
testThreePatterns
Tests filters that consist of three patterns.
[ "Tests", "filters", "that", "consist", "of", "three", "patterns." ]
def testThreePatterns(self): self.RunAndVerify('*oo*:*A*:*One', ['FooTest.Abc', 'FooTest.Xyz', 'BarTest.TestOne', 'BazTest.TestOne', 'BazTest.TestA']) self.RunAndVerify('*oo*::*One', ['FooTest.Abc', 'FooTest.Xyz', 'BarTest.TestOne', 'BazTest.TestOne']) self.RunAndVerify('*oo*::', ['FooTest.Abc', 'FooTest.Xy...
['def', 'testThreePatterns(self):', "self.RunAndVerify('*oo*:*A*:*One',", "['FooTest.Abc',", "'FooTest.Xyz',", "'BarTest.TestOne',", "'BazTest.TestOne',", "'BazTest.TestA'])", "self.RunAndVerify('*oo*::*One',", "['FooTest.Abc',", "'FooTest.Xyz',", "'BarTest.TestOne',", "'BazTest.TestOne'])", "self.RunAndVerify('*oo*::'...
572,273
anony-sub/chameleon
executor.py
Future.done
done
Return True if job was successfully cancelled or finished running.
[ "Return", "True", "if", "job", "was", "successfully", "cancelled", "or", "finished", "running." ]
def done(self): raise NotImplementedError()
['def', 'done(self):', 'raise', 'NotImplementedError()']
477,838
PacktPublishing/Hands-On-Artificial--for-Banking
_shgo.py
SHGO.g_topograph
g_topograph
Returns the topographical vector stemming from the specified value ``x_min`` for the current feasible set ``X_min`` with True boolean values indicating positive entries and False values indicating negative entries.
[ "Returns", "the", "topographical", "vector", "stemming", "from", "the", "specified", "value", "``x_min``", "for", "the", "current", "feasible", "set", "``X_min``", "with", "True", "boolean", "values", "indicating", "positive", "entries", "and", "False", "values", ...
def g_topograph(self, x_min, X_min): x_min = np.array([x_min]) self.Y = spatial.distance.cdist(x_min, X_min, 'euclidean') self.Z = np.argsort(self.Y, axis=-1) self.Ss = X_min[self.Z][0] self.minimizer_pool = self.minimizer_pool[self.Z] self.minimizer_pool = self.minimizer_pool[0] return self...
['def', 'g_topograph(self,', 'x_min,', 'X_min):', 'x_min', '=', 'np.array([x_min])', 'self.Y', '=', 'spatial.distance.cdist(x_min,', 'X_min,', "'euclidean')", 'self.Z', '=', 'np.argsort(self.Y,', 'axis=-1)', 'self.Ss', '=', 'X_min[self.Z][0]', 'self.minimizer_pool', '=', 'self.minimizer_pool[self.Z]', 'self.minimizer_p...
203,032
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
cgi.py
FieldStorage.getfirst
getfirst
Return the first value received.
[ "Return", "the", "first", "value", "received." ]
def getfirst(self, key, default=None): if key in self: value = self[key] if isinstance(value, list): return value[0].value else: return value.value else: return default
['def', 'getfirst(self,', 'key,', 'default=None):', 'if', 'key', 'in', 'self:', 'value', '=', 'self[key]', 'if', 'isinstance(value,', 'list):', 'return', 'value[0].value', 'else:', 'return', 'value.value', 'else:', 'return', 'default']
428,268
eddylau328/fyp-artificial-intelligence-ac-control-device
_upload.py
UploadBase.finished
finished
bool: Flag indicating if the upload has completed.
[ "bool:", "Flag", "indicating", "if", "the", "upload", "has", "completed." ]
def finished(self): return self._finished
['def', 'finished(self):', 'return', 'self._finished']
215,450
arshpreetsingh/quantopian-machinelearning
history.py
HistoryManager.reset
reset
Clear the session history, releasing all object references, and optionally open a new session.
[ "Clear", "the", "session", "history,", "releasing", "all", "object", "references,", "and", "optionally", "open", "a", "new", "session." ]
def reset(self, new_session=True): self.output_hist.clear() self.dir_hist[:] = [os.getcwd()] if new_session: if self.session_number: self.end_session() self.input_hist_parsed[:] = [''] self.input_hist_raw[:] = [''] self.new_session()
['def', 'reset(self,', 'new_session=True):', 'self.output_hist.clear()', 'self.dir_hist[:]', '=', '[os.getcwd()]', 'if', 'new_session:', 'if', 'self.session_number:', 'self.end_session()', 'self.input_hist_parsed[:]', '=', "['']", 'self.input_hist_raw[:]', '=', "['']", 'self.new_session()']
886,225
kornia/kornia
test_draw.py
TestDrawLine.test_draw_line_horizontal
test_draw_line_horizontal
Test drawing a horizontal line.
[ "Test", "drawing", "a", "horizontal", "line." ]
def test_draw_line_horizontal(self, dtype, device): img = torch.zeros(1, 8, 8, dtype=dtype, device=device) img = draw_line(img, torch.tensor([6, 4]), torch.tensor([0, 4]), torch.tensor([255])) img_mask = torch.tensor([[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0,...
['def', 'test_draw_line_horizontal(self,', 'dtype,', 'device):', 'img', '=', 'torch.zeros(1,', '8,', '8,', 'dtype=dtype,', 'device=device)', 'img', '=', 'draw_line(img,', 'torch.tensor([6,', '4]),', 'torch.tensor([0,', '4]),', 'torch.tensor([255]))', 'img_mask', '=', 'torch.tensor([[[0.0,', '0.0,', '0.0,', '0.0,', '0.0...
622,353
ryu-ed/SpaceInvaders_Ros
mask_test.py
MaskModuleTest.test_zero_size_from_surface
test_zero_size_from_surface
Ensures from_surface can create masks from zero sized surfaces.
[ "Ensures", "from_surface", "can", "create", "masks", "from", "zero", "sized", "surfaces." ]
def test_zero_size_from_surface(self): for size in ((100, 0), (0, 100), (0, 0)): mask = pygame.mask.from_surface(pygame.Surface(size)) self.assertIsInstance(mask, pygame.mask.MaskType, 'size={}'.format(size)) self.assertEqual(mask.get_size(), size)
['def', 'test_zero_size_from_surface(self):', 'for', 'size', 'in', '((100,', '0),', '(0,', '100),', '(0,', '0)):', 'mask', '=', 'pygame.mask.from_surface(pygame.Surface(size))', 'self.assertIsInstance(mask,', 'pygame.mask.MaskType,', "'size={}'.format(size))", 'self.assertEqual(mask.get_size(),', 'size)']
369,081
QData/deepWordBug
math2html.py
HybridFunction.writepos
writepos
Write all params as read in the parse position.
[ "Write", "all", "params", "as", "read", "in", "the", "parse", "position." ]
def writepos(self, pos): result = [] while not pos.finished(): if pos.checkskip('$'): param = self.writeparam(pos) if param: result.append(param) elif pos.checkskip('f'): function = self.writefunction(pos) if function: ...
['def', 'writepos(self,', 'pos):', 'result', '=', '[]', 'while', 'not', 'pos.finished():', 'if', "pos.checkskip('$'):", 'param', '=', 'self.writeparam(pos)', 'if', 'param:', 'result.append(param)', 'elif', "pos.checkskip('f'):", 'function', '=', 'self.writefunction(pos)', 'if', 'function:', 'function.type', '=', 'None'...
542,641
PaddlePaddle/PARL
utils.py
itergroups
itergroups
An iterator that iterates a list with batch data.
[ "An", "iterator", "that", "iterates", "a", "list", "with", "batch", "data." ]
def itergroups(items, group_size): assert group_size >= 1 group = [] for x in items: group.append(x) if len(group) == group_size: yield tuple(group) del group[:] if group: yield tuple(group)
['def', 'itergroups(items,', 'group_size):', 'assert', 'group_size', '>=', '1', 'group', '=', '[]', 'for', 'x', 'in', 'items:', 'group.append(x)', 'if', 'len(group)', '==', 'group_size:', 'yield', 'tuple(group)', 'del', 'group[:]', 'if', 'group:', 'yield', 'tuple(group)']
277,798
TJU-DRL-LAB/AI-Optimizer
drnn.py
DRNN.features_from_state
features_from_state
Extract features for the decoder network from a prior or posterior.
[ "Extract", "features", "for", "the", "decoder", "network", "from", "a", "prior", "or", "posterior." ]
def features_from_state(self, state): return state['decoder_state']
['def', 'features_from_state(self,', 'state):', 'return', "state['decoder_state']"]
70,324
rudranil723/mini-main
views.py
kmz
kmz
Return KMZ for the given app label, model, and field name.
[ "Return", "KMZ", "for", "the", "given", "app", "label,", "model,", "and", "field", "name." ]
def kmz(request, label, model, field_name=None, using=DEFAULT_DB_ALIAS): return kml(request, label, model, field_name, compress=True, using=using)
['def', 'kmz(request,', 'label,', 'model,', 'field_name=None,', 'using=DEFAULT_DB_ALIAS):', 'return', 'kml(request,', 'label,', 'model,', 'field_name,', 'compress=True,', 'using=using)']
315,381
BehnoodRasti/SUnCNN
common_utils.py
get_image_grid
get_image_grid
Creates a grid from a list of images by concatenating them.
[ "Creates", "a", "grid", "from", "a", "list", "of", "images", "by", "concatenating", "them." ]
def get_image_grid(images_np, nrow=8): images_torch = [torch.from_numpy(x) for x in images_np] torch_grid = torchvision.utils.make_grid(images_torch, nrow) return torch_grid.numpy()
['def', 'get_image_grid(images_np,', 'nrow=8):', 'images_torch', '=', '[torch.from_numpy(x)', 'for', 'x', 'in', 'images_np]', 'torch_grid', '=', 'torchvision.utils.make_grid(images_torch,', 'nrow)', 'return', 'torch_grid.numpy()']
360,495
pykale/pykale
isonet.py
ISONet.ortho_conv
ortho_conv
regularizes the convolution kernel to be (near) orthogonal during training.
[ "regularizes", "the", "convolution", "kernel", "to", "be", "(near)", "orthogonal", "during", "training." ]
def ortho_conv(self, m, device): operator = m.weight operand = torch.cat(torch.chunk(m.weight, m.groups, dim=0), dim=1) transposed = m.weight.shape[1] < m.weight.shape[0] num_channels = m.weight.shape[1] if transposed else m.weight.shape[0] if transposed: operand = operand.transpose(1, 0) ...
['def', 'ortho_conv(self,', 'm,', 'device):', 'operator', '=', 'm.weight', 'operand', '=', 'torch.cat(torch.chunk(m.weight,', 'm.groups,', 'dim=0),', 'dim=1)', 'transposed', '=', 'm.weight.shape[1]', '<', 'm.weight.shape[0]', 'num_channels', '=', 'm.weight.shape[1]', 'if', 'transposed', 'else', 'm.weight.shape[0]', 'if...
819,751
matsu0228/nlp-jp
pyplot.py
ioff
ioff
Turn interactive mode off.
[ "Turn", "interactive", "mode", "off." ]
def ioff(): matplotlib.interactive(False) uninstall_repl_displayhook()
['def', 'ioff():', 'matplotlib.interactive(False)', 'uninstall_repl_displayhook()']
789,103
qianduoduolr/Spa-then-Temp
augmentation.py
RandomResizedCrop.get_crop_bbox
get_crop_bbox
Get a crop bbox given the area range and aspect ratio range.
[ "Get", "a", "crop", "bbox", "given", "the", "area", "range", "and", "aspect", "ratio", "range." ]
def get_crop_bbox(img_shape, area_range, aspect_ratio_range, bbox=None, crop_ratio=None, max_attempts=20): def calc_over_lab(gt, gen): out = 1 for i in range(2): z_min = max(gt[i], gen[i]) z_max = min(gt[i + 2], gen[i + 2]) if z_min >= z_max: retu...
['def', 'get_crop_bbox(img_shape,', 'area_range,', 'aspect_ratio_range,', 'bbox=None,', 'crop_ratio=None,', 'max_attempts=20):', 'def', 'calc_over_lab(gt,', 'gen):', 'out', '=', '1', 'for', 'i', 'in', 'range(2):', 'z_min', '=', 'max(gt[i],', 'gen[i])', 'z_max', '=', 'min(gt[i', '+', '2],', 'gen[i', '+', '2])', 'if', 'z...
393,916
rlworkgroup/garage
_dtypes.py
TimeStep.timeout
timeout
bool: Whether this step records a timeout condition.
[ "bool:", "Whether", "this", "step", "records", "a", "timeout", "condition." ]
def timeout(self): return self.step_type is StepType.TIMEOUT
['def', 'timeout(self):', 'return', 'self.step_type', 'is', 'StepType.TIMEOUT']
200,133
deep-learning-indaba/Baobab
tests.py
ResponseTagAPITest.test_remove_tag_reviewer
test_remove_tag_reviewer
Test that a reviewer can remove a tag from a response.
[ "Test", "that", "a", "reviewer", "can", "remove", "a", "tag", "from", "a", "response." ]
def test_remove_tag_reviewer(self): self._seed_static_data() params = {'event_id': self.event1.id, 'tag_id': self.tag2.id, 'response_id': self.response2.id} response = self.app.delete('/api/v1/responsetag', headers=self.get_auth_header_for('event1reviewer2@mail.com'), json=params) self.assertEqual(respo...
['def', 'test_remove_tag_reviewer(self):', 'self._seed_static_data()', 'params', '=', "{'event_id':", 'self.event1.id,', "'tag_id':", 'self.tag2.id,', "'response_id':", 'self.response2.id}', 'response', '=', "self.app.delete('/api/v1/responsetag',", "headers=self.get_auth_header_for('event1reviewer2@mail.com'),", 'json...
94,212
ncarraz/ESRGANplus
spectral_norm.py
remove_spectral_norm
remove_spectral_norm
Removes the spectral normalization reparameterization from a module.
[ "Removes", "the", "spectral", "normalization", "reparameterization", "from", "a", "module." ]
def remove_spectral_norm(module, name='weight'): for (k, hook) in module._forward_pre_hooks.items(): if isinstance(hook, SpectralNorm) and hook.name == name: hook.remove(module) del module._forward_pre_hooks[k] return module raise ValueError("spectral_norm of '{}' not...
['def', 'remove_spectral_norm(module,', "name='weight'):", 'for', '(k,', 'hook)', 'in', 'module._forward_pre_hooks.items():', 'if', 'isinstance(hook,', 'SpectralNorm)', 'and', 'hook.name', '==', 'name:', 'hook.remove(module)', 'del', 'module._forward_pre_hooks[k]', 'return', 'module', 'raise', 'ValueError("spectral_nor...
563,302
avalonstrel/SketchBERT
utils.py
resize_strokes
resize_strokes
Return bounds of data.
[ "Return", "bounds", "of", "data." ]
def resize_strokes(data, size=128): min_x = 0 max_x = 0 min_y = 0 max_y = 0 abs_x = 0 abs_y = 0 for i in range(len(data)): x = float(data[i, 0]) y = float(data[i, 1]) abs_x += x abs_y += y min_x = min(min_x, abs_x) min_y = min(min_y, abs_y) ...
['def', 'resize_strokes(data,', 'size=128):', 'min_x', '=', '0', 'max_x', '=', '0', 'min_y', '=', '0', 'max_y', '=', '0', 'abs_x', '=', '0', 'abs_y', '=', '0', 'for', 'i', 'in', 'range(len(data)):', 'x', '=', 'float(data[i,', '0])', 'y', '=', 'float(data[i,', '1])', 'abs_x', '+=', 'x', 'abs_y', '+=', 'y', 'min_x', '=',...
350,962
openvinotoolkit/training_extensions
eval_hook.py
CustomEvalHook.evaluate
evaluate
Evaluate predictions from model with ground truth.
[ "Evaluate", "predictions", "from", "model", "with", "ground", "truth." ]
def evaluate(self, runner, results, results_ema=None): eval_res = self.dataloader.dataset.evaluate(results, logger=runner.logger, **self.eval_kwargs) score = eval_res[self.metric] for (name, val) in eval_res.items(): runner.log_buffer.output[name] = val if results_ema: eval_res_ema = sel...
['def', 'evaluate(self,', 'runner,', 'results,', 'results_ema=None):', 'eval_res', '=', 'self.dataloader.dataset.evaluate(results,', 'logger=runner.logger,', '**self.eval_kwargs)', 'score', '=', 'eval_res[self.metric]', 'for', '(name,', 'val)', 'in', 'eval_res.items():', 'runner.log_buffer.output[name]', '=', 'val', 'i...
917,820
asyml/texar-pytorch
tokenizer_base.py
TokenizerBase.map_id_to_text
map_id_to_text
Maps a sequence of ids (integer) to a string, using the tokenizer and vocabulary with options to remove special tokens and clean up tokenization spaces.
[ "Maps", "a", "sequence", "of", "ids", "(integer)", "to", "a", "string,", "using", "the", "tokenizer", "and", "vocabulary", "with", "options", "to", "remove", "special", "tokens", "and", "clean", "up", "tokenization", "spaces." ]
def map_id_to_text(self, token_ids: List[int], skip_special_tokens: bool=False, clean_up_tokenization_spaces: bool=True) -> str: filtered_tokens = self.map_id_to_token(token_ids, skip_special_tokens=skip_special_tokens) text = self.map_token_to_text(filtered_tokens) if clean_up_tokenization_spaces: ...
['def', 'map_id_to_text(self,', 'token_ids:', 'List[int],', 'skip_special_tokens:', 'bool=False,', 'clean_up_tokenization_spaces:', 'bool=True)', '->', 'str:', 'filtered_tokens', '=', 'self.map_id_to_token(token_ids,', 'skip_special_tokens=skip_special_tokens)', 'text', '=', 'self.map_token_to_text(filtered_tokens)', '...
925,110
scikit-learn/scikit-learn
test_common_curve_display.py
test_display_curve_n_samples_consistency
test_display_curve_n_samples_consistency
Check the error raised when `y_pred` or `sample_weight` have inconsistent length.
[ "Check", "the", "error", "raised", "when", "`y_pred`", "or", "`sample_weight`", "have", "inconsistent", "length." ]
def test_display_curve_n_samples_consistency(pyplot, data_binary, Display): (X, y) = data_binary classifier = DecisionTreeClassifier().fit(X, y) msg = 'Found input variables with inconsistent numbers of samples' with pytest.raises(ValueError, match=msg): Display.from_estimator(classifier, X[:-2]...
['def', 'test_display_curve_n_samples_consistency(pyplot,', 'data_binary,', 'Display):', '(X,', 'y)', '=', 'data_binary', 'classifier', '=', 'DecisionTreeClassifier().fit(X,', 'y)', 'msg', '=', "'Found", 'input', 'variables', 'with', 'inconsistent', 'numbers', 'of', "samples'", 'with', 'pytest.raises(ValueError,', 'mat...
853,724
kubeflow/pipelines
artifact_types.py
SlicedClassificationMetrics.log_roc_reading
log_roc_reading
Logs a single data point in the ROC curve of a slice to metadata.
[ "Logs", "a", "single", "data", "point", "in", "the", "ROC", "curve", "of", "a", "slice", "to", "metadata." ]
def log_roc_reading(self, slice: str, threshold: float, tpr: float, fpr: float) -> None: self._upsert_classification_metrics_for_slice(slice) self._sliced_metrics[slice].log_roc_reading(threshold, tpr, fpr) self._update_metadata(slice)
['def', 'log_roc_reading(self,', 'slice:', 'str,', 'threshold:', 'float,', 'tpr:', 'float,', 'fpr:', 'float)', '->', 'None:', 'self._upsert_classification_metrics_for_slice(slice)', 'self._sliced_metrics[slice].log_roc_reading(threshold,', 'tpr,', 'fpr)', 'self._update_metadata(slice)']
780,271
lalwanii26/openscope-barcodingstim
change.py
DoCTrialGenerator.next
next
Automatically called by the task to get the next trial.
[ "Automatically", "called", "by", "the", "task", "to", "get", "the", "next", "trial." ]
def next(self): if self._previous_trial_result() or self._repeats >= self.failure_repeats: self._repeats = 0 return self.new() else: self._repeats += 1 logging.info('Repeating previous trial.') return self._last_trial
['def', 'next(self):', 'if', 'self._previous_trial_result()', 'or', 'self._repeats', '>=', 'self.failure_repeats:', 'self._repeats', '=', '0', 'return', 'self.new()', 'else:', 'self._repeats', '+=', '1', "logging.info('Repeating", 'previous', "trial.')", 'return', 'self._last_trial']
757,488
tobegit3hub/deep_image_model
tensor_array_ops.py
TensorArray.dtype
dtype
The data type of this TensorArray.
[ "The", "data", "type", "of", "this", "TensorArray." ]
def dtype(self): return self._dtype
['def', 'dtype(self):', 'return', 'self._dtype']
183,091
floodsung/DRL-FlappyBird
flappy_bird_utils.py
getHitmask
getHitmask
returns a hitmask using an image's alpha.
[ "returns", "a", "hitmask", "using", "an", "image's", "alpha." ]
def getHitmask(image): mask = [] for x in range(image.get_width()): mask.append([]) for y in range(image.get_height()): mask[x].append(bool(image.get_at((x, y))[3])) return mask
['def', 'getHitmask(image):', 'mask', '=', '[]', 'for', 'x', 'in', 'range(image.get_width()):', 'mask.append([])', 'for', 'y', 'in', 'range(image.get_height()):', 'mask[x].append(bool(image.get_at((x,', 'y))[3]))', 'return', 'mask']
167,311
ArdaGunay99/Key_Detection_Unsupervised_Learning
test_filter_design.py
TestNormalize.test_errors
test_errors
Test the error cases.
[ "Test", "the", "error", "cases." ]
def test_errors(self): assert_raises(ValueError, normalize, [1, 2], 0) assert_raises(ValueError, normalize, [1, 2], [[1]]) assert_raises(ValueError, normalize, [[[1, 2]]], 1)
['def', 'test_errors(self):', 'assert_raises(ValueError,', 'normalize,', '[1,', '2],', '0)', 'assert_raises(ValueError,', 'normalize,', '[1,', '2],', '[[1]])', 'assert_raises(ValueError,', 'normalize,', '[[[1,', '2]]],', '1)']
260,239
dvlab-research/DecoupleNet
generate_soft_label.py
main_worker
main_worker
Create the model and start the training.
[ "Create", "the", "model", "and", "start", "the", "training." ]
def main_worker(gpu, world_size, dist_url): if gpu == 0: if not os.path.exists(args.snapshot_dir): os.makedirs(args.snapshot_dir) logFilename = os.path.join(args.snapshot_dir, str(time.time())) logging.basicConfig(level=logging.INFO, format='%(asctime)s-%(levelname)s-%(message)s'...
['def', 'main_worker(gpu,', 'world_size,', 'dist_url):', 'if', 'gpu', '==', '0:', 'if', 'not', 'os.path.exists(args.snapshot_dir):', 'os.makedirs(args.snapshot_dir)', 'logFilename', '=', 'os.path.join(args.snapshot_dir,', 'str(time.time()))', 'logging.basicConfig(level=logging.INFO,', "format='%(asctime)s-%(levelname)s...
516,733
TrellixVulnTeam/Unsupervised_Learning_HFI7
pretty.py
_PrettyPrinterBase.indent
indent
with statement support for indenting/dedenting.
[ "with", "statement", "support", "for", "indenting/dedenting." ]
def indent(self, indent): self.indentation += indent try: yield finally: self.indentation -= indent
['def', 'indent(self,', 'indent):', 'self.indentation', '+=', 'indent', 'try:', 'yield', 'finally:', 'self.indentation', '-=', 'indent']
448,749
mfbx9da4/neuron-astrocyte-networks
maskedparameters.py
MaskedParameters.topologyMutate
topologyMutate
flips some bits on the mask (but do not exceed the maximum of enabled parameters).
[ "flips", "some", "bits", "on", "the", "mask", "(but", "do", "not", "exceed", "the", "maximum", "of", "enabled", "parameters)." ]
def topologyMutate(self): for i in range(self.pcontainer.paramdim): if random() < self.maskFlipProbability: self.mask[i] = not self.mask[i] tooMany = sum(self.mask) - self.maxComplexity for i in range(tooMany): while True: ind = int(random() * self.pcontainer.paramdim...
['def', 'topologyMutate(self):', 'for', 'i', 'in', 'range(self.pcontainer.paramdim):', 'if', 'random()', '<', 'self.maskFlipProbability:', 'self.mask[i]', '=', 'not', 'self.mask[i]', 'tooMany', '=', 'sum(self.mask)', '-', 'self.maxComplexity', 'for', 'i', 'in', 'range(tooMany):', 'while', 'True:', 'ind', '=', 'int(rand...
722,651
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
runners.py
wait_for_checkpoint
wait_for_checkpoint
Loops until the session is restored from a checkpoint in logdir.
[ "Loops", "until", "the", "session", "is", "restored", "from", "a", "checkpoint", "in", "logdir." ]
def wait_for_checkpoint(saver, sess, logdir): while True: if restore_checkpoint_if_exists(saver, sess, logdir): break else: tf.logging.info('Checkpoint not found in %s, sleeping for 60 seconds.' % logdir) time.sleep(60)
['def', 'wait_for_checkpoint(saver,', 'sess,', 'logdir):', 'while', 'True:', 'if', 'restore_checkpoint_if_exists(saver,', 'sess,', 'logdir):', 'break', 'else:', "tf.logging.info('Checkpoint", 'not', 'found', 'in', '%s,', 'sleeping', 'for', '60', "seconds.'", '%', 'logdir)', 'time.sleep(60)']
54,641
maoyunyao/CMD
rotation.py
unit_vector
unit_vector
Returns the unit vector of the vector.
[ "Returns", "the", "unit", "vector", "of", "the", "vector." ]
def unit_vector(vector): return vector / np.linalg.norm(vector)
['def', 'unit_vector(vector):', 'return', 'vector', '/', 'np.linalg.norm(vector)']
123,338
intel/neural-compressor
utility.py
dequantize_weight
dequantize_weight
Dequantize the weight with min-max filter tensors.
[ "Dequantize", "the", "weight", "with", "min-max", "filter", "tensors." ]
def dequantize_weight(weight_tensor, min_filter_tensor, max_filter_tensor): weight_channel = weight_tensor.shape[-1] if len(min_filter_tensor) == 1: weight_tensor = weight_tensor * ((max_filter_tensor[0] - min_filter_tensor[0]) / 127.0) else: for i in range(weight_channel): weigh...
['def', 'dequantize_weight(weight_tensor,', 'min_filter_tensor,', 'max_filter_tensor):', 'weight_channel', '=', 'weight_tensor.shape[-1]', 'if', 'len(min_filter_tensor)', '==', '1:', 'weight_tensor', '=', 'weight_tensor', '*', '((max_filter_tensor[0]', '-', 'min_filter_tensor[0])', '/', '127.0)', 'else:', 'for', 'i', '...
721,497
clips/pattern
__init__.py
positive
positive
Returns True if the given sentence has a positive sentiment.
[ "Returns", "True", "if", "the", "given", "sentence", "has", "a", "positive", "sentiment." ]
def positive(s, threshold=0.1, **kwargs): return polarity(s, **kwargs) >= threshold
['def', 'positive(s,', 'threshold=0.1,', '**kwargs):', 'return', 'polarity(s,', '**kwargs)', '>=', 'threshold']
765,017
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
tree.py
Tree.isNil
isNil
Indicates the node is a nil node but may still have children, meaning the tree is a flat list.
[ "Indicates", "the", "node", "is", "a", "nil", "node", "but", "may", "still", "have", "children,", "meaning", "the", "tree", "is", "a", "flat", "list." ]
def isNil(self): raise NotImplementedError
['def', 'isNil(self):', 'raise', 'NotImplementedError']
16,493
mfbx9da4/neuron-astrocyte-networks
fitness.py
FitnessList.worst_member
worst_member
This function returns the member with the worst value based upon the criteria of the fitness type.
[ "This", "function", "returns", "the", "member", "with", "the", "worst", "value", "based", "upon", "the", "criteria", "of", "the", "fitness", "type." ]
def worst_member(self): if self._fitness_type == MIN: return self.max_member() elif self._fitness_type == MAX: return self.min_member() elif self._fitness_type == CENTER: return self.max_member()
['def', 'worst_member(self):', 'if', 'self._fitness_type', '==', 'MIN:', 'return', 'self.max_member()', 'elif', 'self._fitness_type', '==', 'MAX:', 'return', 'self.min_member()', 'elif', 'self._fitness_type', '==', 'CENTER:', 'return', 'self.max_member()']
722,868