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 |
|---|---|---|---|---|---|---|---|---|
simoncadman/CUPS-Cloud-Print | client.py | OAuth2WebServerFlow.step1_get_authorize_url | step1_get_authorize_url | Returns a URI to redirect to the provider. | [
"Returns",
"a",
"URI",
"to",
"redirect",
"to",
"the",
"provider."
] | def step1_get_authorize_url(self, redirect_uri=None):
if redirect_uri is not None:
logger.warning('The redirect_uri parameter for OAuth2WebServerFlow.step1_get_authorize_url is deprecated. Please move to passing the redirect_uri in via the constructor.')
self.redirect_uri = redirect_uri
if self.... | ['def', 'step1_get_authorize_url(self,', 'redirect_uri=None):', 'if', 'redirect_uri', 'is', 'not', 'None:', "logger.warning('The", 'redirect_uri', 'parameter', 'for', 'OAuth2WebServerFlow.step1_get_authorize_url', 'is', 'deprecated.', 'Please', 'move', 'to', 'passing', 'the', 'redirect_uri', 'in', 'via', 'the', "constr... | 197,441 |
google-research/tensor2robot | meta_example.py | append_example | append_example | Add episode Example to Meta TFExample with a prefix. | [
"Add",
"episode",
"Example",
"to",
"Meta",
"TFExample",
"with",
"a",
"prefix."
] | def append_example(example, ep_example, prefix):
context_feature_map = example.features.feature
for (key, feature) in six.iteritems(ep_example.features.feature):
context_feature_map[six.ensure_str(prefix) + '/' + six.ensure_str(key)].CopyFrom(feature) | ['def', 'append_example(example,', 'ep_example,', 'prefix):', 'context_feature_map', '=', 'example.features.feature', 'for', '(key,', 'feature)', 'in', 'six.iteritems(ep_example.features.feature):', 'context_feature_map[six.ensure_str(prefix)', '+', "'/'", '+', 'six.ensure_str(key)].CopyFrom(feature)'] | 908,177 |
replit-archive/empythoned | test_urllib.py | urlretrieve_FileTests.createNewTempFile | createNewTempFile | Creates a new temporary file containing the specified data, registers the file for deletion during the test fixture tear down, and returns the absolute path of the file. | [
"Creates",
"a",
"new",
"temporary",
"file",
"containing",
"the",
"specified",
"data,",
"registers",
"the",
"file",
"for",
"deletion",
"during",
"the",
"test",
"fixture",
"tear",
"down,",
"and",
"returns",
"the",
"absolute",
"path",
"of",
"the",
"file."
] | def createNewTempFile(self, data=''):
(newFd, newFilePath) = tempfile.mkstemp()
try:
self.registerFileForCleanUp(newFilePath)
newFile = os.fdopen(newFd, 'wb')
newFile.write(data)
newFile.close()
finally:
try:
newFile.close()
except:
pas... | ['def', 'createNewTempFile(self,', "data=''):", '(newFd,', 'newFilePath)', '=', 'tempfile.mkstemp()', 'try:', 'self.registerFileForCleanUp(newFilePath)', 'newFile', '=', 'os.fdopen(newFd,', "'wb')", 'newFile.write(data)', 'newFile.close()', 'finally:', 'try:', 'newFile.close()', 'except:', 'pass', 'return', 'newFilePat... | 177,847 |
sunishsheth2009/ChatterBot | visitors.py | traverse | traverse | traverse and visit the given expression structure using the default iterator. | [
"traverse",
"and",
"visit",
"the",
"given",
"expression",
"structure",
"using",
"the",
"default",
"iterator."
] | def traverse(obj, opts, visitors):
return traverse_using(iterate(obj, opts), obj, visitors) | ['def', 'traverse(obj,', 'opts,', 'visitors):', 'return', 'traverse_using(iterate(obj,', 'opts),', 'obj,', 'visitors)'] | 535,116 |
EducationalTestingService/skll | test_regression.py | TestRegression.test_train_string_labels | test_train_string_labels | Test that regression on string labels raises TypeError. | [
"Test",
"that",
"regression",
"on",
"string",
"labels",
"raises",
"TypeError."
] | def test_train_string_labels(self):
train_file = other_dir / 'test_int_labels_cv.jsonlines'
train_fs = NDJReader.for_path(train_file).read()
train_fs.labels = train_fs.labels.astype('str')
learner = Learner('LinearRegression')
with self.assertRaises(TypeError):
learner.train(train_fs, grid_s... | ['def', 'test_train_string_labels(self):', 'train_file', '=', 'other_dir', '/', "'test_int_labels_cv.jsonlines'", 'train_fs', '=', 'NDJReader.for_path(train_file).read()', 'train_fs.labels', '=', "train_fs.labels.astype('str')", 'learner', '=', "Learner('LinearRegression')", 'with', 'self.assertRaises(TypeError):', 'le... | 885,243 |
zihuitang/medical_AI_platform | pyspecific.py | parse_pdb_command | parse_pdb_command | Transform a pdb command signature into RST nodes. | [
"Transform",
"a",
"pdb",
"command",
"signature",
"into",
"RST",
"nodes."
] | def parse_pdb_command(env, sig, signode):
m = pdbcmd_sig_re.match(sig)
if m is None:
raise ValueError
(name, args) = m.groups()
fullname = name.replace('(', '').replace(')', '')
signode += addnodes.desc_name(name, name)
if args:
signode += addnodes.desc_addname(' ' + args, ' ' + ... | ['def', 'parse_pdb_command(env,', 'sig,', 'signode):', 'm', '=', 'pdbcmd_sig_re.match(sig)', 'if', 'm', 'is', 'None:', 'raise', 'ValueError', '(name,', 'args)', '=', 'm.groups()', 'fullname', '=', "name.replace('(',", "'').replace(')',", "'')", 'signode', '+=', 'addnodes.desc_name(name,', 'name)', 'if', 'args:', 'signo... | 280,042 |
mkusner/grammarVAE | elemwise.py | Elemwise.python_constant_folding | python_constant_folding | Return True if we do not want to compile c code when doing constant folding of this node. | [
"Return",
"True",
"if",
"we",
"do",
"not",
"want",
"to",
"compile",
"c",
"code",
"when",
"doing",
"constant",
"folding",
"of",
"this",
"node."
] | def python_constant_folding(self, node):
return node.outputs[0].ndim == 0 | ['def', 'python_constant_folding(self,', 'node):', 'return', 'node.outputs[0].ndim', '==', '0'] | 579,826 |
gunthercox/ChatterBot | _utilities.py | callable_reference | callable_reference | Return an annotated weak ref, supporting bound instance methods. | [
"Return",
"an",
"annotated",
"weak",
"ref,",
"supporting",
"bound",
"instance",
"methods."
] | def callable_reference(object, callback=None):
if hasattr(object, 'im_self') and object.im_self is not None:
return BoundMethodWeakref(target=object, on_delete=callback)
elif hasattr(object, '__self__') and object.__self__ is not None:
return BoundMethodWeakref(target=object, on_delete=callback)... | ['def', 'callable_reference(object,', 'callback=None):', 'if', 'hasattr(object,', "'im_self')", 'and', 'object.im_self', 'is', 'not', 'None:', 'return', 'BoundMethodWeakref(target=object,', 'on_delete=callback)', 'elif', 'hasattr(object,', "'__self__')", 'and', 'object.__self__', 'is', 'not', 'None:', 'return', 'BoundM... | 528,770 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | thinkstats2.py | _DictWrapper.Items | Items | Gets an unsorted sequence of (value, freq/prob) pairs. | [
"Gets",
"an",
"unsorted",
"sequence",
"of",
"(value,",
"freq/prob)",
"pairs."
] | def Items(self):
return self.d.items() | ['def', 'Items(self):', 'return', 'self.d.items()'] | 12,897 |
myothida/Supervised-Machine-Learning | transforms.py | BboxBase.rotated | rotated | Return the axes-aligned bounding box that bounds the result of rotating this `Bbox` by an angle of *radians*. | [
"Return",
"the",
"axes-aligned",
"bounding",
"box",
"that",
"bounds",
"the",
"result",
"of",
"rotating",
"this",
"`Bbox`",
"by",
"an",
"angle",
"of",
"*radians*."
] | def rotated(self, radians):
corners = self.corners()
corners_rotated = Affine2D().rotate(radians).transform(corners)
bbox = Bbox.unit()
bbox.update_from_data_xy(corners_rotated, ignore=True)
return bbox | ['def', 'rotated(self,', 'radians):', 'corners', '=', 'self.corners()', 'corners_rotated', '=', 'Affine2D().rotate(radians).transform(corners)', 'bbox', '=', 'Bbox.unit()', 'bbox.update_from_data_xy(corners_rotated,', 'ignore=True)', 'return', 'bbox'] | 362,379 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | eventloops.py | loop_wx | loop_wx | Start a kernel with wx event loop support. | [
"Start",
"a",
"kernel",
"with",
"wx",
"event",
"loop",
"support."
] | def loop_wx(kernel):
import wx
poll_interval = int(1000 * kernel._poll_interval)
def wake():
for stream in kernel.shell_streams:
if stream.flush(limit=1):
kernel.app.ExitMainLoop()
return
class TimerFrame(wx.Frame):
def __init__(self, func):... | ['def', 'loop_wx(kernel):', 'import', 'wx', 'poll_interval', '=', 'int(1000', '*', 'kernel._poll_interval)', 'def', 'wake():', 'for', 'stream', 'in', 'kernel.shell_streams:', 'if', 'stream.flush(limit=1):', 'kernel.app.ExitMainLoop()', 'return', 'class', 'TimerFrame(wx.Frame):', 'def', '__init__(self,', 'func):', 'wx.F... | 447,783 |
IIM-TTIJ/MVA2023SmallObjectDetection4SpottingBirds | fpn_carafe.py | FPN_CARAFE.slice_as | slice_as | Slice ``src`` as ``dst`` Note: ``src`` should have the same or larger size than ``dst``. | [
"Slice",
"``src``",
"as",
"``dst``",
"Note:",
"``src``",
"should",
"have",
"the",
"same",
"or",
"larger",
"size",
"than",
"``dst``."
] | def slice_as(self, src, dst):
assert src.size(2) >= dst.size(2) and src.size(3) >= dst.size(3)
if src.size(2) == dst.size(2) and src.size(3) == dst.size(3):
return src
else:
return src[:, :, :dst.size(2), :dst.size(3)] | ['def', 'slice_as(self,', 'src,', 'dst):', 'assert', 'src.size(2)', '>=', 'dst.size(2)', 'and', 'src.size(3)', '>=', 'dst.size(3)', 'if', 'src.size(2)', '==', 'dst.size(2)', 'and', 'src.size(3)', '==', 'dst.size(3):', 'return', 'src', 'else:', 'return', 'src[:,', ':,', ':dst.size(2),', ':dst.size(3)]'] | 651,125 |
aisingapore/PeekingDuck | matching.py | ious | ious | Computes a matrix Intersection-over-Union (IoU) values between 2 list of bounding boxes with (x1, y1, x2, y2) format where (x1, y1) is the top left and (x2, y2) is the bottom right. | [
"Computes",
"a",
"matrix",
"Intersection-over-Union",
"(IoU)",
"values",
"between",
"2",
"list",
"of",
"bounding",
"boxes",
"with",
"(x1,",
"y1,",
"x2,",
"y2)",
"format",
"where",
"(x1,",
"y1)",
"is",
"the",
"top",
"left",
"and",
"(x2,",
"y2)",
"is",
"the",
... | def ious(xyxys_1: List[np.ndarray], xyxys_2: List[np.ndarray]) -> np.ndarray:
iou_values = np.zeros((len(xyxys_1), len(xyxys_2)), dtype=np.float)
if iou_values.size == 0:
return iou_values
return bbox_ious(np.ascontiguousarray(xyxys_1, dtype=np.float), np.ascontiguousarray(xyxys_2, dtype=np.float)) | ['def', 'ious(xyxys_1:', 'List[np.ndarray],', 'xyxys_2:', 'List[np.ndarray])', '->', 'np.ndarray:', 'iou_values', '=', 'np.zeros((len(xyxys_1),', 'len(xyxys_2)),', 'dtype=np.float)', 'if', 'iou_values.size', '==', '0:', 'return', 'iou_values', 'return', 'bbox_ious(np.ascontiguousarray(xyxys_1,', 'dtype=np.float),', 'np... | 766,963 |
rudranil723/mini-main | geometry.py | GEOSGeometryBase.envelope | envelope | Return the envelope for this geometry (a polygon). | [
"Return",
"the",
"envelope",
"for",
"this",
"geometry",
"(a",
"polygon)."
] | def envelope(self):
return self._topology(capi.geos_envelope(self.ptr)) | ['def', 'envelope(self):', 'return', 'self._topology(capi.geos_envelope(self.ptr))'] | 315,322 |
enlite-ai/maze | sac_trainer.py | SAC.evaluate | evaluate | Perform evaluation on eval env. | [
"Perform",
"evaluation",
"on",
"eval",
"env."
] | def evaluate(self) -> None:
self.evaluator.evaluate(self.learner_model.policy) | ['def', 'evaluate(self)', '->', 'None:', 'self.evaluator.evaluate(self.learner_model.policy)'] | 647,554 |
youngjoo-epfl/gconvRNN | graph.py | lmax | lmax | Upper-bound on the spectrum. | [
"Upper-bound",
"on",
"the",
"spectrum."
] | def lmax(L, normalized=True):
if normalized:
return 2
else:
return scipy.sparse.linalg.eigsh(L, k=1, which='LM', return_eigenvectors=False)[0] | ['def', 'lmax(L,', 'normalized=True):', 'if', 'normalized:', 'return', '2', 'else:', 'return', 'scipy.sparse.linalg.eigsh(L,', 'k=1,', "which='LM',", 'return_eigenvectors=False)[0]'] | 201,418 |
apeterswu/RL4NMT | algorithmic_math.py | format_sympy_expr | format_sympy_expr | Convert sympy expression into a string which can be encoded. | [
"Convert",
"sympy",
"expression",
"into",
"a",
"string",
"which",
"can",
"be",
"encoded."
] | def format_sympy_expr(sympy_expr, functions=None):
if functions is None:
functions = {}
str_expr = str(sympy_expr)
result = str_expr.replace(' ', '')
for (fn_name, char) in six.iteritems(functions):
result = result.replace(fn_name, char)
return result | ['def', 'format_sympy_expr(sympy_expr,', 'functions=None):', 'if', 'functions', 'is', 'None:', 'functions', '=', '{}', 'str_expr', '=', 'str(sympy_expr)', 'result', '=', "str_expr.replace('", "',", "'')", 'for', '(fn_name,', 'char)', 'in', 'six.iteritems(functions):', 'result', '=', 'result.replace(fn_name,', 'char)', ... | 330,864 |
sentinel-hub/eo-learn | test_common.py | test_is_discrete_type | test_is_discrete_type | Checks the given type and its numpy dtype against the expected answer. | [
"Checks",
"the",
"given",
"type",
"and",
"its",
"numpy",
"dtype",
"against",
"the",
"expected",
"answer."
] | def test_is_discrete_type(number_type, is_discrete):
assert is_discrete_type(number_type) is is_discrete
with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
numpy_dtype = np.dtype(number_type)
assert is_discrete_type(numpy_dtype) is is_discrete | ['def', 'test_is_discrete_type(number_type,', 'is_discrete):', 'assert', 'is_discrete_type(number_type)', 'is', 'is_discrete', 'with', 'warnings.catch_warnings():', "warnings.simplefilter('ignore',", 'DeprecationWarning)', 'numpy_dtype', '=', 'np.dtype(number_type)', 'assert', 'is_discrete_type(numpy_dtype)', 'is', 'is... | 562,688 |
rudranil723/mini-main | srs.py | SpatialReference.inverse_flattening | inverse_flattening | Return the Inverse Flattening for this Spatial Reference. | [
"Return",
"the",
"Inverse",
"Flattening",
"for",
"this",
"Spatial",
"Reference."
] | def inverse_flattening(self):
return capi.invflattening(self.ptr, byref(c_int())) | ['def', 'inverse_flattening(self):', 'return', 'capi.invflattening(self.ptr,', 'byref(c_int()))'] | 315,181 |
joaquimcampos/DeepSplines | manager.py | Manager.build_model | build_model | Build the network model. | [
"Build",
"the",
"network",
"model."
] | def build_model(params, device='cuda:0'):
print('\n==> Building model...')
networks_dict = {'twoDnet': TwoDNet, 'resnet32_cifar': ResNet32Cifar, 'nin_cifar': NiNCifar, 'convnet_mnist': ConvNetMnist}
assert params['net'] in networks_dict.keys(), 'network not found: please add net to networks_dict.'
net =... | ['def', 'build_model(params,', "device='cuda:0'):", "print('\\n==>", 'Building', "model...')", 'networks_dict', '=', "{'twoDnet':", 'TwoDNet,', "'resnet32_cifar':", 'ResNet32Cifar,', "'nin_cifar':", 'NiNCifar,', "'convnet_mnist':", 'ConvNetMnist}', 'assert', "params['net']", 'in', 'networks_dict.keys(),', "'network", '... | 540,062 |
textflint/textflint | config.py | Config.to_json_file | to_json_file | Serializes this instance to a JSON file. | [
"Serializes",
"this",
"instance",
"to",
"a",
"JSON",
"file."
] | def to_json_file(self, json_file):
with open(json_file, 'w+', encoding='utf-8') as writer:
json.dump(self.to_dict(), writer, indent=2, ensure_ascii=False) | ['def', 'to_json_file(self,', 'json_file):', 'with', 'open(json_file,', "'w+',", "encoding='utf-8')", 'as', 'writer:', 'json.dump(self.to_dict(),', 'writer,', 'indent=2,', 'ensure_ascii=False)'] | 913,765 |
Diyago/Graph-clasification-by-computer- | utils.py | load_obj | load_obj | Extract an object from a given path. | [
"Extract",
"an",
"object",
"from",
"a",
"given",
"path."
] | def load_obj(obj_path: str, default_obj_path: str='') -> Any:
obj_path_list = obj_path.rsplit('.', 1)
obj_path = obj_path_list.pop(0) if len(obj_path_list) > 1 else default_obj_path
obj_name = obj_path_list[0]
module_obj = importlib.import_module(obj_path)
if not hasattr(module_obj, obj_name):
... | ['def', 'load_obj(obj_path:', 'str,', 'default_obj_path:', "str='')", '->', 'Any:', 'obj_path_list', '=', "obj_path.rsplit('.',", '1)', 'obj_path', '=', 'obj_path_list.pop(0)', 'if', 'len(obj_path_list)', '>', '1', 'else', 'default_obj_path', 'obj_name', '=', 'obj_path_list[0]', 'module_obj', '=', 'importlib.import_mod... | 580,340 |
myothida/Supervised-Machine-Learning | test_peak_finding.py | TestPeakProminences.test_non_contiguous | test_non_contiguous | Test with non-C-contiguous input arrays. | [
"Test",
"with",
"non-C-contiguous",
"input",
"arrays."
] | def test_non_contiguous(self):
x = np.repeat([-9, 9, 9, 0, 3, 1], 2)
peaks = np.repeat([1, 2, 4], 2)
(proms, lbases, rbases) = peak_prominences(x[::2], peaks[::2])
assert_equal(proms, [9, 9, 2])
assert_equal(lbases, [0, 0, 3])
assert_equal(rbases, [3, 3, 5]) | ['def', 'test_non_contiguous(self):', 'x', '=', 'np.repeat([-9,', '9,', '9,', '0,', '3,', '1],', '2)', 'peaks', '=', 'np.repeat([1,', '2,', '4],', '2)', '(proms,', 'lbases,', 'rbases)', '=', 'peak_prominences(x[::2],', 'peaks[::2])', 'assert_equal(proms,', '[9,', '9,', '2])', 'assert_equal(lbases,', '[0,', '0,', '3])',... | 446,225 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | interval.py | IntervalArray.length | length | Return an Index with entries denoting the length of each Interval in the IntervalArray. | [
"Return",
"an",
"Index",
"with",
"entries",
"denoting",
"the",
"length",
"of",
"each",
"Interval",
"in",
"the",
"IntervalArray."
] | def length(self):
try:
return self.right - self.left
except TypeError as err:
msg = 'IntervalArray contains Intervals without defined length, e.g. Intervals with string endpoints'
raise TypeError(msg) from err | ['def', 'length(self):', 'try:', 'return', 'self.right', '-', 'self.left', 'except', 'TypeError', 'as', 'err:', 'msg', '=', "'IntervalArray", 'contains', 'Intervals', 'without', 'defined', 'length,', 'e.g.', 'Intervals', 'with', 'string', "endpoints'", 'raise', 'TypeError(msg)', 'from', 'err'] | 452,806 |
clvrai/spirl | block.py | Block.above | above | Checks whether current block is above other block. | [
"Checks",
"whether",
"current",
"block",
"is",
"above",
"other",
"block."
] | def above(self, other):
x_dist = np.linalg.norm(self.pos[0] - other.pos[0])
y_dist = np.linalg.norm(self.pos[1] - other.pos[1])
x_dist_correct = x_dist < other.size[0]
y_dist_correct = y_dist < other.size[1]
z_vec = self.pos[-1] - other.pos[-1]
z_vec_correct = z_vec > self.size[-1] + other.size[... | ['def', 'above(self,', 'other):', 'x_dist', '=', 'np.linalg.norm(self.pos[0]', '-', 'other.pos[0])', 'y_dist', '=', 'np.linalg.norm(self.pos[1]', '-', 'other.pos[1])', 'x_dist_correct', '=', 'x_dist', '<', 'other.size[0]', 'y_dist_correct', '=', 'y_dist', '<', 'other.size[1]', 'z_vec', '=', 'self.pos[-1]', '-', 'other.... | 896,929 |
greydanus/pythonic_ocr | compiler.py | CodeGenerator.pull_locals | pull_locals | Pull all the references identifiers into the local scope. | [
"Pull",
"all",
"the",
"references",
"identifiers",
"into",
"the",
"local",
"scope."
] | def pull_locals(self, frame):
for name in frame.identifiers.undeclared:
self.writeline('l_%s = context.resolve(%r)' % (name, name)) | ['def', 'pull_locals(self,', 'frame):', 'for', 'name', 'in', 'frame.identifiers.undeclared:', "self.writeline('l_%s", '=', "context.resolve(%r)'", '%', '(name,', 'name))'] | 299,197 |
facebookresearch/detectron2 | events.py | EventStorage.smoothing_hints | smoothing_hints | Returns: dict[name -> bool]: the user-provided hint on whether the scalar is noisy and needs smoothing. | [
"Returns:",
"dict[name",
"->",
"bool]:",
"the",
"user-provided",
"hint",
"on",
"whether",
"the",
"scalar",
"is",
"noisy",
"and",
"needs",
"smoothing."
] | def smoothing_hints(self):
return self._smoothing_hints | ['def', 'smoothing_hints(self):', 'return', 'self._smoothing_hints'] | 549,375 |
Sunarker/Collaborative-Learning-for-Weakly-Supervised-- | train_val.py | filter_roidb | filter_roidb | Remove roidb entries that have no usable RoIs. | [
"Remove",
"roidb",
"entries",
"that",
"have",
"no",
"usable",
"RoIs."
] | def filter_roidb(roidb):
def is_valid(entry):
overlaps = entry['max_overlaps']
fg_inds = np.where(overlaps >= cfg.TRAIN.FG_THRESH)[0]
bg_inds = np.where((overlaps < cfg.TRAIN.BG_THRESH_HI) & (overlaps >= cfg.TRAIN.BG_THRESH_LO))[0]
valid = len(fg_inds) > 0 or len(bg_inds) > 0
... | ['def', 'filter_roidb(roidb):', 'def', 'is_valid(entry):', 'overlaps', '=', "entry['max_overlaps']", 'fg_inds', '=', 'np.where(overlaps', '>=', 'cfg.TRAIN.FG_THRESH)[0]', 'bg_inds', '=', 'np.where((overlaps', '<', 'cfg.TRAIN.BG_THRESH_HI)', '&', '(overlaps', '>=', 'cfg.TRAIN.BG_THRESH_LO))[0]', 'valid', '=', 'len(fg_in... | 124,886 |
facebookresearch/deep_bisim4control | cartpole.py | swingup_sparse | swingup_sparse | Returns the sparse reward variant of teh Cartpole Swing-Up task. | [
"Returns",
"the",
"sparse",
"reward",
"variant",
"of",
"teh",
"Cartpole",
"Swing-Up",
"task."
] | def swingup_sparse(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
physics = Physics.from_xml_string(*get_model_and_assets())
task = Balance(swing_up=True, sparse=True, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(physics, task, time_limi... | ['def', 'swingup_sparse(time_limit=_DEFAULT_TIME_LIMIT,', 'random=None,', 'environment_kwargs=None):', 'physics', '=', 'Physics.from_xml_string(*get_model_and_assets())', 'task', '=', 'Balance(swing_up=True,', 'sparse=True,', 'random=random)', 'environment_kwargs', '=', 'environment_kwargs', 'or', '{}', 'return', 'cont... | 536,312 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | visitor.py | Expression.makeNodePreformattedExpr | makeNodePreformattedExpr | Make an accept method for expressions with a predefined format string. | [
"Make",
"an",
"accept",
"method",
"for",
"expressions",
"with",
"a",
"predefined",
"format",
"string."
] | def makeNodePreformattedExpr(fs):
def acceptPreformatted(self, node, memo):
expr = self.factory.expr
self.fs = fs
(self.left, self.right) = vs = (expr(parent=self), expr(parent=self))
self.zipWalk(node.children, vs, memo)
return acceptPreformatted | ['def', 'makeNodePreformattedExpr(fs):', 'def', 'acceptPreformatted(self,', 'node,', 'memo):', 'expr', '=', 'self.factory.expr', 'self.fs', '=', 'fs', '(self.left,', 'self.right)', '=', 'vs', '=', '(expr(parent=self),', 'expr(parent=self))', 'self.zipWalk(node.children,', 'vs,', 'memo)', 'return', 'acceptPreformatted'] | 17,109 |
RoboCupULaval/StrategyAI | Graph.py | Graph.exec | exec | Appelle la méthode exec du noeud courant et effectue la transition vers un noued suivant si une des conditions est remplie, ce qui a pour effet de changer la tactique en cours. | [
"Appelle",
"la",
"méthode",
"exec",
"du",
"noeud",
"courant",
"et",
"effectue",
"la",
"transition",
"vers",
"un",
"noued",
"suivant",
"si",
"une",
"des",
"conditions",
"est",
"remplie,",
"ce",
"qui",
"a",
"pour",
"effet",
"de",
"changer",
"la",
"tactique"... | def exec(self):
if len(self.nodes) > 0:
(next_ai_command, next_node) = self.current_node.exec()
if next_node is not None and next_node != self.current_node:
self.set_current_node(next_node)
return next_ai_command
else:
raise EmptyGraphException('Le graph ne contient a... | ['def', 'exec(self):', 'if', 'len(self.nodes)', '>', '0:', '(next_ai_command,', 'next_node)', '=', 'self.current_node.exec()', 'if', 'next_node', 'is', 'not', 'None', 'and', 'next_node', '!=', 'self.current_node:', 'self.set_current_node(next_node)', 'return', 'next_ai_command', 'else:', 'raise', "EmptyGraphException('... | 359,732 |
google-research/scenic | test_matchers.py | sample_cxcywh_bbox | sample_cxcywh_bbox | Samples a bounding box in the [cx, cy, w, h] in [0, 1] range format. | [
"Samples",
"a",
"bounding",
"box",
"in",
"the",
"[cx,",
"cy,",
"w,",
"h]",
"in",
"[0,",
"1]",
"range",
"format."
] | def sample_cxcywh_bbox(key, batch_shape):
frac = 0.8
sample = jax.random.uniform(key, shape=(*batch_shape, 4)) * frac
(cx, cy, w, h) = jnp.split(sample, indices_or_sections=4, axis=-1)
w = jnp.where(cx + w / 2.0 >= 1.0, frac * 2.0 * (1.0 - cx), w)
h = jnp.where(cy + h / 2.0 >= 1.0, frac * 2.0 * (1.0... | ['def', 'sample_cxcywh_bbox(key,', 'batch_shape):', 'frac', '=', '0.8', 'sample', '=', 'jax.random.uniform(key,', 'shape=(*batch_shape,', '4))', '*', 'frac', '(cx,', 'cy,', 'w,', 'h)', '=', 'jnp.split(sample,', 'indices_or_sections=4,', 'axis=-1)', 'w', '=', 'jnp.where(cx', '+', 'w', '/', '2.0', '>=', '1.0,', 'frac', '... | 846,295 |
myothida/Supervised-Machine-Learning | conftest.py | not_daily | not_daily | Several timedelta-like and DateOffset instances that are _not_ compatible with Daily frequencies. | [
"Several",
"timedelta-like",
"and",
"DateOffset",
"instances",
"that",
"are",
"_not_",
"compatible",
"with",
"Daily",
"frequencies."
] | def not_daily(request):
return request.param | ['def', 'not_daily(request):', 'return', 'request.param'] | 443,506 |
myothida/Supervised-Machine-Learning | dtypes.py | IntervalDtype.subtype | subtype | The dtype of the Interval bounds. | [
"The",
"dtype",
"of",
"the",
"Interval",
"bounds."
] | def subtype(self):
return self._subtype | ['def', 'subtype(self):', 'return', 'self._subtype'] | 442,764 |
Eric3911/OpenAGI | gpu_rnnt_kernel.py | compute_betas_kernel | compute_betas_kernel | Compute beta (backward variable) probabilities over the transduction step. | [
"Compute",
"beta",
"(backward",
"variable)",
"probabilities",
"over",
"the",
"transduction",
"step."
] | def compute_betas_kernel(acts: torch.Tensor, denom: torch.Tensor, betas: torch.Tensor, llBackward: torch.Tensor, xlen: torch.Tensor, ylen: torch.Tensor, mlabels: torch.Tensor, minibatch: int, maxT: int, maxU: int, alphabet_size: int, blank_: int):
b = cuda.blockIdx.x
u = cuda.threadIdx.x
T = xlen[b]
U =... | ['def', 'compute_betas_kernel(acts:', 'torch.Tensor,', 'denom:', 'torch.Tensor,', 'betas:', 'torch.Tensor,', 'llBackward:', 'torch.Tensor,', 'xlen:', 'torch.Tensor,', 'ylen:', 'torch.Tensor,', 'mlabels:', 'torch.Tensor,', 'minibatch:', 'int,', 'maxT:', 'int,', 'maxU:', 'int,', 'alphabet_size:', 'int,', 'blank_:', 'int)... | 272,719 |
google-research/crest | resnet_util.py | block1 | block1 | A basic residual block. | [
"A",
"basic",
"residual",
"block."
] | def block1(x, filters, bottleneck=False, stride=1, expansion=1, normalization='bn', activation='relu', name=None):
conv_shortcut = stride != 1 or expansion * filters != x.shape[3]
if conv_shortcut:
shortcut = conv1x1(x, filters=expansion * filters, strides=stride, name=name + '_0_conv')
shortcut... | ['def', 'block1(x,', 'filters,', 'bottleneck=False,', 'stride=1,', 'expansion=1,', "normalization='bn',", "activation='relu',", 'name=None):', 'conv_shortcut', '=', 'stride', '!=', '1', 'or', 'expansion', '*', 'filters', '!=', 'x.shape[3]', 'if', 'conv_shortcut:', 'shortcut', '=', 'conv1x1(x,', 'filters=expansion', '*'... | 138,526 |
rudranil723/mini-main | timezone.py | get_current_timezone_name | get_current_timezone_name | Return the name of the currently active time zone. | [
"Return",
"the",
"name",
"of",
"the",
"currently",
"active",
"time",
"zone."
] | def get_current_timezone_name():
return _get_timezone_name(get_current_timezone()) | ['def', 'get_current_timezone_name():', 'return', '_get_timezone_name(get_current_timezone())'] | 316,809 |
ciads-ut/transfer-learning-ner | stratified_split.py | writefile | writefile | Write the sentences, in CONLL-format, to a file given by filename located in directory filedir. | [
"Write",
"the",
"sentences,",
"in",
"CONLL-format,",
"to",
"a",
"file",
"given",
"by",
"filename",
"located",
"in",
"directory",
"filedir."
] | def writefile(sentences, filedir, filename, sep='\t'):
DIR = filedir
WRITEFILE = os.path.join(DIR, filename)
if not os.path.exists(DIR):
os.makedirs(DIR)
if os.path.isfile(WRITEFILE):
raise ValueError('The file already exists!')
with codecs.open(WRITEFILE, 'a+', encoding='utf-8') as ... | ['def', 'writefile(sentences,', 'filedir,', 'filename,', "sep='\\t'):", 'DIR', '=', 'filedir', 'WRITEFILE', '=', 'os.path.join(DIR,', 'filename)', 'if', 'not', 'os.path.exists(DIR):', 'os.makedirs(DIR)', 'if', 'os.path.isfile(WRITEFILE):', 'raise', "ValueError('The", 'file', 'already', "exists!')", 'with', 'codecs.open... | 929,719 |
tensorflow/agents | environment_utilities.py | compute_optimal_action_with_environment_dynamics | compute_optimal_action_with_environment_dynamics | Computes the optimal action using the environment dynamics. | [
"Computes",
"the",
"optimal",
"action",
"using",
"the",
"environment",
"dynamics."
] | def compute_optimal_action_with_environment_dynamics(observation, environment_dynamics):
return environment_dynamics.compute_optimal_action(observation) | ['def', 'compute_optimal_action_with_environment_dynamics(observation,', 'environment_dynamics):', 'return', 'environment_dynamics.compute_optimal_action(observation)'] | 22,571 |
voxel51/fiftyone | stages.py | Select.ordered | ordered | Whether to sort the samples in the same order as the IDs. | [
"Whether",
"to",
"sort",
"the",
"samples",
"in",
"the",
"same",
"order",
"as",
"the",
"IDs."
] | def ordered(self):
return self._ordered | ['def', 'ordered(self):', 'return', 'self._ordered'] | 583,341 |
lhotse-speech/lhotse | spgispeech.py | spgispeech | spgispeech | SPGISpeech ASR data preparation. | [
"SPGISpeech",
"ASR",
"data",
"preparation."
] | def spgispeech(corpus_dir: Pathlike, output_dir: Pathlike, num_jobs: int, normalize_text: bool):
prepare_spgispeech(corpus_dir, output_dir, num_jobs=num_jobs, normalize_text=normalize_text) | ['def', 'spgispeech(corpus_dir:', 'Pathlike,', 'output_dir:', 'Pathlike,', 'num_jobs:', 'int,', 'normalize_text:', 'bool):', 'prepare_spgispeech(corpus_dir,', 'output_dir,', 'num_jobs=num_jobs,', 'normalize_text=normalize_text)'] | 600,627 |
zihuitang/medical_AI_platform | pydoc.py | Helper.getline | getline | Read one line, using input() when appropriate. | [
"Read",
"one",
"line,",
"using",
"input()",
"when",
"appropriate."
] | def getline(self, prompt):
if self.input is sys.stdin:
return input(prompt)
else:
self.output.write(prompt)
self.output.flush()
return self.input.readline() | ['def', 'getline(self,', 'prompt):', 'if', 'self.input', 'is', 'sys.stdin:', 'return', 'input(prompt)', 'else:', 'self.output.write(prompt)', 'self.output.flush()', 'return', 'self.input.readline()'] | 281,245 |
replit-archive/empythoned | tktools.py | test | test | Test make_text_box(), make_form_entry(), flatten(), boolean(). | [
"Test",
"make_text_box(),",
"make_form_entry(),",
"flatten(),",
"boolean()."
] | def test():
import sys
root = Tk()
(entry, eframe) = make_form_entry(root, 'Boolean:')
(text, tframe) = make_text_box(root)
def enter(event, entry=entry, text=text):
s = boolean(entry.get()) and '\nyes' or '\nno'
text.insert('end', s)
entry.bind('<Return>', enter)
entry.inse... | ['def', 'test():', 'import', 'sys', 'root', '=', 'Tk()', '(entry,', 'eframe)', '=', 'make_form_entry(root,', "'Boolean:')", '(text,', 'tframe)', '=', 'make_text_box(root)', 'def', 'enter(event,', 'entry=entry,', 'text=text):', 's', '=', 'boolean(entry.get())', 'and', "'\\nyes'", 'or', "'\\nno'", "text.insert('end',", '... | 177,137 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | mnist_shift.py | bytes_feature | bytes_feature | Casts value to a TensorFlow bytes feature list. | [
"Casts",
"value",
"to",
"a",
"TensorFlow",
"bytes",
"feature",
"list."
] | def bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) | ['def', 'bytes_feature(value):', 'return', 'tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))'] | 46,924 |
hobson/aima | mdp.py | policy_evaluation | policy_evaluation | Return an updated utility mapping U from each state in the MDP to its utility, using an approximation (modified policy iteration). | [
"Return",
"an",
"updated",
"utility",
"mapping",
"U",
"from",
"each",
"state",
"in",
"the",
"MDP",
"to",
"its",
"utility,",
"using",
"an",
"approximation",
"(modified",
"policy",
"iteration)."
] | def policy_evaluation(pi, U, mdp, k=20):
(R, T, gamma) = (mdp.R, mdp.T, mdp.gamma)
for i in range(k):
for s in mdp.states:
U[s] = R(s) + gamma * sum([p * U[s1] for (p, s1) in T(s, pi[s])])
return U | ['def', 'policy_evaluation(pi,', 'U,', 'mdp,', 'k=20):', '(R,', 'T,', 'gamma)', '=', '(mdp.R,', 'mdp.T,', 'mdp.gamma)', 'for', 'i', 'in', 'range(k):', 'for', 's', 'in', 'mdp.states:', 'U[s]', '=', 'R(s)', '+', 'gamma', '*', 'sum([p', '*', 'U[s1]', 'for', '(p,', 's1)', 'in', 'T(s,', 'pi[s])])', 'return', 'U'] | 86,109 |
erfaneshrati/meta-transfer-learning | reptile.py | Reptile.train_metatransfer_step | train_metatransfer_step | Perform a meta transfer learning training step. | [
"Perform",
"a",
"meta",
"transfer",
"learning",
"training",
"step."
] | def train_metatransfer_step(self, dataset, input_ph, label_ph, real_label, minimize_op_metalearner, minimize_op_classifier, num_classes, num_shots, inner_batch_size, inner_iters, replacement, meta_step_size, meta_batch_size):
beta = 0.1
old_vars = self._model_state.export_variables()
new_vars_meta = []
... | ['def', 'train_metatransfer_step(self,', 'dataset,', 'input_ph,', 'label_ph,', 'real_label,', 'minimize_op_metalearner,', 'minimize_op_classifier,', 'num_classes,', 'num_shots,', 'inner_batch_size,', 'inner_iters,', 'replacement,', 'meta_step_size,', 'meta_batch_size):', 'beta', '=', '0.1', 'old_vars', '=', 'self._mode... | 633,399 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | metaopt.py | test_optimizer | test_optimizer | Tests an optimization algorithm on a given problem. | [
"Tests",
"an",
"optimization",
"algorithm",
"on",
"a",
"given",
"problem."
] | def test_optimizer(optimizer, problem, num_iter, dataset=datasets.EMPTY_DATASET, batch_size=None, seed=None, graph=None, logdir=None, record_every=None):
if dataset is None:
dataset = datasets.EMPTY_DATASET
batch_size = dataset.size
else:
batch_size = dataset.size if batch_size is None e... | ['def', 'test_optimizer(optimizer,', 'problem,', 'num_iter,', 'dataset=datasets.EMPTY_DATASET,', 'batch_size=None,', 'seed=None,', 'graph=None,', 'logdir=None,', 'record_every=None):', 'if', 'dataset', 'is', 'None:', 'dataset', '=', 'datasets.EMPTY_DATASET', 'batch_size', '=', 'dataset.size', 'else:', 'batch_size', '='... | 55,434 |
ylsung/Ladder-Side-Tuning | adapter_controller.py | AdapterController.disable_adapters | disable_adapters | Given a list of tasks, it freezes their corresponding adapter layers' parameters. | [
"Given",
"a",
"list",
"of",
"tasks,",
"it",
"freezes",
"their",
"corresponding",
"adapter",
"layers'",
"parameters."
] | def disable_adapters(self, tasks):
tasks = self.convert_to_list(tasks)
for task in tasks:
adapter = self.get_adapter(task)
for param in adapter.parameters():
param.requires_grad = False | ['def', 'disable_adapters(self,', 'tasks):', 'tasks', '=', 'self.convert_to_list(tasks)', 'for', 'task', 'in', 'tasks:', 'adapter', '=', 'self.get_adapter(task)', 'for', 'param', 'in', 'adapter.parameters():', 'param.requires_grad', '=', 'False'] | 622,907 |
CMU-CREATE-Lab/deep-smoke-machine | opencv_functional.py | rotate | rotate | Rotate the image by angle. | [
"Rotate",
"the",
"image",
"by",
"angle."
] | def rotate(img, angle, resample=False, expand=False, center=None):
if not _is_numpy_image(img):
raise TypeError('img should be numpy Image. Got {}'.format(type(img)))
(rows, cols) = img.shape[0:2]
if center is None:
center = (cols / 2, rows / 2)
M = cv2.getRotationMatrix2D(center, angle,... | ['def', 'rotate(img,', 'angle,', 'resample=False,', 'expand=False,', 'center=None):', 'if', 'not', '_is_numpy_image(img):', 'raise', "TypeError('img", 'should', 'be', 'numpy', 'Image.', 'Got', "{}'.format(type(img)))", '(rows,', 'cols)', '=', 'img.shape[0:2]', 'if', 'center', 'is', 'None:', 'center', '=', '(cols', '/',... | 519,650 |
zehuichen123/AutoAlignV2 | create_gt_database_backup.py | create_groundtruth_database | create_groundtruth_database | Given the raw data, generate the ground truth database. | [
"Given",
"the",
"raw",
"data,",
"generate",
"the",
"ground",
"truth",
"database."
] | def create_groundtruth_database(dataset_class_name, data_path, info_prefix, info_path=None, mask_anno_path=None, used_classes=None, database_save_path=None, db_info_save_path=None, relative_path=True, add_rgb=False, lidar_only=False, bev_only=False, coors_range=None, with_mask=False):
print(f'Create GT Database of ... | ['def', 'create_groundtruth_database(dataset_class_name,', 'data_path,', 'info_prefix,', 'info_path=None,', 'mask_anno_path=None,', 'used_classes=None,', 'database_save_path=None,', 'db_info_save_path=None,', 'relative_path=True,', 'add_rgb=False,', 'lidar_only=False,', 'bev_only=False,', 'coors_range=None,', 'with_mas... | 417,040 |
Eric3911/OpenAGI | download.py | unpack | unpack | Unpack the file to the target_dir. | [
"Unpack",
"the",
"file",
"to",
"the",
"target_dir."
] | def unpack(filepath, target_dir, rm_tar=False):
print('Unpacking %s ...' % filepath)
tar = tarfile.open(filepath)
tar.extractall(target_dir)
tar.close()
if rm_tar:
os.remove(filepath) | ['def', 'unpack(filepath,', 'target_dir,', 'rm_tar=False):', "print('Unpacking", '%s', "...'", '%', 'filepath)', 'tar', '=', 'tarfile.open(filepath)', 'tar.extractall(target_dir)', 'tar.close()', 'if', 'rm_tar:', 'os.remove(filepath)'] | 251,159 |
mj-will/nessai | test_plot.py | test_trace_plot_unstructured | test_trace_plot_unstructured | Test to check that trace_plot raises an error when the nested samples are not a structured array. | [
"Test",
"to",
"check",
"that",
"trace_plot",
"raises",
"an",
"error",
"when",
"the",
"nested",
"samples",
"are",
"not",
"a",
"structured",
"array."
] | def test_trace_plot_unstructured():
log_x = np.linspace(-10, 0, 100)
nested_samples = np.random.randn(log_x.size, 2)
with pytest.raises(TypeError) as excinfo:
plot.plot_trace(log_x, nested_samples)
plt.close()
assert 'structured array' in str(excinfo.value) | ['def', 'test_trace_plot_unstructured():', 'log_x', '=', 'np.linspace(-10,', '0,', '100)', 'nested_samples', '=', 'np.random.randn(log_x.size,', '2)', 'with', 'pytest.raises(TypeError)', 'as', 'excinfo:', 'plot.plot_trace(log_x,', 'nested_samples)', 'plt.close()', 'assert', "'structured", "array'", 'in', 'str(excinfo.v... | 292,388 |
devashish-patel/webcam-motion-detector | base.py | Filter.test_args | test_args | Test whether this filter can be called with the following argument list. | [
"Test",
"whether",
"this",
"filter",
"can",
"be",
"called",
"with",
"the",
"following",
"argument",
"list."
] | def test_args(self, *args):
return test_callable_args(self.__call__, args) | ['def', 'test_args(self,', '*args):', 'return', 'test_callable_args(self.__call__,', 'args)'] | 983,893 |
googleapis/python-aiplatform | jobs.py | BatchPredictionJob.create | create | Create a batch prediction job. | [
"Create",
"a",
"batch",
"prediction",
"job."
] | def create(cls, job_display_name: str, model_name: Union[str, 'aiplatform.Model'], instances_format: str='jsonl', predictions_format: str='jsonl', gcs_source: Optional[Union[str, Sequence[str]]]=None, bigquery_source: Optional[str]=None, gcs_destination_prefix: Optional[str]=None, bigquery_destination_prefix: Optional[... | ['def', 'create(cls,', 'job_display_name:', 'str,', 'model_name:', 'Union[str,', "'aiplatform.Model'],", 'instances_format:', "str='jsonl',", 'predictions_format:', "str='jsonl',", 'gcs_source:', 'Optional[Union[str,', 'Sequence[str]]]=None,', 'bigquery_source:', 'Optional[str]=None,', 'gcs_destination_prefix:', 'Optio... | 809,744 |
43Carrig/recurrent_neural_networks_practice | call_trees.py | FunctionNamer.compiled_function_name | compiled_function_name | Generate the name corresponding to the compiled version of a function. | [
"Generate",
"the",
"name",
"corresponding",
"to",
"the",
"compiled",
"version",
"of",
"a",
"function."
] | def compiled_function_name(self, original_fqn, live_entity=None, owner_type=None):
raise NotImplementedError() | ['def', 'compiled_function_name(self,', 'original_fqn,', 'live_entity=None,', 'owner_type=None):', 'raise', 'NotImplementedError()'] | 312,337 |
Hsankesara/DeepResearch | prototypicalNet.py | PrototypicalNet.get_query_y | get_query_y | Returns labeled representation of classes of Query set and a list of labels. | [
"Returns",
"labeled",
"representation",
"of",
"classes",
"of",
"Query",
"set",
"and",
"a",
"list",
"of",
"labels."
] | def get_query_y(self, Qy, Qyc, class_label):
labels = []
m = len(Qy)
for i in range(m):
labels += [Qy[i]] * Qyc[i]
labels = np.array(labels).reshape(len(labels), 1)
label_encoder = LabelEncoder()
Query_y = torch.Tensor(label_encoder.fit_transform(labels).astype(int)).long()
if self.g... | ['def', 'get_query_y(self,', 'Qy,', 'Qyc,', 'class_label):', 'labels', '=', '[]', 'm', '=', 'len(Qy)', 'for', 'i', 'in', 'range(m):', 'labels', '+=', '[Qy[i]]', '*', 'Qyc[i]', 'labels', '=', 'np.array(labels).reshape(len(labels),', '1)', 'label_encoder', '=', 'LabelEncoder()', 'Query_y', '=', 'torch.Tensor(label_encode... | 539,497 |
mapbox/robosat | unet.py | ConvRelu.forward | forward | The networks forward pass for which autograd synthesizes the backwards pass. | [
"The",
"networks",
"forward",
"pass",
"for",
"which",
"autograd",
"synthesizes",
"the",
"backwards",
"pass."
] | def forward(self, x):
return nn.functional.relu(self.block(x), inplace=True) | ['def', 'forward(self,', 'x):', 'return', 'nn.functional.relu(self.block(x),', 'inplace=True)'] | 825,974 |
apple/ml-cvnets | checkpoint_utils.py | copy_weights | copy_weights | Copy `state_dict` from source model to target model. | [
"Copy",
"`state_dict`",
"from",
"source",
"model",
"to",
"target",
"model."
] | def copy_weights(model_src: torch.nn.Module, model_tgt: torch.nn.Module) -> torch.nn.Module:
with torch.no_grad():
model_state = get_model_state_dict(model=model_src)
return load_state_dict(model=model_tgt, state_dict=model_state) | ['def', 'copy_weights(model_src:', 'torch.nn.Module,', 'model_tgt:', 'torch.nn.Module)', '->', 'torch.nn.Module:', 'with', 'torch.no_grad():', 'model_state', '=', 'get_model_state_dict(model=model_src)', 'return', 'load_state_dict(model=model_tgt,', 'state_dict=model_state)'] | 629,534 |
omarmhaimdat/twitter_nlp_native_swift | request.py | HTTPPasswordMgr.is_suburi | is_suburi | Check if test is below base in a URI tree Both args must be URIs in reduced form. | [
"Check",
"if",
"test",
"is",
"below",
"base",
"in",
"a",
"URI",
"tree",
"Both",
"args",
"must",
"be",
"URIs",
"in",
"reduced",
"form."
] | def is_suburi(self, base, test):
if base == test:
return True
if base[0] != test[0]:
return False
common = posixpath.commonprefix((base[1], test[1]))
if len(common) == len(base[1]):
return True
return False | ['def', 'is_suburi(self,', 'base,', 'test):', 'if', 'base', '==', 'test:', 'return', 'True', 'if', 'base[0]', '!=', 'test[0]:', 'return', 'False', 'common', '=', 'posixpath.commonprefix((base[1],', 'test[1]))', 'if', 'len(common)', '==', 'len(base[1]):', 'return', 'True', 'return', 'False'] | 953,636 |
zihuitang/medical_AI_platform | __init__.py | Misc.grid_location | grid_location | Return a tuple of column and row which identify the cell at which the pixel at position X and Y inside the master widget is located. | [
"Return",
"a",
"tuple",
"of",
"column",
"and",
"row",
"which",
"identify",
"the",
"cell",
"at",
"which",
"the",
"pixel",
"at",
"position",
"X",
"and",
"Y",
"inside",
"the",
"master",
"widget",
"is",
"located."
] | def grid_location(self, x, y):
return self._getints(self.tk.call('grid', 'location', self._w, x, y)) or None | ['def', 'grid_location(self,', 'x,', 'y):', 'return', "self._getints(self.tk.call('grid',", "'location',", 'self._w,', 'x,', 'y))', 'or', 'None'] | 284,141 |
Katja-M/Python_NaturalLanguageProcessing | util.py | conlltags2tree | conlltags2tree | Convert the CoNLL IOB format to a tree. | [
"Convert",
"the",
"CoNLL",
"IOB",
"format",
"to",
"a",
"tree."
] | def conlltags2tree(sentence, chunk_types=('NP', 'PP', 'VP'), root_label='S', strict=False):
tree = Tree(root_label, [])
for (word, postag, chunktag) in sentence:
if chunktag is None:
if strict:
raise ValueError('Bad conll tag sequence')
else:
tree.... | ['def', 'conlltags2tree(sentence,', "chunk_types=('NP',", "'PP',", "'VP'),", "root_label='S',", 'strict=False):', 'tree', '=', 'Tree(root_label,', '[])', 'for', '(word,', 'postag,', 'chunktag)', 'in', 'sentence:', 'if', 'chunktag', 'is', 'None:', 'if', 'strict:', 'raise', "ValueError('Bad", 'conll', 'tag', "sequence')"... | 866,033 |
treigerm/WaterNet | io_util.py | save_tiles | save_tiles | Save the tile data for a satellite image as a pickle. | [
"Save",
"the",
"tile",
"data",
"for",
"a",
"satellite",
"image",
"as",
"a",
"pickle."
] | def save_tiles(file_path, tiled_features, tiled_labels):
print('Store tile data at {}.'.format(file_path))
with open(file_path, 'wb') as out:
pickle.dump({'features': tiled_features, 'labels': tiled_labels}, out) | ['def', 'save_tiles(file_path,', 'tiled_features,', 'tiled_labels):', "print('Store", 'tile', 'data', 'at', "{}.'.format(file_path))", 'with', 'open(file_path,', "'wb')", 'as', 'out:', "pickle.dump({'features':", 'tiled_features,', "'labels':", 'tiled_labels},', 'out)'] | 372,921 |
pranjaldatta/PyVision | toymaker.py | seed | seed | Allows changing the random seed so that the same path is generated repeatedly. | [
"Allows",
"changing",
"the",
"random",
"seed",
"so",
"that",
"the",
"same",
"path",
"is",
"generated",
"repeatedly."
] | def seed(s=0):
random.seed(s) | ['def', 'seed(s=0):', 'random.seed(s)'] | 815,951 |
ancasag/ensembleObjectDetection | generateXML.py | prettify | prettify | Return a pretty-printed XML string for the Element. | [
"Return",
"a",
"pretty-printed",
"XML",
"string",
"for",
"the",
"Element."
] | def prettify(elem):
rough_string = ET.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=' ') | ['def', 'prettify(elem):', 'rough_string', '=', 'ET.tostring(elem,', "'utf-8')", 'reparsed', '=', 'minidom.parseString(rough_string)', 'return', "reparsed.toprettyxml(indent='", "')"] | 561,799 |
IntelLabs/nlp-architect | metrics.py | classification_report | classification_report | Build a text report showing the main classification metrics. | [
"Build",
"a",
"text",
"report",
"showing",
"the",
"main",
"classification",
"metrics."
] | def classification_report(y_true, y_pred, digits=2, suffix=False):
true_entities = set(get_entities(y_true, suffix))
pred_entities = set(get_entities(y_pred, suffix))
name_width = 0
d1 = defaultdict(set)
d2 = defaultdict(set)
for e in true_entities:
d1[e[0]].add((e[1], e[2]))
nam... | ['def', 'classification_report(y_true,', 'y_pred,', 'digits=2,', 'suffix=False):', 'true_entities', '=', 'set(get_entities(y_true,', 'suffix))', 'pred_entities', '=', 'set(get_entities(y_pred,', 'suffix))', 'name_width', '=', '0', 'd1', '=', 'defaultdict(set)', 'd2', '=', 'defaultdict(set)', 'for', 'e', 'in', 'true_ent... | 783,502 |
Farama-Foundation/Gymnasium | vector_env.py | VectorEnv.unwrapped | unwrapped | Return the base environment. | [
"Return",
"the",
"base",
"environment."
] | def unwrapped(self):
return self | ['def', 'unwrapped(self):', 'return', 'self'] | 573,116 |
triaquae/triaquae | geometry.py | GEOSGeometry.point_on_surface | point_on_surface | Computes an interior point of this Geometry. | [
"Computes",
"an",
"interior",
"point",
"of",
"this",
"Geometry."
] | def point_on_surface(self):
return self._topology(capi.geos_pointonsurface(self.ptr)) | ['def', 'point_on_surface(self):', 'return', 'self._topology(capi.geos_pointonsurface(self.ptr))'] | 357,806 |
mvondracek/VUT-FIT-POVa-2018-Pedestrian-Tracking | timer.py | openpose_gpu_binary | openpose_gpu_binary | Measure pedestrian detection using OpenPose binary for GPU. | [
"Measure",
"pedestrian",
"detection",
"using",
"OpenPose",
"binary",
"for",
"GPU."
] | def openpose_gpu_binary(openpose_binary_path=None, repeat=3):
assert openpose_binary_path, 'Provide path to OpenPose binary!'
image = cv2.imread('../testing_data/s2_f_x0y300.png')
person_detector = OpenPoseBinaryDetector(openpose_binary_path, using_gpu=True)
detection = 'people = person_detector.detect(... | ['def', 'openpose_gpu_binary(openpose_binary_path=None,', 'repeat=3):', 'assert', 'openpose_binary_path,', "'Provide", 'path', 'to', 'OpenPose', "binary!'", 'image', '=', "cv2.imread('../testing_data/s2_f_x0y300.png')", 'person_detector', '=', 'OpenPoseBinaryDetector(openpose_binary_path,', 'using_gpu=True)', 'detectio... | 940,976 |
chribsen/simple-machine-learning-examples | test_basic.py | teardown_module | teardown_module | Delete eggs/wheels created by tests. | [
"Delete",
"eggs/wheels",
"created",
"by",
"tests."
] | def teardown_module():
base = pkg_resources.resource_filename('wheel.test', '')
for dist in test_distributions:
for subdir in ('build', 'dist'):
try:
rmtree(os.path.join(base, dist, subdir))
except OSError:
pass | ['def', 'teardown_module():', 'base', '=', "pkg_resources.resource_filename('wheel.test',", "'')", 'for', 'dist', 'in', 'test_distributions:', 'for', 'subdir', 'in', "('build',", "'dist'):", 'try:', 'rmtree(os.path.join(base,', 'dist,', 'subdir))', 'except', 'OSError:', 'pass'] | 883,082 |
rifqind/Agent-Programs-3KS1 | parser_utils.py | move | move | Move the `Node` start_pos. | [
"Move",
"the",
"`Node`",
"start_pos."
] | def move(node, line_offset):
try:
children = node.children
except AttributeError:
node.line += line_offset
else:
for c in children:
move(c, line_offset) | ['def', 'move(node,', 'line_offset):', 'try:', 'children', '=', 'node.children', 'except', 'AttributeError:', 'node.line', '+=', 'line_offset', 'else:', 'for', 'c', 'in', 'children:', 'move(c,', 'line_offset)'] | 42,036 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | core.py | UndirectedGraph.add_edge | add_edge | Adds an edge to the graph. | [
"Adds",
"an",
"edge",
"to",
"the",
"graph."
] | def add_edge(self, s, t):
self.edges[s].add(t)
self.edges[t].add(s) | ['def', 'add_edge(self,', 's,', 't):', 'self.edges[s].add(t)', 'self.edges[t].add(s)'] | 18,210 |
enuguru/artificial_intelligence_and_machine_ | ansisql.py | AlterTableVisitor.append | append | Append content to the SchemaIterator's query buffer. | [
"Append",
"content",
"to",
"the",
"SchemaIterator's",
"query",
"buffer."
] | def append(self, s):
self.buffer.write(s) | ['def', 'append(self,', 's):', 'self.buffer.write(s)'] | 129,537 |
jxhe/unify-parameter-efficient-tuning | style_doc.py | split_text_in_lines | split_text_in_lines | Split `text` in the biggest lines possible with the constraint of `max_len` using `prefix` on the first line and then indenting with the same length as `prefix`. | [
"Split",
"`text`",
"in",
"the",
"biggest",
"lines",
"possible",
"with",
"the",
"constraint",
"of",
"`max_len`",
"using",
"`prefix`",
"on",
"the",
"first",
"line",
"and",
"then",
"indenting",
"with",
"the",
"same",
"length",
"as",
"`prefix`."
] | def split_text_in_lines(text, max_len, prefix='', min_indent=None):
text = re.sub('\\s+', ' ', text)
indent = ' ' * len(prefix)
if min_indent is not None:
if len(indent) < len(min_indent):
indent = min_indent
if len(prefix) < len(min_indent):
prefix = ' ' * (len(min_i... | ['def', 'split_text_in_lines(text,', 'max_len,', "prefix='',", 'min_indent=None):', 'text', '=', "re.sub('\\\\s+',", "'", "',", 'text)', 'indent', '=', "'", "'", '*', 'len(prefix)', 'if', 'min_indent', 'is', 'not', 'None:', 'if', 'len(indent)', '<', 'len(min_indent):', 'indent', '=', 'min_indent', 'if', 'len(prefix)', ... | 949,606 |
KalleHallden/InstaAutomator | _tifffile.py | read_cz_lsm_time_stamps | read_cz_lsm_time_stamps | Read LSM time stamps from file and return as list. | [
"Read",
"LSM",
"time",
"stamps",
"from",
"file",
"and",
"return",
"as",
"list."
] | def read_cz_lsm_time_stamps(fh):
(size, count) = struct.unpack('<ii', fh.read(8))
if size != 8 + 8 * count:
raise ValueError('lsm_time_stamps block is too short')
return fh.read_array('<f8', count=count) | ['def', 'read_cz_lsm_time_stamps(fh):', '(size,', 'count)', '=', "struct.unpack('<ii',", 'fh.read(8))', 'if', 'size', '!=', '8', '+', '8', '*', 'count:', 'raise', "ValueError('lsm_time_stamps", 'block', 'is', 'too', "short')", 'return', "fh.read_array('<f8',", 'count=count)'] | 242,508 |
ggjy/CMT.pytorch | utils.py | sfc_flop_jit | sfc_flop_jit | Count flops for cycle FC. | [
"Count",
"flops",
"for",
"cycle",
"FC."
] | def sfc_flop_jit(inputs: List[Any], outputs: List[Any]) -> typing.Counter[str]:
(x, w) = inputs[:2]
(x_shape, w_shape, out_shape) = (get_shape(x), get_shape(w), get_shape(outputs[0]))
assert w_shape[-1] == 1 and w_shape[-2] == 1, w_shape
return Counter({'conv': conv_flop_count(x_shape, w_shape, out_shap... | ['def', 'sfc_flop_jit(inputs:', 'List[Any],', 'outputs:', 'List[Any])', '->', 'typing.Counter[str]:', '(x,', 'w)', '=', 'inputs[:2]', '(x_shape,', 'w_shape,', 'out_shape)', '=', '(get_shape(x),', 'get_shape(w),', 'get_shape(outputs[0]))', 'assert', 'w_shape[-1]', '==', '1', 'and', 'w_shape[-2]', '==', '1,', 'w_shape', ... | 123,476 |
triaquae/triaquae | sites.py | AdminSite.password_change_done | password_change_done | Displays the "success" page after a password change. | [
"Displays",
"the",
"\"success\"",
"page",
"after",
"a",
"password",
"change."
] | def password_change_done(self, request, extra_context=None):
from django.contrib.auth.views import password_change_done
defaults = {'current_app': self.name, 'extra_context': extra_context or {}}
if self.password_change_done_template is not None:
defaults['template_name'] = self.password_change_done... | ['def', 'password_change_done(self,', 'request,', 'extra_context=None):', 'from', 'django.contrib.auth.views', 'import', 'password_change_done', 'defaults', '=', "{'current_app':", 'self.name,', "'extra_context':", 'extra_context', 'or', '{}}', 'if', 'self.password_change_done_template', 'is', 'not', 'None:', "defaults... | 356,999 |
ratschlab/dpsom | DPSOM_model.py | DPSOM.q_ng | q_ng | Computes the soft assignments between the embeddings and the centroids stopping the gradient of the latent embeddings. | [
"Computes",
"the",
"soft",
"assignments",
"between",
"the",
"embeddings",
"and",
"the",
"centroids",
"stopping",
"the",
"gradient",
"of",
"the",
"latent",
"embeddings."
] | def q_ng(self):
with tf.name_scope('distribution'):
q = tf.keras.backend.epsilon() + 1.0 / (1.0 + self.z_dist_flat_ng / self.alpha) ** ((self.alpha + 1.0) / 2.0)
q = q / tf.reduce_sum(q, axis=1, keepdims=True)
return q | ['def', 'q_ng(self):', 'with', "tf.name_scope('distribution'):", 'q', '=', 'tf.keras.backend.epsilon()', '+', '1.0', '/', '(1.0', '+', 'self.z_dist_flat_ng', '/', 'self.alpha)', '**', '((self.alpha', '+', '1.0)', '/', '2.0)', 'q', '=', 'q', '/', 'tf.reduce_sum(q,', 'axis=1,', 'keepdims=True)', 'return', 'q'] | 166,949 |
suarez12138/AI-Reversi_IMP_TextDichotomy | _minimize.py | standardize_bounds | standardize_bounds | Converts bounds to the form required by the solver. | [
"Converts",
"bounds",
"to",
"the",
"form",
"required",
"by",
"the",
"solver."
] | def standardize_bounds(bounds, x0, meth):
if meth in {'trust-constr', 'powell'}:
if not isinstance(bounds, Bounds):
(lb, ub) = old_bound_to_new(bounds)
bounds = Bounds(lb, ub)
elif meth in ('l-bfgs-b', 'tnc', 'slsqp'):
if isinstance(bounds, Bounds):
bounds = n... | ['def', 'standardize_bounds(bounds,', 'x0,', 'meth):', 'if', 'meth', 'in', "{'trust-constr',", "'powell'}:", 'if', 'not', 'isinstance(bounds,', 'Bounds):', '(lb,', 'ub)', '=', 'old_bound_to_new(bounds)', 'bounds', '=', 'Bounds(lb,', 'ub)', 'elif', 'meth', 'in', "('l-bfgs-b',", "'tnc',", "'slsqp'):", 'if', 'isinstance(b... | 99,746 |
omarmhaimdat/twitter_nlp_native_swift | request.py | localhost | localhost | Return the IP address of the magic hostname 'localhost'. | [
"Return",
"the",
"IP",
"address",
"of",
"the",
"magic",
"hostname",
"'localhost'."
] | def localhost():
global _localhost
if _localhost is None:
_localhost = socket.gethostbyname('localhost')
return _localhost | ['def', 'localhost():', 'global', '_localhost', 'if', '_localhost', 'is', 'None:', '_localhost', '=', "socket.gethostbyname('localhost')", 'return', '_localhost'] | 953,622 |
rlworkgroup/garage | test_tnpg.py | TestTNPG.test_tnpg_inverted_pendulum | test_tnpg_inverted_pendulum | Test TNPG with InvertedPendulum-v2 environment. | [
"Test",
"TNPG",
"with",
"InvertedPendulum-v2",
"environment."
] | def test_tnpg_inverted_pendulum(self):
with TFTrainer(snapshot_config, sess=self.sess) as trainer:
env = normalize(GymEnv('InvertedPendulum-v2'))
policy = GaussianMLPPolicy(name='policy', env_spec=env.spec, hidden_sizes=(32, 32))
baseline = LinearFeatureBaseline(env_spec=env.spec)
sa... | ['def', 'test_tnpg_inverted_pendulum(self):', 'with', 'TFTrainer(snapshot_config,', 'sess=self.sess)', 'as', 'trainer:', 'env', '=', "normalize(GymEnv('InvertedPendulum-v2'))", 'policy', '=', "GaussianMLPPolicy(name='policy',", 'env_spec=env.spec,', 'hidden_sizes=(32,', '32))', 'baseline', '=', 'LinearFeatureBaseline(e... | 200,948 |
sshleifer/object_detection_kitti | prediction_input.py | build_tfrecord_input | build_tfrecord_input | Create input tfrecord tensors. | [
"Create",
"input",
"tfrecord",
"tensors."
] | def build_tfrecord_input(training=True):
filenames = gfile.Glob(os.path.join(FLAGS.data_dir, '*'))
if not filenames:
raise RuntimeError('No data files found.')
index = int(np.floor(FLAGS.train_val_split * len(filenames)))
if training:
filenames = filenames[:index]
else:
filen... | ['def', 'build_tfrecord_input(training=True):', 'filenames', '=', 'gfile.Glob(os.path.join(FLAGS.data_dir,', "'*'))", 'if', 'not', 'filenames:', 'raise', "RuntimeError('No", 'data', 'files', "found.')", 'index', '=', 'int(np.floor(FLAGS.train_val_split', '*', 'len(filenames)))', 'if', 'training:', 'filenames', '=', 'fi... | 795,869 |
enuguru/artificial_intelligence_and_machine_learning | xri.py | escapeForIRI | escapeForIRI | Escape things that need to be escaped when transforming to an IRI. | [
"Escape",
"things",
"that",
"need",
"to",
"be",
"escaped",
"when",
"transforming",
"to",
"an",
"IRI."
] | def escapeForIRI(xri):
xri = xri.replace('%', '%25')
xri = _xref_re.sub(_escape_xref, xri)
return xri | ['def', 'escapeForIRI(xri):', 'xri', '=', "xri.replace('%',", "'%25')", 'xri', '=', '_xref_re.sub(_escape_xref,', 'xri)', 'return', 'xri'] | 130,490 |
famura/SimuRLacra | base.py | QuanserReal.close | close | Sends a zero-step and closes the communication. | [
"Sends",
"a",
"zero-step",
"and",
"closes",
"the",
"communication."
] | def close(self):
if self._qsoc.is_open():
for i in range(10):
self.step(np.zeros(self.act_space.shape))
self._qsoc.close()
print_cbt('Closed the connection to the Quanser device.', 'c') | ['def', 'close(self):', 'if', 'self._qsoc.is_open():', 'for', 'i', 'in', 'range(10):', 'self.step(np.zeros(self.act_space.shape))', 'self._qsoc.close()', "print_cbt('Closed", 'the', 'connection', 'to', 'the', 'Quanser', "device.',", "'c')"] | 883,689 |
Katja-M/Python_NaturalLanguageProcessing | gridspec.py | SubplotSpec.get_topmost_subplotspec | get_topmost_subplotspec | Return the topmost `SubplotSpec` instance associated with the subplot. | [
"Return",
"the",
"topmost",
"`SubplotSpec`",
"instance",
"associated",
"with",
"the",
"subplot."
] | def get_topmost_subplotspec(self):
gridspec = self.get_gridspec()
if hasattr(gridspec, 'get_topmost_subplotspec'):
return gridspec.get_topmost_subplotspec()
else:
return self | ['def', 'get_topmost_subplotspec(self):', 'gridspec', '=', 'self.get_gridspec()', 'if', 'hasattr(gridspec,', "'get_topmost_subplotspec'):", 'return', 'gridspec.get_topmost_subplotspec()', 'else:', 'return', 'self'] | 864,620 |
ivanmontero/autobot | modeling_utils.py | ModuleUtilsMixin.num_parameters | num_parameters | Get number of (optionally, trainable or non-embeddings) parameters in the module. | [
"Get",
"number",
"of",
"(optionally,",
"trainable",
"or",
"non-embeddings)",
"parameters",
"in",
"the",
"module."
] | def num_parameters(self, only_trainable: bool=False, exclude_embeddings: bool=False) -> int:
def parameter_filter(x):
return (x.requires_grad or not only_trainable) and (not (isinstance(x, torch.nn.Embedding) and exclude_embeddings))
params = filter(parameter_filter, self.parameters()) if only_trainabl... | ['def', 'num_parameters(self,', 'only_trainable:', 'bool=False,', 'exclude_embeddings:', 'bool=False)', '->', 'int:', 'def', 'parameter_filter(x):', 'return', '(x.requires_grad', 'or', 'not', 'only_trainable)', 'and', '(not', '(isinstance(x,', 'torch.nn.Embedding)', 'and', 'exclude_embeddings))', 'params', '=', 'filter... | 418,168 |
sarnsdev/social-alignment-data-mining | core.py | MaskedArray.baseclass | baseclass | Class of the underlying data (read-only). | [
"Class",
"of",
"the",
"underlying",
"data",
"(read-only)."
] | def baseclass(self):
return self._baseclass | ['def', 'baseclass(self):', 'return', 'self._baseclass'] | 389,466 |
LucasAlegre/morl-baselines | gpi_pd_continuous_action.py | GPIPDContinuousAction.set_weight_support | set_weight_support | Set the weight support set. | [
"Set",
"the",
"weight",
"support",
"set."
] | def set_weight_support(self, weight_list: List[np.ndarray]):
weights_no_repeat = unique_tol(weight_list)
self.weight_support = [th.tensor(w).float().to(self.device) for w in weights_no_repeat]
if len(self.weight_support) > 0:
self.stacked_weight_support = th.stack(self.weight_support) | ['def', 'set_weight_support(self,', 'weight_list:', 'List[np.ndarray]):', 'weights_no_repeat', '=', 'unique_tol(weight_list)', 'self.weight_support', '=', '[th.tensor(w).float().to(self.device)', 'for', 'w', 'in', 'weights_no_repeat]', 'if', 'len(self.weight_support)', '>', '0:', 'self.stacked_weight_support', '=', 'th... | 655,897 |
intel/neural-compressor | util.py | get_mse_order_per_fp32 | get_mse_order_per_fp32 | This is a helper method to check the mse influence to last module after QDQ(quant/dequant). | [
"This",
"is",
"a",
"helper",
"method",
"to",
"check",
"the",
"mse",
"influence",
"to",
"last",
"module",
"after",
"QDQ(quant/dequant)."
] | def get_mse_order_per_fp32(adaptor, model, example_inp, tune_cfg):
inner_output = None
def output_hook(self, input, output):
nonlocal inner_output
inner_output = output
return output
op_type_dict = {}
for (k, v) in tune_cfg['op'].keys():
op_type_dict[k] = v
from ..py... | ['def', 'get_mse_order_per_fp32(adaptor,', 'model,', 'example_inp,', 'tune_cfg):', 'inner_output', '=', 'None', 'def', 'output_hook(self,', 'input,', 'output):', 'nonlocal', 'inner_output', 'inner_output', '=', 'output', 'return', 'output', 'op_type_dict', '=', '{}', 'for', '(k,', 'v)', 'in', "tune_cfg['op'].keys():", ... | 737,908 |
RasaHQ/rasa_core | utils.py | cancel_cause_not_found | cancel_cause_not_found | Exits with an error because the given path was not valid. | [
"Exits",
"with",
"an",
"error",
"because",
"the",
"given",
"path",
"was",
"not",
"valid."
] | def cancel_cause_not_found(current: Optional[Text], parameter: Text, default: Optional[Text]) -> None:
default_clause = ''
if default:
default_clause = "use the default location ('{}') or ".format(default)
print_error("The path '{}' does not exist. Please make sure to {}specify it with '--{}'.".form... | ['def', 'cancel_cause_not_found(current:', 'Optional[Text],', 'parameter:', 'Text,', 'default:', 'Optional[Text])', '->', 'None:', 'default_clause', '=', "''", 'if', 'default:', 'default_clause', '=', '"use', 'the', 'default', 'location', "('{}')", 'or', '".format(default)', 'print_error("The', 'path', "'{}'", 'does', ... | 838,143 |
Ruturaj123/Flowchart-Detection | device.py | DeviceSpec.parse_from_string | parse_from_string | Parse a `DeviceSpec` name into its components. | [
"Parse",
"a",
"`DeviceSpec`",
"name",
"into",
"its",
"components."
] | def parse_from_string(self, spec):
self._clear()
splits = [x.split(':') for x in spec.split('/')]
for y in splits:
ly = len(y)
if y:
if ly == 2 and y[0] == 'job':
self.job = y[1]
elif ly == 2 and y[0] == 'replica':
self.replica = y[1]
... | ['def', 'parse_from_string(self,', 'spec):', 'self._clear()', 'splits', '=', "[x.split(':')", 'for', 'x', 'in', "spec.split('/')]", 'for', 'y', 'in', 'splits:', 'ly', '=', 'len(y)', 'if', 'y:', 'if', 'ly', '==', '2', 'and', 'y[0]', '==', "'job':", 'self.job', '=', 'y[1]', 'elif', 'ly', '==', '2', 'and', 'y[0]', '==', "... | 605,321 |
rlworkgroup/garage | conjugate_gradient_optimizer.py | ConjugateGradientOptimizer.step | step | Take an optimization step. | [
"Take",
"an",
"optimization",
"step."
] | def step(self, f_loss, f_constraint):
params = []
grads = []
for group in self.param_groups:
for p in group['params']:
if p.grad is not None:
params.append(p)
grads.append(p.grad.reshape(-1))
flat_loss_grads = torch.cat(grads)
f_Ax = _build_hessian... | ['def', 'step(self,', 'f_loss,', 'f_constraint):', 'params', '=', '[]', 'grads', '=', '[]', 'for', 'group', 'in', 'self.param_groups:', 'for', 'p', 'in', "group['params']:", 'if', 'p.grad', 'is', 'not', 'None:', 'params.append(p)', 'grads.append(p.grad.reshape(-1))', 'flat_loss_grads', '=', 'torch.cat(grads)', 'f_Ax', ... | 200,798 |
racsa-lab/Edge-Detect | protoNN.py | ProtoNN.getPredictionsOp | getPredictionsOp | The predictions operator is defined as argmax(protoNNScores) for each prediction. | [
"The",
"predictions",
"operator",
"is",
"defined",
"as",
"argmax(protoNNScores)",
"for",
"each",
"prediction."
] | def getPredictionsOp(self):
return self.predictions | ['def', 'getPredictionsOp(self):', 'return', 'self.predictions'] | 548,125 |
acba/elm | mltools.py | CVError.print_errors | print_errors | Print a mean of all error through all folds. | [
"Print",
"a",
"mean",
"of",
"all",
"error",
"through",
"all",
"folds."
] | def print_errors(self):
for error in sorted(self.all_fold_errors.keys()):
print(error, ' mean:', self.all_fold_mean_errors[error])
print(self.all_fold_errors[error], '\n')
print() | ['def', 'print_errors(self):', 'for', 'error', 'in', 'sorted(self.all_fold_errors.keys()):', 'print(error,', "'", "mean:',", 'self.all_fold_mean_errors[error])', 'print(self.all_fold_errors[error],', "'\\n')", 'print()'] | 561,471 |
intel/neural-compressor | onnx_model.py | ONNXModel.graph_info | graph_info | Return ORT Graph Info object holding information about backend graph. | [
"Return",
"ORT",
"Graph",
"Info",
"object",
"holding",
"information",
"about",
"backend",
"graph."
] | def graph_info(self):
return self._graph_info | ['def', 'graph_info(self):', 'return', 'self._graph_info'] | 738,873 |
intel/neural-compressor | quantization.py | Quantization.execute | execute | Quantization execute routine based on strategy design. | [
"Quantization",
"execute",
"routine",
"based",
"on",
"strategy",
"design."
] | def execute(self):
try:
with time_limit(self.conf.usr_cfg.tuning.exit_policy.timeout):
logger.debug('Dump user yaml configuration:')
logger.debug(self.conf.usr_cfg)
self.strategy.traverse()
except KeyboardInterrupt:
pass
except Exception as e:
logg... | ['def', 'execute(self):', 'try:', 'with', 'time_limit(self.conf.usr_cfg.tuning.exit_policy.timeout):', "logger.debug('Dump", 'user', 'yaml', "configuration:')", 'logger.debug(self.conf.usr_cfg)', 'self.strategy.traverse()', 'except', 'KeyboardInterrupt:', 'pass', 'except', 'Exception', 'as', 'e:', "logger.error('Unexpe... | 738,413 |
myothida/Supervised-Machine-Learning | ast.py | GlyphClass.add_class | add_class | Add glyphs from the given :class:`GlyphClassName` object to the class. | [
"Add",
"glyphs",
"from",
"the",
"given",
":class:`GlyphClassName`",
"object",
"to",
"the",
"class."
] | def add_class(self, gc):
if self.curr < len(self.glyphs):
self.original.extend(self.glyphs[self.curr:])
self.original.append(gc)
self.glyphs.extend(gc.glyphSet())
self.curr = len(self.glyphs) | ['def', 'add_class(self,', 'gc):', 'if', 'self.curr', '<', 'len(self.glyphs):', 'self.original.extend(self.glyphs[self.curr:])', 'self.original.append(gc)', 'self.glyphs.extend(gc.glyphSet())', 'self.curr', '=', 'len(self.glyphs)'] | 360,844 |
atang020/reinforcement | link.py | Link.run | run | Execute the best action without applying learning. | [
"Execute",
"the",
"best",
"action",
"without",
"applying",
"learning."
] | def run(self, env):
self.action = self.argmax(self.make_state(env))
(self.state, self.reward) = env.execute(self.action)
return (self.action, self.state) | ['def', 'run(self,', 'env):', 'self.action', '=', 'self.argmax(self.make_state(env))', '(self.state,', 'self.reward)', '=', 'env.execute(self.action)', 'return', '(self.action,', 'self.state)'] | 286,795 |
muhanzhang/D-VAE | test_ifelse.py | test_ifelse.test_grad_test_values | test_grad_test_values | Regression test for test values of `ifelse` gradient. | [
"Regression",
"test",
"for",
"test",
"values",
"of",
"`ifelse`",
"gradient."
] | def test_grad_test_values(self):
backup = theano.config.compute_test_value
theano.config.compute_test_value = 'raise'
try:
x = tensor.scalar('x')
x.tag.test_value = 1
tensor.grad(ifelse(0, x, x), x)
finally:
theano.config.compute_test_value = backup | ['def', 'test_grad_test_values(self):', 'backup', '=', 'theano.config.compute_test_value', 'theano.config.compute_test_value', '=', "'raise'", 'try:', 'x', '=', "tensor.scalar('x')", 'x.tag.test_value', '=', '1', 'tensor.grad(ifelse(0,', 'x,', 'x),', 'x)', 'finally:', 'theano.config.compute_test_value', '=', 'backup'] | 525,956 |
alibaba/EasyReinforcementLearning | apex_agent.py | ApexAgent.learn | learn | Update upon a batch and send the td_errors to memories if needed Returns: extra_results (dict): contains the fields computed during an update. | [
"Update",
"upon",
"a",
"batch",
"and",
"send",
"the",
"td_errors",
"to",
"memories",
"if",
"needed",
"Returns:",
"extra_results",
"(dict):",
"contains",
"the",
"fields",
"computed",
"during",
"an",
"update."
] | def learn(self, batch_data):
buffer_id = batch_data.pop('buffer_id', 0)
extra_results = super(ApexAgent, self).learn(batch_data, is_chief=self.distributed_handler.is_chief)
extra_results['buffer_id'] = buffer_id
if self.config.get('prioritized_replay', False) and (not self._learner2mem_q.full()):
... | ['def', 'learn(self,', 'batch_data):', 'buffer_id', '=', "batch_data.pop('buffer_id',", '0)', 'extra_results', '=', 'super(ApexAgent,', 'self).learn(batch_data,', 'is_chief=self.distributed_handler.is_chief)', "extra_results['buffer_id']", '=', 'buffer_id', 'if', "self.config.get('prioritized_replay',", 'False)', 'and'... | 174,827 |
ifwe/digsby | __init__.py | create | create | Opens the "create widget" page in a web browser. | [
"Opens",
"the",
"\"create",
"widget\"",
"page",
"in",
"a",
"web",
"browser."
] | def create():
from digsby.web.weblogin import autologin
from common import profile
autologin(profile.username, profile.password, 'http://widget.digsby.com') | ['def', 'create():', 'from', 'digsby.web.weblogin', 'import', 'autologin', 'from', 'common', 'import', 'profile', 'autologin(profile.username,', 'profile.password,', "'http://widget.digsby.com')"] | 185,240 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.