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 |
|---|---|---|---|---|---|---|---|---|
chainer/chainer | variable.py | Variable.requires_grad | requires_grad | It indicates that ``grad`` will be set in backward calculation. | [
"It",
"indicates",
"that",
"``grad``",
"will",
"be",
"set",
"in",
"backward",
"calculation."
] | def requires_grad(self):
return self._requires_grad | ['def', 'requires_grad(self):', 'return', 'self._requires_grad'] | 477,090 |
intel/neural-compressor | test_configuration.py | TestConfiguration.test_when_all_ports_taken_it_fails | test_when_all_ports_taken_it_fails | Test fail when all ports taken. | [
"Test",
"fail",
"when",
"all",
"ports",
"taken."
] | def test_when_all_ports_taken_it_fails(self, mock_socket_bind: MagicMock) -> None:
mock_socket_bind.configure_mock(side_effect=socket.error)
with self.assertRaises(NotFoundException):
configuration = Configuration()
configuration.set_up() | ['def', 'test_when_all_ports_taken_it_fails(self,', 'mock_socket_bind:', 'MagicMock)', '->', 'None:', 'mock_socket_bind.configure_mock(side_effect=socket.error)', 'with', 'self.assertRaises(NotFoundException):', 'configuration', '=', 'Configuration()', 'configuration.set_up()'] | 721,713 |
greydanus/mr_london | test.py | Client.resolve_redirect | resolve_redirect | Resolves a single redirect and triggers the request again directly on this redirect client. | [
"Resolves",
"a",
"single",
"redirect",
"and",
"triggers",
"the",
"request",
"again",
"directly",
"on",
"this",
"redirect",
"client."
] | def resolve_redirect(self, response, new_location, environ, buffered=False):
(scheme, netloc, script_root, qs, anchor) = url_parse(new_location)
base_url = url_unparse((scheme, netloc, '', '', '')).rstrip('/') + '/'
cur_server_name = netloc.split(':', 1)[0].split('.')
real_server_name = get_host(environ... | ['def', 'resolve_redirect(self,', 'response,', 'new_location,', 'environ,', 'buffered=False):', '(scheme,', 'netloc,', 'script_root,', 'qs,', 'anchor)', '=', 'url_parse(new_location)', 'base_url', '=', 'url_unparse((scheme,', 'netloc,', "'',", "'',", "'')).rstrip('/')", '+', "'/'", 'cur_server_name', '=', "netloc.split... | 264,176 |
LeeDongYeun/keras-m2det | coco.py | CocoGenerator.has_name | has_name | Returns True if name is a known class. | [
"Returns",
"True",
"if",
"name",
"is",
"a",
"known",
"class."
] | def has_name(self, name):
return name in self.classes | ['def', 'has_name(self,', 'name):', 'return', 'name', 'in', 'self.classes'] | 595,476 |
RLE-Foundation/rllte | sac.py | SAC.update_actor_and_alpha | update_actor_and_alpha | Update the actor network and temperature. | [
"Update",
"the",
"actor",
"network",
"and",
"temperature."
] | def update_actor_and_alpha(self, obs: th.Tensor) -> Dict[str, float]:
dist = self.policy.get_dist(obs, step=self.global_step)
action = dist.rsample()
log_prob = dist.log_prob(action).sum(-1, keepdim=True)
(Q1, Q2) = self.policy.critic(obs, action)
Q = th.min(Q1, Q2)
actor_loss = (self.alpha.deta... | ['def', 'update_actor_and_alpha(self,', 'obs:', 'th.Tensor)', '->', 'Dict[str,', 'float]:', 'dist', '=', 'self.policy.get_dist(obs,', 'step=self.global_step)', 'action', '=', 'dist.rsample()', 'log_prob', '=', 'dist.log_prob(action).sum(-1,', 'keepdim=True)', '(Q1,', 'Q2)', '=', 'self.policy.critic(obs,', 'action)', 'Q... | 333,221 |
gradio-app/gradio | clear_button.py | ClearButton.add | add | Adds a component or list of components to the list of components that will be cleared when the button is clicked. | [
"Adds",
"a",
"component",
"or",
"list",
"of",
"components",
"to",
"the",
"list",
"of",
"components",
"that",
"will",
"be",
"cleared",
"when",
"the",
"button",
"is",
"clicked."
] | def add(self, components: None | Component | list[Component]) -> ClearButton:
if not components:
return self
if isinstance(components, Component):
components = [components]
clear_values = json.dumps([component.postprocess(None) for component in components])
self.click(None, [], component... | ['def', 'add(self,', 'components:', 'None', '|', 'Component', '|', 'list[Component])', '->', 'ClearButton:', 'if', 'not', 'components:', 'return', 'self', 'if', 'isinstance(components,', 'Component):', 'components', '=', '[components]', 'clear_values', '=', 'json.dumps([component.postprocess(None)', 'for', 'component',... | 578,903 |
PacktPublishing/Hands-On-Artificial--for-Banking | converter.py | MilliSecondLocator.autoscale | autoscale | Set the view limits to include the data range. | [
"Set",
"the",
"view",
"limits",
"to",
"include",
"the",
"data",
"range."
] | def autoscale(self):
(dmin, dmax) = self.datalim_to_dt()
vmin = dates.date2num(dmin)
vmax = dates.date2num(dmax)
return self.nonsingular(vmin, vmax) | ['def', 'autoscale(self):', '(dmin,', 'dmax)', '=', 'self.datalim_to_dt()', 'vmin', '=', 'dates.date2num(dmin)', 'vmax', '=', 'dates.date2num(dmax)', 'return', 'self.nonsingular(vmin,', 'vmax)'] | 237,071 |
sunishsheth2009/ChatterBot | fst.py | BaseCursor.prefix_bytes | prefix_bytes | Returns the label bytes for the path from the root to the current arc as a single joined bytes object. | [
"Returns",
"the",
"label",
"bytes",
"for",
"the",
"path",
"from",
"the",
"root",
"to",
"the",
"current",
"arc",
"as",
"a",
"single",
"joined",
"bytes",
"object."
] | def prefix_bytes(self):
return emptybytes.join(self.prefix()) | ['def', 'prefix_bytes(self):', 'return', 'emptybytes.join(self.prefix())'] | 484,306 |
ternaus/kaggle_dstl_submission | unet_structures.py | threadsafe_generator | threadsafe_generator | A decorator that takes a generator function and makes it thread-safe. | [
"A",
"decorator",
"that",
"takes",
"a",
"generator",
"function",
"and",
"makes",
"it",
"thread-safe."
] | def threadsafe_generator(f):
def g(*a, **kw):
return threadsafe_iter(f(*a, **kw))
return g | ['def', 'threadsafe_generator(f):', 'def', 'g(*a,', '**kw):', 'return', 'threadsafe_iter(f(*a,', '**kw))', 'return', 'g'] | 247,251 |
RasaHQ/rasa | rasa.py | RasaReader.read_from_json | read_from_json | Loads training data stored in the rasa NLU data format. | [
"Loads",
"training",
"data",
"stored",
"in",
"the",
"rasa",
"NLU",
"data",
"format."
] | def read_from_json(self, js: Dict[Text, Any], **_: Any) -> 'TrainingData':
import rasa.shared.nlu.training_data.schemas.data_schema as schema
import rasa.shared.utils.validation as validation_utils
validation_utils.validate_training_data(js, schema.rasa_nlu_data_schema())
data = js['rasa_nlu_data']
... | ['def', 'read_from_json(self,', 'js:', 'Dict[Text,', 'Any],', '**_:', 'Any)', '->', "'TrainingData':", 'import', 'rasa.shared.nlu.training_data.schemas.data_schema', 'as', 'schema', 'import', 'rasa.shared.utils.validation', 'as', 'validation_utils', 'validation_utils.validate_training_data(js,', 'schema.rasa_nlu_data_s... | 837,745 |
DesertsP/SLRNet | slrnet.py | l2norm | l2norm | Normlize the inp tensor with l2-norm. | [
"Normlize",
"the",
"inp",
"tensor",
"with",
"l2-norm."
] | def l2norm(inp, dim):
return inp / (1e-06 + inp.norm(dim=dim, keepdim=True)) | ['def', 'l2norm(inp,', 'dim):', 'return', 'inp', '/', '(1e-06', '+', 'inp.norm(dim=dim,', 'keepdim=True))'] | 351,982 |
Deci-AI/data-gradients | questions.py | is_notebook | is_notebook | Determines if the current environment is a Jupyter notebook. | [
"Determines",
"if",
"the",
"current",
"environment",
"is",
"a",
"Jupyter",
"notebook."
] | def is_notebook() -> bool:
try:
from IPython import get_ipython
shell = get_ipython().__class__.__name__
if shell == 'ZMQInteractiveShell':
return True
elif shell == 'TerminalInteractiveShell':
return False
else:
return False
except Imp... | ['def', 'is_notebook()', '->', 'bool:', 'try:', 'from', 'IPython', 'import', 'get_ipython', 'shell', '=', 'get_ipython().__class__.__name__', 'if', 'shell', '==', "'ZMQInteractiveShell':", 'return', 'True', 'elif', 'shell', '==', "'TerminalInteractiveShell':", 'return', 'False', 'else:', 'return', 'False', 'except', 'I... | 497,352 |
tonandr/keras_unsupervised | style_based_gan_trainer.py | StyleBasedGANTrainer.optimize | optimize | Optimize the style based GAN model via RL. | [
"Optimize",
"the",
"style",
"based",
"GAN",
"model",
"via",
"RL."
] | def optimize(self, f_conf):
rs_mean = 1.0
for i in tqdm(range(self.hps['steps'])):
action = (self.action + 1.0) * 0.5
rs = []
s_funcs = []
s_funcs.append(create_scaling_func(2.0, 8.0))
s_funcs.append(create_scaling_func(100.0, 1000.0))
s_funcs.append(create_scalin... | ['def', 'optimize(self,', 'f_conf):', 'rs_mean', '=', '1.0', 'for', 'i', 'in', "tqdm(range(self.hps['steps'])):", 'action', '=', '(self.action', '+', '1.0)', '*', '0.5', 'rs', '=', '[]', 's_funcs', '=', '[]', 's_funcs.append(create_scaling_func(2.0,', '8.0))', 's_funcs.append(create_scaling_func(100.0,', '1000.0))', 's... | 256,120 |
nuwandda/Artificial-Intelligence | csp.py | CSP.suppose | suppose | Start accumulating inferences from assuming var=value. | [
"Start",
"accumulating",
"inferences",
"from",
"assuming",
"var=value."
] | def suppose(self, var, value):
self.support_pruning()
removals = [(var, a) for a in self.curr_domains[var] if a != value]
self.curr_domains[var] = [value]
return removals | ['def', 'suppose(self,', 'var,', 'value):', 'self.support_pruning()', 'removals', '=', '[(var,', 'a)', 'for', 'a', 'in', 'self.curr_domains[var]', 'if', 'a', '!=', 'value]', 'self.curr_domains[var]', '=', '[value]', 'return', 'removals'] | 115,587 |
cuiziteng/ICCV_MAET | MAET_YOLO.py | random_noise_levels | random_noise_levels | Generates random shot and read noise from a log-log linear distribution. | [
"Generates",
"random",
"shot",
"and",
"read",
"noise",
"from",
"a",
"log-log",
"linear",
"distribution."
] | def random_noise_levels():
log_min_shot_noise = np.log(0.0001)
log_max_shot_noise = np.log(0.012)
log_shot_noise = np.random.uniform(log_min_shot_noise, log_max_shot_noise)
shot_noise = np.exp(log_shot_noise)
line = lambda x: 2.18 * x + 1.2
log_read_noise = line(log_shot_noise) + np.random.norma... | ['def', 'random_noise_levels():', 'log_min_shot_noise', '=', 'np.log(0.0001)', 'log_max_shot_noise', '=', 'np.log(0.012)', 'log_shot_noise', '=', 'np.random.uniform(log_min_shot_noise,', 'log_max_shot_noise)', 'shot_noise', '=', 'np.exp(log_shot_noise)', 'line', '=', 'lambda', 'x:', '2.18', '*', 'x', '+', '1.2', 'log_r... | 228,721 |
Megvii-BaseDetection/cvpods | instances.py | Instances.get | get | Returns the field called `name`. | [
"Returns",
"the",
"field",
"called",
"`name`."
] | def get(self, name: str) -> Any:
return self._fields[name] | ['def', 'get(self,', 'name:', 'str)', '->', 'Any:', 'return', 'self._fields[name]'] | 523,131 |
tensorly/quantum | input_checks.py | expand_circuits | expand_circuits | Function for consistently expanding circuit inputs. | [
"Function",
"for",
"consistently",
"expanding",
"circuit",
"inputs."
] | def expand_circuits(inputs, symbol_names=None, symbol_values=None, deterministic_proto_serialize=False):
symbols_empty = False
if symbol_names is None:
symbol_names = []
if symbol_values is None:
symbols_empty = True
symbol_values = [[]]
if isinstance(symbol_names, (list, tuple))... | ['def', 'expand_circuits(inputs,', 'symbol_names=None,', 'symbol_values=None,', 'deterministic_proto_serialize=False):', 'symbols_empty', '=', 'False', 'if', 'symbol_names', 'is', 'None:', 'symbol_names', '=', '[]', 'if', 'symbol_values', 'is', 'None:', 'symbols_empty', '=', 'True', 'symbol_values', '=', '[[]]', 'if', ... | 835,290 |
jxhe/unify-parameter-efficient-tuning | modeling_frcnn.py | RPNOutputs.predict_objectness_logits | predict_objectness_logits | Returns: pred_objectness_logits (list[Tensor]) -> (N, Hi*Wi*A). | [
"Returns:",
"pred_objectness_logits",
"(list[Tensor])",
"->",
"(N,",
"Hi*Wi*A)."
] | def predict_objectness_logits(self):
pred_objectness_logits = [score.permute(0, 2, 3, 1).reshape(self.num_images, -1) for score in self.pred_objectness_logits]
return pred_objectness_logits | ['def', 'predict_objectness_logits(self):', 'pred_objectness_logits', '=', '[score.permute(0,', '2,', '3,', '1).reshape(self.num_images,', '-1)', 'for', 'score', 'in', 'self.pred_objectness_logits]', 'return', 'pred_objectness_logits'] | 948,149 |
google-research/rigl | tf_sparse_utils.py | log_sparsities | log_sparsities | Logs relevant sparsity stats to tensorboard. | [
"Logs",
"relevant",
"sparsity",
"stats",
"to",
"tensorboard."
] | def log_sparsities(model, model_name='q_net', log_images=False):
for layer in sparse_utils.get_all_pruning_layers(model):
for (_, mask, threshold) in layer.pruning_vars:
if log_images:
reshaped_mask = tf.expand_dims(tf.expand_dims(mask, 0), -1)
with tf.name_scope(... | ['def', 'log_sparsities(model,', "model_name='q_net',", 'log_images=False):', 'for', 'layer', 'in', 'sparse_utils.get_all_pruning_layers(model):', 'for', '(_,', 'mask,', 'threshold)', 'in', 'layer.pruning_vars:', 'if', 'log_images:', 'reshaped_mask', '=', 'tf.expand_dims(tf.expand_dims(mask,', '0),', '-1)', 'with', "tf... | 841,657 |
aws/sagemaker-python-sdk | session.py | Session.wait_for_auto_ml_job | wait_for_auto_ml_job | Wait for an Amazon SageMaker AutoML job to complete. | [
"Wait",
"for",
"an",
"Amazon",
"SageMaker",
"AutoML",
"job",
"to",
"complete."
] | def wait_for_auto_ml_job(self, job, poll=5):
desc = _wait_until(lambda : _auto_ml_job_status(self.sagemaker_client, job), poll)
_check_job_status(job, desc, 'AutoMLJobStatus')
return desc | ['def', 'wait_for_auto_ml_job(self,', 'job,', 'poll=5):', 'desc', '=', '_wait_until(lambda', ':', '_auto_ml_job_status(self.sagemaker_client,', 'job),', 'poll)', '_check_job_status(job,', 'desc,', "'AutoMLJobStatus')", 'return', 'desc'] | 829,614 |
myothida/Supervised-Machine-Learning | test_loadtxt.py | mixed_types_structured | mixed_types_structured | Fixture providing hetergeneous input data with a structured dtype, along with the associated structured array. | [
"Fixture",
"providing",
"hetergeneous",
"input",
"data",
"with",
"a",
"structured",
"dtype,",
"along",
"with",
"the",
"associated",
"structured",
"array."
] | def mixed_types_structured():
data = StringIO('1000;2.4;alpha;-34\n2000;3.1;beta;29\n3500;9.9;gamma;120\n4090;8.1;delta;0\n5001;4.4;epsilon;-99\n6543;7.8;omega;-1\n')
dtype = np.dtype([('f0', np.uint16), ('f1', np.float64), ('f2', 'S7'), ('f3', np.int8)])
expected = np.array([(1000, 2.4, 'alpha', -34), (200... | ['def', 'mixed_types_structured():', 'data', '=', "StringIO('1000;2.4;alpha;-34\\n2000;3.1;beta;29\\n3500;9.9;gamma;120\\n4090;8.1;delta;0\\n5001;4.4;epsilon;-99\\n6543;7.8;omega;-1\\n')", 'dtype', '=', "np.dtype([('f0',", 'np.uint16),', "('f1',", 'np.float64),', "('f2',", "'S7'),", "('f3',", 'np.int8)])', 'expected', ... | 441,859 |
SamsungLabs/imvoxelnet | waymo_converter.py | Waymo2KITTI.save_image | save_image | Parse and save the images in png format. | [
"Parse",
"and",
"save",
"the",
"images",
"in",
"png",
"format."
] | def save_image(self, frame, file_idx, frame_idx):
for img in frame.images:
img_path = f'{self.image_save_dir}{str(img.name - 1)}/' + f'{self.prefix}{str(file_idx).zfill(3)}' + f'{str(frame_idx).zfill(3)}.png'
img = mmcv.imfrombytes(img.image)
mmcv.imwrite(img, img_path) | ['def', 'save_image(self,', 'frame,', 'file_idx,', 'frame_idx):', 'for', 'img', 'in', 'frame.images:', 'img_path', '=', "f'{self.image_save_dir}{str(img.name", '-', "1)}/'", '+', "f'{self.prefix}{str(file_idx).zfill(3)}'", '+', "f'{str(frame_idx).zfill(3)}.png'", 'img', '=', 'mmcv.imfrombytes(img.image)', 'mmcv.imwrite... | 612,192 |
tensorflow/agents | tensor_spec.py | to_placeholder | to_placeholder | Creates a placeholder from TensorSpec. | [
"Creates",
"a",
"placeholder",
"from",
"TensorSpec."
] | def to_placeholder(spec, outer_dims=()):
ph_shape = list(outer_dims) + spec.shape.as_list()
return tf.compat.v1.placeholder(spec.dtype, ph_shape, spec.name) | ['def', 'to_placeholder(spec,', 'outer_dims=()):', 'ph_shape', '=', 'list(outer_dims)', '+', 'spec.shape.as_list()', 'return', 'tf.compat.v1.placeholder(spec.dtype,', 'ph_shape,', 'spec.name)'] | 22,973 |
facebookresearch/CutLER | predictor.py | VisualizationDemo.run_on_video | run_on_video | Visualizes predictions on frames of the input video. | [
"Visualizes",
"predictions",
"on",
"frames",
"of",
"the",
"input",
"video."
] | def run_on_video(self, video):
video_visualizer = VideoVisualizer(self.metadata, self.instance_mode)
def process_predictions(frame, predictions):
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
if 'panoptic_seg' in predictions:
(panoptic_seg, segments_info) = predictions['panoptic_se... | ['def', 'run_on_video(self,', 'video):', 'video_visualizer', '=', 'VideoVisualizer(self.metadata,', 'self.instance_mode)', 'def', 'process_predictions(frame,', 'predictions):', 'frame', '=', 'cv2.cvtColor(frame,', 'cv2.COLOR_BGR2RGB)', 'if', "'panoptic_seg'", 'in', 'predictions:', '(panoptic_seg,', 'segments_info)', '=... | 509,212 |
enuguru/artificial_intelligence_and_machine_ | __init__.py | BaseQuery.get_or_404 | get_or_404 | Like :meth:`get` but aborts with 404 if not found instead of returning `None`. | [
"Like",
":meth:`get`",
"but",
"aborts",
"with",
"404",
"if",
"not",
"found",
"instead",
"of",
"returning",
"`None`."
] | def get_or_404(self, ident):
rv = self.get(ident)
if rv is None:
abort(404)
return rv | ['def', 'get_or_404(self,', 'ident):', 'rv', '=', 'self.get(ident)', 'if', 'rv', 'is', 'None:', 'abort(404)', 'return', 'rv'] | 157,934 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | kernelapp.py | IPKernelApp.init_gui_pylab | init_gui_pylab | Enable GUI event loop integration, taking pylab into account. | [
"Enable",
"GUI",
"event",
"loop",
"integration,",
"taking",
"pylab",
"into",
"account."
] | def init_gui_pylab(self):
if not os.environ.get('MPLBACKEND'):
os.environ['MPLBACKEND'] = 'module://ipykernel.pylab.backend_inline'
shell = self.shell
_showtraceback = shell._showtraceback
try:
def print_tb(etype, evalue, stb):
print('GUI event loop or pylab initialization f... | ['def', 'init_gui_pylab(self):', 'if', 'not', "os.environ.get('MPLBACKEND'):", "os.environ['MPLBACKEND']", '=', "'module://ipykernel.pylab.backend_inline'", 'shell', '=', 'self.shell', '_showtraceback', '=', 'shell._showtraceback', 'try:', 'def', 'print_tb(etype,', 'evalue,', 'stb):', "print('GUI", 'event', 'loop', 'or... | 447,811 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | thinkstats2.py | HypothesisTest.MaxTestStat | MaxTestStat | Returns the largest test statistic seen during simulations. | [
"Returns",
"the",
"largest",
"test",
"statistic",
"seen",
"during",
"simulations."
] | def MaxTestStat(self):
return max(self.test_stats) | ['def', 'MaxTestStat(self):', 'return', 'max(self.test_stats)'] | 13,710 |
GatorEducator/GatorMiner | streamlit_web.py | question_freq | question_freq | Page for individual question's word frequency. | [
"Page",
"for",
"individual",
"question's",
"word",
"frequency."
] | def question_freq(freq_range):
questions = st.multiselect(label='Select specific questions below:', options=selected_nan_df.columns[2:])
plots_range = st.sidebar.slider('Select the number of plots per row', 1, 5, value=1)
question_df = ut.make_questions_df(questions, main_df)
if len(questions) != 0:
... | ['def', 'question_freq(freq_range):', 'questions', '=', "st.multiselect(label='Select", 'specific', 'questions', "below:',", 'options=selected_nan_df.columns[2:])', 'plots_range', '=', "st.sidebar.slider('Select", 'the', 'number', 'of', 'plots', 'per', "row',", '1,', '5,', 'value=1)', 'question_df', '=', 'ut.make_quest... | 567,419 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | mailbox.py | Maildir.discard | discard | If the keyed message exists, remove it. | [
"If",
"the",
"keyed",
"message",
"exists,",
"remove",
"it."
] | def discard(self, key):
try:
self.remove(key)
except (KeyError, FileNotFoundError):
pass | ['def', 'discard(self,', 'key):', 'try:', 'self.remove(key)', 'except', '(KeyError,', 'FileNotFoundError):', 'pass'] | 428,821 |
weimin17/Object-Detection_HelmetDetection | metrics.py | padded_accuracy | padded_accuracy | Percentage of times that predictions matches labels on non-0s. | [
"Percentage",
"of",
"times",
"that",
"predictions",
"matches",
"labels",
"on",
"non-0s."
] | def padded_accuracy(logits, labels):
with tf.variable_scope('padded_accuracy', values=[logits, labels]):
(logits, labels) = _pad_tensors_to_same_length(logits, labels)
weights = tf.to_float(tf.not_equal(labels, 0))
outputs = tf.to_int32(tf.argmax(logits, axis=-1))
padded_labels = tf.... | ['def', 'padded_accuracy(logits,', 'labels):', 'with', "tf.variable_scope('padded_accuracy',", 'values=[logits,', 'labels]):', '(logits,', 'labels)', '=', '_pad_tensors_to_same_length(logits,', 'labels)', 'weights', '=', 'tf.to_float(tf.not_equal(labels,', '0))', 'outputs', '=', 'tf.to_int32(tf.argmax(logits,', 'axis=-... | 748,772 |
danamyu/hedgehog_detector | np_box_list.py | BoxList.add_field | add_field | Add data to a specified field. | [
"Add",
"data",
"to",
"a",
"specified",
"field."
] | def add_field(self, field, field_data):
if self.has_field(field):
raise ValueError('Field ' + field + 'already exists')
if len(field_data.shape) < 1 or field_data.shape[0] != self.num_boxes():
raise ValueError('Invalid dimensions for field data')
self.data[field] = field_data | ['def', 'add_field(self,', 'field,', 'field_data):', 'if', 'self.has_field(field):', 'raise', "ValueError('Field", "'", '+', 'field', '+', "'already", "exists')", 'if', 'len(field_data.shape)', '<', '1', 'or', 'field_data.shape[0]', '!=', 'self.num_boxes():', 'raise', "ValueError('Invalid", 'dimensions', 'for', 'field'... | 590,147 |
hans/pyccg | word_learner.py | WordLearner.predict_zero_shot_tokens | predict_zero_shot_tokens | Yield zero-shot predictions on the syntax and meaning of words in the sentence requiring novel lexical entries. | [
"Yield",
"zero-shot",
"predictions",
"on",
"the",
"syntax",
"and",
"meaning",
"of",
"words",
"in",
"the",
"sentence",
"requiring",
"novel",
"lexical",
"entries."
] | def predict_zero_shot_tokens(self, sentence, model):
(query_tokens, query_token_syntaxes) = self.prepare_lexical_induction(sentence)
(candidates, _) = predict_zero_shot(self.lexicon, query_tokens, query_token_syntaxes, sentence, self.ontology, model, self._build_likelihood_fns(sentence, model))
return (quer... | ['def', 'predict_zero_shot_tokens(self,', 'sentence,', 'model):', '(query_tokens,', 'query_token_syntaxes)', '=', 'self.prepare_lexical_induction(sentence)', '(candidates,', '_)', '=', 'predict_zero_shot(self.lexicon,', 'query_tokens,', 'query_token_syntaxes,', 'sentence,', 'self.ontology,', 'model,', 'self._build_like... | 296,018 |
HakamShams/Semantic-Mesh-Segmentation | tf_util.py | fully_connected | fully_connected | Fully connected layer with non-linear operation. | [
"Fully",
"connected",
"layer",
"with",
"non-linear",
"operation."
] | def fully_connected(inputs, num_outputs, scope, use_xavier=True, stddev=0.001, weight_decay=None, activation_fn=tf.nn.relu, bn=False, bn_decay=None, is_training=None):
with tf.variable_scope(scope) as sc:
num_input_units = inputs.get_shape()[-1].value
weights = _variable_with_weight_decay('weights',... | ['def', 'fully_connected(inputs,', 'num_outputs,', 'scope,', 'use_xavier=True,', 'stddev=0.001,', 'weight_decay=None,', 'activation_fn=tf.nn.relu,', 'bn=False,', 'bn_decay=None,', 'is_training=None):', 'with', 'tf.variable_scope(scope)', 'as', 'sc:', 'num_input_units', '=', 'inputs.get_shape()[-1].value', 'weights', '=... | 844,038 |
Ruturaj123/Flowchart-Detection | image_processing.py | eval_image | eval_image | Prepare one image for evaluation. | [
"Prepare",
"one",
"image",
"for",
"evaluation."
] | def eval_image(image, height, width, scope=None):
with tf.name_scope(values=[image, height, width], name=scope, default_name='eval_image'):
image = tf.image.central_crop(image, central_fraction=0.875)
image = tf.expand_dims(image, 0)
image = tf.image.resize_bilinear(image, [height, width], a... | ['def', 'eval_image(image,', 'height,', 'width,', 'scope=None):', 'with', 'tf.name_scope(values=[image,', 'height,', 'width],', 'name=scope,', "default_name='eval_image'):", 'image', '=', 'tf.image.central_crop(image,', 'central_fraction=0.875)', 'image', '=', 'tf.expand_dims(image,', '0)', 'image', '=', 'tf.image.resi... | 585,708 |
matsu0228/nlp-jp | colors.py | PowerNorm.autoscale_None | autoscale_None | autoscale only None-valued vmin or vmax. | [
"autoscale",
"only",
"None-valued",
"vmin",
"or",
"vmax."
] | def autoscale_None(self, A):
A = np.asanyarray(A)
if self.vmin is None and A.size:
self.vmin = A.min()
if self.vmin < 0:
self.vmin = 0
warnings.warn('Power-law scaling on negative values is ill-defined, clamping to 0.')
if self.vmax is None and A.size:
self.vm... | ['def', 'autoscale_None(self,', 'A):', 'A', '=', 'np.asanyarray(A)', 'if', 'self.vmin', 'is', 'None', 'and', 'A.size:', 'self.vmin', '=', 'A.min()', 'if', 'self.vmin', '<', '0:', 'self.vmin', '=', '0', "warnings.warn('Power-law", 'scaling', 'on', 'negative', 'values', 'is', 'ill-defined,', 'clamping', 'to', "0.')", 'if... | 788,642 |
weimin17/Object-Detection_HelmetDetection | box_list_ops.py | filter_field_value_equals | filter_field_value_equals | Filter to keep only boxes with field entries equal to the given value. | [
"Filter",
"to",
"keep",
"only",
"boxes",
"with",
"field",
"entries",
"equal",
"to",
"the",
"given",
"value."
] | def filter_field_value_equals(boxlist, field, value, scope=None):
with tf.name_scope(scope, 'FilterFieldValueEquals'):
if not isinstance(boxlist, box_list.BoxList):
raise ValueError('boxlist must be a BoxList')
if not boxlist.has_field(field):
raise ValueError('boxlist must c... | ['def', 'filter_field_value_equals(boxlist,', 'field,', 'value,', 'scope=None):', 'with', 'tf.name_scope(scope,', "'FilterFieldValueEquals'):", 'if', 'not', 'isinstance(boxlist,', 'box_list.BoxList):', 'raise', "ValueError('boxlist", 'must', 'be', 'a', "BoxList')", 'if', 'not', 'boxlist.has_field(field):', 'raise', "Va... | 750,547 |
suarez12138/AI-Reversi_IMP_TextDichotomy | afm.py | AFM.get_xheight | get_xheight | Return the xheight as float. | [
"Return",
"the",
"xheight",
"as",
"float."
] | def get_xheight(self):
return self._header[b'XHeight'] | ['def', 'get_xheight(self):', 'return', "self._header[b'XHeight']"] | 96,022 |
zhang614/MicroGrid | cookies.py | RequestsCookieJar.list_domains | list_domains | Utility method to list all the domains in the jar. | [
"Utility",
"method",
"to",
"list",
"all",
"the",
"domains",
"in",
"the",
"jar."
] | def list_domains(self):
domains = []
for cookie in iter(self):
if cookie.domain not in domains:
domains.append(cookie.domain)
return domains | ['def', 'list_domains(self):', 'domains', '=', '[]', 'for', 'cookie', 'in', 'iter(self):', 'if', 'cookie.domain', 'not', 'in', 'domains:', 'domains.append(cookie.domain)', 'return', 'domains'] | 669,019 |
googleapis/python-aiplatform | grpc_asyncio.py | IndexServiceGrpcAsyncIOTransport.wait_operation | wait_operation | Return a callable for the wait_operation method over gRPC. | [
"Return",
"a",
"callable",
"for",
"the",
"wait_operation",
"method",
"over",
"gRPC."
] | def wait_operation(self) -> Callable[[operations_pb2.WaitOperationRequest], None]:
if 'delete_operation' not in self._stubs:
self._stubs['wait_operation'] = self.grpc_channel.unary_unary('/google.longrunning.Operations/WaitOperation', request_serializer=operations_pb2.WaitOperationRequest.SerializeToString,... | ['def', 'wait_operation(self)', '->', 'Callable[[operations_pb2.WaitOperationRequest],', 'None]:', 'if', "'delete_operation'", 'not', 'in', 'self._stubs:', "self._stubs['wait_operation']", '=', "self.grpc_channel.unary_unary('/google.longrunning.Operations/WaitOperation',", 'request_serializer=operations_pb2.WaitOperat... | 810,868 |
kornia/kornia | responses.py | dog_response | dog_response | Compute the Difference-of-Gaussian response. | [
"Compute",
"the",
"Difference-of-Gaussian",
"response."
] | def dog_response(input: Tensor) -> Tensor:
KORNIA_CHECK_SHAPE(input, ['B', 'C', 'L', 'H', 'W'])
return input[:, :, 1:] - input[:, :, :-1] | ['def', 'dog_response(input:', 'Tensor)', '->', 'Tensor:', 'KORNIA_CHECK_SHAPE(input,', "['B',", "'C',", "'L',", "'H',", "'W'])", 'return', 'input[:,', ':,', '1:]', '-', 'input[:,', ':,', ':-1]'] | 621,735 |
IDEA-Research/detrex | group_criterion.py | GroupSetCriterion.loss_boxes | loss_boxes | Compute the losses related to the bounding boxes, the L1 regression loss and the GIoU loss targets dicts must contain the key "boxes" containing a tensor of dim [nb_target_boxes, 4] The target boxes are expected in format (center_x, center_y, w, h), normalized by the image size. | [
"Compute",
"the",
"losses",
"related",
"to",
"the",
"bounding",
"boxes,",
"the",
"L1",
"regression",
"loss",
"and",
"the",
"GIoU",
"loss",
"targets",
"dicts",
"must",
"contain",
"the",
"key",
"\"boxes\"",
"containing",
"a",
"tensor",
"of",
"dim",
"[nb_target_b... | def loss_boxes(self, outputs, targets, indices, num_boxes):
assert 'pred_boxes' in outputs
idx = self._get_src_permutation_idx(indices)
src_boxes = outputs['pred_boxes'][idx]
target_boxes = torch.cat([t['boxes'][i] for (t, (_, i)) in zip(targets, indices)], dim=0)
loss_bbox = F.l1_loss(src_boxes, ta... | ['def', 'loss_boxes(self,', 'outputs,', 'targets,', 'indices,', 'num_boxes):', 'assert', "'pred_boxes'", 'in', 'outputs', 'idx', '=', 'self._get_src_permutation_idx(indices)', 'src_boxes', '=', "outputs['pred_boxes'][idx]", 'target_boxes', '=', "torch.cat([t['boxes'][i]", 'for', '(t,', '(_,', 'i))', 'in', 'zip(targets,... | 549,942 |
rlgraph/rlgraph | ray_executor.py | RayExecutor.result_by_worker | result_by_worker | Retrieves full episode-reward time series for a worker by id (or first worker in registry if None). | [
"Retrieves",
"full",
"episode-reward",
"time",
"series",
"for",
"a",
"worker",
"by",
"id",
"(or",
"first",
"worker",
"in",
"registry",
"if",
"None)."
] | def result_by_worker(self, worker_index=None):
if worker_index is not None:
ray_worker = self.ray_env_sample_workers[worker_index]
else:
ray_worker = self.ray_env_sample_workers[0]
task = ray_worker.get_workload_statistics.remote()
metrics = ray.get(task)
return dict(episode_rewards=... | ['def', 'result_by_worker(self,', 'worker_index=None):', 'if', 'worker_index', 'is', 'not', 'None:', 'ray_worker', '=', 'self.ray_env_sample_workers[worker_index]', 'else:', 'ray_worker', '=', 'self.ray_env_sample_workers[0]', 'task', '=', 'ray_worker.get_workload_statistics.remote()', 'metrics', '=', 'ray.get(task)', ... | 862,563 |
eddylau328/fyp-artificial-intelligence-ac-control-device | egg_info.py | FileList.recursive_include | recursive_include | Include all files anywhere in 'dir/' that match the pattern. | [
"Include",
"all",
"files",
"anywhere",
"in",
"'dir/'",
"that",
"match",
"the",
"pattern."
] | def recursive_include(self, dir, pattern):
full_pattern = os.path.join(dir, '**', pattern)
found = [f for f in glob(full_pattern, recursive=True) if not os.path.isdir(f)]
self.extend(found)
return bool(found) | ['def', 'recursive_include(self,', 'dir,', 'pattern):', 'full_pattern', '=', 'os.path.join(dir,', "'**',", 'pattern)', 'found', '=', '[f', 'for', 'f', 'in', 'glob(full_pattern,', 'recursive=True)', 'if', 'not', 'os.path.isdir(f)]', 'self.extend(found)', 'return', 'bool(found)'] | 199,153 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | nb_008.py | series2cat | series2cat | Categorifies the columns in df. | [
"Categorifies",
"the",
"columns",
"in",
"df."
] | def series2cat(df: DataFrame, *col_names):
for c in listify(col_names):
df[c] = df[c].astype('category').cat.as_ordered() | ['def', 'series2cat(df:', 'DataFrame,', '*col_names):', 'for', 'c', 'in', 'listify(col_names):', 'df[c]', '=', "df[c].astype('category').cat.as_ordered()"] | 32,529 |
wandb/wandb | test_kubernetes.py | test_state_from_conditions | test_state_from_conditions | Test that we extract CRD state from conditions correctly. | [
"Test",
"that",
"we",
"extract",
"CRD",
"state",
"from",
"conditions",
"correctly."
] | def test_state_from_conditions(conditions, expected):
state = _state_from_conditions(conditions)
if isinstance(state, str):
assert CRD_STATE_DICT[state.lower()] == expected
else:
assert state == expected is None | ['def', 'test_state_from_conditions(conditions,', 'expected):', 'state', '=', '_state_from_conditions(conditions)', 'if', 'isinstance(state,', 'str):', 'assert', 'CRD_STATE_DICT[state.lower()]', '==', 'expected', 'else:', 'assert', 'state', '==', 'expected', 'is', 'None'] | 941,302 |
matsu0228/nlp-jp | py3compat.py | annotate | annotate | Python 3 compatible function annotation for Python 2. | [
"Python",
"3",
"compatible",
"function",
"annotation",
"for",
"Python",
"2."
] | def annotate(**kwargs):
if not kwargs:
raise ValueError('annotations must be provided as keyword arguments')
def dec(f):
if hasattr(f, '__annotations__'):
for (k, v) in kwargs.items():
f.__annotations__[k] = v
else:
f.__annotations__ = kwargs
... | ['def', 'annotate(**kwargs):', 'if', 'not', 'kwargs:', 'raise', "ValueError('annotations", 'must', 'be', 'provided', 'as', 'keyword', "arguments')", 'def', 'dec(f):', 'if', 'hasattr(f,', "'__annotations__'):", 'for', '(k,', 'v)', 'in', 'kwargs.items():', 'f.__annotations__[k]', '=', 'v', 'else:', 'f.__annotations__', '... | 787,457 |
pytorch/examples | two_d_parallel_example.py | demo_2d | demo_2d | Main body of the demo of a basic version of tensor parallel by using PyTorch native APIs. | [
"Main",
"body",
"of",
"the",
"demo",
"of",
"a",
"basic",
"version",
"of",
"tensor",
"parallel",
"by",
"using",
"PyTorch",
"native",
"APIs."
] | def demo_2d(rank, args):
print(f'Running basic Megatron style TP example on rank {rank}.')
setup(rank, args.world_size)
assert args.world_size % args.tp_size == 0, 'World size needs to be divisible by TP size'
device_mesh = DeviceMesh('cuda', torch.arange(0, args.world_size).view(-1, args.tp_size))
... | ['def', 'demo_2d(rank,', 'args):', "print(f'Running", 'basic', 'Megatron', 'style', 'TP', 'example', 'on', 'rank', "{rank}.')", 'setup(rank,', 'args.world_size)', 'assert', 'args.world_size', '%', 'args.tp_size', '==', '0,', "'World", 'size', 'needs', 'to', 'be', 'divisible', 'by', 'TP', "size'", 'device_mesh', '=', "D... | 178,601 |
Mdominik/artificial_intelligence | retrying.py | Retrying.stop_after_delay | stop_after_delay | Stop after the time from the first attempt >= stop_max_delay. | [
"Stop",
"after",
"the",
"time",
"from",
"the",
"first",
"attempt",
">=",
"stop_max_delay."
] | def stop_after_delay(self, previous_attempt_number, delay_since_first_attempt_ms):
return delay_since_first_attempt_ms >= self._stop_max_delay | ['def', 'stop_after_delay(self,', 'previous_attempt_number,', 'delay_since_first_attempt_ms):', 'return', 'delay_since_first_attempt_ms', '>=', 'self._stop_max_delay'] | 143,506 |
QData/deepWordBug | configprovider.py | BaseProvider.provide | provide | Provide a config value. | [
"Provide",
"a",
"config",
"value."
] | def provide(self):
raise NotImplementedError('provide') | ['def', 'provide(self):', 'raise', "NotImplementedError('provide')"] | 541,222 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | lexicon.py | build_lexicon | build_lexicon | Constructs a SyntaxNet lexicon at the given path. | [
"Constructs",
"a",
"SyntaxNet",
"lexicon",
"at",
"the",
"given",
"path."
] | def build_lexicon(output_path, training_corpus_path, tf_master='', training_corpus_format='conll-sentence', morph_to_pos=False, **kwargs):
context = create_lexicon_context(output_path)
if morph_to_pos:
context.parameter.add(name='join_category_to_pos', value='true')
context.parameter.add(name='a... | ['def', 'build_lexicon(output_path,', 'training_corpus_path,', "tf_master='',", "training_corpus_format='conll-sentence',", 'morph_to_pos=False,', '**kwargs):', 'context', '=', 'create_lexicon_context(output_path)', 'if', 'morph_to_pos:', "context.parameter.add(name='join_category_to_pos',", "value='true')", "context.p... | 111,212 |
Katja-M/Python_NaturalLanguageProcessing | transforms.py | BboxBase.bounds | bounds | Return (:attr:`x0`, :attr:`y0`, :attr:`width`, :attr:`height`). | [
"Return",
"(:attr:`x0`,",
":attr:`y0`,",
":attr:`width`,",
":attr:`height`)."
] | def bounds(self):
((x0, y0), (x1, y1)) = self.get_points()
return (x0, y0, x1 - x0, y1 - y0) | ['def', 'bounds(self):', '((x0,', 'y0),', '(x1,', 'y1))', '=', 'self.get_points()', 'return', '(x0,', 'y0,', 'x1', '-', 'x0,', 'y1', '-', 'y0)'] | 864,960 |
deepmind/meltingpot | the_matrix.py | create_ready_to_interact_marker | create_ready_to_interact_marker | Create a ready-to-interact marker overlay object. | [
"Create",
"a",
"ready-to-interact",
"marker",
"overlay",
"object."
] | def create_ready_to_interact_marker(player_idx: int) -> Dict[str, Any]:
lua_idx = player_idx + 1
marking_object = {'name': 'avatarReadyToInteractMarker', 'components': [{'component': 'StateManager', 'kwargs': {'initialState': 'avatarMarkingWait', 'stateConfigs': [{'state': 'ready', 'layer': 'overlay', 'sprite':... | ['def', 'create_ready_to_interact_marker(player_idx:', 'int)', '->', 'Dict[str,', 'Any]:', 'lua_idx', '=', 'player_idx', '+', '1', 'marking_object', '=', "{'name':", "'avatarReadyToInteractMarker',", "'components':", "[{'component':", "'StateManager',", "'kwargs':", "{'initialState':", "'avatarMarkingWait',", "'stateCo... | 285,870 |
PeizeSun/OneNet | visualizer.py | Visualizer.draw_sem_seg | draw_sem_seg | Draw semantic segmentation predictions/labels. | [
"Draw",
"semantic",
"segmentation",
"predictions/labels."
] | def draw_sem_seg(self, sem_seg, area_threshold=None, alpha=0.8):
if isinstance(sem_seg, torch.Tensor):
sem_seg = sem_seg.numpy()
(labels, areas) = np.unique(sem_seg, return_counts=True)
sorted_idxs = np.argsort(-areas).tolist()
labels = labels[sorted_idxs]
for label in filter(lambda l: l < l... | ['def', 'draw_sem_seg(self,', 'sem_seg,', 'area_threshold=None,', 'alpha=0.8):', 'if', 'isinstance(sem_seg,', 'torch.Tensor):', 'sem_seg', '=', 'sem_seg.numpy()', '(labels,', 'areas)', '=', 'np.unique(sem_seg,', 'return_counts=True)', 'sorted_idxs', '=', 'np.argsort(-areas).tolist()', 'labels', '=', 'labels[sorted_idxs... | 756,075 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | cmd.py | Command.move_file | move_file | Move a file respecting dry-run flag. | [
"Move",
"a",
"file",
"respecting",
"dry-run",
"flag."
] | def move_file(self, src, dst, level=1):
return file_util.move_file(src, dst, dry_run=self.dry_run) | ['def', 'move_file(self,', 'src,', 'dst,', 'level=1):', 'return', 'file_util.move_file(src,', 'dst,', 'dry_run=self.dry_run)'] | 430,289 |
joao-montanari/artificial_intelligence | retrying.py | Retrying.stop_after_attempt | stop_after_attempt | Stop after the previous attempt >= stop_max_attempt_number. | [
"Stop",
"after",
"the",
"previous",
"attempt",
">=",
"stop_max_attempt_number."
] | def stop_after_attempt(self, previous_attempt_number, delay_since_first_attempt_ms):
return previous_attempt_number >= self._stop_max_attempt_number | ['def', 'stop_after_attempt(self,', 'previous_attempt_number,', 'delay_since_first_attempt_ms):', 'return', 'previous_attempt_number', '>=', 'self._stop_max_attempt_number'] | 74,288 |
huawei-noah/xingtian | prune.py | PruneBatchNorm.apply | apply | Apply mask to batchNorm. | [
"Apply",
"mask",
"to",
"batchNorm."
] | def apply(self, mask_code):
end_mask = np.asarray(mask_code)
idx = np.squeeze(np.argwhere(np.asarray(np.ones(end_mask.shape) - end_mask))).tolist()
self._make_mask(idx)
if zeus.is_tf_backend():
import tensorflow as tf
return tf.assign(self.layer, self.layer * tf.constant(self.mask, dtype... | ['def', 'apply(self,', 'mask_code):', 'end_mask', '=', 'np.asarray(mask_code)', 'idx', '=', 'np.squeeze(np.argwhere(np.asarray(np.ones(end_mask.shape)', '-', 'end_mask))).tolist()', 'self._make_mask(idx)', 'if', 'zeus.is_tf_backend():', 'import', 'tensorflow', 'as', 'tf', 'return', 'tf.assign(self.layer,', 'self.layer'... | 962,732 |
ZhAnGToNG1/transfer_learning_cspt | base_panoptic_fusion_head.py | BasePanopticFusionHead.with_loss | with_loss | bool: whether the panoptic head contains loss function. | [
"bool:",
"whether",
"the",
"panoptic",
"head",
"contains",
"loss",
"function."
] | def with_loss(self):
return self.loss_panoptic is not None | ['def', 'with_loss(self):', 'return', 'self.loss_panoptic', 'is', 'not', 'None'] | 964,281 |
0x5eba/Anime-Character-Generator | ACGAN.py | Discriminator.forward | forward | Defines a forward pass of a discriminator. | [
"Defines",
"a",
"forward",
"pass",
"of",
"a",
"discriminator."
] | def forward(self, _input):
features = self.conv_layers(_input)
discrim_output = self.discriminator_layer(features).view(-1)
flatten = self.bottleneck(features).squeeze()
hair_class = self.hair_classifier(flatten)
eye_class = self.eye_classifier(flatten)
return (discrim_output, hair_class, eye_cl... | ['def', 'forward(self,', '_input):', 'features', '=', 'self.conv_layers(_input)', 'discrim_output', '=', 'self.discriminator_layer(features).view(-1)', 'flatten', '=', 'self.bottleneck(features).squeeze()', 'hair_class', '=', 'self.hair_classifier(flatten)', 'eye_class', '=', 'self.eye_classifier(flatten)', 'return', '... | 416,298 |
weimin17/Object-Detection_HelmetDetection | config_util_test.py | ConfigUtilTest.testNewLabelMapPath | testNewLabelMapPath | Tests that label map path can be overwritten in input readers. | [
"Tests",
"that",
"label",
"map",
"path",
"can",
"be",
"overwritten",
"in",
"input",
"readers."
] | def testNewLabelMapPath(self):
original_label_map_path = 'path/to/original/label_map'
new_label_map_path = 'path//to/new/label_map'
pipeline_config_path = os.path.join(self.get_temp_dir(), 'pipeline.config')
pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
train_input_reader = pipeline_confi... | ['def', 'testNewLabelMapPath(self):', 'original_label_map_path', '=', "'path/to/original/label_map'", 'new_label_map_path', '=', "'path//to/new/label_map'", 'pipeline_config_path', '=', 'os.path.join(self.get_temp_dir(),', "'pipeline.config')", 'pipeline_config', '=', 'pipeline_pb2.TrainEvalPipelineConfig()', 'train_in... | 750,994 |
maiziezhoulab/RNN_BrainMaturation | tools.py | gen_feed_dict | gen_feed_dict | Generate feed_dict for session run. | [
"Generate",
"feed_dict",
"for",
"session",
"run."
] | def gen_feed_dict(model, trial, hp):
if hp['in_type'] == 'normal':
feed_dict = {model.x: trial.x, model.y: trial.y, model.c_mask: trial.c_mask}
elif hp['in_type'] == 'multi':
(n_time, batch_size) = trial.x.shape[:2]
new_shape = [n_time, batch_size, hp['rule_start'] * hp['n_rule']]
... | ['def', 'gen_feed_dict(model,', 'trial,', 'hp):', 'if', "hp['in_type']", '==', "'normal':", 'feed_dict', '=', '{model.x:', 'trial.x,', 'model.y:', 'trial.y,', 'model.c_mask:', 'trial.c_mask}', 'elif', "hp['in_type']", '==', "'multi':", '(n_time,', 'batch_size)', '=', 'trial.x.shape[:2]', 'new_shape', '=', '[n_time,', '... | 325,530 |
MTemraz/autoencoder | setup_inception.py | NodeLookup.load | load | Loads a human readable English name for each softmax node. | [
"Loads",
"a",
"human",
"readable",
"English",
"name",
"for",
"each",
"softmax",
"node."
] | def load(self, label_lookup_path):
if not tf.gfile.Exists(label_lookup_path):
tf.logging.fatal('File does not exist %s', label_lookup_path)
node_id_to_name = {}
proto_as_ascii = tf.gfile.GFile(label_lookup_path).readlines()
for line in proto_as_ascii:
if line:
words = line.sp... | ['def', 'load(self,', 'label_lookup_path):', 'if', 'not', 'tf.gfile.Exists(label_lookup_path):', "tf.logging.fatal('File", 'does', 'not', 'exist', "%s',", 'label_lookup_path)', 'node_id_to_name', '=', '{}', 'proto_as_ascii', '=', 'tf.gfile.GFile(label_lookup_path).readlines()', 'for', 'line', 'in', 'proto_as_ascii:', '... | 418,949 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | nested_utils.py | map_nested | map_nested | Executes map_fn on every element in a (potentially) nested structure. | [
"Executes",
"map_fn",
"on",
"every",
"element",
"in",
"a",
"(potentially)",
"nested",
"structure."
] | def map_nested(map_fn, nested):
out = map(map_fn, nest.flatten(nested))
return nest.pack_sequence_as(nested, out) | ['def', 'map_nested(map_fn,', 'nested):', 'out', '=', 'map(map_fn,', 'nest.flatten(nested))', 'return', 'nest.pack_sequence_as(nested,', 'out)'] | 48,359 |
asvcode/Udacity-AIND-Isolation | isolation.py | Board.is_loser | is_loser | Test whether the specified player has lost the game. | [
"Test",
"whether",
"the",
"specified",
"player",
"has",
"lost",
"the",
"game."
] | def is_loser(self, player):
return player == self.active_player and (not self.get_legal_moves(self.active_player)) | ['def', 'is_loser(self,', 'player):', 'return', 'player', '==', 'self.active_player', 'and', '(not', 'self.get_legal_moves(self.active_player))'] | 427,521 |
weimin17/Object-Detection_HelmetDetection | sentence_io.py | FormatSentenceReader.read | read | Reads a single batch of sentences. | [
"Reads",
"a",
"single",
"batch",
"of",
"sentences."
] | def read(self):
if self._session:
(sentences, is_last) = self._session.run([self._source, self._is_last])
if is_last:
self._session.close()
self._session = None
else:
(sentences, is_last) = ([], True)
return (sentences, is_last) | ['def', 'read(self):', 'if', 'self._session:', '(sentences,', 'is_last)', '=', 'self._session.run([self._source,', 'self._is_last])', 'if', 'is_last:', 'self._session.close()', 'self._session', '=', 'None', 'else:', '(sentences,', 'is_last)', '=', '([],', 'True)', 'return', '(sentences,', 'is_last)'] | 753,466 |
btdobbs/AI | heuristic_search.py | Grid.is_within_boundaries | is_within_boundaries | Checks if the given coordinate is within the grid. | [
"Checks",
"if",
"the",
"given",
"coordinate",
"is",
"within",
"the",
"grid."
] | def is_within_boundaries(self, x, y):
return x >= 0 and x < self.width and (y >= 0) and (y < self.height) | ['def', 'is_within_boundaries(self,', 'x,', 'y):', 'return', 'x', '>=', '0', 'and', 'x', '<', 'self.width', 'and', '(y', '>=', '0)', 'and', '(y', '<', 'self.height)'] | 69,745 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | visitor.py | Class.acceptConstructorDecl | acceptConstructorDecl | Accept and process a constructor declaration. | [
"Accept",
"and",
"process",
"a",
"constructor",
"declaration."
] | def acceptConstructorDecl(self, node, memo):
method = self.factory.method(name='__init__', type=self.name, parent=self)
superCalls = node.findChildrenOfType(tokens.SUPER_CONSTRUCTOR_CALL)
if not any(superCalls) and any(self.bases):
fs = 'super(' + FS.r + ', self).__init__()'
self.factory.exp... | ['def', 'acceptConstructorDecl(self,', 'node,', 'memo):', 'method', '=', "self.factory.method(name='__init__',", 'type=self.name,', 'parent=self)', 'superCalls', '=', 'node.findChildrenOfType(tokens.SUPER_CONSTRUCTOR_CALL)', 'if', 'not', 'any(superCalls)', 'and', 'any(self.bases):', 'fs', '=', "'super('", '+', 'FS.r', ... | 10,957 |
Oporto/CS4341_Artificial_Inteligence | locations.py | write_delete_marker_file | write_delete_marker_file | Write the pip delete marker file into this directory. | [
"Write",
"the",
"pip",
"delete",
"marker",
"file",
"into",
"this",
"directory."
] | def write_delete_marker_file(directory):
filepath = os.path.join(directory, PIP_DELETE_MARKER_FILENAME)
with open(filepath, 'w') as marker_fp:
marker_fp.write(DELETE_MARKER_MESSAGE) | ['def', 'write_delete_marker_file(directory):', 'filepath', '=', 'os.path.join(directory,', 'PIP_DELETE_MARKER_FILENAME)', 'with', 'open(filepath,', "'w')", 'as', 'marker_fp:', 'marker_fp.write(DELETE_MARKER_MESSAGE)'] | 190,784 |
1996scarlet/Laser-Eye | iris_localization.py | IrisLocalizationModel.get_mesh | get_mesh | Detect the face mesh from the image given. | [
"Detect",
"the",
"face",
"mesh",
"from",
"the",
"image",
"given."
] | def get_mesh(self, image, length, center, name=None):
(image, M) = self._preprocess(image, length, center, name)
image = tf.image.convert_image_dtype(image, tf.float32)
image = image[tf.newaxis, :]
self.interpreter.set_tensor(self.input_details[0]['index'], image)
self.interpreter.invoke()
iris ... | ['def', 'get_mesh(self,', 'image,', 'length,', 'center,', 'name=None):', '(image,', 'M)', '=', 'self._preprocess(image,', 'length,', 'center,', 'name)', 'image', '=', 'tf.image.convert_image_dtype(image,', 'tf.float32)', 'image', '=', 'image[tf.newaxis,', ':]', "self.interpreter.set_tensor(self.input_details[0]['index'... | 623,729 |
noambassat/SpeechTrainer | parser.py | CustomOptionParser.insert_option_group | insert_option_group | Insert an OptionGroup at a given position. | [
"Insert",
"an",
"OptionGroup",
"at",
"a",
"given",
"position."
] | def insert_option_group(self, idx, *args, **kwargs):
group = self.add_option_group(*args, **kwargs)
self.option_groups.pop()
self.option_groups.insert(idx, group)
return group | ['def', 'insert_option_group(self,', 'idx,', '*args,', '**kwargs):', 'group', '=', 'self.add_option_group(*args,', '**kwargs)', 'self.option_groups.pop()', 'self.option_groups.insert(idx,', 'group)', 'return', 'group'] | 894,936 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | msvc.py | RegistryInfo.sxs | sxs | Microsoft Visual Studio SxS registry key. | [
"Microsoft",
"Visual",
"Studio",
"SxS",
"registry",
"key."
] | def sxs(self):
return os.path.join(self.visualstudio, 'SxS') | ['def', 'sxs(self):', 'return', 'os.path.join(self.visualstudio,', "'SxS')"] | 950,891 |
noambassat/SpeechTrainer | lazy_wheel.py | LazyZipOverHTTP.closed | closed | Whether the file is closed. | [
"Whether",
"the",
"file",
"is",
"closed."
] | def closed(self):
return self._file.closed | ['def', 'closed(self):', 'return', 'self._file.closed'] | 895,019 |
fhaghighi/DiRA | lovasz.py | mean | mean | Nanmean compatible with generators. | [
"Nanmean",
"compatible",
"with",
"generators."
] | def mean(values, ignore_nan=False, empty=0):
values = iter(values)
if ignore_nan:
values = ifilterfalse(isnan, values)
try:
n = 1
acc = next(values)
except StopIteration:
if empty == 'raise':
raise ValueError('Empty mean')
return empty
for (n, v) i... | ['def', 'mean(values,', 'ignore_nan=False,', 'empty=0):', 'values', '=', 'iter(values)', 'if', 'ignore_nan:', 'values', '=', 'ifilterfalse(isnan,', 'values)', 'try:', 'n', '=', '1', 'acc', '=', 'next(values)', 'except', 'StopIteration:', 'if', 'empty', '==', "'raise':", 'raise', "ValueError('Empty", "mean')", 'return',... | 186,263 |
blakechen97/SASA | fastai_optim.py | listify | listify | Make `p` listy and the same length as `q`. | [
"Make",
"`p`",
"listy",
"and",
"the",
"same",
"length",
"as",
"`q`."
] | def listify(p=None, q=None):
if p is None:
p = []
elif isinstance(p, str):
p = [p]
elif not isinstance(p, Iterable):
p = [p]
n = q if type(q) == int else len(p) if q is None else len(q)
if len(p) == 1:
p = p * n
assert len(p) == n, f'List len mismatch ({len(p)} vs... | ['def', 'listify(p=None,', 'q=None):', 'if', 'p', 'is', 'None:', 'p', '=', '[]', 'elif', 'isinstance(p,', 'str):', 'p', '=', '[p]', 'elif', 'not', 'isinstance(p,', 'Iterable):', 'p', '=', '[p]', 'n', '=', 'q', 'if', 'type(q)', '==', 'int', 'else', 'len(p)', 'if', 'q', 'is', 'None', 'else', 'len(q)', 'if', 'len(p)', '==... | 845,591 |
enlite-ai/maze | wrapper.py | ObservationWrapper.get_observation_and_action_dicts | get_observation_and_action_dicts | Convert the observations, keep actions the same. | [
"Convert",
"the",
"observations,",
"keep",
"actions",
"the",
"same."
] | def get_observation_and_action_dicts(self, maze_state: Optional[MazeStateType], maze_action: Optional[MazeActionType], first_step_in_episode: bool) -> Tuple[Optional[Dict[Union[int, str], Any]], Optional[Dict[Union[int, str], Any]]]:
(obs_dict, act_dict) = self.env.get_observation_and_action_dicts(maze_state, maze_... | ['def', 'get_observation_and_action_dicts(self,', 'maze_state:', 'Optional[MazeStateType],', 'maze_action:', 'Optional[MazeActionType],', 'first_step_in_episode:', 'bool)', '->', 'Tuple[Optional[Dict[Union[int,', 'str],', 'Any]],', 'Optional[Dict[Union[int,', 'str],', 'Any]]]:', '(obs_dict,', 'act_dict)', '=', 'self.en... | 646,937 |
zomux/deepy | annealers.py | LearningRateAnnealer.invoke | invoke | Run it, return whether to end training. | [
"Run",
"it,",
"return",
"whether",
"to",
"end",
"training."
] | def invoke(self):
self._iter += 1
if self._iter - max(self._trainer.best_iter, self._annealed_iter) >= self._patience:
if self._annealed_times >= self._anneal_times:
logging.info('ending')
self._trainer.exit()
else:
self._trainer.set_params(*self._trainer.best... | ['def', 'invoke(self):', 'self._iter', '+=', '1', 'if', 'self._iter', '-', 'max(self._trainer.best_iter,', 'self._annealed_iter)', '>=', 'self._patience:', 'if', 'self._annealed_times', '>=', 'self._anneal_times:', "logging.info('ending')", 'self._trainer.exit()', 'else:', 'self._trainer.set_params(*self._trainer.best_... | 180,992 |
enuguru/artificial_intelligence_and_machine_ | test_sdist.py | TestSdistTest.test_package_data_in_sdist | test_package_data_in_sdist | Regression test for pull request #4: ensures that files listed in package_data are included in the manifest even if they're not added to version control. | [
"Regression",
"test",
"for",
"pull",
"request",
"#4:",
"ensures",
"that",
"files",
"listed",
"in",
"package_data",
"are",
"included",
"in",
"the",
"manifest",
"even",
"if",
"they're",
"not",
"added",
"to",
"version",
"control."
] | def test_package_data_in_sdist(self):
dist = Distribution(SETUP_ATTRS)
dist.script_name = 'setup.py'
cmd = sdist(dist)
cmd.ensure_finalized()
quiet()
try:
cmd.run()
finally:
unquiet()
manifest = cmd.filelist.files
self.assertTrue(os.path.join('sdist_test', 'a.txt') in... | ['def', 'test_package_data_in_sdist(self):', 'dist', '=', 'Distribution(SETUP_ATTRS)', 'dist.script_name', '=', "'setup.py'", 'cmd', '=', 'sdist(dist)', 'cmd.ensure_finalized()', 'quiet()', 'try:', 'cmd.run()', 'finally:', 'unquiet()', 'manifest', '=', 'cmd.filelist.files', "self.assertTrue(os.path.join('sdist_test',",... | 135,211 |
enuguru/artificial_intelligence_and_machine_learning | control.py | Coverage.sys_info | sys_info | Return a list of (key, value) pairs showing internal information. | [
"Return",
"a",
"list",
"of",
"(key,",
"value)",
"pairs",
"showing",
"internal",
"information."
] | def sys_info(self):
import coverage as covmod
self._init()
ft_plugins = []
for ft in self.plugins.file_tracers:
ft_name = ft._coverage_plugin_name
if not ft._coverage_enabled:
ft_name += ' (disabled)'
ft_plugins.append(ft_name)
info = [('version', covmod.__version... | ['def', 'sys_info(self):', 'import', 'coverage', 'as', 'covmod', 'self._init()', 'ft_plugins', '=', '[]', 'for', 'ft', 'in', 'self.plugins.file_tracers:', 'ft_name', '=', 'ft._coverage_plugin_name', 'if', 'not', 'ft._coverage_enabled:', 'ft_name', '+=', "'", "(disabled)'", 'ft_plugins.append(ft_name)', 'info', '=', "[(... | 157,286 |
ifwe/digsby | imwin_tofrom.py | account_menu_item | account_menu_item | Return a menu item object for a "From" account. | [
"Return",
"a",
"menu",
"item",
"object",
"for",
"a",
"\"From\"",
"account."
] | def account_menu_item(acct):
return SimpleMenuItem(account_menucontent(acct)) | ['def', 'account_menu_item(acct):', 'return', 'SimpleMenuItem(account_menucontent(acct))'] | 185,431 |
Katja-M/Python_NaturalLanguageProcessing | font_manager.py | FontProperties.get_family | get_family | Return a list of font names that comprise the font family. | [
"Return",
"a",
"list",
"of",
"font",
"names",
"that",
"comprise",
"the",
"font",
"family."
] | def get_family(self):
return self._family | ['def', 'get_family(self):', 'return', 'self._family'] | 864,574 |
jianlong-yuan/SimpleBaseline | lovasz_losses.py | lovasz_softmax_flat | lovasz_softmax_flat | Multi-class Lovasz-Softmax loss probas: [P, C] Variable, class probabilities at each prediction (between 0 and 1) labels: [P] Tensor, ground truth labels (between 0 and C - 1) classes: 'all' for all, 'present' for classes present in labels, or a list of classes to average. | [
"Multi-class",
"Lovasz-Softmax",
"loss",
"probas:",
"[P,",
"C]",
"Variable,",
"class",
"probabilities",
"at",
"each",
"prediction",
"(between",
"0",
"and",
"1)",
"labels:",
"[P]",
"Tensor,",
"ground",
"truth",
"labels",
"(between",
"0",
"and",
"C",
"-",
"1)",
... | def lovasz_softmax_flat(probas, labels, classes='present'):
if probas.numel() == 0:
return probas * 0.0
C = probas.size(1)
losses = []
class_to_sum = list(range(C)) if classes in ['all', 'present'] else classes
for c in class_to_sum:
fg = (labels == c).float()
if classes == '... | ['def', 'lovasz_softmax_flat(probas,', 'labels,', "classes='present'):", 'if', 'probas.numel()', '==', '0:', 'return', 'probas', '*', '0.0', 'C', '=', 'probas.size(1)', 'losses', '=', '[]', 'class_to_sum', '=', 'list(range(C))', 'if', 'classes', 'in', "['all',", "'present']", 'else', 'classes', 'for', 'c', 'in', 'class... | 883,112 |
liuzuxin/MPC_template-model_predictive_control_for__ | policies.py | ActorCriticPolicy.proba_distribution | proba_distribution | ProbabilityDistribution: distribution of stochastic actions. | [
"ProbabilityDistribution:",
"distribution",
"of",
"stochastic",
"actions."
] | def proba_distribution(self):
return self._proba_distribution | ['def', 'proba_distribution(self):', 'return', 'self._proba_distribution'] | 656,671 |
tobegit3hub/deep_image_model | cifar10_multi_gpu_train.py | tower_loss | tower_loss | Calculate the total loss on a single tower running the CIFAR model. | [
"Calculate",
"the",
"total",
"loss",
"on",
"a",
"single",
"tower",
"running",
"the",
"CIFAR",
"model."
] | def tower_loss(scope):
(images, labels) = cifar10.distorted_inputs()
logits = cifar10.inference(images)
_ = cifar10.loss(logits, labels)
losses = tf.get_collection('losses', scope)
total_loss = tf.add_n(losses, name='total_loss')
loss_averages = tf.train.ExponentialMovingAverage(0.9, name='avg')... | ['def', 'tower_loss(scope):', '(images,', 'labels)', '=', 'cifar10.distorted_inputs()', 'logits', '=', 'cifar10.inference(images)', '_', '=', 'cifar10.loss(logits,', 'labels)', 'losses', '=', "tf.get_collection('losses',", 'scope)', 'total_loss', '=', 'tf.add_n(losses,', "name='total_loss')", 'loss_averages', '=', 'tf.... | 182,239 |
tobegit3hub/deep_image_model | lookup_ops.py | MutableDenseHashTable.insert | insert | Associates `keys` with `values`. | [
"Associates",
"`keys`",
"with",
"`values`."
] | def insert(self, keys, values, name=None):
self._check_table_dtypes(keys.dtype, values.dtype)
with ops.name_scope(name, '%s_lookup_table_insert' % self._name, [self._table_ref, keys, values]) as name:
op = gen_data_flow_ops._lookup_table_insert(self._table_ref, keys, values, name=name)
return op | ['def', 'insert(self,', 'keys,', 'values,', 'name=None):', 'self._check_table_dtypes(keys.dtype,', 'values.dtype)', 'with', 'ops.name_scope(name,', "'%s_lookup_table_insert'", '%', 'self._name,', '[self._table_ref,', 'keys,', 'values])', 'as', 'name:', 'op', '=', 'gen_data_flow_ops._lookup_table_insert(self._table_ref,... | 181,916 |
suarez12138/AI-Reversi_IMP_TextDichotomy | axis.py | XAxis.get_text_heights | get_text_heights | Return how much space should be reserved for text above and below the axes, as a pair of floats. | [
"Return",
"how",
"much",
"space",
"should",
"be",
"reserved",
"for",
"text",
"above",
"and",
"below",
"the",
"axes,",
"as",
"a",
"pair",
"of",
"floats."
] | def get_text_heights(self, renderer):
(bbox, bbox2) = self.get_ticklabel_extents(renderer)
padPixels = self.majorTicks[0].get_pad_pixels()
above = 0.0
if bbox2.height:
above += bbox2.height + padPixels
below = 0.0
if bbox.height:
below += bbox.height + padPixels
if self.get_l... | ['def', 'get_text_heights(self,', 'renderer):', '(bbox,', 'bbox2)', '=', 'self.get_ticklabel_extents(renderer)', 'padPixels', '=', 'self.majorTicks[0].get_pad_pixels()', 'above', '=', '0.0', 'if', 'bbox2.height:', 'above', '+=', 'bbox2.height', '+', 'padPixels', 'below', '=', '0.0', 'if', 'bbox.height:', 'below', '+=',... | 96,117 |
Exusi4/Natural-Language-Processing | data.py | load_glove_embeddings | load_glove_embeddings | Given a vocabulary (mapping from index to token), this function builds an embedding matrix of vocabulary size in which ith row vector is an entry from pretrained embeddings (loaded from embeddings_txt_file). | [
"Given",
"a",
"vocabulary",
"(mapping",
"from",
"index",
"to",
"token),",
"this",
"function",
"builds",
"an",
"embedding",
"matrix",
"of",
"vocabulary",
"size",
"in",
"which",
"ith",
"row",
"vector",
"is",
"an",
"entry",
"from",
"pretrained",
"embeddings",
"(l... | def load_glove_embeddings(embeddings_txt_file: str, embedding_dim: int, vocab_id_to_token: Dict[int, str]) -> np.ndarray:
tokens_to_keep = set(vocab_id_to_token.values())
vocab_size = len(vocab_id_to_token)
embeddings = {}
print('\nReading pretrained embedding file.')
with open(embeddings_txt_file, ... | ['def', 'load_glove_embeddings(embeddings_txt_file:', 'str,', 'embedding_dim:', 'int,', 'vocab_id_to_token:', 'Dict[int,', 'str])', '->', 'np.ndarray:', 'tokens_to_keep', '=', 'set(vocab_id_to_token.values())', 'vocab_size', '=', 'len(vocab_id_to_token)', 'embeddings', '=', '{}', "print('\\nReading", 'pretrained', 'emb... | 685,139 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | model_adapter.py | ModelAdapter.objective | objective | Computes the objective given a list of parameters. | [
"Computes",
"the",
"objective",
"given",
"a",
"list",
"of",
"parameters."
] | def objective(self, parameters, data=None, labels=None):
parameter_mapping = {old_p.name: p for (old_p, p) in zip(self.parameters, parameters)}
with tf.variable_scope(tf.get_variable_scope(), reuse=True):
return _make_with_custom_variables(self.make_loss_fn, parameter_mapping) | ['def', 'objective(self,', 'parameters,', 'data=None,', 'labels=None):', 'parameter_mapping', '=', '{old_p.name:', 'p', 'for', '(old_p,', 'p)', 'in', 'zip(self.parameters,', 'parameters)}', 'with', 'tf.variable_scope(tf.get_variable_scope(),', 'reuse=True):', 'return', '_make_with_custom_variables(self.make_loss_fn,', ... | 55,594 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | compare.py | make_test_filename | make_test_filename | Make a new filename by inserting *purpose* before the file's extension. | [
"Make",
"a",
"new",
"filename",
"by",
"inserting",
"*purpose*",
"before",
"the",
"file's",
"extension."
] | def make_test_filename(fname, purpose):
(base, ext) = os.path.splitext(fname)
return '%s-%s%s' % (base, purpose, ext) | ['def', 'make_test_filename(fname,', 'purpose):', '(base,', 'ext)', '=', 'os.path.splitext(fname)', 'return', "'%s-%s%s'", '%', '(base,', 'purpose,', 'ext)'] | 451,244 |
ancasag/ensembleObjectDetection | generator.py | Generator.filter_annotations | filter_annotations | Filter annotations by removing those that are outside of the image bounds or whose width/height < 0. | [
"Filter",
"annotations",
"by",
"removing",
"those",
"that",
"are",
"outside",
"of",
"the",
"image",
"bounds",
"or",
"whose",
"width/height",
"<",
"0."
] | def filter_annotations(self, image_group, annotations_group, group):
for (index, (image, annotations)) in enumerate(zip(image_group, annotations_group)):
invalid_indices = np.where((annotations['bboxes'][:, 2] <= annotations['bboxes'][:, 0]) | (annotations['bboxes'][:, 3] <= annotations['bboxes'][:, 1]) | (... | ['def', 'filter_annotations(self,', 'image_group,', 'annotations_group,', 'group):', 'for', '(index,', '(image,', 'annotations))', 'in', 'enumerate(zip(image_group,', 'annotations_group)):', 'invalid_indices', '=', "np.where((annotations['bboxes'][:,", '2]', '<=', "annotations['bboxes'][:,", '0])', '|', "(annotations['... | 562,002 |
loicmarie/hands-detection | model_voxel_generation.py | Im2Vox.get_inputs | get_inputs | Loads data for a specified dataset and split. | [
"Loads",
"data",
"for",
"a",
"specified",
"dataset",
"and",
"split."
] | def get_inputs(self, dataset_dir, dataset_name, split_name, batch_size, image_size, vox_size, is_training=True):
del image_size, vox_size
with tf.variable_scope('data_loading_%s/%s' % (dataset_name, split_name)):
common_queue_min = 64
common_queue_capacity = 256
num_readers = 4
i... | ['def', 'get_inputs(self,', 'dataset_dir,', 'dataset_name,', 'split_name,', 'batch_size,', 'image_size,', 'vox_size,', 'is_training=True):', 'del', 'image_size,', 'vox_size', 'with', "tf.variable_scope('data_loading_%s/%s'", '%', '(dataset_name,', 'split_name)):', 'common_queue_min', '=', '64', 'common_queue_capacity',... | 575,151 |
kianak2002/Sentiment-Emotion-Analysis-project | __init__.py | Environment.can_add | can_add | Is distribution `dist` acceptable for this environment? The distribution must match the platform and python version requirements specified when this environment was created, or False is returned. | [
"Is",
"distribution",
"`dist`",
"acceptable",
"for",
"this",
"environment?",
"The",
"distribution",
"must",
"match",
"the",
"platform",
"and",
"python",
"version",
"requirements",
"specified",
"when",
"this",
"environment",
"was",
"created,",
"or",
"False",
"is",
... | def can_add(self, dist):
py_compat = self.python is None or dist.py_version is None or dist.py_version == self.python
return py_compat and compatible_platforms(dist.platform, self.platform) | ['def', 'can_add(self,', 'dist):', 'py_compat', '=', 'self.python', 'is', 'None', 'or', 'dist.py_version', 'is', 'None', 'or', 'dist.py_version', '==', 'self.python', 'return', 'py_compat', 'and', 'compatible_platforms(dist.platform,', 'self.platform)'] | 875,430 |
Eric3911/OpenAGI | text2sparql_model.py | Text2SparqlModel.test_epoch_end | test_epoch_end | Called at the end of test to aggregate outputs and decode them. | [
"Called",
"at",
"the",
"end",
"of",
"test",
"to",
"aggregate",
"outputs",
"and",
"decode",
"them."
] | def test_epoch_end(self, outputs: List[torch.Tensor]) -> Dict[str, List[str]]:
texts = [self.encoder_tokenizer.ids_to_text(seq) for batch in outputs for seq in batch]
self.test_output = [{'texts': texts}]
return {'texts': texts} | ['def', 'test_epoch_end(self,', 'outputs:', 'List[torch.Tensor])', '->', 'Dict[str,', 'List[str]]:', 'texts', '=', '[self.encoder_tokenizer.ids_to_text(seq)', 'for', 'batch', 'in', 'outputs', 'for', 'seq', 'in', 'batch]', 'self.test_output', '=', "[{'texts':", 'texts}]', 'return', "{'texts':", 'texts}'] | 273,653 |
ldkong1205/LaserMix | transforms_3d.py | RandomFlip3D.transform | transform | Call function to flip points, values in the ``bbox3d_fields`` and also flip 2D image and its annotations. | [
"Call",
"function",
"to",
"flip",
"points,",
"values",
"in",
"the",
"``bbox3d_fields``",
"and",
"also",
"flip",
"2D",
"image",
"and",
"its",
"annotations."
] | def transform(self, input_dict: dict) -> dict:
if 'img' in input_dict:
super(RandomFlip3D, self).transform(input_dict)
if self.sync_2d and 'img' in input_dict:
input_dict['pcd_horizontal_flip'] = input_dict['flip']
input_dict['pcd_vertical_flip'] = False
else:
if 'pcd_horizon... | ['def', 'transform(self,', 'input_dict:', 'dict)', '->', 'dict:', 'if', "'img'", 'in', 'input_dict:', 'super(RandomFlip3D,', 'self).transform(input_dict)', 'if', 'self.sync_2d', 'and', "'img'", 'in', 'input_dict:', "input_dict['pcd_horizontal_flip']", '=', "input_dict['flip']", "input_dict['pcd_vertical_flip']", '=', '... | 623,816 |
trojanguy31/NaturalLanguageProcessing | tokenization.py | convert_by_vocab | convert_by_vocab | Converts a sequence of [tokens|ids] using the vocab. | [
"Converts",
"a",
"sequence",
"of",
"[tokens|ids]",
"using",
"the",
"vocab."
] | def convert_by_vocab(vocab, items):
output = []
for item in items:
output.append(vocab[item])
return output | ['def', 'convert_by_vocab(vocab,', 'items):', 'output', '=', '[]', 'for', 'item', 'in', 'items:', 'output.append(vocab[item])', 'return', 'output'] | 800,097 |
kubeflow/pipelines | _components.py | load_component_from_url | load_component_from_url | Loads component from URL and creates a task factory function. | [
"Loads",
"component",
"from",
"URL",
"and",
"creates",
"a",
"task",
"factory",
"function."
] | def load_component_from_url(url: str, auth=None):
component_spec = _load_component_spec_from_url(url, auth)
url = _fix_component_uri(url)
component_ref = ComponentReference(url=url)
return _create_task_factory_from_component_spec(component_spec=component_spec, component_filename=url, component_ref=compo... | ['def', 'load_component_from_url(url:', 'str,', 'auth=None):', 'component_spec', '=', '_load_component_spec_from_url(url,', 'auth)', 'url', '=', '_fix_component_uri(url)', 'component_ref', '=', 'ComponentReference(url=url)', 'return', '_create_task_factory_from_component_spec(component_spec=component_spec,', 'component... | 780,038 |
michellesri/cs188 | staffBot.py | SimpleStaffBot.chooseAction | chooseAction | Reflex agent that follows its plan. | [
"Reflex",
"agent",
"that",
"follows",
"its",
"plan."
] | def chooseAction(self, gameState):
if self.toBroadcast and len(self.toBroadcast) > 0:
action = self.toBroadcast.pop(0)
if action in gameState.getLegalActions(self.index):
ghosts = [gameState.getAgentPosition(ghost) for ghost in gameState.getGhostTeamIndices()]
pacman = gameSt... | ['def', 'chooseAction(self,', 'gameState):', 'if', 'self.toBroadcast', 'and', 'len(self.toBroadcast)', '>', '0:', 'action', '=', 'self.toBroadcast.pop(0)', 'if', 'action', 'in', 'gameState.getLegalActions(self.index):', 'ghosts', '=', '[gameState.getAgentPosition(ghost)', 'for', 'ghost', 'in', 'gameState.getGhostTeamIn... | 224,242 |
lebrice/Sequoia | setting_test.py | TestIncrementalSLSetting.test_observation_spaces_match_dataset | test_observation_spaces_match_dataset | Test to check that the `observation_spaces` and `reward_spaces` dict really correspond to the entries of the corresponding datasets, before we do anything with them. | [
"Test",
"to",
"check",
"that",
"the",
"`observation_spaces`",
"and",
"`reward_spaces`",
"dict",
"really",
"correspond",
"to",
"the",
"entries",
"of",
"the",
"corresponding",
"datasets,",
"before",
"we",
"do",
"anything",
"with",
"them."
] | def test_observation_spaces_match_dataset(self, dataset_name: str):
dataset_class = self.Setting.available_datasets[dataset_name]
dataset = dataset_class('data')
observation_space = self.Setting.base_observation_spaces[dataset_name]
reward_space = self.Setting.base_reward_spaces[dataset_name]
for ta... | ['def', 'test_observation_spaces_match_dataset(self,', 'dataset_name:', 'str):', 'dataset_class', '=', 'self.Setting.available_datasets[dataset_name]', 'dataset', '=', "dataset_class('data')", 'observation_space', '=', 'self.Setting.base_observation_spaces[dataset_name]', 'reward_space', '=', 'self.Setting.base_reward_... | 349,692 |
nicknochnack/RealTimeSignLanguageTFJS | optimizer_factory.py | build_learning_rate | build_learning_rate | Build the learning rate given the provided configuration. | [
"Build",
"the",
"learning",
"rate",
"given",
"the",
"provided",
"configuration."
] | def build_learning_rate(params: base_configs.LearningRateConfig, batch_size: int=None, train_epochs: int=None, train_steps: int=None):
decay_type = params.name
base_lr = params.initial_lr
decay_rate = params.decay_rate
if params.decay_epochs is not None:
decay_steps = params.decay_epochs * train... | ['def', 'build_learning_rate(params:', 'base_configs.LearningRateConfig,', 'batch_size:', 'int=None,', 'train_epochs:', 'int=None,', 'train_steps:', 'int=None):', 'decay_type', '=', 'params.name', 'base_lr', '=', 'params.initial_lr', 'decay_rate', '=', 'params.decay_rate', 'if', 'params.decay_epochs', 'is', 'not', 'Non... | 851,194 |
Sea1004/artificial_intelligence | tarfile.py | TarFile.makefile | makefile | Make a file called targetpath. | [
"Make",
"a",
"file",
"called",
"targetpath."
] | def makefile(self, tarinfo, targetpath):
source = self.fileobj
source.seek(tarinfo.offset_data)
target = bltn_open(targetpath, 'wb')
if tarinfo.sparse is not None:
for (offset, size) in tarinfo.sparse:
target.seek(offset)
copyfileobj(source, target, size)
else:
... | ['def', 'makefile(self,', 'tarinfo,', 'targetpath):', 'source', '=', 'self.fileobj', 'source.seek(tarinfo.offset_data)', 'target', '=', 'bltn_open(targetpath,', "'wb')", 'if', 'tarinfo.sparse', 'is', 'not', 'None:', 'for', '(offset,', 'size)', 'in', 'tarinfo.sparse:', 'target.seek(offset)', 'copyfileobj(source,', 'targ... | 148,926 |
athms/learning-from-brains | sfig3_upstream_performance_pretrained_lms.py | sfig_upstream_performance_pretrained_lms | sfig_upstream_performance_pretrained_lms | Script's main function; creates Appendix Figure 3 of the manuscript. | [
"Script's",
"main",
"function;",
"creates",
"Appendix",
"Figure",
"3",
"of",
"the",
"manuscript."
] | def sfig_upstream_performance_pretrained_lms(config: Dict=None) -> None:
if config is None:
config = vars(get_args().parse_args())
os.makedirs(config['figures_dir'], exist_ok=True)
(fig, fig_axs) = plt.subplot_mosaic('\n AB\n ', figsize=(6, 3))
for (name, print_name, loss_label, ax... | ['def', 'sfig_upstream_performance_pretrained_lms(config:', 'Dict=None)', '->', 'None:', 'if', 'config', 'is', 'None:', 'config', '=', 'vars(get_args().parse_args())', "os.makedirs(config['figures_dir'],", 'exist_ok=True)', '(fig,', 'fig_axs)', '=', "plt.subplot_mosaic('\\n", 'AB\\n', "',", 'figsize=(6,', '3))', 'for',... | 262,100 |
leotms/IAII_II | excercise3_p1.py | normalize | normalize | Normalizes the data provided in dataset using min-max method. | [
"Normalizes",
"the",
"data",
"provided",
"in",
"dataset",
"using",
"min-max",
"method."
] | def normalize(dataset):
vector_min = []
vector_max = []
normalizedDataset = dataset
n_columns = dataset.shape[1]
for i in range(n_columns - 1):
m = np.min(dataset[i])
M = np.max(dataset[i])
vector_min.append(m)
vector_max.append(M)
normalizedDataset[i] = np.su... | ['def', 'normalize(dataset):', 'vector_min', '=', '[]', 'vector_max', '=', '[]', 'normalizedDataset', '=', 'dataset', 'n_columns', '=', 'dataset.shape[1]', 'for', 'i', 'in', 'range(n_columns', '-', '1):', 'm', '=', 'np.min(dataset[i])', 'M', '=', 'np.max(dataset[i])', 'vector_min.append(m)', 'vector_max.append(M)', 'no... | 596,829 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.