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
rishab-sharma/object_detection
class_head.py
MaskRCNNClassHead.predict
predict
Predicts boxes and class scores.
[ "Predicts", "boxes", "and", "class", "scores." ]
def predict(self, features, num_predictions_per_location=1): if num_predictions_per_location != 1: raise ValueError('Only num_predictions_per_location=1 is supported') spatial_averaged_roi_pooled_features = tf.reduce_mean(features, [1, 2], keep_dims=True, name='AvgPool') flattened_roi_pooled_feature...
['def', 'predict(self,', 'features,', 'num_predictions_per_location=1):', 'if', 'num_predictions_per_location', '!=', '1:', 'raise', "ValueError('Only", 'num_predictions_per_location=1', 'is', "supported')", 'spatial_averaged_roi_pooled_features', '=', 'tf.reduce_mean(features,', '[1,', '2],', 'keep_dims=True,', "name=...
774,790
salesforce/CodeRL
testing_utils.py
require_torch_gpu
require_torch_gpu
Decorator marking a test that requires CUDA and PyTorch.
[ "Decorator", "marking", "a", "test", "that", "requires", "CUDA", "and", "PyTorch." ]
def require_torch_gpu(test_case): if torch_device != 'cuda': return unittest.skip('test requires CUDA')(test_case) else: return test_case
['def', 'require_torch_gpu(test_case):', 'if', 'torch_device', '!=', "'cuda':", 'return', "unittest.skip('test", 'requires', "CUDA')(test_case)", 'else:', 'return', 'test_case']
494,109
OpenMDAO/OpenMDAO-Framework
query_hdf5.py
QueryHDF5.vars
vars
Filter the variable columns returned in the row.
[ "Filter", "the", "variable", "columns", "returned", "in", "the", "row." ]
def vars(self, *args): self.vnames = [] for arg in args: if isinstance(arg, basestring): self.vnames.append(arg) else: self.vnames.extend(arg) return self
['def', 'vars(self,', '*args):', 'self.vnames', '=', '[]', 'for', 'arg', 'in', 'args:', 'if', 'isinstance(arg,', 'basestring):', 'self.vnames.append(arg)', 'else:', 'self.vnames.extend(arg)', 'return', 'self']
275,406
eddiecorrigall/Vision
perlin.py
lerp
lerp
Linear interpolation between a and b, given a fraction t.
[ "Linear", "interpolation", "between", "a", "and", "b,", "given", "a", "fraction", "t." ]
def lerp(t: Number, a: Number, b: Number) -> Number: return a + t * (b - a)
['def', 'lerp(t:', 'Number,', 'a:', 'Number,', 'b:', 'Number)', '->', 'Number:', 'return', 'a', '+', 't', '*', '(b', '-', 'a)']
942,456
MarvinTeichmann/KittiSeg
seg_utils.py
setFigLinesBW
setFigLinesBW
Take each axes in the figure, and for each line in the axes, make the line viewable in black and white.
[ "Take", "each", "axes", "in", "the", "figure,", "and", "for", "each", "line", "in", "the", "axes,", "make", "the", "line", "viewable", "in", "black", "and", "white." ]
def setFigLinesBW(fig): for ax in fig.get_axes(): setAxLinesBW(ax)
['def', 'setFigLinesBW(fig):', 'for', 'ax', 'in', 'fig.get_axes():', 'setAxLinesBW(ax)']
596,352
instadeepai/jumanji
env_test.py
test_robot_warehouse__step
test_robot_warehouse__step
Validate the jitted step function of the environment.
[ "Validate", "the", "jitted", "step", "function", "of", "the", "environment." ]
def test_robot_warehouse__step(robot_warehouse_env: RobotWarehouse) -> None: chex.clear_trace_counter() step_fn = chex.assert_max_traces(robot_warehouse_env.step, n=1) step_fn = jax.jit(step_fn) (state_key, action_key1, action_key2) = random.split(random.PRNGKey(10), 3) (state, timestep) = robot_war...
['def', 'test_robot_warehouse__step(robot_warehouse_env:', 'RobotWarehouse)', '->', 'None:', 'chex.clear_trace_counter()', 'step_fn', '=', 'chex.assert_max_traces(robot_warehouse_env.step,', 'n=1)', 'step_fn', '=', 'jax.jit(step_fn)', '(state_key,', 'action_key1,', 'action_key2)', '=', 'random.split(random.PRNGKey(10),...
594,463
rudranil723/mini-main
polygon.py
Polygon.from_bbox
from_bbox
Construct a Polygon from a bounding box (4-tuple).
[ "Construct", "a", "Polygon", "from", "a", "bounding", "box", "(4-tuple)." ]
def from_bbox(cls, bbox): (x0, y0, x1, y1) = bbox for z in bbox: if not isinstance(z, (float, int)): return GEOSGeometry('POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))' % (x0, y0, x0, y1, x1, y1, x1, y0, x0, y0)) return Polygon(((x0, y0), (x0, y1), (x1, y1), (x1, y0), (x0, y0)))
['def', 'from_bbox(cls,', 'bbox):', '(x0,', 'y0,', 'x1,', 'y1)', '=', 'bbox', 'for', 'z', 'in', 'bbox:', 'if', 'not', 'isinstance(z,', '(float,', 'int)):', 'return', "GEOSGeometry('POLYGON((%s", '%s,', '%s', '%s,', '%s', '%s,', '%s', '%s,', '%s', "%s))'", '%', '(x0,', 'y0,', 'x0,', 'y1,', 'x1,', 'y1,', 'x1,', 'y0,', 'x...
315,362
gunthercox/ChatterBot
filters.py
do_reverse
do_reverse
Reverse the object or return an iterator the iterates over it the other way round.
[ "Reverse", "the", "object", "or", "return", "an", "iterator", "the", "iterates", "over", "it", "the", "other", "way", "round." ]
def do_reverse(value): if isinstance(value, string_types): return value[::-1] try: return reversed(value) except TypeError: try: rv = list(value) rv.reverse() return rv except TypeError: raise FilterArgumentError('argument must ...
['def', 'do_reverse(value):', 'if', 'isinstance(value,', 'string_types):', 'return', 'value[::-1]', 'try:', 'return', 'reversed(value)', 'except', 'TypeError:', 'try:', 'rv', '=', 'list(value)', 'rv.reverse()', 'return', 'rv', 'except', 'TypeError:', 'raise', "FilterArgumentError('argument", 'must', 'be', "iterable')"]
479,176
xvjiarui/VFS
bmn.py
BMN.forward
forward
Define the computation performed at every call.
[ "Define", "the", "computation", "performed", "at", "every", "call." ]
def forward(self, raw_feature, gt_bbox=None, video_meta=None, return_loss=True): if return_loss: (label_confidence, label_start, label_end) = self.generate_labels(gt_bbox) device = raw_feature.device label_confidence = label_confidence.to(device) label_start = label_start.to(device) ...
['def', 'forward(self,', 'raw_feature,', 'gt_bbox=None,', 'video_meta=None,', 'return_loss=True):', 'if', 'return_loss:', '(label_confidence,', 'label_start,', 'label_end)', '=', 'self.generate_labels(gt_bbox)', 'device', '=', 'raw_feature.device', 'label_confidence', '=', 'label_confidence.to(device)', 'label_start', ...
379,662
weimin17/Object-Detection_HelmetDetection
pixelda_model.py
lrelu
lrelu
Relu, with optional leaky support.
[ "Relu,", "with", "optional", "leaky", "support." ]
def lrelu(x, leakiness=0.2): return tf.where(tf.less(x, 0.0), leakiness * x, x, name='leaky_relu')
['def', 'lrelu(x,', 'leakiness=0.2):', 'return', 'tf.where(tf.less(x,', '0.0),', 'leakiness', '*', 'x,', 'x,', "name='leaky_relu')"]
749,932
suarez12138/AI-Reversi_IMP_TextDichotomy
axis.py
Axis.get_smart_bounds
get_smart_bounds
Return whether the axis has smart bounds.
[ "Return", "whether", "the", "axis", "has", "smart", "bounds." ]
def get_smart_bounds(self): return self._smart_bounds
['def', 'get_smart_bounds(self):', 'return', 'self._smart_bounds']
96,074
chribsen/simple-machine-learning-examples
ols.py
OLS.t_stat
t_stat
Returns the t-stat values of the betas.
[ "Returns", "the", "t-stat", "values", "of", "the", "betas." ]
def t_stat(self): return Series(self._t_stat_raw, index=self.beta.index)
['def', 't_stat(self):', 'return', 'Series(self._t_stat_raw,', 'index=self.beta.index)']
936,575
yogeshbalaji/InvGAN
gan.py
DefenseGANBase.test_batch
test_batch
Tests the image batch generator.
[ "Tests", "the", "image", "batch", "generator." ]
def test_batch(self): output_dir = os.path.join(self.debug_dir, 'test_batch') ensure_dir(output_dir) (img, target) = self.train_data_gen().next() img = img.reshape([self.batch_size] + self.image_dim) save_images_files(img / 255.0, output_dir=output_dir, labels=target)
['def', 'test_batch(self):', 'output_dir', '=', 'os.path.join(self.debug_dir,', "'test_batch')", 'ensure_dir(output_dir)', '(img,', 'target)', '=', 'self.train_data_gen().next()', 'img', '=', 'img.reshape([self.batch_size]', '+', 'self.image_dim)', 'save_images_files(img', '/', '255.0,', 'output_dir=output_dir,', 'labe...
576,744
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
__init__.py
Misc.winfo_width
winfo_width
Return the width of this widget.
[ "Return", "the", "width", "of", "this", "widget." ]
def winfo_width(self): return self.tk.getint(self.tk.call('winfo', 'width', self._w))
['def', 'winfo_width(self):', 'return', "self.tk.getint(self.tk.call('winfo',", "'width',", 'self._w))']
376,843
arshpreetsingh/quantopian-machinelearning
__init__.py
get_all_formatters
get_all_formatters
Return a generator for all formatter classes.
[ "Return", "a", "generator", "for", "all", "formatter", "classes." ]
def get_all_formatters(): for info in itervalues(FORMATTERS): if info[1] not in _formatter_cache: _load_formatters(info[0]) yield _formatter_cache[info[1]] for (_, formatter) in find_plugin_formatters(): yield formatter
['def', 'get_all_formatters():', 'for', 'info', 'in', 'itervalues(FORMATTERS):', 'if', 'info[1]', 'not', 'in', '_formatter_cache:', '_load_formatters(info[0])', 'yield', '_formatter_cache[info[1]]', 'for', '(_,', 'formatter)', 'in', 'find_plugin_formatters():', 'yield', 'formatter']
892,658
tobegit3hub/deep_image_model
ops.py
Operation.traceback
traceback
Returns the call stack from when this operation was constructed.
[ "Returns", "the", "call", "stack", "from", "when", "this", "operation", "was", "constructed." ]
def traceback(self): return _convert_stack(self._traceback)
['def', 'traceback(self):', 'return', '_convert_stack(self._traceback)']
182,579
SvenGronauer/phoenix-drone-simulation
ddpg.py
DeepDeterministicPolciyGradientAlgorithm.roll_out
roll_out
Rollout >>one<< episode and store to buffer.
[ "Rollout", ">>one<<", "episode", "and", "store", "to", "buffer." ]
def roll_out(self): (o, ep_ret, ep_len) = (self.env.reset(), 0.0, 0) for t in range(self.local_batch_size): self.in_warm_up = True if len(self.buffer) < self.warmup_steps else False if self.in_warm_up: a = self.env.action_space.sample() else: a = self.get_action(o...
['def', 'roll_out(self):', '(o,', 'ep_ret,', 'ep_len)', '=', '(self.env.reset(),', '0.0,', '0)', 'for', 't', 'in', 'range(self.local_batch_size):', 'self.in_warm_up', '=', 'True', 'if', 'len(self.buffer)', '<', 'self.warmup_steps', 'else', 'False', 'if', 'self.in_warm_up:', 'a', '=', 'self.env.action_space.sample()', '...
769,075
nilearn/nilearn
test_nifti_masker.py
test_resample_to_mask_warning
test_resample_to_mask_warning
Check that a warning is raised when data is being resampled to mask's resolution.
[ "Check", "that", "a", "warning", "is", "raised", "when", "data", "is", "being", "resampled", "to", "mask's", "resolution." ]
def test_resample_to_mask_warning(): data = np.zeros((9, 9, 9)) data[3:-3, 3:-3, 3:-3] = 10 img = nibabel.Nifti1Image(data, np.eye(4)) mask = np.zeros((12, 12, 12)) mask[3:-3, 3:-3, 3:-3] = 10 mask = mask.astype('uint8') mask_img = nibabel.Nifti1Image(mask, np.eye(4)) masker = NiftiMaske...
['def', 'test_resample_to_mask_warning():', 'data', '=', 'np.zeros((9,', '9,', '9))', 'data[3:-3,', '3:-3,', '3:-3]', '=', '10', 'img', '=', 'nibabel.Nifti1Image(data,', 'np.eye(4))', 'mask', '=', 'np.zeros((12,', '12,', '12))', 'mask[3:-3,', '3:-3,', '3:-3]', '=', '10', 'mask', '=', "mask.astype('uint8')", 'mask_img',...
724,007
caiiiac/Machine-Learning-with-Python
packers.py
pack
pack
Pack an object and return the packed bytes.
[ "Pack", "an", "object", "and", "return", "the", "packed", "bytes." ]
def pack(o, default=encode, encoding='utf-8', unicode_errors='strict', use_single_float=False, autoreset=1, use_bin_type=1): return Packer(default=default, encoding=encoding, unicode_errors=unicode_errors, use_single_float=use_single_float, autoreset=autoreset, use_bin_type=use_bin_type).pack(o)
['def', 'pack(o,', 'default=encode,', "encoding='utf-8',", "unicode_errors='strict',", 'use_single_float=False,', 'autoreset=1,', 'use_bin_type=1):', 'return', 'Packer(default=default,', 'encoding=encoding,', 'unicode_errors=unicode_errors,', 'use_single_float=use_single_float,', 'autoreset=autoreset,', 'use_bin_type=u...
718,278
danamyu/hedgehog_detector
networks.py
conditional_discriminator
conditional_discriminator
Discriminator for CIFAR images.
[ "Discriminator", "for", "CIFAR", "images." ]
def conditional_discriminator(img, conditioning): (logits, end_points) = dcgan.discriminator(img) (_, one_hot_labels) = conditioning net = _last_conv_layer(end_points) net = tfgan.features.condition_tensor_from_onehot(tf.contrib.layers.flatten(net), one_hot_labels) logits = tf.contrib.layers.linear(...
['def', 'conditional_discriminator(img,', 'conditioning):', '(logits,', 'end_points)', '=', 'dcgan.discriminator(img)', '(_,', 'one_hot_labels)', '=', 'conditioning', 'net', '=', '_last_conv_layer(end_points)', 'net', '=', 'tfgan.features.condition_tensor_from_onehot(tf.contrib.layers.flatten(net),', 'one_hot_labels)',...
589,614
nilearn/nilearn
test_dict_learning.py
test_dict_learning_check_values_epoch_argument_smoke
test_dict_learning_check_values_epoch_argument_smoke
Smoke test to check different values of the epoch argument.
[ "Smoke", "test", "to", "check", "different", "values", "of", "the", "epoch", "argument." ]
def test_dict_learning_check_values_epoch_argument_smoke(mask_img, n_epochs): (data, components, _) = _make_canica_test_data() masker = NiftiMasker(mask_img=mask_img).fit() mask = get_data(mask_img) != 0 flat_mask = mask.ravel() dict_init = masker.inverse_transform(components[:, flat_mask]) dict...
['def', 'test_dict_learning_check_values_epoch_argument_smoke(mask_img,', 'n_epochs):', '(data,', 'components,', '_)', '=', '_make_canica_test_data()', 'masker', '=', 'NiftiMasker(mask_img=mask_img).fit()', 'mask', '=', 'get_data(mask_img)', '!=', '0', 'flat_mask', '=', 'mask.ravel()', 'dict_init', '=', 'masker.inverse...
723,745
google-research/scenic
ops.py
get_random_hue
get_random_hue
Applies random hue transformations.
[ "Applies", "random", "hue", "transformations." ]
def get_random_hue(max_delta=0.1): def _random_hue(image): return tf.image.random_hue(image, max_delta=max_delta) return _random_hue
['def', 'get_random_hue(max_delta=0.1):', 'def', '_random_hue(image):', 'return', 'tf.image.random_hue(image,', 'max_delta=max_delta)', 'return', '_random_hue']
846,100
Alexander-Parker/youtube_nlp
common.py
validate_uuid_representation
validate_uuid_representation
Validate the uuid representation option selected in the URI.
[ "Validate", "the", "uuid", "representation", "option", "selected", "in", "the", "URI." ]
def validate_uuid_representation(dummy, value): try: return _UUID_REPRESENTATIONS[value] except KeyError: raise ValueError('%s is an invalid UUID representation. Must be one of %s' % (value, tuple(_UUID_REPRESENTATIONS)))
['def', 'validate_uuid_representation(dummy,', 'value):', 'try:', 'return', '_UUID_REPRESENTATIONS[value]', 'except', 'KeyError:', 'raise', "ValueError('%s", 'is', 'an', 'invalid', 'UUID', 'representation.', 'Must', 'be', 'one', 'of', "%s'", '%', '(value,', 'tuple(_UUID_REPRESENTATIONS)))']
970,371
shery322/Lunar-Lander-ANN
surface_test.py
SurfaceBlendTest.test_blit_blend_big_rect
test_blit_blend_big_rect
test that an oversized rect works ok.
[ "test", "that", "an", "oversized", "rect", "works", "ok." ]
def test_blit_blend_big_rect(self): color = (1, 2, 3, 255) area = (1, 1, 30, 30) s1 = pygame.Surface((4, 4), 0, 32) r = s1.fill(special_flags=pygame.BLEND_ADD, color=color, rect=area) self.assertEqual(pygame.Rect((1, 1, 3, 3)), r) self.assertEqual(s1.get_at((0, 0)), (0, 0, 0, 255)) self.asse...
['def', 'test_blit_blend_big_rect(self):', 'color', '=', '(1,', '2,', '3,', '255)', 'area', '=', '(1,', '1,', '30,', '30)', 's1', '=', 'pygame.Surface((4,', '4),', '0,', '32)', 'r', '=', 's1.fill(special_flags=pygame.BLEND_ADD,', 'color=color,', 'rect=area)', 'self.assertEqual(pygame.Rect((1,', '1,', '3,', '3)),', 'r)'...
619,182
sunishsheth2009/ChatterBot
propbank.py
PropbankInstance.sensenumber
sensenumber
The sense number of the predicate.
[ "The", "sense", "number", "of", "the", "predicate." ]
def sensenumber(self): return self.roleset.split('.')[1]
['def', 'sensenumber(self):', 'return', "self.roleset.split('.')[1]"]
530,088
gradio-app/gradio
utils.py
sanitize_parameter_names
sanitize_parameter_names
Cleans up a Python parameter name to make the API info more readable.
[ "Cleans", "up", "a", "Python", "parameter", "name", "to", "make", "the", "API", "info", "more", "readable." ]
def sanitize_parameter_names(original_name: str) -> str: return ''.join([char for char in original_name if char.isalnum() or char in ' _']).replace(' ', '_').lower()
['def', 'sanitize_parameter_names(original_name:', 'str)', '->', 'str:', 'return', "''.join([char", 'for', 'char', 'in', 'original_name', 'if', 'char.isalnum()', 'or', 'char', 'in', "'", "_']).replace('", "',", "'_').lower()"]
578,804
jaywalnut310/Vector-Quantized-Autoencoders
transformer_vq.py
get_latent_pred_loss
get_latent_pred_loss
Latent prediction and loss.
[ "Latent", "prediction", "and", "loss." ]
def get_latent_pred_loss(latents_pred, latents_discrete_hot, hparams): latents_logits = tf.layers.dense(latents_pred, 2 ** hparams.bottleneck_bits, name='extra_logits') loss = tf.nn.softmax_cross_entropy_with_logits_v2(labels=tf.stop_gradient(latents_discrete_hot), logits=latents_logits) return loss
['def', 'get_latent_pred_loss(latents_pred,', 'latents_discrete_hot,', 'hparams):', 'latents_logits', '=', 'tf.layers.dense(latents_pred,', '2', '**', 'hparams.bottleneck_bits,', "name='extra_logits')", 'loss', '=', 'tf.nn.softmax_cross_entropy_with_logits_v2(labels=tf.stop_gradient(latents_discrete_hot),', 'logits=lat...
931,055
voxel51/fiftyone
utils.py
justify_headings
justify_headings
Justifies the headings in a list of ``(heading, content)`` string tuples by appending whitespace as necessary to each ``heading``.
[ "Justifies", "the", "headings", "in", "a", "list", "of", "``(heading,", "content)``", "string", "tuples", "by", "appending", "whitespace", "as", "necessary", "to", "each", "``heading``." ]
def justify_headings(elements, width=None): if width is None: width = max((len(e[0]) for e in elements)) fmt = '%%-%ds' % width return [(fmt % e[0], e[1]) for e in elements]
['def', 'justify_headings(elements,', 'width=None):', 'if', 'width', 'is', 'None:', 'width', '=', 'max((len(e[0])', 'for', 'e', 'in', 'elements))', 'fmt', '=', "'%%-%ds'", '%', 'width', 'return', '[(fmt', '%', 'e[0],', 'e[1])', 'for', 'e', 'in', 'elements]']
583,431
michellesri/cs188
capture.py
GameState.hasWall
hasWall
Returns true if (x,y) has a wall, false otherwise.
[ "Returns", "true", "if", "(x,y)", "has", "a", "wall,", "false", "otherwise." ]
def hasWall(self, x, y): return self.data.layout.walls[x][y]
['def', 'hasWall(self,', 'x,', 'y):', 'return', 'self.data.layout.walls[x][y]']
224,024
ldkong1205/LaserMix
bevfusion.py
BEVFusion.parse_losses
parse_losses
Parses the raw outputs (losses) of the network.
[ "Parses", "the", "raw", "outputs", "(losses)", "of", "the", "network." ]
def parse_losses(self, losses: Dict[str, torch.Tensor]) -> Tuple[torch.Tensor, Dict[str, torch.Tensor]]: log_vars = [] for (loss_name, loss_value) in losses.items(): if isinstance(loss_value, torch.Tensor): log_vars.append([loss_name, loss_value.mean()]) elif is_list_of(loss_value, t...
['def', 'parse_losses(self,', 'losses:', 'Dict[str,', 'torch.Tensor])', '->', 'Tuple[torch.Tensor,', 'Dict[str,', 'torch.Tensor]]:', 'log_vars', '=', '[]', 'for', '(loss_name,', 'loss_value)', 'in', 'losses.items():', 'if', 'isinstance(loss_value,', 'torch.Tensor):', 'log_vars.append([loss_name,', 'loss_value.mean()])'...
624,482
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
dp_mnist.py
MnistInput
MnistInput
Create operations to read the MNIST input file.
[ "Create", "operations", "to", "read", "the", "MNIST", "input", "file." ]
def MnistInput(mnist_data_file, batch_size, randomize): file_queue = tf.train.string_input_producer([mnist_data_file]) reader = tf.TFRecordReader() (_, value) = reader.read(file_queue) example = tf.parse_single_example(value, features={'image/encoded': tf.FixedLenFeature(shape=(), dtype=tf.string), 'ima...
['def', 'MnistInput(mnist_data_file,', 'batch_size,', 'randomize):', 'file_queue', '=', 'tf.train.string_input_producer([mnist_data_file])', 'reader', '=', 'tf.TFRecordReader()', '(_,', 'value)', '=', 'reader.read(file_queue)', 'example', '=', 'tf.parse_single_example(value,', "features={'image/encoded':", 'tf.FixedLen...
47,561
sarnsdev/social-alignment-data-mining
req_command.py
RequirementCommand.make_resolver
make_resolver
Create a Resolver instance for the given parameters.
[ "Create", "a", "Resolver", "instance", "for", "the", "given", "parameters." ]
def make_resolver(preparer, session, finder, options, wheel_cache=None, use_user_site=False, ignore_installed=True, ignore_requires_python=False, force_reinstall=False, upgrade_strategy='to-satisfy-only', use_pep517=None, py_version_info=None): make_install_req = partial(install_req_from_req_string, isolated=option...
['def', 'make_resolver(preparer,', 'session,', 'finder,', 'options,', 'wheel_cache=None,', 'use_user_site=False,', 'ignore_installed=True,', 'ignore_requires_python=False,', 'force_reinstall=False,', "upgrade_strategy='to-satisfy-only',", 'use_pep517=None,', 'py_version_info=None):', 'make_install_req', '=', 'partial(i...
389,704
PaddlePaddle/PaddleSpeech
melgan.py
MelGANGenerator.remove_weight_norm
remove_weight_norm
Recursively remove weight normalization from all the Convolution layers in the sublayers.
[ "Recursively", "remove", "weight", "normalization", "from", "all", "the", "Convolution", "layers", "in", "the", "sublayers." ]
def remove_weight_norm(self): def _remove_weight_norm(layer): try: nn.utils.remove_weight_norm(layer) except ValueError: pass self.apply(_remove_weight_norm)
['def', 'remove_weight_norm(self):', 'def', '_remove_weight_norm(layer):', 'try:', 'nn.utils.remove_weight_norm(layer)', 'except', 'ValueError:', 'pass', 'self.apply(_remove_weight_norm)']
277,201
rudranil723/mini-main
models.py
SpatialRefSysMixin.srs
srs
Return a GDAL SpatialReference object.
[ "Return", "a", "GDAL", "SpatialReference", "object." ]
def srs(self): if hasattr(self, '_srs'): return self._srs.clone() else: try: self._srs = gdal.SpatialReference(self.wkt) return self.srs except Exception as e: msg = e try: self._srs = gdal.SpatialReference(self.proj4text) ...
['def', 'srs(self):', 'if', 'hasattr(self,', "'_srs'):", 'return', 'self._srs.clone()', 'else:', 'try:', 'self._srs', '=', 'gdal.SpatialReference(self.wkt)', 'return', 'self.srs', 'except', 'Exception', 'as', 'e:', 'msg', '=', 'e', 'try:', 'self._srs', '=', 'gdal.SpatialReference(self.proj4text)', 'return', 'self.srs',...
314,983
deepmind/acme
networks.py
make_continuous_networks
make_continuous_networks
Creates PPONetworks to be used for continuous action environments.
[ "Creates", "PPONetworks", "to", "be", "used", "for", "continuous", "action", "environments." ]
def make_continuous_networks(environment_spec: specs.EnvironmentSpec, policy_layer_sizes: Sequence[int]=(64, 64), value_layer_sizes: Sequence[int]=(64, 64), use_tanh_gaussian_policy: bool=True) -> PPONetworks: num_dimensions = np.prod(environment_spec.actions.shape, dtype=int) def forward_fn(inputs: networks_l...
['def', 'make_continuous_networks(environment_spec:', 'specs.EnvironmentSpec,', 'policy_layer_sizes:', 'Sequence[int]=(64,', '64),', 'value_layer_sizes:', 'Sequence[int]=(64,', '64),', 'use_tanh_gaussian_policy:', 'bool=True)', '->', 'PPONetworks:', 'num_dimensions', '=', 'np.prod(environment_spec.actions.shape,', 'dty...
7,643
ZumoLabs/zpy
blender.py
verify_view_layer
verify_view_layer
Get and set the view layer in Blender.
[ "Get", "and", "set", "the", "view", "layer", "in", "Blender." ]
def verify_view_layer(view_layer_name: str='View Layer') -> bpy.types.ViewLayer: scene = zpy.blender.verify_blender_scene() view_layer = scene.view_layers.get(view_layer_name, None) if view_layer is None: log.debug(f'Could not find view layer {view_layer_name}') view_layer = scene.view_layer...
['def', 'verify_view_layer(view_layer_name:', "str='View", "Layer')", '->', 'bpy.types.ViewLayer:', 'scene', '=', 'zpy.blender.verify_blender_scene()', 'view_layer', '=', 'scene.view_layers.get(view_layer_name,', 'None)', 'if', 'view_layer', 'is', 'None:', "log.debug(f'Could", 'not', 'find', 'view', 'layer', "{view_lay...
971,964
myothida/Supervised-Machine-Learning
theme.py
ThemeStack.push_theme
push_theme
Push a theme on the top of the stack.
[ "Push", "a", "theme", "on", "the", "top", "of", "the", "stack." ]
def push_theme(self, theme: Theme, inherit: bool=True) -> None: styles: Dict[str, Style] styles = {**self._entries[-1], **theme.styles} if inherit else theme.styles.copy() self._entries.append(styles) self.get = self._entries[-1].get
['def', 'push_theme(self,', 'theme:', 'Theme,', 'inherit:', 'bool=True)', '->', 'None:', 'styles:', 'Dict[str,', 'Style]', 'styles', '=', '{**self._entries[-1],', '**theme.styles}', 'if', 'inherit', 'else', 'theme.styles.copy()', 'self._entries.append(styles)', 'self.get', '=', 'self._entries[-1].get']
445,144
acrosson/nlp
dureader_eval.py
get_desc_result
get_desc_result
Prepare answers for task 'description'.
[ "Prepare", "answers", "for", "task", "'description'." ]
def get_desc_result(qid, pred_result, ref_result): if ref_result[qid]['question_type'] != 'DESCRIPTION': return (None, None) return get_main_result(qid, pred_result, ref_result)
['def', 'get_desc_result(qid,', 'pred_result,', 'ref_result):', 'if', "ref_result[qid]['question_type']", '!=', "'DESCRIPTION':", 'return', '(None,', 'None)', 'return', 'get_main_result(qid,', 'pred_result,', 'ref_result)']
808,800
eddylau328/fyp-artificial-intelligence-ac-control-device
message_test.py
MessageTest.testExtendFloatWithIterable
testExtendFloatWithIterable
Test extending repeated float fields with iterable.
[ "Test", "extending", "repeated", "float", "fields", "with", "iterable." ]
def testExtendFloatWithIterable(self, message_module): m = message_module.TestAllTypes() self.assertSequenceEqual([], m.repeated_float) m.repeated_float.extend(MessageTest.TestIterable([])) self.assertSequenceEqual([], m.repeated_float) m.repeated_float.extend(MessageTest.TestIterable([0.0])) se...
['def', 'testExtendFloatWithIterable(self,', 'message_module):', 'm', '=', 'message_module.TestAllTypes()', 'self.assertSequenceEqual([],', 'm.repeated_float)', 'm.repeated_float.extend(MessageTest.TestIterable([]))', 'self.assertSequenceEqual([],', 'm.repeated_float)', 'm.repeated_float.extend(MessageTest.TestIterable...
215,344
deepmind/bsuite
agent.py
BootstrappedDqn.update
update
Update the agent: add transition to replay and periodically do SGD.
[ "Update", "the", "agent:", "add", "transition", "to", "replay", "and", "periodically", "do", "SGD." ]
def update(self, timestep: dm_env.TimeStep, action: base.Action, new_timestep: dm_env.TimeStep): if new_timestep.last(): k = np.random.randint(self._num_ensemble) self._active_head = self._ensemble[k] mask = np.random.binomial(1, self._mask_prob, self._num_ensemble) noise = np.random.randn(s...
['def', 'update(self,', 'timestep:', 'dm_env.TimeStep,', 'action:', 'base.Action,', 'new_timestep:', 'dm_env.TimeStep):', 'if', 'new_timestep.last():', 'k', '=', 'np.random.randint(self._num_ensemble)', 'self._active_head', '=', 'self._ensemble[k]', 'mask', '=', 'np.random.binomial(1,', 'self._mask_prob,', 'self._num_e...
410,116
shtamura/maskrcnn
loss.py
rpn_offsets_loss
rpn_offsets_loss
RPNのオフセット回帰の損失関数 positive(gt_fg > 0)データのみ評価対象とする gt_offsets: 正解オフセット [N, R, 4] 3軸目は領域提案とアンカãƒ...
[ "RPNのオフセット回帰の損失関数", "positive(gt_fg", ">", "0)データのみ評価対象とする", "gt_offsets:", "正解オフセット", "[N,", "R,", "4]", "3軸目はé...
def rpn_offsets_loss(gt_offsets, gt_fg, pred_offsets): pos_idx = tf.where(gt_fg > 0) gt_offsets = tf.gather_nd(gt_offsets, pos_idx) pred_offsets = tf.gather_nd(pred_offsets, pos_idx) p = 1.0 loss = p * offsets_loss(gt_offsets, pred_offsets) loss = log.tfprint(loss, 'rpn_offsets_loss') return...
['def', 'rpn_offsets_loss(gt_offsets,', 'gt_fg,', 'pred_offsets):', 'pos_idx', '=', 'tf.where(gt_fg', '>', '0)', 'gt_offsets', '=', 'tf.gather_nd(gt_offsets,', 'pos_idx)', 'pred_offsets', '=', 'tf.gather_nd(pred_offsets,', 'pos_idx)', 'p', '=', '1.0', 'loss', '=', 'p', '*', 'offsets_loss(gt_offsets,', 'pred_offsets)', ...
645,169
ZumoLabs/zpy
color.py
reset
reset
Load colors from file and reset random idx.
[ "Load", "colors", "from", "file", "and", "reset", "random", "idx." ]
def reset(random_color_idx: int=1): global COLORS, RANDOM_COLOR_IDX _path = Path(__file__).parent / COLORS_FILE zpy.files.verify_path(_path) COLORS = zpy.files.read_json(_path) RANDOM_COLOR_IDX = random_color_idx
['def', 'reset(random_color_idx:', 'int=1):', 'global', 'COLORS,', 'RANDOM_COLOR_IDX', '_path', '=', 'Path(__file__).parent', '/', 'COLORS_FILE', 'zpy.files.verify_path(_path)', 'COLORS', '=', 'zpy.files.read_json(_path)', 'RANDOM_COLOR_IDX', '=', 'random_color_idx']
971,995
TensorLab/tensorfx
_job.py
Job.prediction
prediction
Retrieves the prediction graph interface for the job.
[ "Retrieves", "the", "prediction", "graph", "interface", "for", "the", "job." ]
def prediction(self): return self._prediction
['def', 'prediction(self):', 'return', 'self._prediction']
365,951
AtlantixJJ/LinearGAN
util.py
get_dtype_and_ctype
get_dtype_and_ctype
Given a type name string (or an object having a __name__ attribute), return matching Numpy and ctypes types that have the same size in bytes.
[ "Given", "a", "type", "name", "string", "(or", "an", "object", "having", "a", "__name__", "attribute),", "return", "matching", "Numpy", "and", "ctypes", "types", "that", "have", "the", "same", "size", "in", "bytes." ]
def get_dtype_and_ctype(type_obj: Any) -> Tuple[np.dtype, Any]: type_str = None if isinstance(type_obj, str): type_str = type_obj elif hasattr(type_obj, '__name__'): type_str = type_obj.__name__ elif hasattr(type_obj, 'name'): type_str = type_obj.name else: raise Runt...
['def', 'get_dtype_and_ctype(type_obj:', 'Any)', '->', 'Tuple[np.dtype,', 'Any]:', 'type_str', '=', 'None', 'if', 'isinstance(type_obj,', 'str):', 'type_str', '=', 'type_obj', 'elif', 'hasattr(type_obj,', "'__name__'):", 'type_str', '=', 'type_obj.__name__', 'elif', 'hasattr(type_obj,', "'name'):", 'type_str', '=', 'ty...
602,657
RasaHQ/rasa
readerwriter.py
TrainingDataWriter.generate_entity_attributes
generate_entity_attributes
Generates text for the entity attributes.
[ "Generates", "text", "for", "the", "entity", "attributes." ]
def generate_entity_attributes(text: Text, entity: Dict[Text, Any], short_allowed: bool=True) -> Text: entity_text = text entity_type = entity.get(ENTITY_ATTRIBUTE_TYPE) entity_value = entity.get(ENTITY_ATTRIBUTE_VALUE) entity_role = entity.get(ENTITY_ATTRIBUTE_ROLE) entity_group = entity.get(ENTITY...
['def', 'generate_entity_attributes(text:', 'Text,', 'entity:', 'Dict[Text,', 'Any],', 'short_allowed:', 'bool=True)', '->', 'Text:', 'entity_text', '=', 'text', 'entity_type', '=', 'entity.get(ENTITY_ATTRIBUTE_TYPE)', 'entity_value', '=', 'entity.get(ENTITY_ATTRIBUTE_VALUE)', 'entity_role', '=', 'entity.get(ENTITY_ATT...
837,762
nicknochnack/RealTimeSignLanguageTFJS
question_answering.py
QuestionAnsweringTask.set_preprocessed_eval_input_path
set_preprocessed_eval_input_path
Sets the path to the preprocessed eval data.
[ "Sets", "the", "path", "to", "the", "preprocessed", "eval", "data." ]
def set_preprocessed_eval_input_path(self, eval_input_path): self._tf_record_input_path = eval_input_path
['def', 'set_preprocessed_eval_input_path(self,', 'eval_input_path):', 'self._tf_record_input_path', '=', 'eval_input_path']
850,545
feast-dev/feast
test_cli_chdir.py
test_cli_chdir
test_cli_chdir
This test simply makes sure that you can run 'feast --chdir COMMAND' to switch to a feature repository before running a COMMAND.
[ "This", "test", "simply", "makes", "sure", "that", "you", "can", "run", "'feast", "--chdir", "COMMAND'", "to", "switch", "to", "a", "feature", "repository", "before", "running", "a", "COMMAND." ]
def test_cli_chdir() -> None: runner = CliRunner() with tempfile.TemporaryDirectory() as temp_dir: temp_path = Path(temp_dir).resolve() result = runner.run(['init', 'my_project'], cwd=temp_path) repo_path = temp_path / 'my_project' / 'feature_repo' assert result.returncode == 0 ...
['def', 'test_cli_chdir()', '->', 'None:', 'runner', '=', 'CliRunner()', 'with', 'tempfile.TemporaryDirectory()', 'as', 'temp_dir:', 'temp_path', '=', 'Path(temp_dir).resolve()', 'result', '=', "runner.run(['init',", "'my_project'],", 'cwd=temp_path)', 'repo_path', '=', 'temp_path', '/', "'my_project'", '/', "'feature_...
544,614
sek788432/Waymo-2D-Object-Detection
instance_heads.py
MaskHead.call
call
Forward pass of mask branch for the Mask-RCNN model.
[ "Forward", "pass", "of", "mask", "branch", "for", "the", "Mask-RCNN", "model." ]
def call(self, inputs: List[tf.Tensor], training: bool=None): (roi_features, roi_classes) = inputs (batch_size, num_rois, height, width, filters) = roi_features.get_shape().as_list() if batch_size is None: batch_size = tf.shape(roi_features)[0] x = tf.reshape(roi_features, [-1, height, width, fi...
['def', 'call(self,', 'inputs:', 'List[tf.Tensor],', 'training:', 'bool=None):', '(roi_features,', 'roi_classes)', '=', 'inputs', '(batch_size,', 'num_rois,', 'height,', 'width,', 'filters)', '=', 'roi_features.get_shape().as_list()', 'if', 'batch_size', 'is', 'None:', 'batch_size', '=', 'tf.shape(roi_features)[0]', 'x...
973,169
sentinel-hub/eo-learn
test_features_utils.py
test_spatially_resize_image_new_size
test_spatially_resize_image_new_size
Test that all methods and backends are able to downscale and upscale images of various dtypes.
[ "Test", "that", "all", "methods", "and", "backends", "are", "able", "to", "downscale", "and", "upscale", "images", "of", "various", "dtypes." ]
def test_spatially_resize_image_new_size(method: ResizeMethod, library: ResizeLib, dtype: np.dtype | type, new_size: tuple[int, int]): if library is ResizeLib.CV2: if np.issubdtype(dtype, np.integer) and method is ResizeMethod.CUBIC or dtype == bool: return old_shape = (111, 111) data_2d...
['def', 'test_spatially_resize_image_new_size(method:', 'ResizeMethod,', 'library:', 'ResizeLib,', 'dtype:', 'np.dtype', '|', 'type,', 'new_size:', 'tuple[int,', 'int]):', 'if', 'library', 'is', 'ResizeLib.CV2:', 'if', 'np.issubdtype(dtype,', 'np.integer)', 'and', 'method', 'is', 'ResizeMethod.CUBIC', 'or', 'dtype', '=...
562,699
openvinotoolkit/training_extensions
mean_teacher.py
MeanTeacher.forward_dummy
forward_dummy
Dummy forward function for UnbiasedTeacher.
[ "Dummy", "forward", "function", "for", "UnbiasedTeacher." ]
def forward_dummy(self, img, **kwargs): return self.model_s.forward_dummy(img, **kwargs)
['def', 'forward_dummy(self,', 'img,', '**kwargs):', 'return', 'self.model_s.forward_dummy(img,', '**kwargs)']
918,135
rudranil723/mini-main
autopep8.py
fix_lines
fix_lines
Return fixed source code.
[ "Return", "fixed", "source", "code." ]
def fix_lines(source_lines, options, filename=''): original_newline = find_newline(source_lines) tmp_source = ''.join(normalize_line_endings(source_lines, '\n')) previous_hashes = set() if options.line_range: fixed_source = tmp_source else: pep8_options = {'ignore': options.ignore, '...
['def', 'fix_lines(source_lines,', 'options,', "filename=''):", 'original_newline', '=', 'find_newline(source_lines)', 'tmp_source', '=', "''.join(normalize_line_endings(source_lines,", "'\\n'))", 'previous_hashes', '=', 'set()', 'if', 'options.line_range:', 'fixed_source', '=', 'tmp_source', 'else:', 'pep8_options', '...
313,886
interpretml/DiCE
public_data_interface.py
PublicData.get_data_type
get_data_type
Infers data type of a continuous feature from the training data.
[ "Infers", "data", "type", "of", "a", "continuous", "feature", "from", "the", "training", "data." ]
def get_data_type(self, col): if self.data_df[col].dtype == np.int64 or self.data_df[col].dtype == np.int32 or self.data_df[col].dtype == np.int16 or (self.data_df[col].dtype == np.int8): return 'int' elif self.data_df[col].dtype == np.float64 or self.data_df[col].dtype == np.float32 or self.data_df[col...
['def', 'get_data_type(self,', 'col):', 'if', 'self.data_df[col].dtype', '==', 'np.int64', 'or', 'self.data_df[col].dtype', '==', 'np.int32', 'or', 'self.data_df[col].dtype', '==', 'np.int16', 'or', '(self.data_df[col].dtype', '==', 'np.int8):', 'return', "'int'", 'elif', 'self.data_df[col].dtype', '==', 'np.float64', ...
550,190
for-ai/rl
tpu.py
create_host_call
create_host_call
Construct a host_call writing scalar summaries.
[ "Construct", "a", "host_call", "writing", "scalar", "summaries." ]
def create_host_call(model_dir): graph = tf.get_default_graph() summaries = graph.get_collection(tf.GraphKeys.SUMMARIES) gs_t = tf.reshape(tf.to_int32(tf.train.get_global_step()), [1]) summary_kwargs = collections.OrderedDict() for t in summaries: if t.op.type not in ['ScalarSummary']: ...
['def', 'create_host_call(model_dir):', 'graph', '=', 'tf.get_default_graph()', 'summaries', '=', 'graph.get_collection(tf.GraphKeys.SUMMARIES)', 'gs_t', '=', 'tf.reshape(tf.to_int32(tf.train.get_global_step()),', '[1])', 'summary_kwargs', '=', 'collections.OrderedDict()', 'for', 't', 'in', 'summaries:', 'if', 't.op.ty...
860,709
deepmind/dm_control
viewer.py
FreeCameraController.free_look
free_look
Switches the camera to a free-look mode.
[ "Switches", "the", "camera", "to", "a", "free-look", "mode." ]
def free_look(self): if self._active: self._tracked_body_idx = -1 self._update_camera_mode()
['def', 'free_look(self):', 'if', 'self._active:', 'self._tracked_body_idx', '=', '-1', 'self._update_camera_mode()']
166,633
keyonvafa/career-code
layers.py
GlobalAvgPool.forward
forward
Average pooling across time steps (dim=1) with optionally lengths.
[ "Average", "pooling", "across", "time", "steps", "(dim=1)", "with", "optionally", "lengths." ]
def forward(self, x, lengths=None): if lengths is None: return x.mean(dim=1, keepdim=False) else: mask = get_mask_from_lengths(lengths).type(x.type()).to(x.device) mask_shape = list(mask.size()) + [1 for _ in range(x.ndimension() - 2)] mask = mask.reshape(*mask_shape) num...
['def', 'forward(self,', 'x,', 'lengths=None):', 'if', 'lengths', 'is', 'None:', 'return', 'x.mean(dim=1,', 'keepdim=False)', 'else:', 'mask', '=', 'get_mask_from_lengths(lengths).type(x.type()).to(x.device)', 'mask_shape', '=', 'list(mask.size())', '+', '[1', 'for', '_', 'in', 'range(x.ndimension()', '-', '2)]', 'mask...
455,074
JesperChristensen89/object_detection_benchmarking
faster_rcnn_meta_arch.py
FasterRCNNMetaArch.restore_fn
restore_fn
Returns callable for loading a checkpoint into the tensorflow graph.
[ "Returns", "callable", "for", "loading", "a", "checkpoint", "into", "the", "tensorflow", "graph." ]
def restore_fn(self, checkpoint_path, from_detection_checkpoint=True): if not from_detection_checkpoint: return self._feature_extractor.restore_from_classification_checkpoint_fn(checkpoint_path, self.first_stage_feature_extractor_scope, self.second_stage_feature_extractor_scope) variables_to_restore = t...
['def', 'restore_fn(self,', 'checkpoint_path,', 'from_detection_checkpoint=True):', 'if', 'not', 'from_detection_checkpoint:', 'return', 'self._feature_extractor.restore_from_classification_checkpoint_fn(checkpoint_path,', 'self.first_stage_feature_extractor_scope,', 'self.second_stage_feature_extractor_scope)', 'varia...
794,368
ryu-ed/SpaceInvaders_Ros
math2html.py
FontFunction.process
process
Simplify if possible using a single character.
[ "Simplify", "if", "possible", "using", "a", "single", "character." ]
def process(self): self.type = 'font' self.simplifyifpossible()
['def', 'process(self):', 'self.type', '=', "'font'", 'self.simplifyifpossible()']
395,307
hamza-murad/AALU
assistant_v1.py
ValueCollection.from_dict
from_dict
Initialize a ValueCollection object from a json dictionary.
[ "Initialize", "a", "ValueCollection", "object", "from", "a", "json", "dictionary." ]
def from_dict(cls, _dict: Dict) -> 'ValueCollection': args = {} valid_keys = ['values', 'pagination'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError('Unrecognized keys detected in dictionary for class ValueCollection: ' + ', '.join(bad_keys)) if 'values' in _dic...
['def', 'from_dict(cls,', '_dict:', 'Dict)', '->', "'ValueCollection':", 'args', '=', '{}', 'valid_keys', '=', "['values',", "'pagination']", 'bad_keys', '=', 'set(_dict.keys())', '-', 'set(valid_keys)', 'if', 'bad_keys:', 'raise', "ValueError('Unrecognized", 'keys', 'detected', 'in', 'dictionary', 'for', 'class', 'Val...
5,268
43Carrig/recurrent_neural_networks_practice
math_ops.py
div_no_nan
div_no_nan
Computes an unsafe divide which returns 0 if the y is zero.
[ "Computes", "an", "unsafe", "divide", "which", "returns", "0", "if", "the", "y", "is", "zero." ]
def div_no_nan(x, y, name=None): with ops.name_scope(name, 'div_no_nan', [x, y]) as name: x = ops.convert_to_tensor(x, name='x') y = ops.convert_to_tensor(y, name='y', dtype=x.dtype.base_dtype) x_dtype = x.dtype.base_dtype y_dtype = y.dtype.base_dtype if x_dtype != y_dtype: ...
['def', 'div_no_nan(x,', 'y,', 'name=None):', 'with', 'ops.name_scope(name,', "'div_no_nan',", '[x,', 'y])', 'as', 'name:', 'x', '=', 'ops.convert_to_tensor(x,', "name='x')", 'y', '=', 'ops.convert_to_tensor(y,', "name='y',", 'dtype=x.dtype.base_dtype)', 'x_dtype', '=', 'x.dtype.base_dtype', 'y_dtype', '=', 'y.dtype.ba...
338,808
omonimus1/super-computer-
libpython.py
PythonCodeExecutor.incref
incref
Increment the reference count of a Python object in the inferior.
[ "Increment", "the", "reference", "count", "of", "a", "Python", "object", "in", "the", "inferior." ]
def incref(self, pointer): gdb.parse_and_eval('Py_IncRef((PyObject *) %d)' % pointer)
['def', 'incref(self,', 'pointer):', "gdb.parse_and_eval('Py_IncRef((PyObject", '*)', "%d)'", '%', 'pointer)']
912,969
Suor/sublime-reform
viewtools.py
expand_min_gap
expand_min_gap
Expands region so that it will cover minimum gap of empty lines around it.
[ "Expands", "region", "so", "that", "it", "will", "cover", "minimum", "gap", "of", "empty", "lines", "around", "it." ]
def expand_min_gap(view, region): empty_lines = view.find_all('^\\s*\\n') empty_neighbours = [r for r in empty_lines if r.end() == region.begin() or r.begin() == region.end()] if not empty_neighbours: return region elif len(empty_neighbours) == 1: if is_view_bordering(view, region): ...
['def', 'expand_min_gap(view,', 'region):', 'empty_lines', '=', "view.find_all('^\\\\s*\\\\n')", 'empty_neighbours', '=', '[r', 'for', 'r', 'in', 'empty_lines', 'if', 'r.end()', '==', 'region.begin()', 'or', 'r.begin()', '==', 'region.end()]', 'if', 'not', 'empty_neighbours:', 'return', 'region', 'elif', 'len(empty_nei...
359,991
famura/SimuRLacra
base.py
Task.rew_fcn
rew_fcn
Get the reward function.
[ "Get", "the", "reward", "function." ]
def rew_fcn(self) -> RewFcn: raise NotImplementedError
['def', 'rew_fcn(self)', '->', 'RewFcn:', 'raise', 'NotImplementedError']
883,997
Trusted-AI/AIX360
utils.py
common_trunk_tree_to_digraph
common_trunk_tree_to_digraph
returns a networkx digraph from the common trunk tree dictionary (jst).
[ "returns", "a", "networkx", "digraph", "from", "the", "common", "trunk", "tree", "dictionary", "(jst)." ]
def common_trunk_tree_to_digraph(root: dict): T = nx.DiGraph() color1 = 'lightpink' color2 = 'lightsalmon' leaf_colors = ['antiquewhite', 'lightcyan', 'grey70', 'antiquewhite3', 'aquamarine', 'floralwhite'] def _recurse(root, parentid, direction, style='', fillcolor='lightgrey'): vnum = T.n...
['def', 'common_trunk_tree_to_digraph(root:', 'dict):', 'T', '=', 'nx.DiGraph()', 'color1', '=', "'lightpink'", 'color2', '=', "'lightsalmon'", 'leaf_colors', '=', "['antiquewhite',", "'lightcyan',", "'grey70',", "'antiquewhite3',", "'aquamarine',", "'floralwhite']", 'def', '_recurse(root,', 'parentid,', 'direction,', ...
413,279
TensorLab/tensorfx
_config.py
Configuration.create_server
create_server
Creates the TensorFlow server, which is required for distributed training.
[ "Creates", "the", "TensorFlow", "server,", "which", "is", "required", "for", "distributed", "training." ]
def create_server(self): if not self.distributed: return None return tf.train.Server(self._cluster, self._task.type, self._task.index, protocol='grpc')
['def', 'create_server(self):', 'if', 'not', 'self.distributed:', 'return', 'None', 'return', 'tf.train.Server(self._cluster,', 'self._task.type,', 'self._task.index,', "protocol='grpc')"]
365,941
facebookresearch/CompilerGym
testing.py
Testing.benchmark_uris_iterator
benchmark_uris_iterator
Return an iterator over the test benchmark URIs.
[ "Return", "an", "iterator", "over", "the", "test", "benchmark", "URIs." ]
def benchmark_uris_iterator(self, env: CompilerEnv) -> Iterable[str]: for _ in range(self.runs_per_benchmark): for bm in self.benchmarks: yield from bm.benchmark_uris_iterator(env)
['def', 'benchmark_uris_iterator(self,', 'env:', 'CompilerEnv)', '->', 'Iterable[str]:', 'for', '_', 'in', 'range(self.runs_per_benchmark):', 'for', 'bm', 'in', 'self.benchmarks:', 'yield', 'from', 'bm.benchmark_uris_iterator(env)']
135,692
43Carrig/recurrent_neural_networks_practice
train.py
get_sequential_train_hooks
get_sequential_train_hooks
Returns a hooks function for sequential GAN training.
[ "Returns", "a", "hooks", "function", "for", "sequential", "GAN", "training." ]
def get_sequential_train_hooks(train_steps=namedtuples.GANTrainSteps(1, 1)): def get_hooks(train_ops): generator_hook = RunTrainOpsHook(train_ops.generator_train_op, train_steps.generator_train_steps) discriminator_hook = RunTrainOpsHook(train_ops.discriminator_train_op, train_steps.discriminator_t...
['def', 'get_sequential_train_hooks(train_steps=namedtuples.GANTrainSteps(1,', '1)):', 'def', 'get_hooks(train_ops):', 'generator_hook', '=', 'RunTrainOpsHook(train_ops.generator_train_op,', 'train_steps.generator_train_steps)', 'discriminator_hook', '=', 'RunTrainOpsHook(train_ops.discriminator_train_op,', 'train_step...
313,159
apeterswu/RL4NMT
common_attention.py
local_attention_2d
local_attention_2d
strided block local self-attention.
[ "strided", "block", "local", "self-attention." ]
def local_attention_2d(q, k, v, query_shape=(8, 16), memory_flange=(8, 16), name=None): with tf.variable_scope(name, default_name='local_self_attention_2d', values=[q, k, v]): q_shape = q.get_shape().as_list() v_shape = tf.shape(v) q = pad_to_multiple_2d(q, query_shape) k = pad_to_mu...
['def', 'local_attention_2d(q,', 'k,', 'v,', 'query_shape=(8,', '16),', 'memory_flange=(8,', '16),', 'name=None):', 'with', 'tf.variable_scope(name,', "default_name='local_self_attention_2d',", 'values=[q,', 'k,', 'v]):', 'q_shape', '=', 'q.get_shape().as_list()', 'v_shape', '=', 'tf.shape(v)', 'q', '=', 'pad_to_multip...
331,461
Farama-Foundation/Gymnasium
step_api_compatibility.py
convert_to_done_step_api
convert_to_done_step_api
Function to transform step returns to old step API irrespective of input API.
[ "Function", "to", "transform", "step", "returns", "to", "old", "step", "API", "irrespective", "of", "input", "API." ]
def convert_to_done_step_api(step_returns: Union[TerminatedTruncatedStepType, DoneStepType], is_vector_env: bool=False) -> DoneStepType: if len(step_returns) == 4: return step_returns else: assert len(step_returns) == 5 (observations, rewards, terminated, truncated, infos) = step_returns...
['def', 'convert_to_done_step_api(step_returns:', 'Union[TerminatedTruncatedStepType,', 'DoneStepType],', 'is_vector_env:', 'bool=False)', '->', 'DoneStepType:', 'if', 'len(step_returns)', '==', '4:', 'return', 'step_returns', 'else:', 'assert', 'len(step_returns)', '==', '5', '(observations,', 'rewards,', 'terminated,...
573,323
mj-will/nessai
test_flowsampler.py
test_init_signal_handling_error
test_init_signal_handling_error
Assert signal handling is skipped if an error is raised.
[ "Assert", "signal", "handling", "is", "skipped", "if", "an", "error", "is", "raised." ]
def test_init_signal_handling_error(flow_sampler, tmp_path, caplog): integration_model = MagicMock() output = tmp_path / 'test' output.mkdir() output = str(output) with patch('signal.signal', side_effect=AttributeError): FlowSampler.__init__(flow_sampler, integration_model, output=output, si...
['def', 'test_init_signal_handling_error(flow_sampler,', 'tmp_path,', 'caplog):', 'integration_model', '=', 'MagicMock()', 'output', '=', 'tmp_path', '/', "'test'", 'output.mkdir()', 'output', '=', 'str(output)', 'with', "patch('signal.signal',", 'side_effect=AttributeError):', 'FlowSampler.__init__(flow_sampler,', 'in...
292,230
tanvirrazin/Machine-Learning-A-Z-Udemy
apyori.py
TransactionManager.num_transaction
num_transaction
Returns the number of transactions.
[ "Returns", "the", "number", "of", "transactions." ]
def num_transaction(self): return self.__num_transaction
['def', 'num_transaction(self):', 'return', 'self.__num_transaction']
620,514
rudranil723/mini-main
base.py
ExtensionArray.nbytes
nbytes
The number of bytes needed to store this object in memory.
[ "The", "number", "of", "bytes", "needed", "to", "store", "this", "object", "in", "memory." ]
def nbytes(self) -> int: raise AbstractMethodError(self)
['def', 'nbytes(self)', '->', 'int:', 'raise', 'AbstractMethodError(self)']
323,415
43Carrig/recurrent_neural_networks_practice
gen_data_flow_ops.py
random_shuffle_queue_v2
random_shuffle_queue_v2
A queue that randomizes the order of elements.
[ "A", "queue", "that", "randomizes", "the", "order", "of", "elements." ]
def random_shuffle_queue_v2(component_types, shapes=[], capacity=-1, min_after_dequeue=0, seed=0, seed2=0, container='', shared_name='', name=None): _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if not isinstance(component_types, (list, tuple)): raise TypeErro...
['def', 'random_shuffle_queue_v2(component_types,', 'shapes=[],', 'capacity=-1,', 'min_after_dequeue=0,', 'seed=0,', 'seed2=0,', "container='',", "shared_name='',", 'name=None):', '_ctx', '=', '_context._context', 'if', '_ctx', 'is', 'None', 'or', 'not', '_ctx._eager_context.is_eager:', 'if', 'not', 'isinstance(compone...
337,756
quantumiracle/Benchmark-Efficient-Reinforcement--with-Demonstrations
logger.py
log
log
Write the sequence of args, with no separators, to the console and output files (if you've configured an output file).
[ "Write", "the", "sequence", "of", "args,", "with", "no", "separators,", "to", "the", "console", "and", "output", "files", "(if", "you've", "configured", "an", "output", "file)." ]
def log(*args, level=INFO): Logger.CURRENT.log(*args, level=level)
['def', 'log(*args,', 'level=INFO):', 'Logger.CURRENT.log(*args,', 'level=level)']
432,656
rudranil723/mini-main
interval.py
IntervalArray.left
left
Return the left endpoints of each Interval in the IntervalArray as an Index.
[ "Return", "the", "left", "endpoints", "of", "each", "Interval", "in", "the", "IntervalArray", "as", "an", "Index." ]
def left(self): from pandas import Index return Index(self._left, copy=False)
['def', 'left(self):', 'from', 'pandas', 'import', 'Index', 'return', 'Index(self._left,', 'copy=False)']
323,498
HDI-Project/ATM
database.py
Database.get_hyperpartition
get_hyperpartition
Get a specific classifier.
[ "Get", "a", "specific", "classifier." ]
def get_hyperpartition(self, hyperpartition_id): return self.session.query(self.Hyperpartition).get(hyperpartition_id)
['def', 'get_hyperpartition(self,', 'hyperpartition_id):', 'return', 'self.session.query(self.Hyperpartition).get(hyperpartition_id)']
402,681
43Carrig/recurrent_neural_networks_practice
device_setter.py
_ReplicaDeviceChooser.device_function
device_function
Choose a device for `op`.
[ "Choose", "a", "device", "for", "`op`." ]
def device_function(self, op): if not self._merge_devices and op.device: return op.device current_device = pydev.DeviceSpec.from_string(op.device or '') node_def = op if isinstance(op, node_def_pb2.NodeDef) else op.node_def if self._ps_tasks and self._ps_device and (node_def.op in self._ps_ops):...
['def', 'device_function(self,', 'op):', 'if', 'not', 'self._merge_devices', 'and', 'op.device:', 'return', 'op.device', 'current_device', '=', 'pydev.DeviceSpec.from_string(op.device', 'or', "'')", 'node_def', '=', 'op', 'if', 'isinstance(op,', 'node_def_pb2.NodeDef)', 'else', 'op.node_def', 'if', 'self._ps_tasks', 'a...
339,542
jshilong/DDQ
base_semantic_head.py
BaseSemanticHead.loss
loss
Get the loss of semantic head.
[ "Get", "the", "loss", "of", "semantic", "head." ]
def loss(self, seg_preds, gt_semantic_seg): if seg_preds.shape[-2:] != gt_semantic_seg.shape[-2:]: seg_preds = interpolate_as(seg_preds, gt_semantic_seg) seg_preds = seg_preds.permute((0, 2, 3, 1)) loss_seg = self.loss_seg(seg_preds.reshape(-1, self.num_classes), gt_semantic_seg.reshape(-1).long()) ...
['def', 'loss(self,', 'seg_preds,', 'gt_semantic_seg):', 'if', 'seg_preds.shape[-2:]', '!=', 'gt_semantic_seg.shape[-2:]:', 'seg_preds', '=', 'interpolate_as(seg_preds,', 'gt_semantic_seg)', 'seg_preds', '=', 'seg_preds.permute((0,', '2,', '3,', '1))', 'loss_seg', '=', 'self.loss_seg(seg_preds.reshape(-1,', 'self.num_c...
516,268
salu133445/bmusegan
components.py
Component.get_summary
get_summary
Return the summary string.
[ "Return", "the", "summary", "string." ]
def get_summary(self): cleansed_nets = [] for net in self.nets.values(): if isinstance(net, NeuralNet): if net.scope is not None: cleansed_nets.append(net) if isinstance(net, list): if net[0].scope is not None: cleansed_nets.append(net[0]) ...
['def', 'get_summary(self):', 'cleansed_nets', '=', '[]', 'for', 'net', 'in', 'self.nets.values():', 'if', 'isinstance(net,', 'NeuralNet):', 'if', 'net.scope', 'is', 'not', 'None:', 'cleansed_nets.append(net)', 'if', 'isinstance(net,', 'list):', 'if', 'net[0].scope', 'is', 'not', 'None:', 'cleansed_nets.append(net[0])'...
461,851
TARGET-SIDE-DATA-AUG/TSDASG
alignment_utils.py
align_features_to_words
align_features_to_words
Align given features to words.
[ "Align", "given", "features", "to", "words." ]
def align_features_to_words(roberta, features, alignment): assert features.dim() == 2 bpe_counts = Counter((j for bpe_indices in alignment for j in bpe_indices)) assert bpe_counts[0] == 0 denom = features.new([bpe_counts.get(j, 1) for j in range(len(features))]) weighted_features = features / denom....
['def', 'align_features_to_words(roberta,', 'features,', 'alignment):', 'assert', 'features.dim()', '==', '2', 'bpe_counts', '=', 'Counter((j', 'for', 'bpe_indices', 'in', 'alignment', 'for', 'j', 'in', 'bpe_indices))', 'assert', 'bpe_counts[0]', '==', '0', 'denom', '=', 'features.new([bpe_counts.get(j,', '1)', 'for', ...
952,184
AgnostiqHQ/covalent
devices_base.py
QiskitSamplerDevice.set_distribution
set_distribution
Set the current quasi-distribution for statistics computations.
[ "Set", "the", "current", "quasi-distribution", "for", "statistics", "computations." ]
def set_distribution(self, quasi_dist): self._current_quasi_dist = quasi_dist try: yield finally: self._current_quasi_dist = None
['def', 'set_distribution(self,', 'quasi_dist):', 'self._current_quasi_dist', '=', 'quasi_dist', 'try:', 'yield', 'finally:', 'self._current_quasi_dist', '=', 'None']
489,413
mideind/GreynirServer
test_queries.py
qmcall
qmcall
Use passed client object to call query API with query string key value pairs provided in dict arg.
[ "Use", "passed", "client", "object", "to", "call", "query", "API", "with", "query", "string", "key", "value", "pairs", "provided", "in", "dict", "arg." ]
def qmcall(c: FlaskClient, qdict: Dict[str, Any], qtype: Optional[str]=None) -> ResponseDict: assert isinstance(c, FlaskClient) if 'test' not in qdict: qdict['test'] = True if 'private' not in qdict: qdict['private'] = True if 'client_id' not in qdict: qdict['client_id'] = DUMMY_...
['def', 'qmcall(c:', 'FlaskClient,', 'qdict:', 'Dict[str,', 'Any],', 'qtype:', 'Optional[str]=None)', '->', 'ResponseDict:', 'assert', 'isinstance(c,', 'FlaskClient)', 'if', "'test'", 'not', 'in', 'qdict:', "qdict['test']", '=', 'True', 'if', "'private'", 'not', 'in', 'qdict:', "qdict['private']", '=', 'True', 'if', "'...
581,324
RasaHQ/rasa
io.py
WriteRow.writerow
writerow
Write the given row.
[ "Write", "the", "given", "row." ]
def writerow(self, row: List[Text]) -> None: ...
['def', 'writerow(self,', 'row:', 'List[Text])', '->', 'None:', '...']
837,869
OpenMDAO/OpenMDAO-Framework
hasparameters.py
Parameter.get_low
get_low
Returns lower limits as a sequence.
[ "Returns", "lower", "limits", "as", "a", "sequence." ]
def get_low(self): return [self.low]
['def', 'get_low(self):', 'return', '[self.low]']
275,781
TonyLianLong/VAI-ReinforcementLearning
wrappers.py
MjModelWrapper.dof_damping
dof_damping
damping coefficient (nv x 1).
[ "damping", "coefficient", "(nv", "x", "1)." ]
def dof_damping(self): return util.buf_to_npy(self._ptr.contents.dof_damping, (self.nv,))
['def', 'dof_damping(self):', 'return', 'util.buf_to_npy(self._ptr.contents.dof_damping,', '(self.nv,))']
440,279
lzfelix/bag-of-samplings
plot_learning_curves.py
plot_metric_evolution
plot_metric_evolution
Shorthand function to plot metrics with their stds.
[ "Shorthand", "function", "to", "plot", "metrics", "with", "their", "stds." ]
def plot_metric_evolution(x, means, stds, metric, color, fmt='-', label=None): label = label or metric.capitalize() plot_with_std(x, means[metric], stds[metric] + 0.01, label, color, fmt)
['def', 'plot_metric_evolution(x,', 'means,', 'stds,', 'metric,', 'color,', "fmt='-',", 'label=None):', 'label', '=', 'label', 'or', 'metric.capitalize()', 'plot_with_std(x,', 'means[metric],', 'stds[metric]', '+', '0.01,', 'label,', 'color,', 'fmt)']
94,017
openvinotoolkit/training_extensions
base_task.py
OTXTask.evaluate
evaluate
Evaluate function of OTX Task.
[ "Evaluate", "function", "of", "OTX", "Task." ]
def evaluate(self, output_resultset: ResultSetEntity, evaluation_metric: Optional[str]=None): raise NotImplementedError
['def', 'evaluate(self,', 'output_resultset:', 'ResultSetEntity,', 'evaluation_metric:', 'Optional[str]=None):', 'raise', 'NotImplementedError']
917,989
thaines/helit
corpus.py
Corpus.getAlphaMult
getAlphaMult
Returns the current alpha multiplier.
[ "Returns", "the", "current", "alpha", "multiplier." ]
def getAlphaMult(self): return self.alphaMult
['def', 'getAlphaMult(self):', 'return', 'self.alphaMult']
592,049
tensorly/quantum
differentiator_test.py
DifferentiatorTest.test_subclass
test_subclass
Test that the BaseDifferentiator can be subclassed.
[ "Test", "that", "the", "BaseDifferentiator", "can", "be", "subclassed." ]
def test_subclass(self): WorkingDifferentiator()
['def', 'test_subclass(self):', 'WorkingDifferentiator()']
835,196
ucas-vg/PointTinyBenchmark
utils.py
ort_validate
ort_validate
Validate the output of the onnxruntime backend is the same as the output generated by torch.
[ "Validate", "the", "output", "of", "the", "onnxruntime", "backend", "is", "the", "same", "as", "the", "output", "generated", "by", "torch." ]
def ort_validate(model, feats, onnx_io='tmp.onnx'): if isinstance(model, nn.Module): wrap_model = model else: wrap_model = WrapFunction(model) wrap_model.cpu().eval() with torch.no_grad(): torch.onnx.export(wrap_model, feats, onnx_io, export_params=True, keep_initializers_as_inpu...
['def', 'ort_validate(model,', 'feats,', "onnx_io='tmp.onnx'):", 'if', 'isinstance(model,', 'nn.Module):', 'wrap_model', '=', 'model', 'else:', 'wrap_model', '=', 'WrapFunction(model)', 'wrap_model.cpu().eval()', 'with', 'torch.no_grad():', 'torch.onnx.export(wrap_model,', 'feats,', 'onnx_io,', 'export_params=True,', '...
781,946
filerock/FileRock-Client
ProofManager.py
ProofManager.flushOperationList
flushOperationList
Empties the operations list.
[ "Empties", "the", "operations", "list." ]
def flushOperationList(self): self.operations = []
['def', 'flushOperationList(self):', 'self.operations', '=', '[]']
180,168
zihuitang/medical_AI_platform
ssl.py
SSLObject.selected_npn_protocol
selected_npn_protocol
Return the currently selected NPN protocol as a string, or ``None`` if a next protocol was not negotiated or if NPN is not supported by one of the peers.
[ "Return", "the", "currently", "selected", "NPN", "protocol", "as", "a", "string,", "or", "``None``", "if", "a", "next", "protocol", "was", "not", "negotiated", "or", "if", "NPN", "is", "not", "supported", "by", "one", "of", "the", "peers." ]
def selected_npn_protocol(self): if _ssl.HAS_NPN: return self._sslobj.selected_npn_protocol()
['def', 'selected_npn_protocol(self):', 'if', '_ssl.HAS_NPN:', 'return', 'self._sslobj.selected_npn_protocol()']
281,453
43Carrig/recurrent_neural_networks_practice
array_ops.py
rank_internal
rank_internal
Returns the rank of a tensor.
[ "Returns", "the", "rank", "of", "a", "tensor." ]
def rank_internal(input, name=None, optimize=True): with ops.name_scope(name, 'Rank', [input]) as name: if isinstance(input, (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue)): return gen_array_ops.size(input.dense_shape, name=name) else: input_tensor = ops.conver...
['def', 'rank_internal(input,', 'name=None,', 'optimize=True):', 'with', 'ops.name_scope(name,', "'Rank',", '[input])', 'as', 'name:', 'if', 'isinstance(input,', '(sparse_tensor.SparseTensor,', 'sparse_tensor.SparseTensorValue)):', 'return', 'gen_array_ops.size(input.dense_shape,', 'name=name)', 'else:', 'input_tensor'...
337,075
KalleHallden/InstaAutomator
_tifffile.py
imagej_metadata
imagej_metadata
Return dictionary from ImageJ metadata tag value.
[ "Return", "dictionary", "from", "ImageJ", "metadata", "tag", "value." ]
def imagej_metadata(data, bytecounts, byteorder): _str = str if sys.version_info[0] < 3 else lambda x: str(x, 'cp1252') def read_string(data, byteorder): return _str(stripnull(data[0 if byteorder == '<' else 1::2])) def read_double(data, byteorder): return struct.unpack(byteorder + 'd' * (...
['def', 'imagej_metadata(data,', 'bytecounts,', 'byteorder):', '_str', '=', 'str', 'if', 'sys.version_info[0]', '<', '3', 'else', 'lambda', 'x:', 'str(x,', "'cp1252')", 'def', 'read_string(data,', 'byteorder):', 'return', '_str(stripnull(data[0', 'if', 'byteorder', '==', "'<'", 'else', '1::2]))', 'def', 'read_double(da...
230,015
LIX-shape-analysis/SURFMNet
loss_DFMnet.py
penalty_ortho
penalty_ortho
Orthogonal constraint on the functional map implying that the underlying map T is area-preserving.
[ "Orthogonal", "constraint", "on", "the", "functional", "map", "implying", "that", "the", "underlying", "map", "T", "is", "area-preserving." ]
def penalty_ortho(C_est): return tf.nn.l2_loss(tf.subtract(tf.matmul(tf.transpose(C_est, perm=[0, 2, 1]), C_est), tf.eye(tf.shape(C_est)[1])))
['def', 'penalty_ortho(C_est):', 'return', 'tf.nn.l2_loss(tf.subtract(tf.matmul(tf.transpose(C_est,', 'perm=[0,', '2,', '1]),', 'C_est),', 'tf.eye(tf.shape(C_est)[1])))']
365,002
BlissChapman/ICW-fMRI-GAN
test_base.py
TestBase.setUp
setUp
Create a new Dataset and add features.
[ "Create", "a", "new", "Dataset", "and", "add", "features." ]
def setUp(self): self.dataset = get_test_dataset() self.real_dataset = get_test_dataset(prefix='test_real')
['def', 'setUp(self):', 'self.dataset', '=', 'get_test_dataset()', 'self.real_dataset', '=', "get_test_dataset(prefix='test_real')"]
597,106
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
thinkstats2.py
Residuals
Residuals
Computes residuals for a linear fit with parameters inter and slope.
[ "Computes", "residuals", "for", "a", "linear", "fit", "with", "parameters", "inter", "and", "slope." ]
def Residuals(xs, ys, inter, slope): xs = np.asarray(xs) ys = np.asarray(ys) res = ys - (inter + slope * xs) return res
['def', 'Residuals(xs,', 'ys,', 'inter,', 'slope):', 'xs', '=', 'np.asarray(xs)', 'ys', '=', 'np.asarray(ys)', 'res', '=', 'ys', '-', '(inter', '+', 'slope', '*', 'xs)', 'return', 'res']
19,902
cqlengine/cqlengine
test_queryset.py
TestMinMaxTimeUUIDFunctions.test_tzaware_datetime_support
test_tzaware_datetime_support
Test that using timezone aware datetime instances works with the MinTimeUUID/MaxTimeUUID functions.
[ "Test", "that", "using", "timezone", "aware", "datetime", "instances", "works", "with", "the", "MinTimeUUID/MaxTimeUUID", "functions." ]
def test_tzaware_datetime_support(self): pk = uuid4() midpoint_utc = datetime.utcnow().replace(tzinfo=TzOffset(0)) midpoint_helsinki = midpoint_utc.astimezone(TzOffset(3)) assert midpoint_utc.utctimetuple() == midpoint_helsinki.utctimetuple() assert midpoint_utc.timetuple() != midpoint_helsinki.time...
['def', 'test_tzaware_datetime_support(self):', 'pk', '=', 'uuid4()', 'midpoint_utc', '=', 'datetime.utcnow().replace(tzinfo=TzOffset(0))', 'midpoint_helsinki', '=', 'midpoint_utc.astimezone(TzOffset(3))', 'assert', 'midpoint_utc.utctimetuple()', '==', 'midpoint_helsinki.utctimetuple()', 'assert', 'midpoint_utc.timetup...
138,403
DPerrySvendsen/COS30002
entities.py
Planet.copy
copy
Provides a copy of the Planet instance.
[ "Provides", "a", "copy", "of", "the", "Planet", "instance." ]
def copy(self): p = Planet(self.x, self.y, self.id, self.owner_id, self.num_ships, self.growth_rate) p.was_battle = self.was_battle return p
['def', 'copy(self):', 'p', '=', 'Planet(self.x,', 'self.y,', 'self.id,', 'self.owner_id,', 'self.num_ships,', 'self.growth_rate)', 'p.was_battle', '=', 'self.was_battle', 'return', 'p']
137,523
yogeshbalaji/InvGAN
attack_bundling.py
AttackGoal.get_attack_config
get_attack_config
Returns an AttackConfig to run on the next batch.
[ "Returns", "an", "AttackConfig", "to", "run", "on", "the", "next", "batch." ]
def get_attack_config(self, attack_configs, run_counts, criteria): raise NotImplementedError(str(type(self)) + ' needs to implement get_attack_config')
['def', 'get_attack_config(self,', 'attack_configs,', 'run_counts,', 'criteria):', 'raise', 'NotImplementedError(str(type(self))', '+', "'", 'needs', 'to', 'implement', "get_attack_config')"]
576,540
SergiosKar/Deep-Learning-models
preprocess_imagenet.py
download_dataset
download_dataset
Download the Imagenet dataset into the temporary directory.
[ "Download", "the", "Imagenet", "dataset", "into", "the", "temporary", "directory." ]
def download_dataset(raw_data_dir): def _download(url, filename): urllib.request.urlretrieve(url, filename) def _get_members(filename): tar = tarfile.open(filename) members = tar.getmembers() tar.close() return members def _untar_file(filename, directory, member=No...
['def', 'download_dataset(raw_data_dir):', 'def', '_download(url,', 'filename):', 'urllib.request.urlretrieve(url,', 'filename)', 'def', '_get_members(filename):', 'tar', '=', 'tarfile.open(filename)', 'members', '=', 'tar.getmembers()', 'tar.close()', 'return', 'members', 'def', '_untar_file(filename,', 'directory,', ...
518,800