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 |
|---|---|---|---|---|---|---|---|---|
nilearn/nilearn | test_multi_pca.py | test_multi_pca_with_masker_without_cca_smoke | test_multi_pca_with_masker_without_cca_smoke | Multi-pca can run with a masker and without canonical correlation analysis. | [
"Multi-pca",
"can",
"run",
"with",
"a",
"masker",
"and",
"without",
"canonical",
"correlation",
"analysis."
] | def test_multi_pca_with_masker_without_cca_smoke(multi_pca_data):
masker = MultiNiftiMasker(mask_args=dict(opening=0))
multi_pca = _MultiPCA(mask=masker, do_cca=False, n_components=3)
multi_pca.fit(multi_pca_data[:2])
multi_pca.inverse_transform(multi_pca.transform(multi_pca_data[-2:])) | ['def', 'test_multi_pca_with_masker_without_cca_smoke(multi_pca_data):', 'masker', '=', 'MultiNiftiMasker(mask_args=dict(opening=0))', 'multi_pca', '=', '_MultiPCA(mask=masker,', 'do_cca=False,', 'n_components=3)', 'multi_pca.fit(multi_pca_data[:2])', 'multi_pca.inverse_transform(multi_pca.transform(multi_pca_data[-2:]... | 723,751 |
triaquae/triaquae | options.py | ModelAdmin.get_changelist_formset | get_changelist_formset | Returns a FormSet class for use on the changelist page if list_editable is used. | [
"Returns",
"a",
"FormSet",
"class",
"for",
"use",
"on",
"the",
"changelist",
"page",
"if",
"list_editable",
"is",
"used."
] | def get_changelist_formset(self, request, **kwargs):
defaults = {'formfield_callback': partial(self.formfield_for_dbfield, request=request)}
defaults.update(kwargs)
return modelformset_factory(self.model, self.get_changelist_form(request), extra=0, fields=self.list_editable, **defaults) | ['def', 'get_changelist_formset(self,', 'request,', '**kwargs):', 'defaults', '=', "{'formfield_callback':", 'partial(self.formfield_for_dbfield,', 'request=request)}', 'defaults.update(kwargs)', 'return', 'modelformset_factory(self.model,', 'self.get_changelist_form(request),', 'extra=0,', 'fields=self.list_editable,'... | 356,960 |
instadeepai/jumanji | random.py | make_random_policy_game_2048 | make_random_policy_game_2048 | Make random policy for 2048. | [
"Make",
"random",
"policy",
"for",
"2048."
] | def make_random_policy_game_2048() -> RandomPolicy:
return masked_categorical_random | ['def', 'make_random_policy_game_2048()', '->', 'RandomPolicy:', 'return', 'masked_categorical_random'] | 594,614 |
FreshAirTonight/af2complex | data_transforms.py | make_hhblits_profile | make_hhblits_profile | Compute the HHblits MSA profile if not already present. | [
"Compute",
"the",
"HHblits",
"MSA",
"profile",
"if",
"not",
"already",
"present."
] | def make_hhblits_profile(protein):
if 'hhblits_profile' in protein:
return protein
protein['hhblits_profile'] = tf.reduce_mean(tf.one_hot(protein['msa'], 22), axis=0)
return protein | ['def', 'make_hhblits_profile(protein):', 'if', "'hhblits_profile'", 'in', 'protein:', 'return', 'protein', "protein['hhblits_profile']", '=', "tf.reduce_mean(tf.one_hot(protein['msa'],", '22),', 'axis=0)', 'return', 'protein'] | 400,782 |
jfzhuang/IFR | testing.py | assert_keys_equal | assert_keys_equal | Check if target_keys is equal to result_keys. | [
"Check",
"if",
"target_keys",
"is",
"equal",
"to",
"result_keys."
] | def assert_keys_equal(result_keys: List[str], target_keys: List[str]) -> bool:
return set(result_keys) == set(target_keys) | ['def', 'assert_keys_equal(result_keys:', 'List[str],', 'target_keys:', 'List[str])', '->', 'bool:', 'return', 'set(result_keys)', '==', 'set(target_keys)'] | 597,456 |
XuyangSHEN/Non-binary-deep-transfer-learning-for-image-classification | models.py | tf2th | tf2th | Possibly convert HWIO to OIHW. | [
"Possibly",
"convert",
"HWIO",
"to",
"OIHW."
] | def tf2th(conv_weights):
if conv_weights.ndim == 4:
conv_weights = conv_weights.transpose([3, 2, 0, 1])
return torch.from_numpy(conv_weights) | ['def', 'tf2th(conv_weights):', 'if', 'conv_weights.ndim', '==', '4:', 'conv_weights', '=', 'conv_weights.transpose([3,', '2,', '0,', '1])', 'return', 'torch.from_numpy(conv_weights)'] | 729,387 |
sunishsheth2009/ChatterBot | searching.py | Hit.fields | fields | Returns a dictionary of the stored fields of the document this object represents. | [
"Returns",
"a",
"dictionary",
"of",
"the",
"stored",
"fields",
"of",
"the",
"document",
"this",
"object",
"represents."
] | def fields(self):
if self._fields is None:
self._fields = self.searcher.stored_fields(self.docnum)
return self._fields | ['def', 'fields(self):', 'if', 'self._fields', 'is', 'None:', 'self._fields', '=', 'self.searcher.stored_fields(self.docnum)', 'return', 'self._fields'] | 526,430 |
Ruturaj123/Flowchart-Detection | quantize_graph.py | GraphRewriter.eightbitize_reshape_node | eightbitize_reshape_node | Replaces a Reshape node with the eight bit equivalent sub-graph. | [
"Replaces",
"a",
"Reshape",
"node",
"with",
"the",
"eight",
"bit",
"equivalent",
"sub-graph."
] | def eightbitize_reshape_node(self, original_node):
namespace_prefix = original_node.name + '_eightbit'
quantized_reshape_name = namespace_prefix + '_quantized_reshape'
(reshape_dims_name, reduction_dims_name) = self.add_common_quantization_nodes(namespace_prefix)
shape_input_name = original_node.input[1... | ['def', 'eightbitize_reshape_node(self,', 'original_node):', 'namespace_prefix', '=', 'original_node.name', '+', "'_eightbit'", 'quantized_reshape_name', '=', 'namespace_prefix', '+', "'_quantized_reshape'", '(reshape_dims_name,', 'reduction_dims_name)', '=', 'self.add_common_quantization_nodes(namespace_prefix)', 'sha... | 606,805 |
ml-tooling/lazycluster | runtimes.py | Runtime.echo | echo | Convenient method for echoing a string on the `Runtime` and returning the result. | [
"Convenient",
"method",
"for",
"echoing",
"a",
"string",
"on",
"the",
"`Runtime`",
"and",
"returning",
"the",
"result."
] | def echo(self, msg: str) -> str:
cxn = self._fabric_connection
with cxn.cd(self.working_dir):
return cxn.run(f'echo {msg}', env=self._env_variables, hide=True).stdout | ['def', 'echo(self,', 'msg:', 'str)', '->', 'str:', 'cxn', '=', 'self._fabric_connection', 'with', 'cxn.cd(self.working_dir):', 'return', "cxn.run(f'echo", "{msg}',", 'env=self._env_variables,', 'hide=True).stdout'] | 624,776 |
thanhkaist/CCFDM1 | curl_sac_pretrain_v3.py | weight_init | weight_init | Custom weight init for Conv2D and Linear layers. | [
"Custom",
"weight",
"init",
"for",
"Conv2D",
"and",
"Linear",
"layers."
] | def weight_init(m):
if isinstance(m, nn.Linear):
nn.init.orthogonal_(m.weight.data)
m.bias.data.fill_(0.0)
elif isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):
assert m.weight.size(2) == m.weight.size(3)
m.weight.data.fill_(0.0)
m.bias.data.fill_(0.0)
... | ['def', 'weight_init(m):', 'if', 'isinstance(m,', 'nn.Linear):', 'nn.init.orthogonal_(m.weight.data)', 'm.bias.data.fill_(0.0)', 'elif', 'isinstance(m,', 'nn.Conv2d)', 'or', 'isinstance(m,', 'nn.ConvTranspose2d):', 'assert', 'm.weight.size(2)', '==', 'm.weight.size(3)', 'm.weight.data.fill_(0.0)', 'm.bias.data.fill_(0.... | 457,039 |
kornia/kornia | data_utils.py | instantiate_ray_dataloader | instantiate_ray_dataloader | Initializes a dataloader to manage a ray dataset. | [
"Initializes",
"a",
"dataloader",
"to",
"manage",
"a",
"ray",
"dataset."
] | def instantiate_ray_dataloader(dataset: RayDataset, batch_size: int=1, shuffle: bool=True) -> DataLoader[RayGroup]:
def collate_rays(items: List[RayGroup]) -> RayGroup:
return items[0]
if TYPE_CHECKING:
return DataLoader(dataset)
else:
return DataLoader(dataset, sampler=BatchSampler... | ['def', 'instantiate_ray_dataloader(dataset:', 'RayDataset,', 'batch_size:', 'int=1,', 'shuffle:', 'bool=True)', '->', 'DataLoader[RayGroup]:', 'def', 'collate_rays(items:', 'List[RayGroup])', '->', 'RayGroup:', 'return', 'items[0]', 'if', 'TYPE_CHECKING:', 'return', 'DataLoader(dataset)', 'else:', 'return', 'DataLoade... | 622,251 |
pycroscopy/atomai | reg_cls.py | RegressorNet.forward | forward | Forward pass of the RegressorNet. | [
"Forward",
"pass",
"of",
"the",
"RegressorNet."
] | def forward(self, x: torch.Tensor):
x = self.backbone(x)
x = self.flatten(x)
x = self.output_layer(x)
return x | ['def', 'forward(self,', 'x:', 'torch.Tensor):', 'x', '=', 'self.backbone(x)', 'x', '=', 'self.flatten(x)', 'x', '=', 'self.output_layer(x)', 'return', 'x'] | 402,812 |
myothida/Supervised-Machine-Learning | test_ticker.py | TestLogitLocator.test_maxn_major | test_maxn_major | When the axis is zoomed, the locator must have the same behavior as MaxNLocator. | [
"When",
"the",
"axis",
"is",
"zoomed,",
"the",
"locator",
"must",
"have",
"the",
"same",
"behavior",
"as",
"MaxNLocator."
] | def test_maxn_major(self, lims):
loc = mticker.LogitLocator(nbins=100)
maxn_loc = mticker.MaxNLocator(nbins=100, steps=[1, 2, 5, 10])
for nbins in (4, 8, 16):
loc.set_params(nbins=nbins)
maxn_loc.set_params(nbins=nbins)
ticks = loc.tick_values(*lims)
maxn_ticks = maxn_loc.tic... | ['def', 'test_maxn_major(self,', 'lims):', 'loc', '=', 'mticker.LogitLocator(nbins=100)', 'maxn_loc', '=', 'mticker.MaxNLocator(nbins=100,', 'steps=[1,', '2,', '5,', '10])', 'for', 'nbins', 'in', '(4,', '8,', '16):', 'loc.set_params(nbins=nbins)', 'maxn_loc.set_params(nbins=nbins)', 'ticks', '=', 'loc.tick_values(*lims... | 362,942 |
Ruturaj123/Flowchart-Detection | tfexample_decoder_test.py | TFExampleDecoderTest.GenerateImage | GenerateImage | Generates an image and an example containing the encoded image. | [
"Generates",
"an",
"image",
"and",
"an",
"example",
"containing",
"the",
"encoded",
"image."
] | def GenerateImage(self, image_format, image_shape):
num_pixels = image_shape[0] * image_shape[1] * image_shape[2]
image = np.linspace(0, num_pixels - 1, num=num_pixels).reshape(image_shape).astype(np.uint8)
tf_encoded = self._Encoder(image, image_format)
example = example_pb2.Example(features=feature_pb... | ['def', 'GenerateImage(self,', 'image_format,', 'image_shape):', 'num_pixels', '=', 'image_shape[0]', '*', 'image_shape[1]', '*', 'image_shape[2]', 'image', '=', 'np.linspace(0,', 'num_pixels', '-', '1,', 'num=num_pixels).reshape(image_shape).astype(np.uint8)', 'tf_encoded', '=', 'self._Encoder(image,', 'image_format)'... | 604,492 |
thaines/helit | glyph_db.py | Glyph.get_center | get_center | Returns the 'center' of the glyph - its density weighted in an attempt to make it robust to crazy tails. | [
"Returns",
"the",
"'center'",
"of",
"the",
"glyph",
"-",
"its",
"density",
"weighted",
"in",
"an",
"attempt",
"to",
"make",
"it",
"robust",
"to",
"crazy",
"tails."
] | def get_center(self):
if self.center is None:
self.center = numpy.zeros(2, dtype=numpy.float32)
weight = 0.0
for i in xrange(self.lg.vertex_count):
info = self.lg.get_vertex(i)
w = info[5] * info[5] * info[6]
if w > 1e-06:
weight += w
... | ['def', 'get_center(self):', 'if', 'self.center', 'is', 'None:', 'self.center', '=', 'numpy.zeros(2,', 'dtype=numpy.float32)', 'weight', '=', '0.0', 'for', 'i', 'in', 'xrange(self.lg.vertex_count):', 'info', '=', 'self.lg.get_vertex(i)', 'w', '=', 'info[5]', '*', 'info[5]', '*', 'info[6]', 'if', 'w', '>', '1e-06:', 'we... | 591,909 |
sktime/sktime | test_all_estimators.py | TestAllEstimators.test_fit_does_not_overwrite_hyper_params | test_fit_does_not_overwrite_hyper_params | Check that we do not overwrite hyper-parameters in fit. | [
"Check",
"that",
"we",
"do",
"not",
"overwrite",
"hyper-parameters",
"in",
"fit."
] | def test_fit_does_not_overwrite_hyper_params(self, estimator_instance, scenario):
estimator = estimator_instance
set_random_state(estimator)
params = estimator.get_params()
original_params = deepcopy(params)
fitted_est = scenario.run(estimator_instance, method_sequence=['fit'])
new_params = fitt... | ['def', 'test_fit_does_not_overwrite_hyper_params(self,', 'estimator_instance,', 'scenario):', 'estimator', '=', 'estimator_instance', 'set_random_state(estimator)', 'params', '=', 'estimator.get_params()', 'original_params', '=', 'deepcopy(params)', 'fitted_est', '=', 'scenario.run(estimator_instance,', "method_sequen... | 877,620 |
sek788432/Waymo-2D-Object-Detection | retinanet.py | retinanet_spinenet_coco | retinanet_spinenet_coco | COCO object detection with RetinaNet using SpineNet backbone. | [
"COCO",
"object",
"detection",
"with",
"RetinaNet",
"using",
"SpineNet",
"backbone."
] | def retinanet_spinenet_coco() -> cfg.ExperimentConfig:
train_batch_size = 256
eval_batch_size = 8
steps_per_epoch = COCO_TRAIN_EXAMPLES // train_batch_size
input_size = 640
config = cfg.ExperimentConfig(runtime=cfg.RuntimeConfig(mixed_precision_dtype='float32'), task=RetinaNetTask(annotation_file=os... | ['def', 'retinanet_spinenet_coco()', '->', 'cfg.ExperimentConfig:', 'train_batch_size', '=', '256', 'eval_batch_size', '=', '8', 'steps_per_epoch', '=', 'COCO_TRAIN_EXAMPLES', '//', 'train_batch_size', 'input_size', '=', '640', 'config', '=', "cfg.ExperimentConfig(runtime=cfg.RuntimeConfig(mixed_precision_dtype='float3... | 973,026 |
TheCurryMan/MedicAI | __init__.py | DebuggedApplication.log_pin_request | log_pin_request | Log the pin if needed. | [
"Log",
"the",
"pin",
"if",
"needed."
] | def log_pin_request(self):
if self.pin_logging and self.pin is not None:
_log('info', ' * To enable the debugger you need to enter the security pin:')
_log('info', ' * Debugger pin code: %s' % self.pin)
return Response('') | ['def', 'log_pin_request(self):', 'if', 'self.pin_logging', 'and', 'self.pin', 'is', 'not', 'None:', "_log('info',", "'", '*', 'To', 'enable', 'the', 'debugger', 'you', 'need', 'to', 'enter', 'the', 'security', "pin:')", "_log('info',", "'", '*', 'Debugger', 'pin', 'code:', "%s'", '%', 'self.pin)', 'return', "Response(... | 649,913 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | mtf_layers.py | attention_mask_ignore_padding | attention_mask_ignore_padding | Bias for encoder-decoder attention. | [
"Bias",
"for",
"encoder-decoder",
"attention."
] | def attention_mask_ignore_padding(inputs, dtype=tf.float32):
inputs = rename_length_to_memory_length(inputs)
return mtf.cast(mtf.equal(inputs, 0), dtype) * -1000000000.0 | ['def', 'attention_mask_ignore_padding(inputs,', 'dtype=tf.float32):', 'inputs', '=', 'rename_length_to_memory_length(inputs)', 'return', 'mtf.cast(mtf.equal(inputs,', '0),', 'dtype)', '*', '-1000000000.0'] | 965,541 |
phoenix2/phoenix | KernelInterface.py | KernelInterface.getName | getName | Gets the configured name for this kernel. | [
"Gets",
"the",
"configured",
"name",
"for",
"this",
"kernel."
] | def getName(self):
return self.options.get('name', self.deviceID) | ['def', 'getName(self):', 'return', "self.options.get('name',", 'self.deviceID)'] | 304,876 |
theduynguyen/Keras-FCN | augment.py | resize_with_pad | resize_with_pad | Resize a square while keeping the original aspect ratio, padding with black for the image and boundary for the label. | [
"Resize",
"a",
"square",
"while",
"keeping",
"the",
"original",
"aspect",
"ratio,",
"padding",
"with",
"black",
"for",
"the",
"image",
"and",
"boundary",
"for",
"the",
"label."
] | def resize_with_pad(image, label, size=512):
image = tf.image.resize_with_pad(image, size, size, method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)
label = tf.image.resize_with_pad(label + 1, size, size, method=tf.image.ResizeMethod.NEAREST_NEIGHBOR) - 1
return (image, label) | ['def', 'resize_with_pad(image,', 'label,', 'size=512):', 'image', '=', 'tf.image.resize_with_pad(image,', 'size,', 'size,', 'method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)', 'label', '=', 'tf.image.resize_with_pad(label', '+', '1,', 'size,', 'size,', 'method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)', '-', '1', 'return'... | 595,428 |
flavioschneider/rl-transfer- | _dtypes.py | TimeStep.from_env_step | from_env_step | Create a TimeStep from a EnvStep. | [
"Create",
"a",
"TimeStep",
"from",
"a",
"EnvStep."
] | def from_env_step(cls, env_step, last_observation, agent_info, episode_info):
return cls(env_spec=env_step.env_spec, episode_info=episode_info, observation=last_observation, action=env_step.action, reward=env_step.reward, next_observation=env_step.observation, env_info=env_step.env_info, agent_info=agent_info, step... | ['def', 'from_env_step(cls,', 'env_step,', 'last_observation,', 'agent_info,', 'episode_info):', 'return', 'cls(env_spec=env_step.env_spec,', 'episode_info=episode_info,', 'observation=last_observation,', 'action=env_step.action,', 'reward=env_step.reward,', 'next_observation=env_step.observation,', 'env_info=env_step.... | 860,945 |
DrSleep/light-weight-refinenet | network.py | get_encoder_and_decoder_params | get_encoder_and_decoder_params | Filter model parameters into two groups: encoder and decoder. | [
"Filter",
"model",
"parameters",
"into",
"two",
"groups:",
"encoder",
"and",
"decoder."
] | def get_encoder_and_decoder_params(model):
logger = logging.getLogger(__name__)
enc_params = []
dec_params = []
for (k, v) in model.named_parameters():
if bool(re.match('.*conv1.*|.*bn1.*|.*layer.*', k)):
enc_params.append(v)
logger.info(' Enc. parameter: {}'.format(k))
... | ['def', 'get_encoder_and_decoder_params(model):', 'logger', '=', 'logging.getLogger(__name__)', 'enc_params', '=', '[]', 'dec_params', '=', '[]', 'for', '(k,', 'v)', 'in', 'model.named_parameters():', 'if', "bool(re.match('.*conv1.*|.*bn1.*|.*layer.*',", 'k)):', 'enc_params.append(v)', "logger.info('", 'Enc.', 'paramet... | 602,199 |
ArdaGunay99/Key_Detection_Unsupervised_Learning | backend_bases.py | FigureCanvasBase.key_press_event | key_press_event | Pass a `KeyEvent` to all functions connected to ``key_press_event``. | [
"Pass",
"a",
"`KeyEvent`",
"to",
"all",
"functions",
"connected",
"to",
"``key_press_event``."
] | def key_press_event(self, key, guiEvent=None):
self._key = key
s = 'key_press_event'
event = KeyEvent(s, self, key, self._lastx, self._lasty, guiEvent=guiEvent)
self.callbacks.process(s, event) | ['def', 'key_press_event(self,', 'key,', 'guiEvent=None):', 'self._key', '=', 'key', 's', '=', "'key_press_event'", 'event', '=', 'KeyEvent(s,', 'self,', 'key,', 'self._lastx,', 'self._lasty,', 'guiEvent=guiEvent)', 'self.callbacks.process(s,', 'event)'] | 256,703 |
rudranil723/mini-main | regutil.py | GetRegistryDefaultValue | GetRegistryDefaultValue | A helper to return the default value for a key in the registry. | [
"A",
"helper",
"to",
"return",
"the",
"default",
"value",
"for",
"a",
"key",
"in",
"the",
"registry."
] | def GetRegistryDefaultValue(subkey, rootkey=None):
if rootkey is None:
rootkey = GetRootKey()
return win32api.RegQueryValue(rootkey, subkey) | ['def', 'GetRegistryDefaultValue(subkey,', 'rootkey=None):', 'if', 'rootkey', 'is', 'None:', 'rootkey', '=', 'GetRootKey()', 'return', 'win32api.RegQueryValue(rootkey,', 'subkey)'] | 271,078 |
DevanshuSave/Pacman-and-Ghostbusters | captureAgents.py | CaptureAgent.getPreviousObservation | getPreviousObservation | Returns the GameState object corresponding to the last state this agent saw (the observed state of the game last time this agent moved - this may not include all of your opponent's agent locations exactly). | [
"Returns",
"the",
"GameState",
"object",
"corresponding",
"to",
"the",
"last",
"state",
"this",
"agent",
"saw",
"(the",
"observed",
"state",
"of",
"the",
"game",
"last",
"time",
"this",
"agent",
"moved",
"-",
"this",
"may",
"not",
"include",
"all",
"of",
"... | def getPreviousObservation(self):
if len(self.observationHistory) == 1:
return None
else:
return self.observationHistory[-2] | ['def', 'getPreviousObservation(self):', 'if', 'len(self.observationHistory)', '==', '1:', 'return', 'None', 'else:', 'return', 'self.observationHistory[-2]'] | 253,936 |
zihuitang/medical_AI_platform | deccheck.py | SkipHandler.log10 | log10 | Resolve Underflow or ULP difference. | [
"Resolve",
"Underflow",
"or",
"ULP",
"difference."
] | def log10(self, t):
return self.resolve_underflow(t) | ['def', 'log10(self,', 't):', 'return', 'self.resolve_underflow(t)'] | 284,679 |
microsoft/fastseq | test_bart_optimizer.py | BARTOptimizerTest.setUp | setUp | Load model, tokenizer and expected output. | [
"Load",
"model,",
"tokenizer",
"and",
"expected",
"output."
] | def setUp(self):
self.tokenizer = BartTokenizer.from_pretrained('facebook/bart-large-cnn')
self.bart_model = BartForConditionalGeneration.from_pretrained('facebook/bart-large-cnn')
self.source_path = 'tests/optimizer/transformers/data/cnndm_128.txt'
self.expected_output_path = 'tests/optimizer/transform... | ['def', 'setUp(self):', 'self.tokenizer', '=', "BartTokenizer.from_pretrained('facebook/bart-large-cnn')", 'self.bart_model', '=', "BartForConditionalGeneration.from_pretrained('facebook/bart-large-cnn')", 'self.source_path', '=', "'tests/optimizer/transformers/data/cnndm_128.txt'", 'self.expected_output_path', '=', "'... | 559,935 |
astooke/rlpyt | r2d1.py | R2D1.value_scale | value_scale | Value scaling function to handle raw rewards across games (not clipped). | [
"Value",
"scaling",
"function",
"to",
"handle",
"raw",
"rewards",
"across",
"games",
"(not",
"clipped)."
] | def value_scale(self, x):
return torch.sign(x) * (torch.sqrt(abs(x) + 1) - 1) + self.value_scale_eps * x | ['def', 'value_scale(self,', 'x):', 'return', 'torch.sign(x)', '*', '(torch.sqrt(abs(x)', '+', '1)', '-', '1)', '+', 'self.value_scale_eps', '*', 'x'] | 334,503 |
deepmind/dm_control | lqr.py | get_model_and_assets | get_model_and_assets | Returns the model description as an XML string and a dict of assets. | [
"Returns",
"the",
"model",
"description",
"as",
"an",
"XML",
"string",
"and",
"a",
"dict",
"of",
"assets."
] | def get_model_and_assets(n_bodies, n_actuators, random):
return (_make_model(n_bodies, n_actuators, random), common.ASSETS) | ['def', 'get_model_and_assets(n_bodies,', 'n_actuators,', 'random):', 'return', '(_make_model(n_bodies,', 'n_actuators,', 'random),', 'common.ASSETS)'] | 166,399 |
PacktPublishing/Hands-On-Artificial--for-Banking | filters.py | do_wordcount | do_wordcount | Count the words in that string. | [
"Count",
"the",
"words",
"in",
"that",
"string."
] | def do_wordcount(s):
return len(_word_re.findall(soft_unicode(s))) | ['def', 'do_wordcount(s):', 'return', 'len(_word_re.findall(soft_unicode(s)))'] | 235,055 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | bulk_component.py | fetch_linked_embedding | fetch_linked_embedding | Looks up linked embeddings in other components. | [
"Looks",
"up",
"linked",
"embeddings",
"in",
"other",
"components."
] | def fetch_linked_embedding(comp, network_states, feature_spec):
if feature_spec.source_translator != 'identity':
raise NotImplementedError(feature_spec.source_translator)
if feature_spec.source_component == comp.name:
raise RuntimeError('Recurrent linked features are not supported in bulk extrac... | ['def', 'fetch_linked_embedding(comp,', 'network_states,', 'feature_spec):', 'if', 'feature_spec.source_translator', '!=', "'identity':", 'raise', 'NotImplementedError(feature_spec.source_translator)', 'if', 'feature_spec.source_component', '==', 'comp.name:', 'raise', "RuntimeError('Recurrent", 'linked', 'features', '... | 28,048 |
chainer/chainerrl | async_.py | set_shared_params | set_shared_params | Set shared params (and persistent values) to a link. | [
"Set",
"shared",
"params",
"(and",
"persistent",
"values)",
"to",
"a",
"link."
] | def set_shared_params(a, b):
assert isinstance(a, chainer.Link)
remaining_keys = set(b.keys())
for (param_name, param) in a.namedparams():
if param_name in b:
shared_param = b[param_name]
param.array = np.frombuffer(shared_param, dtype=param.dtype).reshape(param.shape)
... | ['def', 'set_shared_params(a,', 'b):', 'assert', 'isinstance(a,', 'chainer.Link)', 'remaining_keys', '=', 'set(b.keys())', 'for', '(param_name,', 'param)', 'in', 'a.namedparams():', 'if', 'param_name', 'in', 'b:', 'shared_param', '=', 'b[param_name]', 'param.array', '=', 'np.frombuffer(shared_param,', 'dtype=param.dtyp... | 104,470 |
ZhAnGToNG1/transfer_learning_cspt | cascade_roi_head.py | CascadeRoIHead.init_mask_head | init_mask_head | Initialize mask head and mask roi extractor. | [
"Initialize",
"mask",
"head",
"and",
"mask",
"roi",
"extractor."
] | def init_mask_head(self, mask_roi_extractor, mask_head):
self.mask_head = nn.ModuleList()
if not isinstance(mask_head, list):
mask_head = [mask_head for _ in range(self.num_stages)]
assert len(mask_head) == self.num_stages
for head in mask_head:
self.mask_head.append(build_head(head))
... | ['def', 'init_mask_head(self,', 'mask_roi_extractor,', 'mask_head):', 'self.mask_head', '=', 'nn.ModuleList()', 'if', 'not', 'isinstance(mask_head,', 'list):', 'mask_head', '=', '[mask_head', 'for', '_', 'in', 'range(self.num_stages)]', 'assert', 'len(mask_head)', '==', 'self.num_stages', 'for', 'head', 'in', 'mask_hea... | 964,220 |
enuguru/artificial_intelligence_and_machine_ | default.py | QueryParser.add_plugins | add_plugins | Adds the given list of plugins to the list of plugins in this parser. | [
"Adds",
"the",
"given",
"list",
"of",
"plugins",
"to",
"the",
"list",
"of",
"plugins",
"in",
"this",
"parser."
] | def add_plugins(self, pins):
for pin in pins:
self.add_plugin(pin) | ['def', 'add_plugins(self,', 'pins):', 'for', 'pin', 'in', 'pins:', 'self.add_plugin(pin)'] | 162,638 |
Kvatsx/Artificial-Intelligence-Assignments | polar.py | PolarAxes.get_rlabel_position | get_rlabel_position | Returns ------- float The theta position of the radius labels in degrees. | [
"Returns",
"-------",
"float",
"The",
"theta",
"position",
"of",
"the",
"radius",
"labels",
"in",
"degrees."
] | def get_rlabel_position(self):
return np.rad2deg(self._r_label_position.get_matrix()[0, 2]) | ['def', 'get_rlabel_position(self):', 'return', 'np.rad2deg(self._r_label_position.get_matrix()[0,', '2])'] | 1,319 |
scikit-learn/scikit-learn | test_logistic.py | test_passing_params_without_enabling_metadata_routing | test_passing_params_without_enabling_metadata_routing | Test that the right error message is raised when metadata params are passed while not supported when `enable_metadata_routing=False`. | [
"Test",
"that",
"the",
"right",
"error",
"message",
"is",
"raised",
"when",
"metadata",
"params",
"are",
"passed",
"while",
"not",
"supported",
"when",
"`enable_metadata_routing=False`."
] | def test_passing_params_without_enabling_metadata_routing():
(X, y) = make_classification(n_samples=10, random_state=0)
lr_cv = LogisticRegressionCV()
msg = 'is only supported if enable_metadata_routing=True'
with config_context(enable_metadata_routing=False):
params = {'extra_param': 1.0}
... | ['def', 'test_passing_params_without_enabling_metadata_routing():', '(X,', 'y)', '=', 'make_classification(n_samples=10,', 'random_state=0)', 'lr_cv', '=', 'LogisticRegressionCV()', 'msg', '=', "'is", 'only', 'supported', 'if', "enable_metadata_routing=True'", 'with', 'config_context(enable_metadata_routing=False):', '... | 853,562 |
google-research/crest | data_util.py | color_jitter | color_jitter | Distorts the color of the image. | [
"Distorts",
"the",
"color",
"of",
"the",
"image."
] | def color_jitter(image, strength, random_order=True):
brightness = 0.8 * strength
contrast = 0.8 * strength
saturation = 0.8 * strength
hue = 0.2 * strength
if random_order:
return color_jitter_rand(image, brightness, contrast, saturation, hue)
else:
return color_jitter_nonrand(i... | ['def', 'color_jitter(image,', 'strength,', 'random_order=True):', 'brightness', '=', '0.8', '*', 'strength', 'contrast', '=', '0.8', '*', 'strength', 'saturation', '=', '0.8', '*', 'strength', 'hue', '=', '0.2', '*', 'strength', 'if', 'random_order:', 'return', 'color_jitter_rand(image,', 'brightness,', 'contrast,', '... | 138,554 |
Kvatsx/Artificial-Intelligence-Assignments | misc_util.py | Configuration.get_distribution | get_distribution | Return the distutils distribution object for self. | [
"Return",
"the",
"distutils",
"distribution",
"object",
"for",
"self."
] | def get_distribution(self):
from numpy.distutils.core import get_distribution
return get_distribution() | ['def', 'get_distribution(self):', 'from', 'numpy.distutils.core', 'import', 'get_distribution', 'return', 'get_distribution()'] | 2,603 |
asyml/texar-pytorch | layers_test.py | MergeLayerTest.test_layer_logic | test_layer_logic | Test the logic of MergeLayer. | [
"Test",
"the",
"logic",
"of",
"MergeLayer."
] | def test_layer_logic(self):
layers_ = list()
layers_.append(nn.Conv1d(in_channels=32, out_channels=32, kernel_size=3))
layers_.append(nn.Conv1d(in_channels=32, out_channels=32, kernel_size=3))
layers_.append(nn.Conv1d(in_channels=32, out_channels=32, kernel_size=3))
modes = ['concat', 'sum', 'mean',... | ['def', 'test_layer_logic(self):', 'layers_', '=', 'list()', 'layers_.append(nn.Conv1d(in_channels=32,', 'out_channels=32,', 'kernel_size=3))', 'layers_.append(nn.Conv1d(in_channels=32,', 'out_channels=32,', 'kernel_size=3))', 'layers_.append(nn.Conv1d(in_channels=32,', 'out_channels=32,', 'kernel_size=3))', 'modes', '... | 924,869 |
Layman0527/Parallel-Swin-Transformer-for-- | builder.py | build_pixel_sampler | build_pixel_sampler | Build pixel sampler for segmentation map. | [
"Build",
"pixel",
"sampler",
"for",
"segmentation",
"map."
] | def build_pixel_sampler(cfg, **default_args):
return build_from_cfg(cfg, PIXEL_SAMPLERS, default_args) | ['def', 'build_pixel_sampler(cfg,', '**default_args):', 'return', 'build_from_cfg(cfg,', 'PIXEL_SAMPLERS,', 'default_args)'] | 764,230 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | template.py | Base.toExpr | toExpr | Returns an expression for the given value if it is a string. | [
"Returns",
"an",
"expression",
"for",
"the",
"given",
"value",
"if",
"it",
"is",
"a",
"string."
] | def toExpr(self, value):
try:
return self.factory.expr(left=value + '')
except (TypeError,):
return value | ['def', 'toExpr(self,', 'value):', 'try:', 'return', 'self.factory.expr(left=value', '+', "'')", 'except', '(TypeError,):', 'return', 'value'] | 10,760 |
salesforce/CodeRL | logging.py | remove_handler | remove_handler | removes given handler from the HuggingFace Transformers's root logger. | [
"removes",
"given",
"handler",
"from",
"the",
"HuggingFace",
"Transformers's",
"root",
"logger."
] | def remove_handler(handler: logging.Handler) -> None:
_configure_library_root_logger()
assert handler is not None and handler not in _get_library_root_logger().handlers
_get_library_root_logger().removeHandler(handler) | ['def', 'remove_handler(handler:', 'logging.Handler)', '->', 'None:', '_configure_library_root_logger()', 'assert', 'handler', 'is', 'not', 'None', 'and', 'handler', 'not', 'in', '_get_library_root_logger().handlers', '_get_library_root_logger().removeHandler(handler)'] | 495,602 |
cuiziteng/ICCV_MAET | sabl_head.py | SABLHead.reg_pred | reg_pred | Predict bucketing esimation (cls_pred) and fine regression (offset pred) with side-aware features. | [
"Predict",
"bucketing",
"esimation",
"(cls_pred)",
"and",
"fine",
"regression",
"(offset",
"pred)",
"with",
"side-aware",
"features."
] | def reg_pred(self, x, offfset_fcs, cls_fcs):
x_offset = x.view(-1, self.reg_in_channels)
x_cls = x.view(-1, self.reg_in_channels)
for fc in offfset_fcs:
x_offset = self.relu(fc(x_offset))
for fc in cls_fcs:
x_cls = self.relu(fc(x_cls))
offset_pred = self.fc_reg_offset(x_offset)
c... | ['def', 'reg_pred(self,', 'x,', 'offfset_fcs,', 'cls_fcs):', 'x_offset', '=', 'x.view(-1,', 'self.reg_in_channels)', 'x_cls', '=', 'x.view(-1,', 'self.reg_in_channels)', 'for', 'fc', 'in', 'offfset_fcs:', 'x_offset', '=', 'self.relu(fc(x_offset))', 'for', 'fc', 'in', 'cls_fcs:', 'x_cls', '=', 'self.relu(fc(x_cls))', 'o... | 228,798 |
sek788432/Waymo-2D-Object-Detection | autoaugment_utils.py | posterize | posterize | Equivalent of PIL Posterize. | [
"Equivalent",
"of",
"PIL",
"Posterize."
] | def posterize(image, bits):
shift = 8 - bits
return tf.bitwise.left_shift(tf.bitwise.right_shift(image, shift), shift) | ['def', 'posterize(image,', 'bits):', 'shift', '=', '8', '-', 'bits', 'return', 'tf.bitwise.left_shift(tf.bitwise.right_shift(image,', 'shift),', 'shift)'] | 975,332 |
microsoft/nni | bayesian.py | IncrementalGaussianProcess.incremental_fit | incremental_fit | Incrementally fit the regressor. | [
"Incrementally",
"fit",
"the",
"regressor."
] | def incremental_fit(self, train_x, train_y):
if not self._first_fitted:
raise ValueError('The first_fit function needs to be called first.')
(train_x, train_y) = (np.array(train_x), np.array(train_y))
up_right_k = edit_distance_matrix(self._x, train_x)
down_left_k = np.transpose(up_right_k)
... | ['def', 'incremental_fit(self,', 'train_x,', 'train_y):', 'if', 'not', 'self._first_fitted:', 'raise', "ValueError('The", 'first_fit', 'function', 'needs', 'to', 'be', 'called', "first.')", '(train_x,', 'train_y)', '=', '(np.array(train_x),', 'np.array(train_y))', 'up_right_k', '=', 'edit_distance_matrix(self._x,', 'tr... | 728,354 |
suarez12138/AI-Reversi_IMP_TextDichotomy | kernels.py | Kernel.hyperparameters | hyperparameters | Returns a list of all hyperparameter specifications. | [
"Returns",
"a",
"list",
"of",
"all",
"hyperparameter",
"specifications."
] | def hyperparameters(self):
r = [getattr(self, attr) for attr in dir(self) if attr.startswith('hyperparameter_')]
return r | ['def', 'hyperparameters(self):', 'r', '=', '[getattr(self,', 'attr)', 'for', 'attr', 'in', 'dir(self)', 'if', "attr.startswith('hyperparameter_')]", 'return', 'r'] | 101,268 |
RLE-Foundation/rllte | truncated_normal_noise.py | TruncatedNormalNoise.mode | mode | Returns the mode of the distribution. | [
"Returns",
"the",
"mode",
"of",
"the",
"distribution."
] | def mode(self) -> th.Tensor:
return self.noiseless_action | ['def', 'mode(self)', '->', 'th.Tensor:', 'return', 'self.noiseless_action'] | 333,409 |
jialeli1/lidarseg3d | oss.py | OSSPath.parent | parent | The logical parent of the path. | [
"The",
"logical",
"parent",
"of",
"the",
"path."
] | def parent(self):
if not len(self._key_parts):
return self
return self._create(self._client, self.bucket, self._key_parts[:-1]) | ['def', 'parent(self):', 'if', 'not', 'len(self._key_parts):', 'return', 'self', 'return', 'self._create(self._client,', 'self.bucket,', 'self._key_parts[:-1])'] | 601,453 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | evaluation.py | parser_summaries | parser_summaries | Computes parser evaluation summaries for gold and annotated sentences. | [
"Computes",
"parser",
"evaluation",
"summaries",
"for",
"gold",
"and",
"annotated",
"sentences."
] | def parser_summaries(gold_corpus, annotated_corpus):
(pos, uas, las) = calculate_parse_metrics(gold_corpus, annotated_corpus)
return {'POS': pos, 'LAS': las, 'UAS': uas, 'eval_metric': las} | ['def', 'parser_summaries(gold_corpus,', 'annotated_corpus):', '(pos,', 'uas,', 'las)', '=', 'calculate_parse_metrics(gold_corpus,', 'annotated_corpus)', 'return', "{'POS':", 'pos,', "'LAS':", 'las,', "'UAS':", 'uas,', "'eval_metric':", 'las}'] | 111,054 |
GMvandeVen/brain-inspired-replay | visdom.py | visualize_hist | visualize_hist | Plot histogram of entries contained in 1D-tensor [X] to visdom-server. | [
"Plot",
"histogram",
"of",
"entries",
"contained",
"in",
"1D-tensor",
"[X]",
"to",
"visdom-server."
] | def visualize_hist(X, title, win=None, env='main', w=400, h=400):
options = dict(title=title, width=w, height=h)
win = title if win is None else win
_WINDOW_CASH[win] = _vis(env).histogram(X, win=_WINDOW_CASH.get(win), opts=options) | ['def', 'visualize_hist(X,', 'title,', 'win=None,', "env='main',", 'w=400,', 'h=400):', 'options', '=', 'dict(title=title,', 'width=w,', 'height=h)', 'win', '=', 'title', 'if', 'win', 'is', 'None', 'else', 'win', '_WINDOW_CASH[win]', '=', '_vis(env).histogram(X,', 'win=_WINDOW_CASH.get(win),', 'opts=options)'] | 409,535 |
somepago/AMA | cifar_models_bNorm.py | avg_pool2d | avg_pool2d | Twice differentiable implementation of 2x2 average pooling. | [
"Twice",
"differentiable",
"implementation",
"of",
"2x2",
"average",
"pooling."
] | def avg_pool2d(x):
return (x[:, :, ::2, ::2] + x[:, :, 1::2, ::2] + x[:, :, ::2, 1::2] + x[:, :, 1::2, 1::2]) / 4 | ['def', 'avg_pool2d(x):', 'return', '(x[:,', ':,', '::2,', '::2]', '+', 'x[:,', ':,', '1::2,', '::2]', '+', 'x[:,', ':,', '::2,', '1::2]', '+', 'x[:,', ':,', '1::2,', '1::2])', '/', '4'] | 415,968 |
mozilla/bugbug | rust_code_analysis_server.py | RustCodeAnalysisServer.metrics | metrics | Get code metrics for a file. | [
"Get",
"code",
"metrics",
"for",
"a",
"file."
] | def metrics(self, filename, code, unit=True):
unit = 1 if unit else 0
url = f'{self.base_url}/metrics?file_name={filename}&unit={unit}'
r = requests.post(url, data=code, headers=HEADERS)
if not r.ok:
return {}
return r.json() | ['def', 'metrics(self,', 'filename,', 'code,', 'unit=True):', 'unit', '=', '1', 'if', 'unit', 'else', '0', 'url', '=', "f'{self.base_url}/metrics?file_name={filename}&unit={unit}'", 'r', '=', 'requests.post(url,', 'data=code,', 'headers=HEADERS)', 'if', 'not', 'r.ok:', 'return', '{}', 'return', 'r.json()'] | 410,330 |
WangFeng18/InvariancePropagation | loaders.py | balanced_loader | balanced_loader | Returns a `DataLoader` instance, which yields a class-balanced minibatch of samples. | [
"Returns",
"a",
"`DataLoader`",
"instance,",
"which",
"yields",
"a",
"class-balanced",
"minibatch",
"of",
"samples."
] | def balanced_loader(dataset: torch.utils.data.Dataset, batch_size: int, shuffle: bool=True, num_workers: int=0, drop_last: bool=False, pin_memory: bool=False):
sampler = ImbalancedDatasetSampler(dataset)
return DataLoader(dataset=dataset, batch_size=batch_size, shuffle=shuffle, sampler=sampler, num_workers=num_... | ['def', 'balanced_loader(dataset:', 'torch.utils.data.Dataset,', 'batch_size:', 'int,', 'shuffle:', 'bool=True,', 'num_workers:', 'int=0,', 'drop_last:', 'bool=False,', 'pin_memory:', 'bool=False):', 'sampler', '=', 'ImbalancedDatasetSampler(dataset)', 'return', 'DataLoader(dataset=dataset,', 'batch_size=batch_size,', ... | 245,853 |
enlite-ai/maze | dummy_struct_env.py | DummyStructuredEnvironment.is_actor_done | is_actor_done | Actors are never destroyed in this env. | [
"Actors",
"are",
"never",
"destroyed",
"in",
"this",
"env."
] | def is_actor_done(self) -> bool:
return False | ['def', 'is_actor_done(self)', '->', 'bool:', 'return', 'False'] | 647,315 |
zihuitang/medical_AI_platform | _pydecimal.py | setcontext | setcontext | Set this thread's context to context. | [
"Set",
"this",
"thread's",
"context",
"to",
"context."
] | def setcontext(context):
if context in (DefaultContext, BasicContext, ExtendedContext):
context = context.copy()
context.clear_flags()
threading.current_thread().__decimal_context__ = context | ['def', 'setcontext(context):', 'if', 'context', 'in', '(DefaultContext,', 'BasicContext,', 'ExtendedContext):', 'context', '=', 'context.copy()', 'context.clear_flags()', 'threading.current_thread().__decimal_context__', '=', 'context'] | 281,872 |
ArdaGunay99/Key_Detection_Unsupervised_Learning | __init__.py | FCompiler.get_flags_linker_exe | get_flags_linker_exe | List of linker flags to build an executable. | [
"List",
"of",
"linker",
"flags",
"to",
"build",
"an",
"executable."
] | def get_flags_linker_exe(self):
return self._get_command_flags('linker_exe') | ['def', 'get_flags_linker_exe(self):', 'return', "self._get_command_flags('linker_exe')"] | 258,487 |
Deeplite/deeplite-torch-zoo | utils.py | curl_download | curl_download | Download a file from a url to a filename using curl. | [
"Download",
"a",
"file",
"from",
"a",
"url",
"to",
"a",
"filename",
"using",
"curl."
] | def curl_download(url, filename, *, silent: bool=False) -> bool:
silent_option = 'sS' if silent else ''
proc = subprocess.run(['curl', '-#', f'-{silent_option}L', url, '--output', filename, '--retry', '9', '-C', '-'])
return proc.returncode == 0 | ['def', 'curl_download(url,', 'filename,', '*,', 'silent:', 'bool=False)', '->', 'bool:', 'silent_option', '=', "'sS'", 'if', 'silent', 'else', "''", 'proc', '=', "subprocess.run(['curl',", "'-#',", "f'-{silent_option}L',", 'url,', "'--output',", 'filename,', "'--retry',", "'9',", "'-C',", "'-'])", 'return', 'proc.retu... | 538,888 |
enuguru/artificial_intelligence_and_machine_ | results.py | Analysis.branch_lines | branch_lines | Returns a list of line numbers that have more than one exit. | [
"Returns",
"a",
"list",
"of",
"line",
"numbers",
"that",
"have",
"more",
"than",
"one",
"exit."
] | def branch_lines(self):
return [l1 for (l1, count) in iitems(self.exit_counts) if count > 1] | ['def', 'branch_lines(self):', 'return', '[l1', 'for', '(l1,', 'count)', 'in', 'iitems(self.exit_counts)', 'if', 'count', '>', '1]'] | 157,613 |
43Carrig/recurrent_neural_networks_practice | control_flow_ops.py | ControlFlowState.GetGradState | GetGradState | Return the grad state for this op if it's in a forward loop context. | [
"Return",
"the",
"grad",
"state",
"for",
"this",
"op",
"if",
"it's",
"in",
"a",
"forward",
"loop",
"context."
] | def GetGradState(self, op, before):
if before and util.IsLoopExit(op):
forward_ctxt = op._get_control_flow_context()
forward_ctxt = forward_ctxt.outer_context
if forward_ctxt:
forward_ctxt = forward_ctxt.GetWhileContext()
else:
forward_ctxt = _GetWhileContext(op)
... | ['def', 'GetGradState(self,', 'op,', 'before):', 'if', 'before', 'and', 'util.IsLoopExit(op):', 'forward_ctxt', '=', 'op._get_control_flow_context()', 'forward_ctxt', '=', 'forward_ctxt.outer_context', 'if', 'forward_ctxt:', 'forward_ctxt', '=', 'forward_ctxt.GetWhileContext()', 'else:', 'forward_ctxt', '=', '_GetWhile... | 337,150 |
microsoft/maro | proxy.py | Proxy.get_peer_type | get_peer_type | Get peer type from given peer name. | [
"Get",
"peer",
"type",
"from",
"given",
"peer",
"name."
] | def get_peer_type(self, peer_name: str) -> str:
peer_type = peer_name[:peer_name.rfind('_proxy_')]
if peer_type not in list(self._onboard_peer_dict.keys()):
self._logger.error(f"The message's destination {peer_name} does not belong to any recognized peer type. Please check the input of message.")
... | ['def', 'get_peer_type(self,', 'peer_name:', 'str)', '->', 'str:', 'peer_type', '=', "peer_name[:peer_name.rfind('_proxy_')]", 'if', 'peer_type', 'not', 'in', 'list(self._onboard_peer_dict.keys()):', 'self._logger.error(f"The', "message's", 'destination', '{peer_name}', 'does', 'not', 'belong', 'to', 'any', 'recognized... | 628,364 |
ezliu/dream | policy.py | Policy.stats | stats | Returns a dict of relevant statistics about the policy. | [
"Returns",
"a",
"dict",
"of",
"relevant",
"statistics",
"about",
"the",
"policy."
] | def stats(self):
return {} | ['def', 'stats(self):', 'return', '{}'] | 552,592 |
hobson/aima | text.py | all_shifts | all_shifts | Return a list of all 26 possible encodings of text by a shift cipher. | [
"Return",
"a",
"list",
"of",
"all",
"26",
"possible",
"encodings",
"of",
"text",
"by",
"a",
"shift",
"cipher."
] | def all_shifts(text):
return [shift_encode(text, n) for n in range(len(alphabet))] | ['def', 'all_shifts(text):', 'return', '[shift_encode(text,', 'n)', 'for', 'n', 'in', 'range(len(alphabet))]'] | 86,234 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | metrics.py | add_volume_iou_metrics | add_volume_iou_metrics | Computes the per-instance volume IOU. | [
"Computes",
"the",
"per-instance",
"volume",
"IOU."
] | def add_volume_iou_metrics(inputs, outputs):
names_to_values = dict()
names_to_updates = dict()
labels = tf.greater_equal(inputs['voxels'], 0.5)
predictions = tf.greater_equal(outputs['voxels_1'], 0.5)
labels = 2 - tf.to_int32(labels) - 1
predictions = 3 - tf.to_int32(predictions) * 2 - 1
(t... | ['def', 'add_volume_iou_metrics(inputs,', 'outputs):', 'names_to_values', '=', 'dict()', 'names_to_updates', '=', 'dict()', 'labels', '=', "tf.greater_equal(inputs['voxels'],", '0.5)', 'predictions', '=', "tf.greater_equal(outputs['voxels_1'],", '0.5)', 'labels', '=', '2', '-', 'tf.to_int32(labels)', '-', '1', 'predict... | 26,309 |
tomcatmanager/tomcatmanager | mock_server_ssl.py | MockRequestHandlerSSL.get_ssl_connector_certs | get_ssl_connector_certs | Send the SSL certs. | [
"Send",
"the",
"SSL",
"certs."
] | def get_ssl_connector_certs(self):
self.send_text('OK - Connector / Certificate Chain information\nConnector[HTTP/1.1-8080]\nSSL is not enabled for this connector') | ['def', 'get_ssl_connector_certs(self):', "self.send_text('OK", '-', 'Connector', '/', 'Certificate', 'Chain', 'information\\nConnector[HTTP/1.1-8080]\\nSSL', 'is', 'not', 'enabled', 'for', 'this', "connector')"] | 355,665 |
Eric3911/OpenAGI | env_var_parsing.py | get_envdict | get_envdict | Return env var as a dict. | [
"Return",
"env",
"var",
"as",
"a",
"dict."
] | def get_envdict(key, *default):
return get_env(key, *default, coerce=_dict) | ['def', 'get_envdict(key,', '*default):', 'return', 'get_env(key,', '*default,', 'coerce=_dict)'] | 274,193 |
wikimedia/revscoring | model.py | Model.load | load | Reads serialized model information from a file. | [
"Reads",
"serialized",
"model",
"information",
"from",
"a",
"file."
] | def load(cls, f, error_on_env_check=False):
if hasattr(f, 'buffer'):
model = pickle.load(f.buffer)
else:
model = pickle.load(f)
model.info['environment'].check(raise_exception=error_on_env_check)
return model | ['def', 'load(cls,', 'f,', 'error_on_env_check=False):', 'if', 'hasattr(f,', "'buffer'):", 'model', '=', 'pickle.load(f.buffer)', 'else:', 'model', '=', 'pickle.load(f)', "model.info['environment'].check(raise_exception=error_on_env_check)", 'return', 'model'] | 841,099 |
facebookresearch/fvcore | flop_count.py | flop_count | flop_count | Given a model and an input to the model, compute the per-operator Gflops of the given model. | [
"Given",
"a",
"model",
"and",
"an",
"input",
"to",
"the",
"model,",
"compute",
"the",
"per-operator",
"Gflops",
"of",
"the",
"given",
"model."
] | def flop_count(model: nn.Module, inputs: Tuple[Any, ...], supported_ops: Optional[Dict[str, Handle]]=None) -> Tuple[DefaultDict[str, float], Counter[str]]:
if supported_ops is None:
supported_ops = {}
flop_counter = FlopCountAnalysis(model, inputs).set_op_handle(**supported_ops)
giga_flops = default... | ['def', 'flop_count(model:', 'nn.Module,', 'inputs:', 'Tuple[Any,', '...],', 'supported_ops:', 'Optional[Dict[str,', 'Handle]]=None)', '->', 'Tuple[DefaultDict[str,', 'float],', 'Counter[str]]:', 'if', 'supported_ops', 'is', 'None:', 'supported_ops', '=', '{}', 'flop_counter', '=', 'FlopCountAnalysis(model,', 'inputs).... | 565,892 |
AboudyKreidieh/h-baselines | humanoid_maze_env.py | HumanoidMazeEnv.get_range_sensor_obs | get_range_sensor_obs | Return egocentric range sensor observations of maze. | [
"Return",
"egocentric",
"range",
"sensor",
"observations",
"of",
"maze."
] | def get_range_sensor_obs(self):
(robot_x, robot_y, robot_z) = self.wrapped_env.get_body_com('torso')[:3]
ori = self.get_ori()
structure = self.MAZE_STRUCTURE
size_scaling = self.MAZE_SIZE_SCALING
height = self.MAZE_HEIGHT
segments = []
for i in range(len(structure)):
for j in range(l... | ['def', 'get_range_sensor_obs(self):', '(robot_x,', 'robot_y,', 'robot_z)', '=', "self.wrapped_env.get_body_com('torso')[:3]", 'ori', '=', 'self.get_ori()', 'structure', '=', 'self.MAZE_STRUCTURE', 'size_scaling', '=', 'self.MAZE_SIZE_SCALING', 'height', '=', 'self.MAZE_HEIGHT', 'segments', '=', '[]', 'for', 'i', 'in',... | 573,863 |
ivanalberico/Probabilistic-Artificial-Intelligence-ETH | solution.py | BayesNet.log_post | log_post | Computes the log posterior over all layers. | [
"Computes",
"the",
"log",
"posterior",
"over",
"all",
"layers."
] | def log_post(self):
log_posterior = torch.zeros(1)
for i in range(self.num_layers + 1):
log_posterior += self.net[i][0].log_post
log_posterior += self.net[self.num_layers + 1].log_post
return log_posterior | ['def', 'log_post(self):', 'log_posterior', '=', 'torch.zeros(1)', 'for', 'i', 'in', 'range(self.num_layers', '+', '1):', 'log_posterior', '+=', 'self.net[i][0].log_post', 'log_posterior', '+=', 'self.net[self.num_layers', '+', '1].log_post', 'return', 'log_posterior'] | 295,477 |
frapa/tbcnn | network.py | init_net | init_net | Initialize an empty network. | [
"Initialize",
"an",
"empty",
"network."
] | def init_net(feature_size, label_size):
with tf.name_scope('inputs'):
nodes = tf.placeholder(tf.float32, shape=(None, None, feature_size), name='tree')
children = tf.placeholder(tf.int32, shape=(None, None, None), name='children')
with tf.name_scope('network'):
conv1 = conv_layer(1, 100,... | ['def', 'init_net(feature_size,', 'label_size):', 'with', "tf.name_scope('inputs'):", 'nodes', '=', 'tf.placeholder(tf.float32,', 'shape=(None,', 'None,', 'feature_size),', "name='tree')", 'children', '=', 'tf.placeholder(tf.int32,', 'shape=(None,', 'None,', 'None),', "name='children')", 'with', "tf.name_scope('network... | 365,545 |
sek788432/Waymo-2D-Object-Detection | create_xlnet_pretraining_data.py | shuffle_and_combine_preprocessed_data | shuffle_and_combine_preprocessed_data | Shuffles and combines preprocessed token/sentence IDs from documents. | [
"Shuffles",
"and",
"combines",
"preprocessed",
"token/sentence",
"IDs",
"from",
"documents."
] | def shuffle_and_combine_preprocessed_data(all_data: List[Tuple[np.array, np.array]]) -> Tuple[np.array, np.array]:
document_permutation = np.random.permutation(len(all_data))
previous_sentence_id = None
(all_tokens, all_sentence_ids) = ([], [])
for document_index in document_permutation:
(tokens... | ['def', 'shuffle_and_combine_preprocessed_data(all_data:', 'List[Tuple[np.array,', 'np.array]])', '->', 'Tuple[np.array,', 'np.array]:', 'document_permutation', '=', 'np.random.permutation(len(all_data))', 'previous_sentence_id', '=', 'None', '(all_tokens,', 'all_sentence_ids)', '=', '([],', '[])', 'for', 'document_ind... | 972,506 |
som-shahlab/femr | flowsheet_cleaner.py | get_concepts_to_add | get_concepts_to_add | Pull out the new concept_ids that we have to map. | [
"Pull",
"out",
"the",
"new",
"concept_ids",
"that",
"we",
"have",
"to",
"map."
] | def get_concepts_to_add(root: str, child: str) -> Tuple[Set[str], Set[Tuple[str, str]]]:
new_concepts = set()
new_relationships = set()
try:
source_path = os.path.join(root, 'observation', child)
with io.TextIOWrapper(zstandard.ZstdDecompressor().stream_reader(open(source_path, 'rb'))) as f:... | ['def', 'get_concepts_to_add(root:', 'str,', 'child:', 'str)', '->', 'Tuple[Set[str],', 'Set[Tuple[str,', 'str]]]:', 'new_concepts', '=', 'set()', 'new_relationships', '=', 'set()', 'try:', 'source_path', '=', 'os.path.join(root,', "'observation',", 'child)', 'with', 'io.TextIOWrapper(zstandard.ZstdDecompressor().strea... | 179,845 |
noambassat/SpeechTrainer | tags.py | interpreter_version | interpreter_version | Returns the version of the running interpreter. | [
"Returns",
"the",
"version",
"of",
"the",
"running",
"interpreter."
] | def interpreter_version(**kwargs):
warn = _warn_keyword_parameter('interpreter_version', kwargs)
version = _get_config_var('py_version_nodot', warn=warn)
if version:
version = str(version)
else:
version = _version_nodot(sys.version_info[:2])
return version | ['def', 'interpreter_version(**kwargs):', 'warn', '=', "_warn_keyword_parameter('interpreter_version',", 'kwargs)', 'version', '=', "_get_config_var('py_version_nodot',", 'warn=warn)', 'if', 'version:', 'version', '=', 'str(version)', 'else:', 'version', '=', '_version_nodot(sys.version_info[:2])', 'return', 'version'] | 895,945 |
mfbx9da4/neuron-astrocyte-networks | fitnesslandscapes.py | plotCovEllipse | plotCovEllipse | Plots a covariance ellipse. | [
"Plots",
"a",
"covariance",
"ellipse."
] | def plotCovEllipse(emat, center, segments=50, color='y', transp=1.0):
ex = zeros(segments + 1)
ey = zeros(segments + 1)
(u, s, d) = svd(emat)
sm = dot(d, dot(diag(sqrt(s)), u))
for i in range(segments + 1):
circlex = cos(2 * pi * i / float(segments))
circley = sin(2 * pi * i / float(... | ['def', 'plotCovEllipse(emat,', 'center,', 'segments=50,', "color='y',", 'transp=1.0):', 'ex', '=', 'zeros(segments', '+', '1)', 'ey', '=', 'zeros(segments', '+', '1)', '(u,', 's,', 'd)', '=', 'svd(emat)', 'sm', '=', 'dot(d,', 'dot(diag(sqrt(s)),', 'u))', 'for', 'i', 'in', 'range(segments', '+', '1):', 'circlex', '=', ... | 722,775 |
shazow/workerpool | test_equipped.py | CountJob.run | run | Append the current count to results and increment. | [
"Append",
"the",
"current",
"count",
"to",
"results",
"and",
"increment."
] | def run(self, toolbox):
self.results.put(toolbox.count)
toolbox.count += 1 | ['def', 'run(self,', 'toolbox):', 'self.results.put(toolbox.count)', 'toolbox.count', '+=', '1'] | 373,675 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | vgslspecs.py | VGSLSpecs.AddMaxPool | AddMaxPool | Add a maxpool layer. | [
"Add",
"a",
"maxpool",
"layer."
] | def AddMaxPool(self, prev_layer, index):
pattern = re.compile('(Mp)({\\w+})?(\\d+),(\\d+)(?:,(\\d+),(\\d+))?')
m = pattern.match(self.model_str, index)
if m is None:
return (None, None)
name = self._GetLayerName(m.group(0), index, m.group(2))
height = int(m.group(3))
width = int(m.group(... | ['def', 'AddMaxPool(self,', 'prev_layer,', 'index):', 'pattern', '=', "re.compile('(Mp)({\\\\w+})?(\\\\d+),(\\\\d+)(?:,(\\\\d+),(\\\\d+))?')", 'm', '=', 'pattern.match(self.model_str,', 'index)', 'if', 'm', 'is', 'None:', 'return', '(None,', 'None)', 'name', '=', 'self._GetLayerName(m.group(0),', 'index,', 'm.group(2))... | 110,591 |
sktime/sktime | test_testscenario_getter.py | test_get_scenarios_errors | test_get_scenarios_errors | Test that errors are raised for bad input args. | [
"Test",
"that",
"errors",
"are",
"raised",
"for",
"bad",
"input",
"args."
] | def test_get_scenarios_errors():
with pytest.raises(TypeError):
retrieve_scenarios()
with pytest.raises(TypeError):
retrieve_scenarios(obj=1) | ['def', 'test_get_scenarios_errors():', 'with', 'pytest.raises(TypeError):', 'retrieve_scenarios()', 'with', 'pytest.raises(TypeError):', 'retrieve_scenarios(obj=1)'] | 878,172 |
sarnsdev/social-alignment-data-mining | test_peak_finding.py | TestPeakProminences.test_warnings | test_warnings | Verify that appropriate warnings are raised. | [
"Verify",
"that",
"appropriate",
"warnings",
"are",
"raised."
] | def test_warnings(self):
msg = 'some peaks have a prominence of 0'
for p in [0, 1, 2]:
with warns(PeakPropertyWarning, match=msg):
peak_prominences([1, 0, 2], [p])
with warns(PeakPropertyWarning, match=msg):
peak_prominences([0, 1, 1, 1, 0], [2], wlen=2) | ['def', 'test_warnings(self):', 'msg', '=', "'some", 'peaks', 'have', 'a', 'prominence', 'of', "0'", 'for', 'p', 'in', '[0,', '1,', '2]:', 'with', 'warns(PeakPropertyWarning,', 'match=msg):', 'peak_prominences([1,', '0,', '2],', '[p])', 'with', 'warns(PeakPropertyWarning,', 'match=msg):', 'peak_prominences([0,', '1,', ... | 391,247 |
aangelopoulos/conformal-risk | convert_predictions.py | metric_max_over_answers | metric_max_over_answers | Return the maximum score between any (prediction, answer) pair. | [
"Return",
"the",
"maximum",
"score",
"between",
"any",
"(prediction,",
"answer)",
"pair."
] | def metric_max_over_answers(metric_fn, prediction, answer_set):
max_score = -float('inf')
for answer in answer_set:
score = metric_fn(prediction, answer)
max_score = max(max_score, score)
return max_score | ['def', 'metric_max_over_answers(metric_fn,', 'prediction,', 'answer_set):', 'max_score', '=', "-float('inf')", 'for', 'answer', 'in', 'answer_set:', 'score', '=', 'metric_fn(prediction,', 'answer)', 'max_score', '=', 'max(max_score,', 'score)', 'return', 'max_score'] | 515,055 |
openvinotoolkit/datumaro | loss_dynamics_analyzer.py | LossDynamicsAnalyzer.ema_dataframe | ema_dataframe | Pandas DataFrame including full EMA loss dynamics statistics. | [
"Pandas",
"DataFrame",
"including",
"full",
"EMA",
"loss",
"dynamics",
"statistics."
] | def ema_dataframe(self) -> pd.DataFrame:
return self._df | ['def', 'ema_dataframe(self)', '->', 'pd.DataFrame:', 'return', 'self._df'] | 498,172 |
arshpreetsingh/quantopian-machinelearning | document.py | Document.lines | lines | Array of all the lines. | [
"Array",
"of",
"all",
"the",
"lines."
] | def lines(self):
if self._cache.lines is None:
self._cache.lines = _ImmutableLineList(self.text.split('\n'))
return self._cache.lines | ['def', 'lines(self):', 'if', 'self._cache.lines', 'is', 'None:', 'self._cache.lines', '=', "_ImmutableLineList(self.text.split('\\n'))", 'return', 'self._cache.lines'] | 892,020 |
triaquae/triaquae | models.py | BaseModelFormSet.save_new | save_new | Saves and returns a new model instance for the given form. | [
"Saves",
"and",
"returns",
"a",
"new",
"model",
"instance",
"for",
"the",
"given",
"form."
] | def save_new(self, form, commit=True):
return form.save(commit=commit) | ['def', 'save_new(self,', 'form,', 'commit=True):', 'return', 'form.save(commit=commit)'] | 423,712 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | utils.py | compute_pairwise_distances | compute_pairwise_distances | Computes the squared pairwise Euclidean distances between x and y. | [
"Computes",
"the",
"squared",
"pairwise",
"Euclidean",
"distances",
"between",
"x",
"and",
"y."
] | def compute_pairwise_distances(x, y):
if not len(x.get_shape()) == len(y.get_shape()) == 2:
raise ValueError('Both inputs should be matrices.')
if x.get_shape().as_list()[1] != y.get_shape().as_list()[1]:
raise ValueError('The number of features should be the same.')
norm = lambda x: tf.redu... | ['def', 'compute_pairwise_distances(x,', 'y):', 'if', 'not', 'len(x.get_shape())', '==', 'len(y.get_shape())', '==', '2:', 'raise', "ValueError('Both", 'inputs', 'should', 'be', "matrices.')", 'if', 'x.get_shape().as_list()[1]', '!=', 'y.get_shape().as_list()[1]:', 'raise', "ValueError('The", 'number', 'of', 'features'... | 48,081 |
pytorch/rl | env_creator.py | get_env_metadata | get_env_metadata | Retrieves a EnvMetaData object from an env. | [
"Retrieves",
"a",
"EnvMetaData",
"object",
"from",
"an",
"env."
] | def get_env_metadata(env_or_creator: Union[EnvBase, Callable], kwargs: Optional[Dict]=None):
if isinstance(env_or_creator, (EnvBase,)):
return EnvMetaData.metadata_from_env(env_or_creator)
elif not isinstance(env_or_creator, EnvBase) and (not isinstance(env_or_creator, EnvCreator)):
if kwargs is... | ['def', 'get_env_metadata(env_or_creator:', 'Union[EnvBase,', 'Callable],', 'kwargs:', 'Optional[Dict]=None):', 'if', 'isinstance(env_or_creator,', '(EnvBase,)):', 'return', 'EnvMetaData.metadata_from_env(env_or_creator)', 'elif', 'not', 'isinstance(env_or_creator,', 'EnvBase)', 'and', '(not', 'isinstance(env_or_creato... | 858,987 |
mattchorlian/Berkeley-CS188-Spring21 | search.py | SearchProblem.expand | expand | state: Search state For a given state, this should return a list of triples, (child, action, stepCost), where 'child' is a child to the current state, 'action' is the action required to get there, and 'stepCost' is the incremental cost of expanding to that child. | [
"state:",
"Search",
"state",
"For",
"a",
"given",
"state,",
"this",
"should",
"return",
"a",
"list",
"of",
"triples,",
"(child,",
"action,",
"stepCost),",
"where",
"'child'",
"is",
"a",
"child",
"to",
"the",
"current",
"state,",
"'action'",
"is",
"the",
"act... | def expand(self, state):
util.raiseNotDefined() | ['def', 'expand(self,', 'state):', 'util.raiseNotDefined()'] | 106,365 |
felixwzh/La-DTL | mmd.py | maximum_mean_discrepancy | maximum_mean_discrepancy | Computes the Maximum Mean Discrepancy (MMD) of two samples: x and y. | [
"Computes",
"the",
"Maximum",
"Mean",
"Discrepancy",
"(MMD)",
"of",
"two",
"samples:",
"x",
"and",
"y."
] | def maximum_mean_discrepancy(x, y, kernel=gaussian_kernel_matrix):
cost = tf.reduce_mean(kernel(x, x))
cost += tf.reduce_mean(kernel(y, y))
cost -= 2 * tf.reduce_mean(kernel(x, y))
cost = tf.where(cost > 0, cost, 0, name='value')
return cost | ['def', 'maximum_mean_discrepancy(x,', 'y,', 'kernel=gaussian_kernel_matrix):', 'cost', '=', 'tf.reduce_mean(kernel(x,', 'x))', 'cost', '+=', 'tf.reduce_mean(kernel(y,', 'y))', 'cost', '-=', '2', '*', 'tf.reduce_mean(kernel(x,', 'y))', 'cost', '=', 'tf.where(cost', '>', '0,', 'cost,', '0,', "name='value')", 'return', '... | 622,416 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | test_logging.py | RecordingHandler.handle | handle | Keep track of all the emitted records. | [
"Keep",
"track",
"of",
"all",
"the",
"emitted",
"records."
] | def handle(self, record):
self.records.append(record) | ['def', 'handle(self,', 'record):', 'self.records.append(record)'] | 376,226 |
opendilab/DI-star | actions.py | cmd_screen | cmd_screen | Do a command that needs a point on the screen. | [
"Do",
"a",
"command",
"that",
"needs",
"a",
"point",
"on",
"the",
"screen."
] | def cmd_screen(action, action_space, ability_id, queued, screen):
action_cmd = spatial(action, action_space).unit_command
action_cmd.ability_id = ability_id
action_cmd.queue_command = queued
screen.assign_to(action_cmd.target_screen_coord) | ['def', 'cmd_screen(action,', 'action_space,', 'ability_id,', 'queued,', 'screen):', 'action_cmd', '=', 'spatial(action,', 'action_space).unit_command', 'action_cmd.ability_id', '=', 'ability_id', 'action_cmd.queue_command', '=', 'queued', 'screen.assign_to(action_cmd.target_screen_coord)'] | 184,661 |
meowoodie/Reinforcement-Learning-of-Spatio-Temporal-Point-Processes | utils.py | plot_spatial_kernel | plot_spatial_kernel | Plot spatial kernel parameters over the spatial region, including sigma_x, sigma_x, and rho. | [
"Plot",
"spatial",
"kernel",
"parameters",
"over",
"the",
"spatial",
"region,",
"including",
"sigma_x,",
"sigma_x,",
"and",
"rho."
] | def plot_spatial_kernel(path, kernel, S, grid_size, sigma_x_clim=None, sigma_y_clim=None, rho_clim=None):
assert len(S) == 2, '%d is an invalid dimension of the space.' % len(S)
x_span = np.linspace(S[0][0], S[0][1], grid_size + 1)[:-1]
y_span = np.linspace(S[1][0], S[1][1], grid_size + 1)[:-1]
sigma_x_... | ['def', 'plot_spatial_kernel(path,', 'kernel,', 'S,', 'grid_size,', 'sigma_x_clim=None,', 'sigma_y_clim=None,', 'rho_clim=None):', 'assert', 'len(S)', '==', '2,', "'%d", 'is', 'an', 'invalid', 'dimension', 'of', 'the', "space.'", '%', 'len(S)', 'x_span', '=', 'np.linspace(S[0][0],', 'S[0][1],', 'grid_size', '+', '1)[:-... | 833,503 |
xvjiarui/VFS | binary_logistic_regression_loss.py | binary_logistic_regression_loss | binary_logistic_regression_loss | Binary Logistic Regression Loss. | [
"Binary",
"Logistic",
"Regression",
"Loss."
] | def binary_logistic_regression_loss(reg_score, label, threshold=0.5, ratio_range=(1.05, 21), eps=1e-05):
label = label.view(-1).to(reg_score.device)
reg_score = reg_score.contiguous().view(-1)
pmask = (label > threshold).float().to(reg_score.device)
num_positive = max(torch.sum(pmask), 1)
num_entrie... | ['def', 'binary_logistic_regression_loss(reg_score,', 'label,', 'threshold=0.5,', 'ratio_range=(1.05,', '21),', 'eps=1e-05):', 'label', '=', 'label.view(-1).to(reg_score.device)', 'reg_score', '=', 'reg_score.contiguous().view(-1)', 'pmask', '=', '(label', '>', 'threshold).float().to(reg_score.device)', 'num_positive',... | 379,671 |
myothida/Supervised-Machine-Learning | test_predict_error_display.py | test_from_estimator_not_fitted | test_from_estimator_not_fitted | Check that we raise a `NotFittedError` when the passed regressor is not fit. | [
"Check",
"that",
"we",
"raise",
"a",
"`NotFittedError`",
"when",
"the",
"passed",
"regressor",
"is",
"not",
"fit."
] | def test_from_estimator_not_fitted(pyplot):
regressor = Ridge()
with pytest.raises(NotFittedError, match='is not fitted yet.'):
PredictionErrorDisplay.from_estimator(regressor, X, y) | ['def', 'test_from_estimator_not_fitted(pyplot):', 'regressor', '=', 'Ridge()', 'with', 'pytest.raises(NotFittedError,', "match='is", 'not', 'fitted', "yet.'):", 'PredictionErrorDisplay.from_estimator(regressor,', 'X,', 'y)'] | 364,304 |
chainer/chainerrl | agent.py | BatchAgent.batch_observe | batch_observe | Observe a batch of action consequences for evaluation. | [
"Observe",
"a",
"batch",
"of",
"action",
"consequences",
"for",
"evaluation."
] | def batch_observe(self, batch_obs, batch_reward, batch_done, batch_reset):
raise NotImplementedError() | ['def', 'batch_observe(self,', 'batch_obs,', 'batch_reward,', 'batch_done,', 'batch_reset):', 'raise', 'NotImplementedError()'] | 104,519 |
GregorKobsik/Octree-Transformer | kd_tree_test.py | TestQuadtree.mnist_28x28_binarized | mnist_28x28_binarized | Return a single binarized MNIST image, with a resolution of 28x28. | [
"Return",
"a",
"single",
"binarized",
"MNIST",
"image,",
"with",
"a",
"resolution",
"of",
"28x28."
] | def mnist_28x28_binarized(self):
return self.binarize(self.mnist_28x28()) | ['def', 'mnist_28x28_binarized(self):', 'return', 'self.binarize(self.mnist_28x28())'] | 755,104 |
sshleifer/object_detection_kitti | problem_spec.py | Spec.build | build | Returns the output of the callable. | [
"Returns",
"the",
"output",
"of",
"the",
"callable."
] | def build(self):
return self.callable(*self.args, **self.kwargs) | ['def', 'build(self):', 'return', 'self.callable(*self.args,', '**self.kwargs)'] | 794,942 |
enuguru/artificial_intelligence_and_machine_learning | compiler.py | CodeGenerator.visit_Block | visit_Block | Call a block and register it for the template. | [
"Call",
"a",
"block",
"and",
"register",
"it",
"for",
"the",
"template."
] | def visit_Block(self, node, frame):
level = 1
if frame.toplevel:
if self.has_known_extends:
return
if self.extends_so_far > 0:
self.writeline('if parent_template is None:')
self.indent()
level += 1
context = node.scoped and 'context.derived(loc... | ['def', 'visit_Block(self,', 'node,', 'frame):', 'level', '=', '1', 'if', 'frame.toplevel:', 'if', 'self.has_known_extends:', 'return', 'if', 'self.extends_so_far', '>', '0:', "self.writeline('if", 'parent_template', 'is', "None:')", 'self.indent()', 'level', '+=', '1', 'context', '=', 'node.scoped', 'and', "'context.d... | 129,056 |
miyosuda/unreal | experience.py | ExperienceFrame.get_action_reward | get_action_reward | Return one hot vectored action + reward. | [
"Return",
"one",
"hot",
"vectored",
"action",
"+",
"reward."
] | def get_action_reward(self, action_size):
return ExperienceFrame.concat_action_and_reward(self.action, action_size, self.reward) | ['def', 'get_action_reward(self,', 'action_size):', 'return', 'ExperienceFrame.concat_action_and_reward(self.action,', 'action_size,', 'self.reward)'] | 378,649 |
Alexander-Parker/youtube_nlp | google_auth_httplib2.py | _Response.headers | headers | Mapping[str, str]: The HTTP response headers. | [
"Mapping[str,",
"str]:",
"The",
"HTTP",
"response",
"headers."
] | def headers(self):
return dict(self._response) | ['def', 'headers(self):', 'return', 'dict(self._response)'] | 969,916 |
phoenix2/phoenix | RPCProtocol.py | RPCPoller.parse | parse | Attempt to load JSON-RPC data. | [
"Attempt",
"to",
"load",
"JSON-RPC",
"data."
] | def parse(cls, data):
response = json.loads(data)
try:
message = response['error']['message']
except (KeyError, TypeError):
pass
else:
raise ServerMessage(message)
return response.get('result') | ['def', 'parse(cls,', 'data):', 'response', '=', 'json.loads(data)', 'try:', 'message', '=', "response['error']['message']", 'except', '(KeyError,', 'TypeError):', 'pass', 'else:', 'raise', 'ServerMessage(message)', 'return', "response.get('result')"] | 304,866 |
greydanus/pythonic_ocr | pildriver.py | PILDriver.do_brightness | do_brightness | usage: brightness <image:pic1> Enhance brightness in the top image. | [
"usage:",
"brightness",
"<image:pic1>",
"Enhance",
"brightness",
"in",
"the",
"top",
"image."
] | def do_brightness(self):
from PIL import ImageEnhance
factor = float(self.do_pop())
image = self.do_pop()
enhancer = ImageEnhance.Brightness(image)
self.push(enhancer.enhance(factor)) | ['def', 'do_brightness(self):', 'from', 'PIL', 'import', 'ImageEnhance', 'factor', '=', 'float(self.do_pop())', 'image', '=', 'self.do_pop()', 'enhancer', '=', 'ImageEnhance.Brightness(image)', 'self.push(enhancer.enhance(factor))'] | 298,517 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.