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 |
|---|---|---|---|---|---|---|---|---|
ArdaGunay99/Key_Detection_Unsupervised_Learning | backend_pgf.py | FigureCanvasPgf.print_png | print_png | Use LaTeX to compile a pgf figure to pdf and convert it to png. | [
"Use",
"LaTeX",
"to",
"compile",
"a",
"pgf",
"figure",
"to",
"pdf",
"and",
"convert",
"it",
"to",
"png."
] | def print_png(self, fname_or_fh, *args, **kwargs):
if kwargs.get('dryrun', False):
self._print_pgf_to_fh(None, *args, **kwargs)
return
with cbook.open_file_cm(fname_or_fh, 'wb') as file:
self._print_png_to_fh(file, *args, **kwargs) | ['def', 'print_png(self,', 'fname_or_fh,', '*args,', '**kwargs):', 'if', "kwargs.get('dryrun',", 'False):', 'self._print_pgf_to_fh(None,', '*args,', '**kwargs)', 'return', 'with', 'cbook.open_file_cm(fname_or_fh,', "'wb')", 'as', 'file:', 'self._print_png_to_fh(file,', '*args,', '**kwargs)'] | 257,674 |
43Carrig/recurrent_neural_networks_practice | rnn_cell.py | AttentionCellWrapper.call | call | Long short-term memory cell with attention (LSTMA). | [
"Long",
"short-term",
"memory",
"cell",
"with",
"attention",
"(LSTMA)."
] | def call(self, inputs, state):
if self._state_is_tuple:
(state, attns, attn_states) = state
else:
states = state
state = array_ops.slice(states, [0, 0], [-1, self._cell.state_size])
attns = array_ops.slice(states, [0, self._cell.state_size], [-1, self._attn_size])
attn_st... | ['def', 'call(self,', 'inputs,', 'state):', 'if', 'self._state_is_tuple:', '(state,', 'attns,', 'attn_states)', '=', 'state', 'else:', 'states', '=', 'state', 'state', '=', 'array_ops.slice(states,', '[0,', '0],', '[-1,', 'self._cell.state_size])', 'attns', '=', 'array_ops.slice(states,', '[0,', 'self._cell.state_size]... | 335,113 |
tensorflow/agents | train_eval.py | create_critic_network | create_critic_network | Create a critic network for DDPG. | [
"Create",
"a",
"critic",
"network",
"for",
"DDPG."
] | def create_critic_network(obs_fc_layer_units, action_fc_layer_units, joint_fc_layer_units):
def split_inputs(inputs):
return {'observation': inputs[0], 'action': inputs[1]}
obs_network = create_fc_network(obs_fc_layer_units) if obs_fc_layer_units else create_identity_layer()
action_network = create... | ['def', 'create_critic_network(obs_fc_layer_units,', 'action_fc_layer_units,', 'joint_fc_layer_units):', 'def', 'split_inputs(inputs):', 'return', "{'observation':", 'inputs[0],', "'action':", 'inputs[1]}', 'obs_network', '=', 'create_fc_network(obs_fc_layer_units)', 'if', 'obs_fc_layer_units', 'else', 'create_identity... | 22,478 |
ADLab3Ds/TiG-BEV | train_mixins.py | AnchorTrainMixin.anchor_target_single_assigner | anchor_target_single_assigner | Assign anchors and encode positive anchors. | [
"Assign",
"anchors",
"and",
"encode",
"positive",
"anchors."
] | def anchor_target_single_assigner(self, bbox_assigner, anchors, gt_bboxes, gt_bboxes_ignore, gt_labels, input_meta, num_classes=1, sampling=True):
anchors = anchors.reshape(-1, anchors.size(-1))
num_valid_anchors = anchors.shape[0]
bbox_targets = torch.zeros_like(anchors)
bbox_weights = torch.zeros_like... | ['def', 'anchor_target_single_assigner(self,', 'bbox_assigner,', 'anchors,', 'gt_bboxes,', 'gt_bboxes_ignore,', 'gt_labels,', 'input_meta,', 'num_classes=1,', 'sampling=True):', 'anchors', '=', 'anchors.reshape(-1,', 'anchors.size(-1))', 'num_valid_anchors', '=', 'anchors.shape[0]', 'bbox_targets', '=', 'torch.zeros_li... | 917,040 |
open-mmlab/mmtracking | eval_mot.py | eval_mot | eval_mot | Evaluation CLEAR MOT metrics. | [
"Evaluation",
"CLEAR",
"MOT",
"metrics."
] | def eval_mot(results, annotations, logger=None, classes=None, iou_thr=0.5, ignore_iof_thr=0.5, ignore_by_classes=False, nproc=4):
print_log('---CLEAR MOT Evaluation---', logger)
t = time.time()
gts = annotations.copy()
if classes is None:
classes = [i + 1 for i in range(len(results[0]))]
ass... | ['def', 'eval_mot(results,', 'annotations,', 'logger=None,', 'classes=None,', 'iou_thr=0.5,', 'ignore_iof_thr=0.5,', 'ignore_by_classes=False,', 'nproc=4):', "print_log('---CLEAR", 'MOT', "Evaluation---',", 'logger)', 't', '=', 'time.time()', 'gts', '=', 'annotations.copy()', 'if', 'classes', 'is', 'None:', 'classes', ... | 625,668 |
fortyMiles/PAIP-Python | lowest_cost_problem.py | path_cost | path_cost | The total cost of a path (which is stored in a tuple with the final action). | [
"The",
"total",
"cost",
"of",
"a",
"path",
"(which",
"is",
"stored",
"in",
"a",
"tuple",
"with",
"the",
"final",
"action)."
] | def path_cost(path):
if len(path) < 3:
return 0
else:
(action, total_cost) = path[-2]
return total_cost | ['def', 'path_cost(path):', 'if', 'len(path)', '<', '3:', 'return', '0', 'else:', '(action,', 'total_cost)', '=', 'path[-2]', 'return', 'total_cost'] | 277,447 |
rudranil723/mini-main | format.py | DataFrameFormatter.get_strcols | get_strcols | Render a DataFrame to a list of columns (as lists of strings). | [
"Render",
"a",
"DataFrame",
"to",
"a",
"list",
"of",
"columns",
"(as",
"lists",
"of",
"strings)."
] | def get_strcols(self) -> list[list[str]]:
strcols = self._get_strcols_without_index()
if self.index:
str_index = self._get_formatted_index(self.tr_frame)
strcols.insert(0, str_index)
return strcols | ['def', 'get_strcols(self)', '->', 'list[list[str]]:', 'strcols', '=', 'self._get_strcols_without_index()', 'if', 'self.index:', 'str_index', '=', 'self._get_formatted_index(self.tr_frame)', 'strcols.insert(0,', 'str_index)', 'return', 'strcols'] | 267,230 |
Eric3911/OpenAGI | tokenization_bert_word_level.py | BertTokenizer.from_pretrained | from_pretrained | Instantiate a BertTokenizer from pre-trained vocabulary files. | [
"Instantiate",
"a",
"BertTokenizer",
"from",
"pre-trained",
"vocabulary",
"files."
] | def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs):
if pretrained_model_name_or_path in PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES:
if '-cased' in pretrained_model_name_or_path and kwargs.get('do_lower_case', True):
logger.warning('The pre-trained model you are loading is a c... | ['def', 'from_pretrained(cls,', 'pretrained_model_name_or_path,', '*inputs,', '**kwargs):', 'if', 'pretrained_model_name_or_path', 'in', 'PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES:', 'if', "'-cased'", 'in', 'pretrained_model_name_or_path', 'and', "kwargs.get('do_lower_case',", 'True):', "logger.warning('The", 'pre-trained... | 250,824 |
omarmhaimdat/twitter_nlp_native_swift | socket.py | socket.dup | dup | dup() -> socket object Return a new socket object connected to the same system resource. | [
"dup()",
"->",
"socket",
"object",
"Return",
"a",
"new",
"socket",
"object",
"connected",
"to",
"the",
"same",
"system",
"resource."
] | def dup(self):
fd = dup(self.fileno())
sock = self.__class__(self.family, self.type, self.proto, fileno=fd)
sock.settimeout(self.gettimeout())
return sock | ['def', 'dup(self):', 'fd', '=', 'dup(self.fileno())', 'sock', '=', 'self.__class__(self.family,', 'self.type,', 'self.proto,', 'fileno=fd)', 'sock.settimeout(self.gettimeout())', 'return', 'sock'] | 953,242 |
aws/sagemaker-python-sdk | automl.py | AutoML.deploy | deploy | Deploy a candidate to a SageMaker Inference Pipeline. | [
"Deploy",
"a",
"candidate",
"to",
"a",
"SageMaker",
"Inference",
"Pipeline."
] | def deploy(self, initial_instance_count, instance_type, serializer=None, deserializer=None, candidate=None, sagemaker_session=None, name=None, endpoint_name=None, tags=None, wait=True, vpc_config=None, enable_network_isolation=False, model_kms_key=None, predictor_cls=None, inference_response_keys=None, volume_size=None... | ['def', 'deploy(self,', 'initial_instance_count,', 'instance_type,', 'serializer=None,', 'deserializer=None,', 'candidate=None,', 'sagemaker_session=None,', 'name=None,', 'endpoint_name=None,', 'tags=None,', 'wait=True,', 'vpc_config=None,', 'enable_network_isolation=False,', 'model_kms_key=None,', 'predictor_cls=None,... | 829,796 |
instadeepai/jumanji | env.py | CVRP.animate | animate | Creates an animated gif of the CVRP environment based on the sequence of states. | [
"Creates",
"an",
"animated",
"gif",
"of",
"the",
"CVRP",
"environment",
"based",
"on",
"the",
"sequence",
"of",
"states."
] | def animate(self, states: Sequence[State], interval: int=200, save_path: Optional[str]=None) -> matplotlib.animation.FuncAnimation:
return self._viewer.animate(states, interval, save_path) | ['def', 'animate(self,', 'states:', 'Sequence[State],', 'interval:', 'int=200,', 'save_path:', 'Optional[str]=None)', '->', 'matplotlib.animation.FuncAnimation:', 'return', 'self._viewer.animate(states,', 'interval,', 'save_path)'] | 594,350 |
ryu-ed/SpaceInvaders_Ros | image_test.py | ImageModuleTest.testSavePNG24 | testSavePNG24 | see if we can save a png with color values in the proper channels. | [
"see",
"if",
"we",
"can",
"save",
"a",
"png",
"with",
"color",
"values",
"in",
"the",
"proper",
"channels."
] | def testSavePNG24(self):
reddish_pixel = (215, 0, 0)
greenish_pixel = (0, 225, 0)
bluish_pixel = (0, 0, 235)
greyish_pixel = (115, 125, 135)
surf = pygame.Surface((1, 4), 0, 24)
surf.set_at((0, 0), reddish_pixel)
surf.set_at((0, 1), greenish_pixel)
surf.set_at((0, 2), bluish_pixel)
s... | ['def', 'testSavePNG24(self):', 'reddish_pixel', '=', '(215,', '0,', '0)', 'greenish_pixel', '=', '(0,', '225,', '0)', 'bluish_pixel', '=', '(0,', '0,', '235)', 'greyish_pixel', '=', '(115,', '125,', '135)', 'surf', '=', 'pygame.Surface((1,', '4),', '0,', '24)', 'surf.set_at((0,', '0),', 'reddish_pixel)', 'surf.set_at(... | 368,993 |
myothida/Supervised-Machine-Learning | ttFont.py | TTFont.keys | keys | Returns the list of tables in the font, along with the ``GlyphOrder`` pseudo-table. | [
"Returns",
"the",
"list",
"of",
"tables",
"in",
"the",
"font,",
"along",
"with",
"the",
"``GlyphOrder``",
"pseudo-table."
] | def keys(self):
keys = list(self.tables.keys())
if self.reader:
for key in list(self.reader.keys()):
if key not in keys:
keys.append(key)
if 'GlyphOrder' in keys:
keys.remove('GlyphOrder')
keys = sortedTagList(keys)
return ['GlyphOrder'] + keys | ['def', 'keys(self):', 'keys', '=', 'list(self.tables.keys())', 'if', 'self.reader:', 'for', 'key', 'in', 'list(self.reader.keys()):', 'if', 'key', 'not', 'in', 'keys:', 'keys.append(key)', 'if', "'GlyphOrder'", 'in', 'keys:', "keys.remove('GlyphOrder')", 'keys', '=', 'sortedTagList(keys)', 'return', "['GlyphOrder']", ... | 361,189 |
mikhaildubov/AST-text-analysis | utils.py | itersubclasses | itersubclasses | Generator over all subclasses of a given class in depth first order. | [
"Generator",
"over",
"all",
"subclasses",
"of",
"a",
"given",
"class",
"in",
"depth",
"first",
"order."
] | def itersubclasses(cls, _seen=None):
if not isinstance(cls, type):
raise TypeError(_('itersubclasses must be called with new-style classes, not %.100r') % cls)
_seen = _seen or set()
try:
subs = cls.__subclasses__()
except TypeError:
subs = cls.__subclasses__(cls)
for sub in ... | ['def', 'itersubclasses(cls,', '_seen=None):', 'if', 'not', 'isinstance(cls,', 'type):', 'raise', "TypeError(_('itersubclasses", 'must', 'be', 'called', 'with', 'new-style', 'classes,', 'not', "%.100r')", '%', 'cls)', '_seen', '=', '_seen', 'or', 'set()', 'try:', 'subs', '=', 'cls.__subclasses__()', 'except', 'TypeErro... | 402,521 |
aeon-toolkit/aeon | test_numpy_metrics.py | test_metric_output | test_metric_output | Test output is correct class. | [
"Test",
"output",
"is",
"correct",
"class."
] | def test_metric_output(metric, multioutput, n_columns):
y_pred = _make_series(n_columns=n_columns, n_timepoints=20, random_state=21)
y_true = _make_series(n_columns=n_columns, n_timepoints=20, random_state=42)
y_pred = pd.DataFrame(y_pred)
y_true = pd.DataFrame(y_true)
res = metric(y_true=y_true, y_... | ['def', 'test_metric_output(metric,', 'multioutput,', 'n_columns):', 'y_pred', '=', '_make_series(n_columns=n_columns,', 'n_timepoints=20,', 'random_state=21)', 'y_true', '=', '_make_series(n_columns=n_columns,', 'n_timepoints=20,', 'random_state=42)', 'y_pred', '=', 'pd.DataFrame(y_pred)', 'y_true', '=', 'pd.DataFrame... | 399,790 |
drprojects/superpoint_transformer | tensor.py | is_sorted | is_sorted | Checks whether a 1D tensor of indices is sorted. | [
"Checks",
"whether",
"a",
"1D",
"tensor",
"of",
"indices",
"is",
"sorted."
] | def is_sorted(a: torch.LongTensor, increasing=True, strict=False):
assert a.dim() == 1, 'Only supports 1D tensors'
assert not a.is_floating_point(), 'Float tensors are not supported'
if increasing and strict:
f = torch.gt
if increasing and (not strict):
f = torch.ge
if not increasing... | ['def', 'is_sorted(a:', 'torch.LongTensor,', 'increasing=True,', 'strict=False):', 'assert', 'a.dim()', '==', '1,', "'Only", 'supports', '1D', "tensors'", 'assert', 'not', 'a.is_floating_point(),', "'Float", 'tensors', 'are', 'not', "supported'", 'if', 'increasing', 'and', 'strict:', 'f', '=', 'torch.gt', 'if', 'increa... | 880,944 |
Xianpeng919/MonoCon | nuimage_converter.py | get_img_annos | get_img_annos | Get semantic segmentation map for an image. | [
"Get",
"semantic",
"segmentation",
"map",
"for",
"an",
"image."
] | def get_img_annos(nuim, img_info, cat2id, out_dir, data_root, seg_root):
sd_token = img_info['token']
image_id = img_info['id']
name_to_index = name_to_index_mapping(nuim.category)
(width, height) = (img_info['width'], img_info['height'])
semseg_mask = np.zeros((height, width)).astype('uint8')
s... | ['def', 'get_img_annos(nuim,', 'img_info,', 'cat2id,', 'out_dir,', 'data_root,', 'seg_root):', 'sd_token', '=', "img_info['token']", 'image_id', '=', "img_info['id']", 'name_to_index', '=', 'name_to_index_mapping(nuim.category)', '(width,', 'height)', '=', "(img_info['width'],", "img_info['height'])", 'semseg_mask', '=... | 654,715 |
jimtin/Stock_Comparison | mpltools.py | is_bar | is_bar | A test to decide whether a path is a bar from a vertical bar chart. | [
"A",
"test",
"to",
"decide",
"whether",
"a",
"path",
"is",
"a",
"bar",
"from",
"a",
"vertical",
"bar",
"chart."
] | def is_bar(bar_containers, **props):
for container in bar_containers:
if props['mplobj'] in container:
return True
return False | ['def', 'is_bar(bar_containers,', '**props):', 'for', 'container', 'in', 'bar_containers:', 'if', "props['mplobj']", 'in', 'container:', 'return', 'True', 'return', 'False'] | 389,250 |
RasaHQ/rasa | model_training.py | train | train | Trains a Rasa model (Core and NLU). | [
"Trains",
"a",
"Rasa",
"model",
"(Core",
"and",
"NLU)."
] | def train(domain: Text, config: Text, training_files: Optional[Union[Text, List[Text]]], output: Text=rasa.shared.constants.DEFAULT_MODELS_PATH, dry_run: bool=False, force_training: bool=False, fixed_model_name: Optional[Text]=None, persist_nlu_training_data: bool=False, core_additional_arguments: Optional[Dict]=None, ... | ['def', 'train(domain:', 'Text,', 'config:', 'Text,', 'training_files:', 'Optional[Union[Text,', 'List[Text]]],', 'output:', 'Text=rasa.shared.constants.DEFAULT_MODELS_PATH,', 'dry_run:', 'bool=False,', 'force_training:', 'bool=False,', 'fixed_model_name:', 'Optional[Text]=None,', 'persist_nlu_training_data:', 'bool=Fa... | 836,519 |
sktime/sktime | test_auto_reg.py | test_against_statsmodels_exog | test_against_statsmodels_exog | Compare sktime's autoReg interface with statsmodels autoReg, with exog data. | [
"Compare",
"sktime's",
"autoReg",
"interface",
"with",
"statsmodels",
"autoReg,",
"with",
"exog",
"data."
] | def test_against_statsmodels_exog():
from statsmodels.tsa.ar_model import AutoReg as _AutoReg
from sktime.datasets import load_longley
(y, X_og) = load_longley()
X_oos = X_og.iloc[-5:, :]
y = y.iloc[:-5]
X = X_og.iloc[:-5, :]
X = X[['GNPDEFL', 'GNP']]
X_oos = X_oos[['GNPDEFL', 'GNP']]
... | ['def', 'test_against_statsmodels_exog():', 'from', 'statsmodels.tsa.ar_model', 'import', 'AutoReg', 'as', '_AutoReg', 'from', 'sktime.datasets', 'import', 'load_longley', '(y,', 'X_og)', '=', 'load_longley()', 'X_oos', '=', 'X_og.iloc[-5:,', ':]', 'y', '=', 'y.iloc[:-5]', 'X', '=', 'X_og.iloc[:-5,', ':]', 'X', '=', "X... | 877,306 |
mfbx9da4/neuron-astrocyte-networks | networkwrapper.py | EvolinoNetwork.setOutputWeightMatrix | setOutputWeightMatrix | Sets the weight matrix of the output layer's input connection. | [
"Sets",
"the",
"weight",
"matrix",
"of",
"the",
"output",
"layer's",
"input",
"connection."
] | def setOutputWeightMatrix(self, W):
c = self._hid_to_out_connection
c.params[:] = W.flatten() | ['def', 'setOutputWeightMatrix(self,', 'W):', 'c', '=', 'self._hid_to_out_connection', 'c.params[:]', '=', 'W.flatten()'] | 723,238 |
QData/deepWordBug | math2html.py | FormulaConstant.computesize | computesize | Compute the size of the constant: always 1. | [
"Compute",
"the",
"size",
"of",
"the",
"constant:",
"always",
"1."
] | def computesize(self):
return self.size | ['def', 'computesize(self):', 'return', 'self.size'] | 542,457 |
apeterswu/RL4NMT | transformer_vae.py | ae_decompress | ae_decompress | Decompress from z, leaking from ae. | [
"Decompress",
"from",
"z,",
"leaking",
"from",
"ae."
] | def ae_decompress(z, ae, x, is_2d, hparams, name, reuse=None):
with tf.variable_scope(name + '_decompress', reuse=reuse):
if hparams.use_gumbel_softmax or hparams.do_vae:
z = mix(z, ae, hparams.startup_steps)
else:
z = tf.stop_gradient(z) + ae - tf.stop_gradient(ae)
p... | ['def', 'ae_decompress(z,', 'ae,', 'x,', 'is_2d,', 'hparams,', 'name,', 'reuse=None):', 'with', 'tf.variable_scope(name', '+', "'_decompress',", 'reuse=reuse):', 'if', 'hparams.use_gumbel_softmax', 'or', 'hparams.do_vae:', 'z', '=', 'mix(z,', 'ae,', 'hparams.startup_steps)', 'else:', 'z', '=', 'tf.stop_gradient(z)', '+... | 331,705 |
ryu-ed/SpaceInvaders_Ros | ale_python_interface.py | ALEInterface.restoreSystemState | restoreSystemState | Reverse operation of cloneSystemState. | [
"Reverse",
"operation",
"of",
"cloneSystemState."
] | def restoreSystemState(self, state):
ale_lib.restoreSystemState(self.obj, state) | ['def', 'restoreSystemState(self,', 'state):', 'ale_lib.restoreSystemState(self.obj,', 'state)'] | 394,585 |
flavioschneider/rl-transfer- | gaussian_mlp_task_embedding_policy.py | GaussianMLPTaskEmbeddingPolicy.get_actions_given_latents | get_actions_given_latents | Sample a batch of actions given observations and latents. | [
"Sample",
"a",
"batch",
"of",
"actions",
"given",
"observations",
"and",
"latents."
] | def get_actions_given_latents(self, observations, latents):
flat_obses = self.observation_space.flatten_n(observations)
flat_obses = np.expand_dims(flat_obses, 1)
flat_latents = self.latent_space.flatten_n(latents)
flat_latents = np.expand_dims(flat_latents, 1)
(samples, means, log_stds) = self._f_d... | ['def', 'get_actions_given_latents(self,', 'observations,', 'latents):', 'flat_obses', '=', 'self.observation_space.flatten_n(observations)', 'flat_obses', '=', 'np.expand_dims(flat_obses,', '1)', 'flat_latents', '=', 'self.latent_space.flatten_n(latents)', 'flat_latents', '=', 'np.expand_dims(flat_latents,', '1)', '(s... | 861,490 |
KalleHallden/InstaAutomator | _tifffile.py | read_uic_image_property | read_uic_image_property | Read UIC ImagePropertyEx tag from file and return as dict. | [
"Read",
"UIC",
"ImagePropertyEx",
"tag",
"from",
"file",
"and",
"return",
"as",
"dict."
] | def read_uic_image_property(fh):
size = struct.unpack('B', fh.read(1))[0]
name = struct.unpack('%is' % size, fh.read(size))[0][:-1]
(flags, prop) = struct.unpack('<IB', fh.read(5))
if prop == 1:
value = struct.unpack('II', fh.read(8))
value = value[0] / value[1]
else:
size = ... | ['def', 'read_uic_image_property(fh):', 'size', '=', "struct.unpack('B',", 'fh.read(1))[0]', 'name', '=', "struct.unpack('%is'", '%', 'size,', 'fh.read(size))[0][:-1]', '(flags,', 'prop)', '=', "struct.unpack('<IB',", 'fh.read(5))', 'if', 'prop', '==', '1:', 'value', '=', "struct.unpack('II',", 'fh.read(8))', 'value', ... | 242,504 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | visitor.py | MethodContent.acceptWhile | acceptWhile | Accept and process a while block. | [
"Accept",
"and",
"process",
"a",
"while",
"block."
] | def acceptWhile(self, node, memo):
(parNode, blkNode) = node.children
whileStat = self.factory.statement('while', fs=FS.lsrc, parent=self)
whileStat.expr.walk(parNode, memo)
if not blkNode.children:
self.factory.expr(left='pass', parent=whileStat)
else:
whileStat.walk(blkNode, memo) | ['def', 'acceptWhile(self,', 'node,', 'memo):', '(parNode,', 'blkNode)', '=', 'node.children', 'whileStat', '=', "self.factory.statement('while',", 'fs=FS.lsrc,', 'parent=self)', 'whileStat.expr.walk(parNode,', 'memo)', 'if', 'not', 'blkNode.children:', "self.factory.expr(left='pass',", 'parent=whileStat)', 'else:', 'w... | 17,163 |
iceye-ltd/icecube | sar_datacube_metadata.py | SARDatacubeMetadata.compute_metdatadf_from_folder | compute_metdatadf_from_folder | The function will go throuh the metadata. | [
"The",
"function",
"will",
"go",
"throuh",
"the",
"metadata."
] | def compute_metdatadf_from_folder(self, raster_dir: str, product_type: str):
logger.info(f'Building the metadata from the folder {raster_dir} using {product_type}')
self.metadata_df = self._crawl_metadata(raster_dir, product_type)
logger.debug(f'length metadata from the directory {len(self.metadata_df)}')
... | ['def', 'compute_metdatadf_from_folder(self,', 'raster_dir:', 'str,', 'product_type:', 'str):', "logger.info(f'Building", 'the', 'metadata', 'from', 'the', 'folder', '{raster_dir}', 'using', "{product_type}')", 'self.metadata_df', '=', 'self._crawl_metadata(raster_dir,', 'product_type)', "logger.debug(f'length", 'metad... | 228,897 |
zhang614/MicroGrid | base.py | EventLoop.on_window_close | on_window_close | Default window close handler. | [
"Default",
"window",
"close",
"handler."
] | def on_window_close(self, window):
if len(app.windows) == 0:
self.exit() | ['def', 'on_window_close(self,', 'window):', 'if', 'len(app.windows)', '==', '0:', 'self.exit()'] | 668,550 |
nancheng58/Self-supervised-learning-for-Sequential-Recommender-Systems | utils.py | load_split_dataloaders | load_split_dataloaders | Load split dataloaders if saved dataloaders exist and their :attr:`config` of dataset are the same as current :attr:`config` of dataset. | [
"Load",
"split",
"dataloaders",
"if",
"saved",
"dataloaders",
"exist",
"and",
"their",
":attr:`config`",
"of",
"dataset",
"are",
"the",
"same",
"as",
"current",
":attr:`config`",
"of",
"dataset."
] | def load_split_dataloaders(config):
default_file = os.path.join(config['checkpoint_dir'], f"{config['dataset']}-for-{config['model']}-dataloader.pth")
dataloaders_save_path = config['dataloaders_save_path'] or default_file
if not os.path.exists(dataloaders_save_path):
return None
with open(datal... | ['def', 'load_split_dataloaders(config):', 'default_file', '=', "os.path.join(config['checkpoint_dir'],", 'f"{config[\'dataset\']}-for-{config[\'model\']}-dataloader.pth")', 'dataloaders_save_path', '=', "config['dataloaders_save_path']", 'or', 'default_file', 'if', 'not', 'os.path.exists(dataloaders_save_path):', 'ret... | 341,780 |
liuwei1206/deep-learning | rf3.py | TensorForestEstimator.predict | predict | Returns predictions for given features. | [
"Returns",
"predictions",
"for",
"given",
"features."
] | def predict(self, x=None, input_fn=None, axis=None, batch_size=None):
probabilities = self.predict_proba(x, input_fn, batch_size)
if self.params.regression:
return probabilities
else:
return np.argmax(probabilities, axis=1) | ['def', 'predict(self,', 'x=None,', 'input_fn=None,', 'axis=None,', 'batch_size=None):', 'probabilities', '=', 'self.predict_proba(x,', 'input_fn,', 'batch_size)', 'if', 'self.params.regression:', 'return', 'probabilities', 'else:', 'return', 'np.argmax(probabilities,', 'axis=1)'] | 518,665 |
deepmind/dm_control | dog.py | make_model | make_model | Sets floor size, removes ball and walls (Stand and Move tasks). | [
"Sets",
"floor",
"size,",
"removes",
"ball",
"and",
"walls",
"(Stand",
"and",
"Move",
"tasks)."
] | def make_model(floor_size, remove_ball):
xml_string = common.read_model('dog.xml')
parser = etree.XMLParser(remove_blank_text=True)
mjcf = etree.XML(xml_string, parser)
floor = xml_tools.find_element(mjcf, 'geom', 'floor')
floor.attrib['size'] = str(floor_size) + ' ' + str(floor_size) + ' .1'
if... | ['def', 'make_model(floor_size,', 'remove_ball):', 'xml_string', '=', "common.read_model('dog.xml')", 'parser', '=', 'etree.XMLParser(remove_blank_text=True)', 'mjcf', '=', 'etree.XML(xml_string,', 'parser)', 'floor', '=', 'xml_tools.find_element(mjcf,', "'geom',", "'floor')", "floor.attrib['size']", '=', 'str(floor_si... | 165,407 |
dojoteef/dvae | dataloader.py | Dataset.copy | copy | Return a shallow copy of the dataset. | [
"Return",
"a",
"shallow",
"copy",
"of",
"the",
"dataset."
] | def copy(self):
return Dataset(self.test.copy(), self.train.copy(), self.validation.copy()) | ['def', 'copy(self):', 'return', 'Dataset(self.test.copy(),', 'self.train.copy(),', 'self.validation.copy())'] | 554,982 |
Ruturaj123/Flowchart-Detection | ops.py | Operation.outputs | outputs | The list of `Tensor` objects representing the outputs of this op. | [
"The",
"list",
"of",
"`Tensor`",
"objects",
"representing",
"the",
"outputs",
"of",
"this",
"op."
] | def outputs(self):
return self._outputs | ['def', 'outputs(self):', 'return', 'self._outputs'] | 605,437 |
Liyunfan1998/FDU_Artificial-Intelligence | csp.py | CSP.add_variable | add_variable | Add a new variable to the CSP. | [
"Add",
"a",
"new",
"variable",
"to",
"the",
"CSP."
] | def add_variable(self, var, domain):
if var in self.variables:
raise Exception('Variable name already exists: %s' % str(var))
self.vars_num += 1
self.variables.append(var)
self.values[var] = domain
self.unary_factors[var] = None
self.binary_factors[var] = {} | ['def', 'add_variable(self,', 'var,', 'domain):', 'if', 'var', 'in', 'self.variables:', 'raise', "Exception('Variable", 'name', 'already', 'exists:', "%s'", '%', 'str(var))', 'self.vars_num', '+=', '1', 'self.variables.append(var)', 'self.values[var]', '=', 'domain', 'self.unary_factors[var]', '=', 'None', 'self.binary... | 179,409 |
joaquimcampos/DeepSplines | basemodel.py | BaseModel.init_activation_list | init_activation_list | Initialize list of activation modules (deepspline or standard). | [
"Initialize",
"list",
"of",
"activation",
"modules",
"(deepspline",
"or",
"standard)."
] | def init_activation_list(self, activation_specs, bias=True, **kwargs):
assert isinstance(activation_specs, list), f'activation_specs type: {type(activation_specs)}'
if self.using_deepsplines:
activations = nn.ModuleList()
for (mode, num_activations) in activation_specs:
activations.a... | ['def', 'init_activation_list(self,', 'activation_specs,', 'bias=True,', '**kwargs):', 'assert', 'isinstance(activation_specs,', 'list),', "f'activation_specs", 'type:', "{type(activation_specs)}'", 'if', 'self.using_deepsplines:', 'activations', '=', 'nn.ModuleList()', 'for', '(mode,', 'num_activations)', 'in', 'activ... | 540,091 |
ryu-ed/SpaceInvaders_Ros | pixelarray_test.py | PixelArrayTypeTest.test_pixelarray__subclassed_surface | test_pixelarray__subclassed_surface | Ensure the PixelArray constructor accepts subclassed surfaces. | [
"Ensure",
"the",
"PixelArray",
"constructor",
"accepts",
"subclassed",
"surfaces."
] | def test_pixelarray__subclassed_surface(self):
surface = SurfaceSubclass((3, 5), 0, 32)
pixelarray = pygame.PixelArray(surface)
self.assertIsInstance(pixelarray, pygame.PixelArray) | ['def', 'test_pixelarray__subclassed_surface(self):', 'surface', '=', 'SurfaceSubclass((3,', '5),', '0,', '32)', 'pixelarray', '=', 'pygame.PixelArray(surface)', 'self.assertIsInstance(pixelarray,', 'pygame.PixelArray)'] | 369,114 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | imagenet_test.py | BaseTest.input_fn | input_fn | Provides random features and labels. | [
"Provides",
"random",
"features",
"and",
"labels."
] | def input_fn(self):
features = tf.random_uniform([_BATCH_SIZE, 224, 224, 3])
labels = tf.one_hot(tf.random_uniform([_BATCH_SIZE], maxval=_LABEL_CLASSES - 1, dtype=tf.int32), _LABEL_CLASSES)
return (features, labels) | ['def', 'input_fn(self):', 'features', '=', 'tf.random_uniform([_BATCH_SIZE,', '224,', '224,', '3])', 'labels', '=', 'tf.one_hot(tf.random_uniform([_BATCH_SIZE],', 'maxval=_LABEL_CLASSES', '-', '1,', 'dtype=tf.int32),', '_LABEL_CLASSES)', 'return', '(features,', 'labels)'] | 14,011 |
huggingface/datasets-server | parquet_utils.py | RowsIndex.query | query | Query the parquet files Note that this implementation will always read at least one row group, to get the list of columns and always have the same schema, even if the requested rows are invalid (out of range). | [
"Query",
"the",
"parquet",
"files",
"Note",
"that",
"this",
"implementation",
"will",
"always",
"read",
"at",
"least",
"one",
"row",
"group,",
"to",
"get",
"the",
"list",
"of",
"columns",
"and",
"always",
"have",
"the",
"same",
"schema,",
"even",
"if",
"th... | def query(self, offset: int, length: int) -> pa.Table:
logging.info(f'Query {type(self.parquet_index).__name__} for dataset={self.dataset}, config={self.config}, split={self.split}, offset={offset}, length={length}')
return self.parquet_index.query(offset=offset, length=length) | ['def', 'query(self,', 'offset:', 'int,', 'length:', 'int)', '->', 'pa.Table:', "logging.info(f'Query", '{type(self.parquet_index).__name__}', 'for', 'dataset={self.dataset},', 'config={self.config},', 'split={self.split},', 'offset={offset},', "length={length}')", 'return', 'self.parquet_index.query(offset=offset,', '... | 497,852 |
octree-nn/ocnn-pytorch | octree_pad.py | octree_pad | octree_pad | Pads :attr:`val` to make the number of elements of :attr:`data` equal to the octree node number. | [
"Pads",
":attr:`val`",
"to",
"make",
"the",
"number",
"of",
"elements",
"of",
":attr:`data`",
"equal",
"to",
"the",
"octree",
"node",
"number."
] | def octree_pad(data: torch.Tensor, octree: Octree, depth: int, val: float=0.0):
mask = octree.nempty_mask(depth)
size = (octree.nnum[depth], data.shape[1])
out = torch.full(size, val, dtype=data.dtype, device=data.device)
out[mask] = data
return out | ['def', 'octree_pad(data:', 'torch.Tensor,', 'octree:', 'Octree,', 'depth:', 'int,', 'val:', 'float=0.0):', 'mask', '=', 'octree.nempty_mask(depth)', 'size', '=', '(octree.nnum[depth],', 'data.shape[1])', 'out', '=', 'torch.full(size,', 'val,', 'dtype=data.dtype,', 'device=data.device)', 'out[mask]', '=', 'data', 'retu... | 249,923 |
EducationalTestingService/skll | test_featureset.py | TestFeatureset.test_vectorizer_inequality | test_vectorizer_inequality | Test to make sure that vectorizer equality fails properly. | [
"Test",
"to",
"make",
"sure",
"that",
"vectorizer",
"equality",
"fails",
"properly."
] | def test_vectorizer_inequality(self):
v = DictVectorizer()
self.assertNotEqual(v, 1)
self.assertNotEqual(v, 'passthrough')
self.assertNotEqual(v, [1.0, 2.0, 3.0]) | ['def', 'test_vectorizer_inequality(self):', 'v', '=', 'DictVectorizer()', 'self.assertNotEqual(v,', '1)', 'self.assertNotEqual(v,', "'passthrough')", 'self.assertNotEqual(v,', '[1.0,', '2.0,', '3.0])'] | 885,128 |
asyml/texar | mode.py | is_train_mode_py | is_train_mode_py | Returns a python boolean indicating whether the mode is TRAIN. | [
"Returns",
"a",
"python",
"boolean",
"indicating",
"whether",
"the",
"mode",
"is",
"TRAIN."
] | def is_train_mode_py(mode, default=True):
if mode is None:
return default
if mode not in context.valid_modes():
raise ValueError('Unknown mode: {}'.format(mode))
return mode == tf.estimator.ModeKeys.TRAIN | ['def', 'is_train_mode_py(mode,', 'default=True):', 'if', 'mode', 'is', 'None:', 'return', 'default', 'if', 'mode', 'not', 'in', 'context.valid_modes():', 'raise', "ValueError('Unknown", 'mode:', "{}'.format(mode))", 'return', 'mode', '==', 'tf.estimator.ModeKeys.TRAIN'] | 924,778 |
salesforce/CodeRL | test_modeling_mbart.py | AbstractSeq2SeqIntegrationTest.model | model | Only load the model if needed. | [
"Only",
"load",
"the",
"model",
"if",
"needed."
] | def model(self):
model = MBartForConditionalGeneration.from_pretrained(self.checkpoint_name).to(torch_device)
if 'cuda' in torch_device:
model = model.half()
return model | ['def', 'model(self):', 'model', '=', 'MBartForConditionalGeneration.from_pretrained(self.checkpoint_name).to(torch_device)', 'if', "'cuda'", 'in', 'torch_device:', 'model', '=', 'model.half()', 'return', 'model'] | 495,649 |
google-research/crest | cifar.py | CIFAR100.load_raw_data | load_raw_data | Loads CIFAR100 raw data. | [
"Loads",
"CIFAR100",
"raw",
"data."
] | def load_raw_data(self):
self.data_name = 'cifar100'
(x_train, y_train) = data_util.load_tfrecord(os.path.join(CIFAR_DIR, 'cifar100-train.tfrecord'))
(x_test, y_test) = data_util.load_tfrecord(os.path.join(CIFAR_DIR, 'cifar100-test.tfrecord'))
self.x_train = x_train
self.y_train = y_train
self.x... | ['def', 'load_raw_data(self):', 'self.data_name', '=', "'cifar100'", '(x_train,', 'y_train)', '=', 'data_util.load_tfrecord(os.path.join(CIFAR_DIR,', "'cifar100-train.tfrecord'))", '(x_test,', 'y_test)', '=', 'data_util.load_tfrecord(os.path.join(CIFAR_DIR,', "'cifar100-test.tfrecord'))", 'self.x_train', '=', 'x_train'... | 138,512 |
AgnostiqHQ/covalent | write_result_to_db_test.py | test_update_lattice_completed_electron_num | test_update_lattice_completed_electron_num | Test the function used to update the number of completed electrons for a lattice by 1. | [
"Test",
"the",
"function",
"used",
"to",
"update",
"the",
"number",
"of",
"completed",
"electrons",
"for",
"a",
"lattice",
"by",
"1."
] | def test_update_lattice_completed_electron_num(test_db, mocker):
mocker.patch('covalent_dispatcher._db.write_result_to_db.workflow_db', test_db)
cur_time = dt.now(timezone.utc)
insert_lattices_data(**get_lattice_kwargs(created_at=cur_time, updated_at=cur_time, started_at=cur_time))
update_lattice_comple... | ['def', 'test_update_lattice_completed_electron_num(test_db,', 'mocker):', "mocker.patch('covalent_dispatcher._db.write_result_to_db.workflow_db',", 'test_db)', 'cur_time', '=', 'dt.now(timezone.utc)', 'insert_lattices_data(**get_lattice_kwargs(created_at=cur_time,', 'updated_at=cur_time,', 'started_at=cur_time))', "up... | 489,738 |
myothida/Supervised-Machine-Learning | test_neighbors.py | test_neighbors_minkowski_semimetric_algo_error | test_neighbors_minkowski_semimetric_algo_error | Check that we raise a proper error if `algorithm!='brute'` and `p<1`. | [
"Check",
"that",
"we",
"raise",
"a",
"proper",
"error",
"if",
"`algorithm!='brute'`",
"and",
"`p<1`."
] | def test_neighbors_minkowski_semimetric_algo_error(Estimator, n_features, algorithm):
X = rng.random_sample((10, 2))
y = np.ones(10)
model = Estimator(algorithm=algorithm, p=0.1)
msg = f'algorithm="{algorithm}" does not support 0 < p < 1 for the Minkowski metric. To resolve this problem either set p >= ... | ['def', 'test_neighbors_minkowski_semimetric_algo_error(Estimator,', 'n_features,', 'algorithm):', 'X', '=', 'rng.random_sample((10,', '2))', 'y', '=', 'np.ones(10)', 'model', '=', 'Estimator(algorithm=algorithm,', 'p=0.1)', 'msg', '=', 'f\'algorithm="{algorithm}"', 'does', 'not', 'support', '0', '<', 'p', '<', '1', 'f... | 364,421 |
AtlantixJJ/LinearGAN | semantic_extractor.py | LSE.build | build | Build the architecture of LSE. | [
"Build",
"the",
"architecture",
"of",
"LSE."
] | def build(self):
def conv_block(in_dim, out_dim):
return nn.Conv2d(in_dim, out_dim, 1, bias=self.use_bias)
self.extractor = nn.ModuleList([conv_block(dim, self.n_class) for dim in self.dims])
self.layer_weight = nn.Parameter(torch.ones((len(self.layers),))) | ['def', 'build(self):', 'def', 'conv_block(in_dim,', 'out_dim):', 'return', 'nn.Conv2d(in_dim,', 'out_dim,', '1,', 'bias=self.use_bias)', 'self.extractor', '=', 'nn.ModuleList([conv_block(dim,', 'self.n_class)', 'for', 'dim', 'in', 'self.dims])', 'self.layer_weight', '=', 'nn.Parameter(torch.ones((len(self.layers),)))'... | 602,620 |
alibaba/EasyCV | recognizer3d.py | Recognizer3D.extract_feat | extract_feat | Extract features through a backbone. | [
"Extract",
"features",
"through",
"a",
"backbone."
] | def extract_feat(self, imgs):
x = self.backbone(imgs)
return x | ['def', 'extract_feat(self,', 'imgs):', 'x', '=', 'self.backbone(imgs)', 'return', 'x'] | 546,749 |
scikit-learn/scikit-learn | test_search.py | test_refit_callable_out_bound | test_refit_callable_out_bound | Test implementation catches the errors when 'best_index_' returns an out of bound result. | [
"Test",
"implementation",
"catches",
"the",
"errors",
"when",
"'best_index_'",
"returns",
"an",
"out",
"of",
"bound",
"result."
] | def test_refit_callable_out_bound(out_bound_value, search_cv):
def refit_callable_out_bound(cv_results):
return out_bound_value
(X, y) = make_classification(n_samples=100, n_features=4, random_state=42)
clf = search_cv(LinearSVC(dual='auto', random_state=42), {'C': [0.1, 1]}, scoring='precision', r... | ['def', 'test_refit_callable_out_bound(out_bound_value,', 'search_cv):', 'def', 'refit_callable_out_bound(cv_results):', 'return', 'out_bound_value', '(X,', 'y)', '=', 'make_classification(n_samples=100,', 'n_features=4,', 'random_state=42)', 'clf', '=', "search_cv(LinearSVC(dual='auto',", 'random_state=42),', "{'C':",... | 853,804 |
facebookresearch/CompilerGym | shell_format.py | indent | indent | Indent a multi-line string by given number of spaces. | [
"Indent",
"a",
"multi-line",
"string",
"by",
"given",
"number",
"of",
"spaces."
] | def indent(string: str, n=4) -> str:
return '\n'.join((' ' * n + x for x in str(string).split('\n'))) | ['def', 'indent(string:', 'str,', 'n=4)', '->', 'str:', 'return', "'\\n'.join(('", "'", '*', 'n', '+', 'x', 'for', 'x', 'in', "str(string).split('\\n')))"] | 135,522 |
intel/neural-compressor | test_keras.py | TestKerasModel.test_supports_correct_path | test_supports_correct_path | Test getting correct framework name. | [
"Test",
"getting",
"correct",
"framework",
"name."
] | def test_supports_correct_path(self) -> None:
self.assertTrue(KerasModel.supports_path('/path/to/keras.pb')) | ['def', 'test_supports_correct_path(self)', '->', 'None:', "self.assertTrue(KerasModel.supports_path('/path/to/keras.pb'))"] | 721,662 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | ssl.py | SSLObject.selected_alpn_protocol | selected_alpn_protocol | Return the currently selected ALPN protocol as a string, or ``None`` if a next protocol was not negotiated or if ALPN is not supported by one of the peers. | [
"Return",
"the",
"currently",
"selected",
"ALPN",
"protocol",
"as",
"a",
"string,",
"or",
"``None``",
"if",
"a",
"next",
"protocol",
"was",
"not",
"negotiated",
"or",
"if",
"ALPN",
"is",
"not",
"supported",
"by",
"one",
"of",
"the",
"peers."
] | def selected_alpn_protocol(self):
if _ssl.HAS_ALPN:
return self._sslobj.selected_alpn_protocol() | ['def', 'selected_alpn_protocol(self):', 'if', '_ssl.HAS_ALPN:', 'return', 'self._sslobj.selected_alpn_protocol()'] | 429,543 |
eddylau328/fyp-artificial-intelligence-ac-control-device | firestore.py | client | client | Returns a client that can be used to interact with Google Cloud Firestore. | [
"Returns",
"a",
"client",
"that",
"can",
"be",
"used",
"to",
"interact",
"with",
"Google",
"Cloud",
"Firestore."
] | def client(app=None):
fs_client = _utils.get_app_service(app, _FIRESTORE_ATTRIBUTE, _FirestoreClient.from_app)
return fs_client.get() | ['def', 'client(app=None):', 'fs_client', '=', '_utils.get_app_service(app,', '_FIRESTORE_ATTRIBUTE,', '_FirestoreClient.from_app)', 'return', 'fs_client.get()'] | 214,287 |
PacktPublishing/TensorFlow-Reinforcement-Learning-Quick-Start-Guide | snakeoil3_gym.py | ServerState.parse_server_str | parse_server_str | Parse the server string. | [
"Parse",
"the",
"server",
"string."
] | def parse_server_str(self, server_string):
self.servstr = server_string.strip()[:-1]
sslisted = self.servstr.strip().lstrip('(').rstrip(')').split(')(')
for i in sslisted:
w = i.split(' ')
self.d[w[0]] = destringify(w[1:]) | ['def', 'parse_server_str(self,', 'server_string):', 'self.servstr', '=', 'server_string.strip()[:-1]', 'sslisted', '=', "self.servstr.strip().lstrip('(').rstrip(')').split(')(')", 'for', 'i', 'in', 'sslisted:', 'w', '=', "i.split('", "')", 'self.d[w[0]]', '=', 'destringify(w[1:])'] | 921,741 |
ShuLiu1993/PANet | keypoints.py | nms_oks | nms_oks | Nms based on kp predictions. | [
"Nms",
"based",
"on",
"kp",
"predictions."
] | def nms_oks(kp_predictions, rois, thresh):
scores = np.mean(kp_predictions[:, 2, :], axis=1)
order = scores.argsort()[::-1]
keep = []
while order.size > 0:
i = order[0]
keep.append(i)
ovr = compute_oks(kp_predictions[i], rois[i], kp_predictions[order[1:]], rois[order[1:]])
... | ['def', 'nms_oks(kp_predictions,', 'rois,', 'thresh):', 'scores', '=', 'np.mean(kp_predictions[:,', '2,', ':],', 'axis=1)', 'order', '=', 'scores.argsort()[::-1]', 'keep', '=', '[]', 'while', 'order.size', '>', '0:', 'i', '=', 'order[0]', 'keep.append(i)', 'ovr', '=', 'compute_oks(kp_predictions[i],', 'rois[i],', 'kp_p... | 778,908 |
intel/neural-compressor | component.py | Component.eval_func | eval_func | Not support get eval_func. | [
"Not",
"support",
"get",
"eval_func."
] | def eval_func(self):
assert False, 'Should not try to get the value of `eval_func` attribute.'
return None | ['def', 'eval_func(self):', 'assert', 'False,', "'Should", 'not', 'try', 'to', 'get', 'the', 'value', 'of', '`eval_func`', "attribute.'", 'return', 'None'] | 738,324 |
gunthercox/ChatterBot | mongodb.py | MongoDatabaseAdapter.create_many | create_many | Creates multiple statement entries. | [
"Creates",
"multiple",
"statement",
"entries."
] | def create_many(self, statements):
create_statements = []
for statement in statements:
statement_data = statement.serialize()
tag_data = list(set(statement_data.pop('tags', [])))
statement_data['tags'] = tag_data
if not statement.search_text:
statement_data['search_te... | ['def', 'create_many(self,', 'statements):', 'create_statements', '=', '[]', 'for', 'statement', 'in', 'statements:', 'statement_data', '=', 'statement.serialize()', 'tag_data', '=', "list(set(statement_data.pop('tags',", '[])))', "statement_data['tags']", '=', 'tag_data', 'if', 'not', 'statement.search_text:', "statem... | 478,148 |
aws/sagemaker-python-sdk | association.py | Association.list | list | Return a list of context summaries. | [
"Return",
"a",
"list",
"of",
"context",
"summaries."
] | def list(cls, source_arn: str=None, destination_arn: str=None, source_type: str=None, destination_type: str=None, association_type: str=None, created_after: Optional[datetime]=None, created_before: Optional[datetime]=None, sort_by: Optional[str]=None, sort_order: Optional[str]=None, max_results: Optional[int]=None, nex... | ['def', 'list(cls,', 'source_arn:', 'str=None,', 'destination_arn:', 'str=None,', 'source_type:', 'str=None,', 'destination_type:', 'str=None,', 'association_type:', 'str=None,', 'created_after:', 'Optional[datetime]=None,', 'created_before:', 'Optional[datetime]=None,', 'sort_by:', 'Optional[str]=None,', 'sort_order:'... | 830,262 |
Sentdex/Carla-RL | util.py | make_connection | make_connection | Context manager to create and connect a networking client object. | [
"Context",
"manager",
"to",
"create",
"and",
"connect",
"a",
"networking",
"client",
"object."
] | def make_connection(client_type, *args, **kwargs):
client = None
try:
client = client_type(*args, **kwargs)
client.connect()
yield client
finally:
if client is not None:
client.disconnect() | ['def', 'make_connection(client_type,', '*args,', '**kwargs):', 'client', '=', 'None', 'try:', 'client', '=', 'client_type(*args,', '**kwargs)', 'client.connect()', 'yield', 'client', 'finally:', 'if', 'client', 'is', 'not', 'None:', 'client.disconnect()'] | 103,078 |
nicknochnack/RealTimeSignLanguageTFJS | reader.py | DataReader.compile_file_list | compile_file_list | Creates a list of input files. | [
"Creates",
"a",
"list",
"of",
"input",
"files."
] | def compile_file_list(self, data_dir, split, load_pose=False):
logging.info('data_dir: %s', data_dir)
with gfile.Open(os.path.join(data_dir, '%s.txt' % split), 'r') as f:
frames = f.readlines()
subfolders = [x.split(' ')[0] for x in frames]
frame_ids = [x.split(' ')[1][:-1] for x in frames]
... | ['def', 'compile_file_list(self,', 'data_dir,', 'split,', 'load_pose=False):', "logging.info('data_dir:", "%s',", 'data_dir)', 'with', 'gfile.Open(os.path.join(data_dir,', "'%s.txt'", '%', 'split),', "'r')", 'as', 'f:', 'frames', '=', 'f.readlines()', 'subfolders', '=', "[x.split('", "')[0]", 'for', 'x', 'in', 'frames]... | 831,377 |
vliu15/tts-gan | utils.py | compose | compose | Composes a list of functions. | [
"Composes",
"a",
"list",
"of",
"functions."
] | def compose(*fns):
def compose2(f, g):
return lambda x: f(g(x))
return functools.reduce(compose2, fns, lambda x: x) | ['def', 'compose(*fns):', 'def', 'compose2(f,', 'g):', 'return', 'lambda', 'x:', 'f(g(x))', 'return', 'functools.reduce(compose2,', 'fns,', 'lambda', 'x:', 'x)'] | 952,716 |
intel/neural-compressor | criterion.py | KnowledgeDistillationLoss.teacher_model_forward | teacher_model_forward | Define parameters for teacher_model_forward function. | [
"Define",
"parameters",
"for",
"teacher_model_forward",
"function."
] | def teacher_model_forward(self, input, teacher_model=None):
raise NotImplementedError('Function teacher_model_forward should be framework related.') | ['def', 'teacher_model_forward(self,', 'input,', 'teacher_model=None):', 'raise', "NotImplementedError('Function", 'teacher_model_forward', 'should', 'be', 'framework', "related.')"] | 738,432 |
gunthercox/ChatterBot | api.py | ModelI.generate | generate | Generate n words of text from the language model. | [
"Generate",
"n",
"words",
"of",
"text",
"from",
"the",
"language",
"model."
] | def generate(self, n):
raise NotImplementedError() | ['def', 'generate(self,', 'n):', 'raise', 'NotImplementedError()'] | 527,705 |
mlcommons/medperf | run.py | CompatibilityTestExecution.initialize_report | initialize_report | Initializes an instance of `TestReport` to hold the current test information. | [
"Initializes",
"an",
"instance",
"of",
"`TestReport`",
"to",
"hold",
"the",
"current",
"test",
"information."
] | def initialize_report(self):
report_data = {'demo_dataset_url': self.demo_dataset_url, 'demo_dataset_hash': self.demo_dataset_hash, 'data_path': self.data_path, 'labels_path': self.labels_path, 'prepared_data_hash': self.data_uid, 'data_preparation_mlcube': self.data_prep, 'model': self.model, 'data_evaluator_mlcub... | ['def', 'initialize_report(self):', 'report_data', '=', "{'demo_dataset_url':", 'self.demo_dataset_url,', "'demo_dataset_hash':", 'self.demo_dataset_hash,', "'data_path':", 'self.data_path,', "'labels_path':", 'self.labels_path,', "'prepared_data_hash':", 'self.data_uid,', "'data_preparation_mlcube':", 'self.data_prep,... | 284,957 |
thunderhoser/ai2es_xai_course | utils.py | plot_basic_activations | plot_basic_activations | Plots basic activation functions. | [
"Plots",
"basic",
"activation",
"functions."
] | def plot_basic_activations():
function_names = [SIGMOID_FUNCTION_NAME, TANH_FUNCTION_NAME, RELU_FUNCTION_NAME]
function_names_verbose = ['Sigmoid', 'tanh', 'ReLU']
input_values = numpy.linspace(-3, 3, num=1000, dtype=float)
(_, axes_object) = pyplot.subplots(1, 1, figsize=(FIGURE_WIDTH_INCHES, FIGURE_HE... | ['def', 'plot_basic_activations():', 'function_names', '=', '[SIGMOID_FUNCTION_NAME,', 'TANH_FUNCTION_NAME,', 'RELU_FUNCTION_NAME]', 'function_names_verbose', '=', "['Sigmoid',", "'tanh',", "'ReLU']", 'input_values', '=', 'numpy.linspace(-3,', '3,', 'num=1000,', 'dtype=float)', '(_,', 'axes_object)', '=', 'pyplot.subpl... | 85,296 |
MIT-SPARK/PD-MeshNet | dual_primal_conv.py | DualPrimalConv.forward | forward | Performs the convolution operation on the dual-primal network, by first performing a GATConv convolution on the dual graph and then carrying out a modified GATConv convolution on the primal graph, in which the attention coefficients are computed based on the node features of the dual graph. | [
"Performs",
"the",
"convolution",
"operation",
"on",
"the",
"dual-primal",
"network,",
"by",
"first",
"performing",
"a",
"GATConv",
"convolution",
"on",
"the",
"dual",
"graph",
"and",
"then",
"carrying",
"out",
"a",
"modified",
"GATConv",
"convolution",
"on",
"t... | def forward(self, x_primal, x_dual, edge_index_primal, edge_index_dual, primal_edge_to_dual_node_idx):
x_dual = F.relu(self._dual_layer(x_dual, edge_index_dual))
(x_primal_before_relu, primal_attention_coefficients) = self._primal_layer(x_primal, x_dual, edge_index_primal, primal_edge_to_dual_node_idx)
x_pr... | ['def', 'forward(self,', 'x_primal,', 'x_dual,', 'edge_index_primal,', 'edge_index_dual,', 'primal_edge_to_dual_node_idx):', 'x_dual', '=', 'F.relu(self._dual_layer(x_dual,', 'edge_index_dual))', '(x_primal_before_relu,', 'primal_attention_coefficients)', '=', 'self._primal_layer(x_primal,', 'x_dual,', 'edge_index_prim... | 278,885 |
trenton3983/Programming_Computer__with_Python | camera.py | Camera.project | project | Project points in X (4*n array) and normalize coordinates. | [
"Project",
"points",
"in",
"X",
"(4*n",
"array)",
"and",
"normalize",
"coordinates."
] | def project(self, X):
x = dot(self.P, X)
for i in range(3):
x[i] /= x[2]
return x | ['def', 'project(self,', 'X):', 'x', '=', 'dot(self.P,', 'X)', 'for', 'i', 'in', 'range(3):', 'x[i]', '/=', 'x[2]', 'return', 'x'] | 817,354 |
flavioschneider/rl-transfer- | uniform_random_policy.py | UniformRandomPolicy.get_actions | get_actions | Get actions from this policy for the input observation. | [
"Get",
"actions",
"from",
"this",
"policy",
"for",
"the",
"input",
"observation."
] | def get_actions(self, observations):
return ([self._env_spec.action_space.sample() for obs in observations], dict()) | ['def', 'get_actions(self,', 'observations):', 'return', '([self._env_spec.action_space.sample()', 'for', 'obs', 'in', 'observations],', 'dict())'] | 861,236 |
boostcampaitech2/semantic-segmentation-level2-cv-07 | detr.py | DETR.onnx_export | onnx_export | Test function for exporting to ONNX, without test time augmentation. | [
"Test",
"function",
"for",
"exporting",
"to",
"ONNX,",
"without",
"test",
"time",
"augmentation."
] | def onnx_export(self, img, img_metas):
x = self.extract_feat(img)
outs = self.bbox_head.forward_onnx(x, img_metas)
img_shape = torch._shape_as_tensor(img)[2:]
img_metas[0]['img_shape_for_onnx'] = img_shape
(det_bboxes, det_labels) = self.bbox_head.onnx_export(*outs, img_metas)
return (det_bboxes... | ['def', 'onnx_export(self,', 'img,', 'img_metas):', 'x', '=', 'self.extract_feat(img)', 'outs', '=', 'self.bbox_head.forward_onnx(x,', 'img_metas)', 'img_shape', '=', 'torch._shape_as_tensor(img)[2:]', "img_metas[0]['img_shape_for_onnx']", '=', 'img_shape', '(det_bboxes,', 'det_labels)', '=', 'self.bbox_head.onnx_expor... | 857,183 |
rishab-sharma/object_detection | bbox.py | iou_bbox | iou_bbox | Compute the IoUs between bounding boxes. | [
"Compute",
"the",
"IoUs",
"between",
"bounding",
"boxes."
] | def iou_bbox(bboxes1, bboxes2):
bboxes1 = np.array(bboxes1, np.float32)
bboxes2 = np.array(bboxes2, np.float32)
intersection_min_y = np.maximum(bboxes1[:, 0], bboxes2[:, 0])
intersection_max_y = np.minimum(bboxes1[:, 0] + bboxes1[:, 2] - 1, bboxes2[:, 0] + bboxes2[:, 2] - 1)
intersection_height = np... | ['def', 'iou_bbox(bboxes1,', 'bboxes2):', 'bboxes1', '=', 'np.array(bboxes1,', 'np.float32)', 'bboxes2', '=', 'np.array(bboxes2,', 'np.float32)', 'intersection_min_y', '=', 'np.maximum(bboxes1[:,', '0],', 'bboxes2[:,', '0])', 'intersection_max_y', '=', 'np.minimum(bboxes1[:,', '0]', '+', 'bboxes1[:,', '2]', '-', '1,', ... | 744,892 |
openvinotoolkit/training_extensions | media.py | IMedia2DEntity.numpy | numpy | Returns the numpy representation of the 2D Media object. | [
"Returns",
"the",
"numpy",
"representation",
"of",
"the",
"2D",
"Media",
"object."
] | def numpy(self) -> np.ndarray:
raise NotImplementedError | ['def', 'numpy(self)', '->', 'np.ndarray:', 'raise', 'NotImplementedError'] | 918,582 |
gunthercox/ChatterBot | base.py | SQLiteIdentifierPreparer.format_index | format_index | Prepare a quoted index and schema name. | [
"Prepare",
"a",
"quoted",
"index",
"and",
"schema",
"name."
] | def format_index(self, index, use_schema=True, name=None):
if name is None:
name = index.name
result = self.quote(name, index.quote)
if not self.omit_schema and use_schema and getattr(index.table, 'schema', None):
result = self.quote_schema(index.table.schema, index.table.quote_schema) + '.'... | ['def', 'format_index(self,', 'index,', 'use_schema=True,', 'name=None):', 'if', 'name', 'is', 'None:', 'name', '=', 'index.name', 'result', '=', 'self.quote(name,', 'index.quote)', 'if', 'not', 'self.omit_schema', 'and', 'use_schema', 'and', 'getattr(index.table,', "'schema',", 'None):', 'result', '=', 'self.quote_sch... | 481,026 |
Sabrinas-workspace/nlp-project-similar-lyrics | song_information.py | get_artist | get_artist | Finds the artist of a song. | [
"Finds",
"the",
"artist",
"of",
"a",
"song."
] | def get_artist(et_element, lyrics=None):
if lyrics is not None:
for child in et_element:
if get_lyrics(child) == lyrics:
artist_child = child.find('artist')
artist = ''.join(artist_child.attrib.values())
else:
artist_child = et_element.find('artist')
... | ['def', 'get_artist(et_element,', 'lyrics=None):', 'if', 'lyrics', 'is', 'not', 'None:', 'for', 'child', 'in', 'et_element:', 'if', 'get_lyrics(child)', '==', 'lyrics:', 'artist_child', '=', "child.find('artist')", 'artist', '=', "''.join(artist_child.attrib.values())", 'else:', 'artist_child', '=', "et_element.find('a... | 731,111 |
cjrd/self-supervised-pretraining | keypoint_head.py | keypoint_rcnn_inference | keypoint_rcnn_inference | Post process each predicted keypoint heatmap in `pred_keypoint_logits` into (x, y, score) and add it to the `pred_instances` as a `pred_keypoints` field. | [
"Post",
"process",
"each",
"predicted",
"keypoint",
"heatmap",
"in",
"`pred_keypoint_logits`",
"into",
"(x,",
"y,",
"score)",
"and",
"add",
"it",
"to",
"the",
"`pred_instances`",
"as",
"a",
"`pred_keypoints`",
"field."
] | def keypoint_rcnn_inference(pred_keypoint_logits: torch.Tensor, pred_instances: List[Instances]):
bboxes_flat = cat([b.pred_boxes.tensor for b in pred_instances], dim=0)
pred_keypoint_logits = pred_keypoint_logits.detach()
keypoint_results = heatmaps_to_keypoints(pred_keypoint_logits, bboxes_flat.detach())
... | ['def', 'keypoint_rcnn_inference(pred_keypoint_logits:', 'torch.Tensor,', 'pred_instances:', 'List[Instances]):', 'bboxes_flat', '=', 'cat([b.pred_boxes.tensor', 'for', 'b', 'in', 'pred_instances],', 'dim=0)', 'pred_keypoint_logits', '=', 'pred_keypoint_logits.detach()', 'keypoint_results', '=', 'heatmaps_to_keypoints(... | 843,576 |
TonyLianLong/VAI-ReinforcementLearning | wrappers.py | MjDataWrapper.ten_J_rownnz | ten_J_rownnz | number of non-zeros in Jacobian row (ntendon x 1). | [
"number",
"of",
"non-zeros",
"in",
"Jacobian",
"row",
"(ntendon",
"x",
"1)."
] | def ten_J_rownnz(self):
return util.buf_to_npy(self._ptr.contents.ten_J_rownnz, (self._model.ntendon,)) | ['def', 'ten_J_rownnz(self):', 'return', 'util.buf_to_npy(self._ptr.contents.ten_J_rownnz,', '(self._model.ntendon,))'] | 440,564 |
Ruturaj123/Flowchart-Detection | model_analyzer.py | Profiler.advise | advise | Automatically detect problems and generate reports. | [
"Automatically",
"detect",
"problems",
"and",
"generate",
"reports."
] | def advise(self, options):
advise_pb = tfprof_output_pb2.AdviceProto()
opts = _build_advisor_options(options)
advise_pb.ParseFromString(print_mdl.Profile('advise'.encode('utf-8'), opts.SerializeToString()))
return advise_pb | ['def', 'advise(self,', 'options):', 'advise_pb', '=', 'tfprof_output_pb2.AdviceProto()', 'opts', '=', '_build_advisor_options(options)', "advise_pb.ParseFromString(print_mdl.Profile('advise'.encode('utf-8'),", 'opts.SerializeToString()))', 'return', 'advise_pb'] | 606,357 |
deephyper/deephyper | _base.py | BaseTrainer.evaluate | evaluate | Evaluate the performance of your model for the same configuration. | [
"Evaluate",
"the",
"performance",
"of",
"your",
"model",
"for",
"the",
"same",
"configuration."
] | def evaluate(self, dataset='train'):
if dataset == 'train':
return self.model.evaluate(self.dataset_train, steps=self.train_steps_per_epoch)
else:
return self.model.evaluate(self.dataset_valid, steps=self.valid_steps_per_epoch) | ['def', 'evaluate(self,', "dataset='train'):", 'if', 'dataset', '==', "'train':", 'return', 'self.model.evaluate(self.dataset_train,', 'steps=self.train_steps_per_epoch)', 'else:', 'return', 'self.model.evaluate(self.dataset_valid,', 'steps=self.valid_steps_per_epoch)'] | 520,931 |
feast-dev/feast | version.py | get_version | get_version | Returns version information of the Feast Python Package. | [
"Returns",
"version",
"information",
"of",
"the",
"Feast",
"Python",
"Package."
] | def get_version():
try:
sdk_version = version('feast')
except PackageNotFoundError:
sdk_version = 'unknown'
return sdk_version | ['def', 'get_version():', 'try:', 'sdk_version', '=', "version('feast')", 'except', 'PackageNotFoundError:', 'sdk_version', '=', "'unknown'", 'return', 'sdk_version'] | 544,313 |
aimclub/FEDOT | data_preprocessing.py | data_has_missing_values | data_has_missing_values | Check data for missing values. | [
"Check",
"data",
"for",
"missing",
"values."
] | def data_has_missing_values(data: InputData) -> bool:
if data_type_is_suitable_preprocessing(data):
return pd.DataFrame(data.features).isna().sum().sum() > 0
return False | ['def', 'data_has_missing_values(data:', 'InputData)', '->', 'bool:', 'if', 'data_type_is_suitable_preprocessing(data):', 'return', 'pd.DataFrame(data.features).isna().sum().sum()', '>', '0', 'return', 'False'] | 545,669 |
CarperAI/trlx | modeling_nemo_ppo.py | RefLMHeads.offload_policy_model | offload_policy_model | Move language model to CPU. | [
"Move",
"language",
"model",
"to",
"CPU."
] | def offload_policy_model(self):
self.reference_model.onload()
self._lm.to('cpu', non_blocking=True) | ['def', 'offload_policy_model(self):', 'self.reference_model.onload()', "self._lm.to('cpu',", 'non_blocking=True)'] | 425,966 |
Vedaank/cs188-sp19 | models.py | PerceptronModel.get_weights | get_weights | Return a Parameter instance with the current weights of the perceptron. | [
"Return",
"a",
"Parameter",
"instance",
"with",
"the",
"current",
"weights",
"of",
"the",
"perceptron."
] | def get_weights(self):
return self.w | ['def', 'get_weights(self):', 'return', 'self.w'] | 226,128 |
nosmokingbandit/watcher | java.py | parse_method_descriptor | parse_method_descriptor | Parse a method descriptor (params type and return type), and returns it as human-readable string representation. | [
"Parse",
"a",
"method",
"descriptor",
"(params",
"type",
"and",
"return",
"type),",
"and",
"returns",
"it",
"as",
"human-readable",
"string",
"representation."
] | def parse_method_descriptor(descr, name=None):
assert descr and descr[0] == '('
descr = descr[1:]
params_list = []
while descr[0] != ')':
(param, descr) = eat_descriptor(descr)
params_list.append(param)
(type, tail) = eat_descriptor(descr[1:])
assert not tail
params = ', '.jo... | ['def', 'parse_method_descriptor(descr,', 'name=None):', 'assert', 'descr', 'and', 'descr[0]', '==', "'('", 'descr', '=', 'descr[1:]', 'params_list', '=', '[]', 'while', 'descr[0]', '!=', "')':", '(param,', 'descr)', '=', 'eat_descriptor(descr)', 'params_list.append(param)', '(type,', 'tail)', '=', 'eat_descriptor(desc... | 381,728 |
opendilab/DI-star | lstm.py | script_lnlstm | script_lnlstm | Returns a ScriptModule that mimics a PyTorch native LSTM. | [
"Returns",
"a",
"ScriptModule",
"that",
"mimics",
"a",
"PyTorch",
"native",
"LSTM."
] | def script_lnlstm(input_size, hidden_size, num_layers, bias=True, batch_first=False, dropout=False, bidirectional=False, decompose_layernorm=False):
assert bias
assert not batch_first
assert not dropout
if bidirectional:
stack_type = StackedLSTM2
layer_type = BidirLSTMLayer
dirs ... | ['def', 'script_lnlstm(input_size,', 'hidden_size,', 'num_layers,', 'bias=True,', 'batch_first=False,', 'dropout=False,', 'bidirectional=False,', 'decompose_layernorm=False):', 'assert', 'bias', 'assert', 'not', 'batch_first', 'assert', 'not', 'dropout', 'if', 'bidirectional:', 'stack_type', '=', 'StackedLSTM2', 'layer... | 184,435 |
rouge8/20questions | webinterface.py | learn.POST | POST | Processes the learning form and learns the correct character and new question. | [
"Processes",
"the",
"learning",
"form",
"and",
"learns",
"the",
"correct",
"character",
"and",
"new",
"question."
] | def POST(self):
inputs = web.input()
name = inputs.get('name')
if name == 'new':
name = inputs.get('new_character')
question = inputs.get('question', '')
if question:
new_question_answer = inputs.get('new_question_answer')
if new_question_answer in ['yes', 'no', 'unsure']:
... | ['def', 'POST(self):', 'inputs', '=', 'web.input()', 'name', '=', "inputs.get('name')", 'if', 'name', '==', "'new':", 'name', '=', "inputs.get('new_character')", 'question', '=', "inputs.get('question',", "'')", 'if', 'question:', 'new_question_answer', '=', "inputs.get('new_question_answer')", 'if', 'new_question_answ... | 4,403 |
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform | ctx.py | AppContext.push | push | Binds the app context to the current context. | [
"Binds",
"the",
"app",
"context",
"to",
"the",
"current",
"context."
] | def push(self):
self._refcnt += 1
if hasattr(sys, 'exc_clear'):
sys.exc_clear()
_app_ctx_stack.push(self)
appcontext_pushed.send(self.app) | ['def', 'push(self):', 'self._refcnt', '+=', '1', 'if', 'hasattr(sys,', "'exc_clear'):", 'sys.exc_clear()', '_app_ctx_stack.push(self)', 'appcontext_pushed.send(self.app)'] | 102,017 |
Westlake-AI/openmixup | revvit.py | RevTransformerEncoderLayer.seed_cuda | seed_cuda | Fix seeds to allow for stochastic elements such as dropout to be reproduced exactly in activation recomputation in the backward pass. | [
"Fix",
"seeds",
"to",
"allow",
"for",
"stochastic",
"elements",
"such",
"as",
"dropout",
"to",
"be",
"reproduced",
"exactly",
"in",
"activation",
"recomputation",
"in",
"the",
"backward",
"pass."
] | def seed_cuda(self, key):
if hasattr(torch.cuda, 'default_generators') and len(torch.cuda.default_generators) > 0:
device_idx = torch.cuda.current_device()
seed = torch.cuda.default_generators[device_idx].seed()
else:
seed = int(torch.seed() % sys.maxsize)
self.seeds[key] = seed
... | ['def', 'seed_cuda(self,', 'key):', 'if', 'hasattr(torch.cuda,', "'default_generators')", 'and', 'len(torch.cuda.default_generators)', '>', '0:', 'device_idx', '=', 'torch.cuda.current_device()', 'seed', '=', 'torch.cuda.default_generators[device_idx].seed()', 'else:', 'seed', '=', 'int(torch.seed()', '%', 'sys.maxsize... | 252,429 |
takuseno/d3rlpy | replay_buffer.py | ReplayBuffer.append_episode | append_episode | Appends episode to buffer. | [
"Appends",
"episode",
"to",
"buffer."
] | def append_episode(self, episode: EpisodeBase) -> None:
for i in range(episode.transition_count):
self._buffer.append(episode, i) | ['def', 'append_episode(self,', 'episode:', 'EpisodeBase)', '->', 'None:', 'for', 'i', 'in', 'range(episode.transition_count):', 'self._buffer.append(episode,', 'i)'] | 197,835 |
alibaba/EasyCV | bevformer_predictor.py | BEVFormerInputProcessor.process_single | process_single | Process single input sample. | [
"Process",
"single",
"input",
"sample."
] | def process_single(self, input):
data_info = mmcv.load(input) if isinstance(input, str) else input
result = self._prepare_input_dict(data_info)
result = self.processor(result)
if self.adapt_jit:
result['can_bus'] = DC(to_tensor(result['img_metas'][0]._data['can_bus']), cpu_only=False)
re... | ['def', 'process_single(self,', 'input):', 'data_info', '=', 'mmcv.load(input)', 'if', 'isinstance(input,', 'str)', 'else', 'input', 'result', '=', 'self._prepare_input_dict(data_info)', 'result', '=', 'self.processor(result)', 'if', 'self.adapt_jit:', "result['can_bus']", '=', "DC(to_tensor(result['img_metas'][0]._dat... | 546,780 |
youngjoo-epfl/gconvRNN | graph.py | distance_scipy_spatial | distance_scipy_spatial | Compute exact pairwise distances. | [
"Compute",
"exact",
"pairwise",
"distances."
] | def distance_scipy_spatial(z, k=4, metric='euclidean'):
d = scipy.spatial.distance.pdist(z, metric)
d = scipy.spatial.distance.squareform(d)
idx = np.argsort(d)[:, 1:k + 1]
d.sort()
d = d[:, 1:k + 1]
return (d, idx) | ['def', 'distance_scipy_spatial(z,', 'k=4,', "metric='euclidean'):", 'd', '=', 'scipy.spatial.distance.pdist(z,', 'metric)', 'd', '=', 'scipy.spatial.distance.squareform(d)', 'idx', '=', 'np.argsort(d)[:,', '1:k', '+', '1]', 'd.sort()', 'd', '=', 'd[:,', '1:k', '+', '1]', 'return', '(d,', 'idx)'] | 201,411 |
intel/neural-compressor | utils.py | parse_to_prune_tf | parse_to_prune_tf | Keep target pruned layers. | [
"Keep",
"target",
"pruned",
"layers."
] | def parse_to_prune_tf(config, model):
modules = {}
classifier_head_name = parse_last_linear_tf(model)
if classifier_head_name is not None:
config['excluded_op_names'].append(classifier_head_name)
if config['op_names'] is None or config['op_names'] == []:
config['op_names'] = ['.*']
f... | ['def', 'parse_to_prune_tf(config,', 'model):', 'modules', '=', '{}', 'classifier_head_name', '=', 'parse_last_linear_tf(model)', 'if', 'classifier_head_name', 'is', 'not', 'None:', "config['excluded_op_names'].append(classifier_head_name)", 'if', "config['op_names']", 'is', 'None', 'or', "config['op_names']", '==', '[... | 738,080 |
hitchtest/hitch | commandline.py | installpackages | installpackages | Install packages with hitchsystem. | [
"Install",
"packages",
"with",
"hitchsystem."
] | def installpackages():
hitchsystem = path.abspath(path.join('.hitch', 'virtualenv', 'bin', 'hitchsystem'))
signal.signal(signal.SIGINT, signal.SIG_IGN)
check_call([hitchsystem, 'installpackages'])
signal.signal(signal.SIGINT, stop_everything) | ['def', 'installpackages():', 'hitchsystem', '=', "path.abspath(path.join('.hitch',", "'virtualenv',", "'bin',", "'hitchsystem'))", 'signal.signal(signal.SIGINT,', 'signal.SIG_IGN)', 'check_call([hitchsystem,', "'installpackages'])", 'signal.signal(signal.SIGINT,', 'stop_everything)'] | 206,540 |
intel/neural-compressor | bleu.py | BLEU.reset | reset | Clear the predictions and labels in the cache. | [
"Clear",
"the",
"predictions",
"and",
"labels",
"in",
"the",
"cache."
] | def reset(self) -> None:
self.predictions = []
self.labels = [] | ['def', 'reset(self)', '->', 'None:', 'self.predictions', '=', '[]', 'self.labels', '=', '[]'] | 738,782 |
SALT-NLP/Adaptive-Compositional-Modules | modeling_rag.py | RagTokenForGeneration.generate | generate | Implements RAG token decoding. | [
"Implements",
"RAG",
"token",
"decoding."
] | def generate(self, input_ids: Optional[torch.LongTensor]=None, attention_mask: Optional[torch.LongTensor]=None, context_input_ids=None, context_attention_mask=None, doc_scores=None, max_length=None, min_length=None, early_stopping=None, use_cache=None, num_beams=None, num_beam_groups=None, diversity_penalty=None, bos_t... | ['def', 'generate(self,', 'input_ids:', 'Optional[torch.LongTensor]=None,', 'attention_mask:', 'Optional[torch.LongTensor]=None,', 'context_input_ids=None,', 'context_attention_mask=None,', 'doc_scores=None,', 'max_length=None,', 'min_length=None,', 'early_stopping=None,', 'use_cache=None,', 'num_beams=None,', 'num_bea... | 409,030 |
Ruturaj123/Flowchart-Detection | context.py | Context.devices | devices | List of the names of devices available to execute operations. | [
"List",
"of",
"the",
"names",
"of",
"devices",
"available",
"to",
"execute",
"operations."
] | def devices(self):
return self._devices | ['def', 'devices(self):', 'return', 'self._devices'] | 605,155 |
audioku/meta-transfer-learning | misc.py | count_acc | count_acc | The function to calculate the . | [
"The",
"function",
"to",
"calculate",
"the",
"."
] | def count_acc(logits, label):
pred = F.softmax(logits, dim=1).argmax(dim=1)
if torch.cuda.is_available():
return (pred == label).type(torch.cuda.FloatTensor).mean().item()
return (pred == label).type(torch.FloatTensor).mean().item() | ['def', 'count_acc(logits,', 'label):', 'pred', '=', 'F.softmax(logits,', 'dim=1).argmax(dim=1)', 'if', 'torch.cuda.is_available():', 'return', '(pred', '==', 'label).type(torch.cuda.FloatTensor).mean().item()', 'return', '(pred', '==', 'label).type(torch.FloatTensor).mean().item()'] | 633,065 |
matsu0228/nlp-jp | monitoring.py | CommandStartedEvent.database_name | database_name | The name of the database this command was run against. | [
"The",
"name",
"of",
"the",
"database",
"this",
"command",
"was",
"run",
"against."
] | def database_name(self):
return self.__db | ['def', 'database_name(self):', 'return', 'self.__db'] | 804,935 |
IIT-PAVIS/acoustic-images-self-supervision | dualcamnet.py | buildDualCamClassNetworkV4 | buildDualCamClassNetworkV4 | Builds a DualCamNet network for classification using less aggressive filters. | [
"Builds",
"a",
"DualCamNet",
"network",
"for",
"classification",
"using",
"less",
"aggressive",
"filters."
] | def buildDualCamClassNetworkV4(x, keep_prob, is_training, num_classes, name_scope='DualCamClassNetV4'):
with tf.variable_scope(name_scope):
conv1 = build2DConvolution(x, 512, 512, 1, 1, name_scope='conv1', padding='SAME')
relu1 = buildReLU(conv1, 'conv1')
conv2 = build2DConvolution(relu1, 51... | ['def', 'buildDualCamClassNetworkV4(x,', 'keep_prob,', 'is_training,', 'num_classes,', "name_scope='DualCamClassNetV4'):", 'with', 'tf.variable_scope(name_scope):', 'conv1', '=', 'build2DConvolution(x,', '512,', '512,', '1,', '1,', "name_scope='conv1',", "padding='SAME')", 'relu1', '=', 'buildReLU(conv1,', "'conv1')", ... | 8,603 |
Kvatsx/Artificial-Intelligence-Assignments | __init__.py | common_substring | common_substring | Returns the longest common substring to the two strings, starting from the left. | [
"Returns",
"the",
"longest",
"common",
"substring",
"to",
"the",
"two",
"strings,",
"starting",
"from",
"the",
"left."
] | def common_substring(s1, s2):
chunks = []
path1 = splitall(s1)
path2 = splitall(s2)
for (dir1, dir2) in zip(path1, path2):
if dir1 != dir2:
break
chunks.append(dir1)
return os.path.join(*chunks) | ['def', 'common_substring(s1,', 's2):', 'chunks', '=', '[]', 'path1', '=', 'splitall(s1)', 'path2', '=', 'splitall(s2)', 'for', '(dir1,', 'dir2)', 'in', 'zip(path1,', 'path2):', 'if', 'dir1', '!=', 'dir2:', 'break', 'chunks.append(dir1)', 'return', 'os.path.join(*chunks)'] | 74,521 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | word2vec.py | Word2Vec.build_graph | build_graph | Build the graph for the full model. | [
"Build",
"the",
"graph",
"for",
"the",
"full",
"model."
] | def build_graph(self):
opts = self._options
(words, counts, words_per_epoch, self._epoch, self._words, examples, labels) = word2vec.skipgram_word2vec(filename=opts.train_data, batch_size=opts.batch_size, window_size=opts.window_size, min_count=opts.min_count, subsample=opts.subsample)
(opts.vocab_words, opt... | ['def', 'build_graph(self):', 'opts', '=', 'self._options', '(words,', 'counts,', 'words_per_epoch,', 'self._epoch,', 'self._words,', 'examples,', 'labels)', '=', 'word2vec.skipgram_word2vec(filename=opts.train_data,', 'batch_size=opts.batch_size,', 'window_size=opts.window_size,', 'min_count=opts.min_count,', 'subsamp... | 112,940 |
MolecularAI/Siamese-RNN-Self-Attention | trainer.py | Train.get_mispredictions | get_mispredictions | Selects false positive and false negative predictions from binary similarity inference task. | [
"Selects",
"false",
"positive",
"and",
"false",
"negative",
"predictions",
"from",
"binary",
"similarity",
"inference",
"task."
] | def get_mispredictions(self):
df = pd.DataFrame(zip(self.smi_1, self.smi_2, self.predictions, self.ground_truth), columns=['SMILES_1', 'SMILES_2', 'predictions', 'ground_truth'])
mispredictions = df[df.iloc[:, 2] != df.iloc[:, -1]]
(decoded_pair_1, decoded_pair_2) = list(map(main_decoder, [mispredictions['S... | ['def', 'get_mispredictions(self):', 'df', '=', 'pd.DataFrame(zip(self.smi_1,', 'self.smi_2,', 'self.predictions,', 'self.ground_truth),', "columns=['SMILES_1',", "'SMILES_2',", "'predictions',", "'ground_truth'])", 'mispredictions', '=', 'df[df.iloc[:,', '2]', '!=', 'df.iloc[:,', '-1]]', '(decoded_pair_1,', 'decoded_p... | 350,428 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.