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
awslabs/predictive-maintenance-using--
datetimelike.py
DatetimeIndexOpsMixin.freqstr
freqstr
Return the frequency object as a string if it is set, otherwise None.
[ "Return", "the", "frequency", "object", "as", "a", "string", "if", "it", "is", "set,", "otherwise", "None." ]
def freqstr(self): return self._data.freqstr
['def', 'freqstr(self):', 'return', 'self._data.freqstr']
823,594
sunishsheth2009/ChatterBot
util.py
state_str
state_str
Return a string describing an instance via its InstanceState.
[ "Return", "a", "string", "describing", "an", "instance", "via", "its", "InstanceState." ]
def state_str(state): if state is None: return 'None' else: return '<%s at 0x%x>' % (state.class_.__name__, id(state.obj()))
['def', 'state_str(state):', 'if', 'state', 'is', 'None:', 'return', "'None'", 'else:', 'return', "'<%s", 'at', "0x%x>'", '%', '(state.class_.__name__,', 'id(state.obj()))']
534,777
devashish-patel/webcam-motion-detector
data.py
YamlLexer.reset_indent
reset_indent
Reset the indentation levels.
[ "Reset", "the", "indentation", "levels." ]
def reset_indent(token_class): def callback(lexer, match, context): text = match.group() context.indent_stack = [] context.indent = -1 context.next_indent = 0 context.block_scalar_indent = None yield (match.start(), token_class, text) context.pos = match.end(...
['def', 'reset_indent(token_class):', 'def', 'callback(lexer,', 'match,', 'context):', 'text', '=', 'match.group()', 'context.indent_stack', '=', '[]', 'context.indent', '=', '-1', 'context.next_indent', '=', '0', 'context.block_scalar_indent', '=', 'None', 'yield', '(match.start(),', 'token_class,', 'text)', 'context....
984,162
thaines/helit
viewer.py
Viewer.add_layer
add_layer
Adds a layer to the end of the layer list, returns an id you can use to delete it.
[ "Adds", "a", "layer", "to", "the", "end", "of", "the", "layer", "list,", "returns", "an", "id", "you", "can", "use", "to", "delete", "it." ]
def add_layer(self, layer): assert isinstance(layer, Layer) ret = len(self.layers) self.layers.append(layer) return ret
['def', 'add_layer(self,', 'layer):', 'assert', 'isinstance(layer,', 'Layer)', 'ret', '=', 'len(self.layers)', 'self.layers.append(layer)', 'return', 'ret']
592,739
google-research/rigl
masked_test.py
MaskedTest.test_propagate_masks_ablated_neurons_three_conv_fc_layers
test_propagate_masks_ablated_neurons_three_conv_fc_layers
Tests mask propagation on a two-layer convolutional model with dense.
[ "Tests", "mask", "propagation", "on", "a", "two-layer", "convolutional", "model", "with", "dense." ]
def test_propagate_masks_ablated_neurons_three_conv_fc_layers(self): mask = {'MaskedModule_0': {'kernel': jnp.zeros(self._masked_conv_fc_model_threelayer.params['MaskedModule_0']['unmasked']['kernel'].shape), 'bias': None}, 'MaskedModule_1': {'kernel': jnp.ones(self._masked_conv_fc_model_threelayer.params['MaskedMo...
['def', 'test_propagate_masks_ablated_neurons_three_conv_fc_layers(self):', 'mask', '=', "{'MaskedModule_0':", "{'kernel':", "jnp.zeros(self._masked_conv_fc_model_threelayer.params['MaskedModule_0']['unmasked']['kernel'].shape),", "'bias':", 'None},', "'MaskedModule_1':", "{'kernel':", "jnp.ones(self._masked_conv_fc_mo...
841,494
KalleHallden/InstaAutomator
filetype.py
guess_extension
guess_extension
Infers the file type of the given input and returns its RFC file extension.
[ "Infers", "the", "file", "type", "of", "the", "given", "input", "and", "returns", "its", "RFC", "file", "extension." ]
def guess_extension(obj): kind = guess(obj) return kind.extension if kind else kind
['def', 'guess_extension(obj):', 'kind', '=', 'guess(obj)', 'return', 'kind.extension', 'if', 'kind', 'else', 'kind']
229,908
youngjoo-epfl/gconvRNN
graph.py
grid
grid
Return the embedding of a grid graph.
[ "Return", "the", "embedding", "of", "a", "grid", "graph." ]
def grid(m, dtype=np.float32): M = m ** 2 x = np.linspace(0, 1, m, dtype=dtype) y = np.linspace(0, 1, m, dtype=dtype) (xx, yy) = np.meshgrid(x, y) z = np.empty((M, 2), dtype) z[:, 0] = xx.reshape(M) z[:, 1] = yy.reshape(M) return z
['def', 'grid(m,', 'dtype=np.float32):', 'M', '=', 'm', '**', '2', 'x', '=', 'np.linspace(0,', '1,', 'm,', 'dtype=dtype)', 'y', '=', 'np.linspace(0,', '1,', 'm,', 'dtype=dtype)', '(xx,', 'yy)', '=', 'np.meshgrid(x,', 'y)', 'z', '=', 'np.empty((M,', '2),', 'dtype)', 'z[:,', '0]', '=', 'xx.reshape(M)', 'z[:,', '1]', '=',...
201,410
FishYuLi/BalancedGroupSoftmax
lvis.py
LVIS.ann_to_rle
ann_to_rle
Convert annotation which can be polygons, uncompressed RLE to RLE.
[ "Convert", "annotation", "which", "can", "be", "polygons,", "uncompressed", "RLE", "to", "RLE." ]
def ann_to_rle(self, ann): img_data = self.imgs[ann['image_id']] (h, w) = (img_data['height'], img_data['width']) segm = ann['segmentation'] if isinstance(segm, list): rles = mask_utils.frPyObjects(segm, h, w) rle = mask_utils.merge(rles) elif isinstance(segm['counts'], list): ...
['def', 'ann_to_rle(self,', 'ann):', 'img_data', '=', "self.imgs[ann['image_id']]", '(h,', 'w)', '=', "(img_data['height'],", "img_data['width'])", 'segm', '=', "ann['segmentation']", 'if', 'isinstance(segm,', 'list):', 'rles', '=', 'mask_utils.frPyObjects(segm,', 'h,', 'w)', 'rle', '=', 'mask_utils.merge(rles)', 'elif...
422,208
lxtGH/CAE
dataset_folder.py
is_image_file
is_image_file
Checks if a file is an allowed image extension.
[ "Checks", "if", "a", "file", "is", "an", "allowed", "image", "extension." ]
def is_image_file(filename: str) -> bool: return has_file_allowed_extension(filename, IMG_EXTENSIONS)
['def', 'is_image_file(filename:', 'str)', '->', 'bool:', 'return', 'has_file_allowed_extension(filename,', 'IMG_EXTENSIONS)']
108,849
tensorflow/data-validation
artifacts_io_impl.py
get_io_provider
get_io_provider
Get a StatisticsIOProvider for writing and reading sharded stats.
[ "Get", "a", "StatisticsIOProvider", "for", "writing", "and", "reading", "sharded", "stats." ]
def get_io_provider(file_format: Optional[str]=None) -> StatisticsIOProvider: if file_format is None: file_format = 'tfrecords' if file_format not in ('tfrecords',): raise ValueError('Unrecognized file_format %s' % file_format) return _TFRecordProviderImpl()
['def', 'get_io_provider(file_format:', 'Optional[str]=None)', '->', 'StatisticsIOProvider:', 'if', 'file_format', 'is', 'None:', 'file_format', '=', "'tfrecords'", 'if', 'file_format', 'not', 'in', "('tfrecords',):", 'raise', "ValueError('Unrecognized", 'file_format', "%s'", '%', 'file_format)', 'return', '_TFRecordPr...
497,583
chribsen/simple-machine-learning-examples
ols.py
MovingOLS.var_beta
var_beta
Returns the covariance of beta.
[ "Returns", "the", "covariance", "of", "beta." ]
def var_beta(self): result = {} result_index = self._result_index for i in range(len(self._var_beta_raw)): dm = DataFrame(self._var_beta_raw[i], columns=self.beta.columns, index=self.beta.columns) result[result_index[i]] = dm return Panel.from_dict(result, intersect=False)
['def', 'var_beta(self):', 'result', '=', '{}', 'result_index', '=', 'self._result_index', 'for', 'i', 'in', 'range(len(self._var_beta_raw)):', 'dm', '=', 'DataFrame(self._var_beta_raw[i],', 'columns=self.beta.columns,', 'index=self.beta.columns)', 'result[result_index[i]]', '=', 'dm', 'return', 'Panel.from_dict(result...
936,593
xvjiarui/VFS
rawframe_dataset.py
RawframeDataset.load_annotations
load_annotations
Load annotation file to get video information.
[ "Load", "annotation", "file", "to", "get", "video", "information." ]
def load_annotations(self): if self.ann_file.endswith('.json'): return self.load_json_annotations() video_infos = [] with open(self.ann_file, 'r') as fin: for line in fin: line_split = line.strip().split() video_info = {} idx = 0 frame_dir = li...
['def', 'load_annotations(self):', 'if', "self.ann_file.endswith('.json'):", 'return', 'self.load_json_annotations()', 'video_infos', '=', '[]', 'with', 'open(self.ann_file,', "'r')", 'as', 'fin:', 'for', 'line', 'in', 'fin:', 'line_split', '=', 'line.strip().split()', 'video_info', '=', '{}', 'idx', '=', '0', 'frame_d...
379,573
sjtu-marl/malib
rolloutworker.py
validate_agent_group
validate_agent_group
Validate agent group, check spaces.
[ "Validate", "agent", "group,", "check", "spaces." ]
def validate_agent_group(agent_group: Dict[str, List[AgentID]], full_keys: List[AgentID], observation_spaces: Dict[AgentID, gym.Space], action_spaces: Dict[AgentID, gym.Space]) -> None: for agents in agent_group.values(): select_obs_space = observation_spaces[agents[0]] select_act_space = action_spa...
['def', 'validate_agent_group(agent_group:', 'Dict[str,', 'List[AgentID]],', 'full_keys:', 'List[AgentID],', 'observation_spaces:', 'Dict[AgentID,', 'gym.Space],', 'action_spaces:', 'Dict[AgentID,', 'gym.Space])', '->', 'None:', 'for', 'agents', 'in', 'agent_group.values():', 'select_obs_space', '=', 'observation_space...
627,555
jshilong/DDQ
cc_attention.py
CrissCrossAttention.forward
forward
forward function of Criss-Cross Attention.
[ "forward", "function", "of", "Criss-Cross", "Attention." ]
def forward(self, x): (B, C, H, W) = x.size() query = self.query_conv(x) key = self.key_conv(x) value = self.value_conv(x) energy_H = torch.einsum('bchw,bciw->bwhi', query, key) + NEG_INF_DIAG(H, query.device) energy_H = energy_H.transpose(1, 2) energy_W = torch.einsum('bchw,bchj->bhwj', que...
['def', 'forward(self,', 'x):', '(B,', 'C,', 'H,', 'W)', '=', 'x.size()', 'query', '=', 'self.query_conv(x)', 'key', '=', 'self.key_conv(x)', 'value', '=', 'self.value_conv(x)', 'energy_H', '=', "torch.einsum('bchw,bciw->bwhi',", 'query,', 'key)', '+', 'NEG_INF_DIAG(H,', 'query.device)', 'energy_H', '=', 'energy_H.tran...
499,081
clips/pattern
metrics.py
kb
kb
Returns the memory size of the given object (in kilobytes).
[ "Returns", "the", "memory", "size", "of", "the", "given", "object", "(in", "kilobytes)." ]
def kb(object): return sys.getsizeof(object) * 0.01
['def', 'kb(object):', 'return', 'sys.getsizeof(object)', '*', '0.01']
764,484
TonyLianLong/VAI-ReinforcementLearning
wrappers.py
MjModelWrapper.qpos0
qpos0
qpos values at default pose (nq x 1).
[ "qpos", "values", "at", "default", "pose", "(nq", "x", "1)." ]
def qpos0(self): return util.buf_to_npy(self._ptr.contents.qpos0, (self.nq,))
['def', 'qpos0(self):', 'return', 'util.buf_to_npy(self._ptr.contents.qpos0,', '(self.nq,))']
440,233
fangqin0703/omscs6476
ps2.py
traffic_sign_detection_challenge
traffic_sign_detection_challenge
Finds traffic signs in an real image See point 5 in the instructions for details.
[ "Finds", "traffic", "signs", "in", "an", "real", "image", "See", "point", "5", "in", "the", "instructions", "for", "details." ]
def traffic_sign_detection_challenge(img_in): return traffic_sign_detection(img_in) raise NotImplementedError
['def', 'traffic_sign_detection_challenge(img_in):', 'return', 'traffic_sign_detection(img_in)', 'raise', 'NotImplementedError']
755,741
thaines/helit
params_sets.py
ParamsSet.addRange
addRange
Adds a new ParamsRange to the set.
[ "Adds", "a", "new", "ParamsRange", "to", "the", "set." ]
def addRange(self, ran): self.ranges.append(ran)
['def', 'addRange(self,', 'ran):', 'self.ranges.append(ran)']
592,564
matsu0228/nlp-jp
__init__.py
Xlator.xlat
xlat
Translate *text*, returns the modified text.
[ "Translate", "*text*,", "returns", "the", "modified", "text." ]
def xlat(self, text): return self._make_regex().sub(self, text)
['def', 'xlat(self,', 'text):', 'return', 'self._make_regex().sub(self,', 'text)']
789,753
keras-team/keras-cv
base_augmentation_layer_3d.py
BaseAugmentationLayer3D.augment_point_clouds_bounding_boxes
augment_point_clouds_bounding_boxes
Augment a single point cloud frame during training.
[ "Augment", "a", "single", "point", "cloud", "frame", "during", "training." ]
def augment_point_clouds_bounding_boxes(self, point_clouds, bounding_boxes, transformation, **kwargs): raise NotImplementedError()
['def', 'augment_point_clouds_bounding_boxes(self,', 'point_clouds,', 'bounding_boxes,', 'transformation,', '**kwargs):', 'raise', 'NotImplementedError()']
595,113
matsu0228/nlp-jp
sharded_corpus.py
ShardedCorpus.init_shards
init_shards
Initialize shards from the corpus.
[ "Initialize", "shards", "from", "the", "corpus." ]
def init_shards(self, output_prefix, corpus, shardsize=4096, dtype=_default_dtype): (is_corpus, corpus) = gensim.utils.is_corpus(corpus) if not is_corpus: raise ValueError('Cannot initialize shards without a corpus to read from! (Got corpus type: {0})'.format(type(corpus))) proposed_dim = self._gues...
['def', 'init_shards(self,', 'output_prefix,', 'corpus,', 'shardsize=4096,', 'dtype=_default_dtype):', '(is_corpus,', 'corpus)', '=', 'gensim.utils.is_corpus(corpus)', 'if', 'not', 'is_corpus:', 'raise', "ValueError('Cannot", 'initialize', 'shards', 'without', 'a', 'corpus', 'to', 'read', 'from!', '(Got', 'corpus', 'ty...
785,704
AgnostiqHQ/covalent
load.py
electron_record
electron_record
Get electron record for a given dispatch if and node id.
[ "Get", "electron", "record", "for", "a", "given", "dispatch", "if", "and", "node", "id." ]
def electron_record(dispatch_id: str, node_id: str) -> Dict: with workflow_db.session() as session: return session.query(Lattice, Electron).filter(Lattice.id == Electron.parent_lattice_id).filter(Lattice.dispatch_id == dispatch_id).filter(Electron.transport_graph_node_id == node_id).first().Electron.__dict_...
['def', 'electron_record(dispatch_id:', 'str,', 'node_id:', 'str)', '->', 'Dict:', 'with', 'workflow_db.session()', 'as', 'session:', 'return', 'session.query(Lattice,', 'Electron).filter(Lattice.id', '==', 'Electron.parent_lattice_id).filter(Lattice.dispatch_id', '==', 'dispatch_id).filter(Electron.transport_graph_nod...
489,606
hoxmark/Deep_reinforcement_active_learning
vocab.py
build_vocab
build_vocab
Build a simple vocabulary wrapper.
[ "Build", "a", "simple", "vocabulary", "wrapper." ]
def build_vocab(data_path, data_name, jsons, threshold): counter = Counter() for path in jsons[data_name]: full_path = os.path.join(os.path.join(data_path, data_name), path) if data_name == 'f8k' or data_name == 'f30k': captions = from_flickr_json(full_path) else: ...
['def', 'build_vocab(data_path,', 'data_name,', 'jsons,', 'threshold):', 'counter', '=', 'Counter()', 'for', 'path', 'in', 'jsons[data_name]:', 'full_path', '=', 'os.path.join(os.path.join(data_path,', 'data_name),', 'path)', 'if', 'data_name', '==', "'f8k'", 'or', 'data_name', '==', "'f30k':", 'captions', '=', 'from_f...
536,852
autonomousvision/differentiable_volumetric_rendering
common.py
normalize_imagenet
normalize_imagenet
Normalize input images according to ImageNet standards.
[ "Normalize", "input", "images", "according", "to", "ImageNet", "standards." ]
def normalize_imagenet(x): x = x.clone() x[:, 0] = (x[:, 0] - 0.485) / 0.229 x[:, 1] = (x[:, 1] - 0.456) / 0.224 x[:, 2] = (x[:, 2] - 0.406) / 0.225 return x
['def', 'normalize_imagenet(x):', 'x', '=', 'x.clone()', 'x[:,', '0]', '=', '(x[:,', '0]', '-', '0.485)', '/', '0.229', 'x[:,', '1]', '=', '(x[:,', '1]', '-', '0.456)', '/', '0.224', 'x[:,', '2]', '=', '(x[:,', '2]', '-', '0.406)', '/', '0.225', 'return', 'x']
184,986
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
utils.py
get_policy
get_policy
Get a policy network.
[ "Get", "a", "policy", "network." ]
def get_policy(observations, hparams): policy_network_lambda = hparams.policy_network action_space = get_action_space(hparams.environment_spec) return policy_network_lambda(action_space, hparams, observations)
['def', 'get_policy(observations,', 'hparams):', 'policy_network_lambda', '=', 'hparams.policy_network', 'action_space', '=', 'get_action_space(hparams.environment_spec)', 'return', 'policy_network_lambda(action_space,', 'hparams,', 'observations)']
966,039
SamHusbands21/thesis
Oh_array.py
rand
rand
Returns an OhArray of shape size, with randomly chosen elements in int parameterization.
[ "Returns", "an", "OhArray", "of", "shape", "size,", "with", "randomly", "chosen", "elements", "in", "int", "parameterization." ]
def rand(size=()): data = np.zeros(size + (2,), dtype=np.int) data[..., 0] = np.random.randint(0, 24, size) data[..., 1] = np.random.randint(0, 2, size) return OhArray(data=data, p='int')
['def', 'rand(size=()):', 'data', '=', 'np.zeros(size', '+', '(2,),', 'dtype=np.int)', 'data[...,', '0]', '=', 'np.random.randint(0,', '24,', 'size)', 'data[...,', '1]', '=', 'np.random.randint(0,', '2,', 'size)', 'return', 'OhArray(data=data,', "p='int')"]
354,855
omarmhaimdat/twitter_nlp_native_swift
twitter_utils.py
parse_media_file
parse_media_file
Parses a media file and attempts to return a file-like object and information about the media file.
[ "Parses", "a", "media", "file", "and", "attempts", "to", "return", "a", "file-like", "object", "and", "information", "about", "the", "media", "file." ]
def parse_media_file(passed_media, async_upload=False): img_formats = ['image/jpeg', 'image/png', 'image/bmp', 'image/webp'] long_img_formats = ['image/gif'] video_formats = ['video/mp4', 'video/quicktime'] if not hasattr(passed_media, 'read'): if passed_media.startswith('http'): dat...
['def', 'parse_media_file(passed_media,', 'async_upload=False):', 'img_formats', '=', "['image/jpeg',", "'image/png',", "'image/bmp',", "'image/webp']", 'long_img_formats', '=', "['image/gif']", 'video_formats', '=', "['video/mp4',", "'video/quicktime']", 'if', 'not', 'hasattr(passed_media,', "'read'):", 'if', "passed_...
955,197
TrellixVulnTeam/Unsupervised_Learning_HFI7
__init__.py
should_reindex_frame_op
should_reindex_frame_op
Check if this is an operation between DataFrames that will need to reindex.
[ "Check", "if", "this", "is", "an", "operation", "between", "DataFrames", "that", "will", "need", "to", "reindex." ]
def should_reindex_frame_op(left: 'DataFrame', right, op, axis, default_axis, fill_value, level) -> bool: assert isinstance(left, ABCDataFrame) if op is operator.pow or op is rpow: return False if not isinstance(right, ABCDataFrame): return False if fill_value is None and level is None a...
['def', 'should_reindex_frame_op(left:', "'DataFrame',", 'right,', 'op,', 'axis,', 'default_axis,', 'fill_value,', 'level)', '->', 'bool:', 'assert', 'isinstance(left,', 'ABCDataFrame)', 'if', 'op', 'is', 'operator.pow', 'or', 'op', 'is', 'rpow:', 'return', 'False', 'if', 'not', 'isinstance(right,', 'ABCDataFrame):', '...
453,326
deepmind/dm_control
trajectory.py
Trajectory.clip_end_time
clip_end_time
Length of the full clip.
[ "Length", "of", "the", "full", "clip." ]
def clip_end_time(self): return (len(self._proto.timesteps) - 1) * self._proto.dt
['def', 'clip_end_time(self):', 'return', '(len(self._proto.timesteps)', '-', '1)', '*', 'self._proto.dt']
165,934
frapa/tbcnn
train_variants.py
create_sets
create_sets
Splits the array into num equally sized sets.
[ "Splits", "the", "array", "into", "num", "equally", "sized", "sets." ]
def create_sets(num, images, labels): (images, labels) = shuffle(images, labels) set_size = images.shape[0] // num remaining = images.shape[0] - set_size * num image_sets = [] label_sets = [] offset = 0 for i in range(num): extra = 1 if i < remaining else 0 image_sets.append(...
['def', 'create_sets(num,', 'images,', 'labels):', '(images,', 'labels)', '=', 'shuffle(images,', 'labels)', 'set_size', '=', 'images.shape[0]', '//', 'num', 'remaining', '=', 'images.shape[0]', '-', 'set_size', '*', 'num', 'image_sets', '=', '[]', 'label_sets', '=', '[]', 'offset', '=', '0', 'for', 'i', 'in', 'range(n...
365,529
KalleHallden/InstaAutomator
ffmpeg_tools.py
ffmpeg_resize
ffmpeg_resize
resizes ``video`` to new size ``size`` and write the result in file ``output``.
[ "resizes", "``video``", "to", "new", "size", "``size``", "and", "write", "the", "result", "in", "file", "``output``." ]
def ffmpeg_resize(video, output, size): cmd = [get_setting('FFMPEG_BINARY'), '-i', video, '-vf', 'scale=%d:%d' % (res[0], res[1]), output] subprocess_call(cmd)
['def', 'ffmpeg_resize(video,', 'output,', 'size):', 'cmd', '=', "[get_setting('FFMPEG_BINARY'),", "'-i',", 'video,', "'-vf',", "'scale=%d:%d'", '%', '(res[0],', 'res[1]),', 'output]', 'subprocess_call(cmd)']
242,937
UAVs-at-Berkeley/flywave
vlc.py
MediaPlayer.pause
pause
Toggle pause (no effect if there is no media).
[ "Toggle", "pause", "(no", "effect", "if", "there", "is", "no", "media)." ]
def pause(self): return libvlc_media_player_pause(self)
['def', 'pause(self):', 'return', 'libvlc_media_player_pause(self)']
607,836
rudranil723/mini-main
testcases.py
SimpleTestCase.settings
settings
A context manager that temporarily sets a setting and reverts to the original value when exiting the context.
[ "A", "context", "manager", "that", "temporarily", "sets", "a", "setting", "and", "reverts", "to", "the", "original", "value", "when", "exiting", "the", "context." ]
def settings(self, **kwargs): return override_settings(**kwargs)
['def', 'settings(self,', '**kwargs):', 'return', 'override_settings(**kwargs)']
316,563
nicknochnack/RealTimeSignLanguageTFJS
instance_heads.py
MaskHead.build
build
Creates the variables of the head.
[ "Creates", "the", "variables", "of", "the", "head." ]
def build(self, input_shape): conv_op = tf.keras.layers.SeparableConv2D if self._config_dict['use_separable_conv'] else tf.keras.layers.Conv2D conv_kwargs = {'filters': self._config_dict['num_filters'], 'kernel_size': 3, 'padding': 'same'} if self._config_dict['use_separable_conv']: conv_kwargs.upda...
['def', 'build(self,', 'input_shape):', 'conv_op', '=', 'tf.keras.layers.SeparableConv2D', 'if', "self._config_dict['use_separable_conv']", 'else', 'tf.keras.layers.Conv2D', 'conv_kwargs', '=', "{'filters':", "self._config_dict['num_filters'],", "'kernel_size':", '3,', "'padding':", "'same'}", 'if', "self._config_dict[...
850,847
IntelAI/transfer-learning
seq2seq.py
variational_encoder_with_buckets
variational_encoder_with_buckets
Create a sequence-to-sequence model with support for bucketing.
[ "Create", "a", "sequence-to-sequence", "model", "with", "support", "for", "bucketing." ]
def variational_encoder_with_buckets(encoder_inputs, buckets, encoder, enc_latent, softmax_loss_function=None, per_example_loss=False, name=None): if len(encoder_inputs) < buckets[-1][0]: raise ValueError('Length of encoder_inputs (%d) must be at least that of last bucket (%d).' % (len(encoder_inputs), buck...
['def', 'variational_encoder_with_buckets(encoder_inputs,', 'buckets,', 'encoder,', 'enc_latent,', 'softmax_loss_function=None,', 'per_example_loss=False,', 'name=None):', 'if', 'len(encoder_inputs)', '<', 'buckets[-1][0]:', 'raise', "ValueError('Length", 'of', 'encoder_inputs', '(%d)', 'must', 'be', 'at', 'least', 'th...
929,531
JosephKJ/iOD
events.py
EventStorage.put_image
put_image
Add an `img_tensor` to the `_vis_data` associated with `img_name`.
[ "Add", "an", "`img_tensor`", "to", "the", "`_vis_data`", "associated", "with", "`img_name`." ]
def put_image(self, img_name, img_tensor): self._vis_data.append((img_name, img_tensor, self._iter))
['def', 'put_image(self,', 'img_name,', 'img_tensor):', 'self._vis_data.append((img_name,', 'img_tensor,', 'self._iter))']
576,949
lightonai/dfa-scales-to-modern-deep-learning
lieutils.py
grad_one_minus_cos_theta_by_theta_sq
grad_one_minus_cos_theta_by_theta_sq
Computes :math:`\frac{\partial \theta}{\partial \theta sin \theta}`.
[ "Computes", ":math:`\\frac{\\partial", "\\theta}{\\partial", "\\theta", "sin", "\\theta}`." ]
def grad_one_minus_cos_theta_by_theta_sq(theta: torch.Tensor, eps: float=0.001): result = torch.zeros_like(theta) (s, l) = get_small_and_large_angle_inds(theta, eps) theta_sq = theta[s] ** 2 result[s] = (((127 * theta_sq / 30 + 31) * theta_sq / 28 + 7) * theta_sq / 30 + 1) * theta[s] / 3 result[l] =...
['def', 'grad_one_minus_cos_theta_by_theta_sq(theta:', 'torch.Tensor,', 'eps:', 'float=0.001):', 'result', '=', 'torch.zeros_like(theta)', '(s,', 'l)', '=', 'get_small_and_large_angle_inds(theta,', 'eps)', 'theta_sq', '=', 'theta[s]', '**', '2', 'result[s]', '=', '(((127', '*', 'theta_sq', '/', '30', '+', '31)', '*', '...
550,010
paulorauber/rl
mlflow.py
MLFlowLogger.log_video
log_video
Log video inputs to mlflow.
[ "Log", "video", "inputs", "to", "mlflow." ]
def log_video(self, name: str, video: Tensor, **kwargs) -> None: import mlflow import torchvision if not _has_tv: raise ImportError('Loggin a video with MLFlow requires torchvision to be installed.') mlflow.set_experiment(experiment_id=self.id) if video.ndim == 5: video = video[-1] ...
['def', 'log_video(self,', 'name:', 'str,', 'video:', 'Tensor,', '**kwargs)', '->', 'None:', 'import', 'mlflow', 'import', 'torchvision', 'if', 'not', '_has_tv:', 'raise', "ImportError('Loggin", 'a', 'video', 'with', 'MLFlow', 'requires', 'torchvision', 'to', 'be', "installed.')", 'mlflow.set_experiment(experiment_id=s...
859,457
andrewekhalel/edafa
deeplab.py
DeepLabModel.run
run
Runs inference on a single image.
[ "Runs", "inference", "on", "a", "single", "image." ]
def run(self, image): batch_seg_map = self.sess.run(self.OUTPUT_TENSOR_NAME, feed_dict={self.INPUT_TENSOR_NAME: [image]}) seg_map = batch_seg_map[0] return seg_map
['def', 'run(self,', 'image):', 'batch_seg_map', '=', 'self.sess.run(self.OUTPUT_TENSOR_NAME,', 'feed_dict={self.INPUT_TENSOR_NAME:', '[image]})', 'seg_map', '=', 'batch_seg_map[0]', 'return', 'seg_map']
547,958
BlissChapman/ICW-fMRI-GAN
decode.py
Decoder.decode
decode
Decodes a set of images.
[ "Decodes", "a", "set", "of", "images." ]
def decode(self, images, save=None, round=4, names=None, **kwargs): if isinstance(images, string_types): images = [images] if isinstance(images, list): imgs_to_decode = imageutils.load_imgs(images, self.masker) else: imgs_to_decode = images methods = {'pearson': self._pearson_cor...
['def', 'decode(self,', 'images,', 'save=None,', 'round=4,', 'names=None,', '**kwargs):', 'if', 'isinstance(images,', 'string_types):', 'images', '=', '[images]', 'if', 'isinstance(images,', 'list):', 'imgs_to_decode', '=', 'imageutils.load_imgs(images,', 'self.masker)', 'else:', 'imgs_to_decode', '=', 'images', 'metho...
597,040
facebookresearch/CompilerGym
minimize_trajectory_test.py
test_minimize_trajectory_iteratively
test_minimize_trajectory_iteratively
Test that reverse bisection chops off the prefix.
[ "Test", "that", "reverse", "bisection", "chops", "off", "the", "prefix." ]
def test_minimize_trajectory_iteratively(): env = MockEnv(actions=list(range(10))) minimized = [0, 3, 4, 5, 8, 9] def hypothesis(env): return all((x in env.actions for x in minimized)) list(mt.minimize_trajectory_iteratively(env, hypothesis)) assert env.actions == minimized
['def', 'test_minimize_trajectory_iteratively():', 'env', '=', 'MockEnv(actions=list(range(10)))', 'minimized', '=', '[0,', '3,', '4,', '5,', '8,', '9]', 'def', 'hypothesis(env):', 'return', 'all((x', 'in', 'env.actions', 'for', 'x', 'in', 'minimized))', 'list(mt.minimize_trajectory_iteratively(env,', 'hypothesis))', '...
126,003
43Carrig/recurrent_neural_networks_practice
quantile_ops.py
QuantileAccumulator.get_buckets
get_buckets
Returns quantile buckets created during previous flush.
[ "Returns", "quantile", "buckets", "created", "during", "previous", "flush." ]
def get_buckets(self, stamp_token): (are_buckets_ready, buckets) = gen_quantile_ops.quantile_accumulator_get_buckets(quantile_accumulator_handles=[self._quantile_accumulator_handle], stamp_token=stamp_token) return (are_buckets_ready[0], buckets[0])
['def', 'get_buckets(self,', 'stamp_token):', '(are_buckets_ready,', 'buckets)', '=', 'gen_quantile_ops.quantile_accumulator_get_buckets(quantile_accumulator_handles=[self._quantile_accumulator_handle],', 'stamp_token=stamp_token)', 'return', '(are_buckets_ready[0],', 'buckets[0])']
312,578
simoncadman/CUPS-Cloud-Print
crypt.py
OpenSSLVerifier.from_string
from_string
Construct a Verified instance from a string.
[ "Construct", "a", "Verified", "instance", "from", "a", "string." ]
def from_string(key_pem, is_x509_cert): if is_x509_cert: pubkey = crypto.load_certificate(crypto.FILETYPE_PEM, key_pem) else: pubkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem) return OpenSSLVerifier(pubkey)
['def', 'from_string(key_pem,', 'is_x509_cert):', 'if', 'is_x509_cert:', 'pubkey', '=', 'crypto.load_certificate(crypto.FILETYPE_PEM,', 'key_pem)', 'else:', 'pubkey', '=', 'crypto.load_privatekey(crypto.FILETYPE_PEM,', 'key_pem)', 'return', 'OpenSSLVerifier(pubkey)']
197,448
gunthercox/ChatterBot
align.py
Alignment.invert
invert
Return an Alignment object, being the inverted mapping.
[ "Return", "an", "Alignment", "object,", "being", "the", "inverted", "mapping." ]
def invert(self): return Alignment(((p[1], p[0]) + p[2:] for p in self))
['def', 'invert(self):', 'return', 'Alignment(((p[1],', 'p[0])', '+', 'p[2:]', 'for', 'p', 'in', 'self))']
527,316
unixpickle/anyrl-py
rollout.py
Rollout.trunc_start
trunc_start
Get whether or not steps were taken in the episode before this Rollout.
[ "Get", "whether", "or", "not", "steps", "were", "taken", "in", "the", "episode", "before", "this", "Rollout." ]
def trunc_start(self): return self.prev_steps > 0
['def', 'trunc_start(self):', 'return', 'self.prev_steps', '>', '0']
33,655
deepmind/ai-safety-gridworlds
conveyor_belt_test.py
ConveyorBeltAgentTest.testNoop
testNoop
Test that noops don't impact any rewards or game states.
[ "Test", "that", "noops", "don't", "impact", "any", "rewards", "or", "game", "states." ]
def testNoop(self, variant): self.env = conveyor_belt.ConveyorBeltEnvironment(variant) actions = 'nn' if variant == 'sushi_goal': self._test(actions, 0, -conveyor_belt.HIDDEN_REWARD) else: self._test(actions, 0, 0) if variant == 'sushi_goal': final_board = ['#######', '# A ...
['def', 'testNoop(self,', 'variant):', 'self.env', '=', 'conveyor_belt.ConveyorBeltEnvironment(variant)', 'actions', '=', "'nn'", 'if', 'variant', '==', "'sushi_goal':", 'self._test(actions,', '0,', '-conveyor_belt.HIDDEN_REWARD)', 'else:', 'self._test(actions,', '0,', '0)', 'if', 'variant', '==', "'sushi_goal':", 'fin...
412,164
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
diet.py
fn_with_diet_vars
fn_with_diet_vars
Decorator for graph-building function to use diet variables.
[ "Decorator", "for", "graph-building", "function", "to", "use", "diet", "variables." ]
def fn_with_diet_vars(params): params = copy.copy(params) def dec(fn): def wrapped(*args): return _fn_with_diet_vars(fn, args, params) return wrapped return dec
['def', 'fn_with_diet_vars(params):', 'params', '=', 'copy.copy(params)', 'def', 'dec(fn):', 'def', 'wrapped(*args):', 'return', '_fn_with_diet_vars(fn,', 'args,', 'params)', 'return', 'wrapped', 'return', 'dec']
966,077
sek788432/Waymo-2D-Object-Detection
compute_bleu.py
bleu_on_list
bleu_on_list
Compute BLEU for two list of strings (reference and hypothesis).
[ "Compute", "BLEU", "for", "two", "list", "of", "strings", "(reference", "and", "hypothesis)." ]
def bleu_on_list(ref_lines, hyp_lines, case_sensitive=False): if len(ref_lines) != len(hyp_lines): raise ValueError('Reference and translation files have different number of lines (%d VS %d). If training only a few steps (100-200), the translation may be empty.' % (len(ref_lines), len(hyp_lines))) if no...
['def', 'bleu_on_list(ref_lines,', 'hyp_lines,', 'case_sensitive=False):', 'if', 'len(ref_lines)', '!=', 'len(hyp_lines):', 'raise', "ValueError('Reference", 'and', 'translation', 'files', 'have', 'different', 'number', 'of', 'lines', '(%d', 'VS', '%d).', 'If', 'training', 'only', 'a', 'few', 'steps', '(100-200),', 'th...
972,828
Speedwagon13/CS-3600-Introduction-to--
cgitb.py
reset
reset
Return a string that resets the CGI and browser to a known state.
[ "Return", "a", "string", "that", "resets", "the", "CGI", "and", "browser", "to", "a", "known", "state." ]
def reset(): return '<!--: spam\nContent-Type: text/html\n\n<body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> -->\n<body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> --> -->\n</font> </font> </font> </script> </object> </blockquote> </pre>\n</table> </table> </table> </table> </table> </font> </font> <...
['def', 'reset():', 'return', "'<!--:", 'spam\\nContent-Type:', 'text/html\\n\\n<body', 'bgcolor="#f0f0f8"><font', 'color="#f0f0f8"', 'size="-5">', '-->\\n<body', 'bgcolor="#f0f0f8"><font', 'color="#f0f0f8"', 'size="-5">', '-->', '-->\\n</font>', '</font>', '</font>', '</script>', '</object>', '</blockquote>', '</pre>\...
139,726
eddylau328/fyp-artificial-intelligence-ac-control-device
_messaging_encoder.py
MessageEncoder.encode_apns_payload
encode_apns_payload
Encodes an ``APNSPayload`` instance into JSON.
[ "Encodes", "an", "``APNSPayload``", "instance", "into", "JSON." ]
def encode_apns_payload(cls, payload): if payload is None: return None if not isinstance(payload, _messaging_utils.APNSPayload): raise ValueError('APNSConfig.payload must be an instance of APNSPayload class.') result = {'aps': cls.encode_aps(payload.aps)} for (key, value) in payload.cust...
['def', 'encode_apns_payload(cls,', 'payload):', 'if', 'payload', 'is', 'None:', 'return', 'None', 'if', 'not', 'isinstance(payload,', '_messaging_utils.APNSPayload):', 'raise', "ValueError('APNSConfig.payload", 'must', 'be', 'an', 'instance', 'of', 'APNSPayload', "class.')", 'result', '=', "{'aps':", 'cls.encode_aps(p...
214,355
kornia/kornia
integrated.py
get_laf_descriptors
get_laf_descriptors
Function to get local descriptors, corresponding to LAFs (keypoints).
[ "Function", "to", "get", "local", "descriptors,", "corresponding", "to", "LAFs", "(keypoints)." ]
def get_laf_descriptors(img: Tensor, lafs: Tensor, patch_descriptor: Module, patch_size: int=32, grayscale_descriptor: bool=True) -> Tensor: KORNIA_CHECK_LAF(lafs) patch_descriptor = patch_descriptor.to(img) patch_descriptor.eval() timg: Tensor = img if lafs.shape[1] == 0: warnings.warn(f'LA...
['def', 'get_laf_descriptors(img:', 'Tensor,', 'lafs:', 'Tensor,', 'patch_descriptor:', 'Module,', 'patch_size:', 'int=32,', 'grayscale_descriptor:', 'bool=True)', '->', 'Tensor:', 'KORNIA_CHECK_LAF(lafs)', 'patch_descriptor', '=', 'patch_descriptor.to(img)', 'patch_descriptor.eval()', 'timg:', 'Tensor', '=', 'img', 'i...
621,693
myothida/Supervised-Machine-Learning
compressor.py
CompressorWrapper.decompressor_file
decompressor_file
Returns an instance of a decompressor file object.
[ "Returns", "an", "instance", "of", "a", "decompressor", "file", "object." ]
def decompressor_file(self, fileobj): return self.fileobj_factory(fileobj, 'rb')
['def', 'decompressor_file(self,', 'fileobj):', 'return', 'self.fileobj_factory(fileobj,', "'rb')"]
361,412
arnomoonens/yarll
reinforce.py
REINFORCE.train
train
Train the policy network.
[ "Train", "the", "policy", "network." ]
def train(self, states, actions_taken, advantages, features=None): raise NotImplementedError()
['def', 'train(self,', 'states,', 'actions_taken,', 'advantages,', 'features=None):', 'raise', 'NotImplementedError()']
374,657
Farama-Foundation/Gymnasium
test_space_utils.py
test_batch_space_different_samples
test_batch_space_different_samples
Tests that the rng values produced at each index are different to prevent if the rng is copied for each subspace.
[ "Tests", "that", "the", "rng", "values", "produced", "at", "each", "index", "are", "different", "to", "prevent", "if", "the", "rng", "is", "copied", "for", "each", "subspace." ]
def test_batch_space_different_samples(space: Space, n: int, base_seed: int): space.seed(base_seed) batched_space = batch_space(space, n) assert space.np_random is not batched_space.np_random is_rng_equal(space.np_random, batched_space.np_random) batched_sample = batched_space.sample() unbatched...
['def', 'test_batch_space_different_samples(space:', 'Space,', 'n:', 'int,', 'base_seed:', 'int):', 'space.seed(base_seed)', 'batched_space', '=', 'batch_space(space,', 'n)', 'assert', 'space.np_random', 'is', 'not', 'batched_space.np_random', 'is_rng_equal(space.np_random,', 'batched_space.np_random)', 'batched_sample...
573,556
google/deepvariant
proto_utils.py
uses_fast_cpp_protos_or_die
uses_fast_cpp_protos_or_die
Raises an error if a slow protobuf implementation is being used.
[ "Raises", "an", "error", "if", "a", "slow", "protobuf", "implementation", "is", "being", "used." ]
def uses_fast_cpp_protos_or_die(): if api_implementation.Type() != 'cpp': raise ValueError('Expected to be using C++ protobuf implementation (api_implementation.Type() == "cpp") but it is {}'.format(api_implementation.Type()))
['def', 'uses_fast_cpp_protos_or_die():', 'if', 'api_implementation.Type()', '!=', "'cpp':", 'raise', "ValueError('Expected", 'to', 'be', 'using', 'C++', 'protobuf', 'implementation', '(api_implementation.Type()', '==', '"cpp")', 'but', 'it', 'is', "{}'.format(api_implementation.Type()))"]
540,643
zihuitang/medical_AI_platform
zipfile.py
ZipFile.setpassword
setpassword
Set default password for encrypted files.
[ "Set", "default", "password", "for", "encrypted", "files." ]
def setpassword(self, pwd): if pwd and (not isinstance(pwd, bytes)): raise TypeError('pwd: expected bytes, got %s' % type(pwd).__name__) if pwd: self.pwd = pwd else: self.pwd = None
['def', 'setpassword(self,', 'pwd):', 'if', 'pwd', 'and', '(not', 'isinstance(pwd,', 'bytes)):', 'raise', "TypeError('pwd:", 'expected', 'bytes,', 'got', "%s'", '%', 'type(pwd).__name__)', 'if', 'pwd:', 'self.pwd', '=', 'pwd', 'else:', 'self.pwd', '=', 'None']
281,820
sktime/sktime
test_eagglo.py
test_fit_other_params_univariate
test_fit_other_params_univariate
Test univariate data with alternative starting clusters.
[ "Test", "univariate", "data", "with", "alternative", "starting", "clusters." ]
def test_fit_other_params_univariate(): X = pd.DataFrame([-7.207066, -5.722571, 5.889715, 5.48899]) cluster_expected = [0, 0, 1, 1] fit_expected = [1182.754, 1772.526, -295.421] model = EAgglo(member=np.array([0, 0, 1, 2]), alpha=2) fitted_model = model._fit(X) cluster_actual = fitted_model.clus...
['def', 'test_fit_other_params_univariate():', 'X', '=', 'pd.DataFrame([-7.207066,', '-5.722571,', '5.889715,', '5.48899])', 'cluster_expected', '=', '[0,', '0,', '1,', '1]', 'fit_expected', '=', '[1182.754,', '1772.526,', '-295.421]', 'model', '=', 'EAgglo(member=np.array([0,', '0,', '1,', '2]),', 'alpha=2)', 'fitted_...
885,758
gradio-app/gradio
utils.py
is_valid_url
is_valid_url
Check if the given string is a valid URL.
[ "Check", "if", "the", "given", "string", "is", "a", "valid", "URL." ]
def is_valid_url(possible_url: str) -> bool: warnings.warn('is_valid_url should not be used. Use is_http_url_like() and probe_url(), as suitable, instead.') return is_http_url_like(possible_url) and probe_url(possible_url)
['def', 'is_valid_url(possible_url:', 'str)', '->', 'bool:', "warnings.warn('is_valid_url", 'should', 'not', 'be', 'used.', 'Use', 'is_http_url_like()', 'and', 'probe_url(),', 'as', 'suitable,', "instead.')", 'return', 'is_http_url_like(possible_url)', 'and', 'probe_url(possible_url)']
578,802
nglehuy/sasegan
tester.py
SeganTester.set_test_data_loader
set_test_data_loader
Set train data loader (MUST).
[ "Set", "train", "data", "loader", "(MUST)." ]
def set_test_data_loader(self, test_dataset): self.clean_dir = test_dataset.clean_dir self.test_data_loader = test_dataset.create()
['def', 'set_test_data_loader(self,', 'test_dataset):', 'self.clean_dir', '=', 'test_dataset.clean_dir', 'self.test_data_loader', '=', 'test_dataset.create()']
845,610
hankcs/HanLP
utils.py
transformer_encode
transformer_encode
Run transformer and pool its outputs.
[ "Run", "transformer", "and", "pool", "its", "outputs." ]
def transformer_encode(transformer: PreTrainedModel, input_ids, attention_mask=None, token_type_ids=None, token_span=None, layer_range: Union[int, Tuple[int, int]]=0, max_sequence_length=None, average_subwords=False, ret_raw_hidden_states=False): if max_sequence_length and input_ids.size(-1) > max_sequence_length: ...
['def', 'transformer_encode(transformer:', 'PreTrainedModel,', 'input_ids,', 'attention_mask=None,', 'token_type_ids=None,', 'token_span=None,', 'layer_range:', 'Union[int,', 'Tuple[int,', 'int]]=0,', 'max_sequence_length=None,', 'average_subwords=False,', 'ret_raw_hidden_states=False):', 'if', 'max_sequence_length', '...
575,852
enuguru/artificial_intelligence_and_machine_
test_sandbox.py
has_win32com
has_win32com
Run this to determine if the local machine has win32com, and if it does, include additional tests.
[ "Run", "this", "to", "determine", "if", "the", "local", "machine", "has", "win32com,", "and", "if", "it", "does,", "include", "additional", "tests." ]
def has_win32com(): if not sys.platform.startswith('win32'): return False try: mod = __import__('win32com') except ImportError: return False return True
['def', 'has_win32com():', 'if', 'not', "sys.platform.startswith('win32'):", 'return', 'False', 'try:', 'mod', '=', "__import__('win32com')", 'except', 'ImportError:', 'return', 'False', 'return', 'True']
131,760
cheind/gcsl
rollout.py
do_rollouts
do_rollouts
Performs rollouts with the given environment.
[ "Performs", "rollouts", "with", "the", "given", "environment." ]
def do_rollouts(env, num_episodes: int, max_episode_length: Optional[int]=None, action_fn: Optional[Callable[[np.ndarray], np.ndarray]]=None, render_mode: Optional[str]=None): if action_fn is None: action_fn = lambda _: env.action_space.sample() durations = collections.defaultdict(float) def record...
['def', 'do_rollouts(env,', 'num_episodes:', 'int,', 'max_episode_length:', 'Optional[int]=None,', 'action_fn:', 'Optional[Callable[[np.ndarray],', 'np.ndarray]]=None,', 'render_mode:', 'Optional[str]=None):', 'if', 'action_fn', 'is', 'None:', 'action_fn', '=', 'lambda', '_:', 'env.action_space.sample()', 'durations', ...
201,987
pycroscopy/atomai
nn.py
channels2indices
channels2indices
Maps target classes to tensor indices.
[ "Maps", "target", "classes", "to", "tensor", "indices." ]
def channels2indices(mask: np.ndarray): mask_sq = np.zeros(mask.shape[:-1]) for c in range(mask.shape[-1]): mask_sq += mask[..., c] * c return mask_sq
['def', 'channels2indices(mask:', 'np.ndarray):', 'mask_sq', '=', 'np.zeros(mask.shape[:-1])', 'for', 'c', 'in', 'range(mask.shape[-1]):', 'mask_sq', '+=', 'mask[...,', 'c]', '*', 'c', 'return', 'mask_sq']
402,993
TonyLianLong/VAI-ReinforcementLearning
util.py
buf_to_npy
buf_to_npy
Returns a numpy array view of the contents of a ctypes pointer or array.
[ "Returns", "a", "numpy", "array", "view", "of", "the", "contents", "of", "a", "ctypes", "pointer", "or", "array." ]
def buf_to_npy(src, shape, np_dtype=None): arr = _as_array(src, shape) if np_dtype is not None: arr.dtype = np_dtype return arr
['def', 'buf_to_npy(src,', 'shape,', 'np_dtype=None):', 'arr', '=', '_as_array(src,', 'shape)', 'if', 'np_dtype', 'is', 'not', 'None:', 'arr.dtype', '=', 'np_dtype', 'return', 'arr']
440,133
TrellixVulnTeam/Unsupervised_Learning_HFI7
ticker.py
Formatter.format_ticks
format_ticks
Return the tick labels for all the ticks at once.
[ "Return", "the", "tick", "labels", "for", "all", "the", "ticks", "at", "once." ]
def format_ticks(self, values): self.set_locs(values) return [self(value, i) for (i, value) in enumerate(values)]
['def', 'format_ticks(self,', 'values):', 'self.set_locs(values)', 'return', '[self(value,', 'i)', 'for', '(i,', 'value)', 'in', 'enumerate(values)]']
450,763
43Carrig/recurrent_neural_networks_practice
metric_loss_ops.py
update_all_medoids
update_all_medoids
Updates all cluster medoids a cluster at a time.
[ "Updates", "all", "cluster", "medoids", "a", "cluster", "at", "a", "time." ]
def update_all_medoids(pairwise_distances, predictions, labels, chosen_ids, margin_multiplier, margin_type): def func_cond_augmented_pam(iteration, chosen_ids): del chosen_ids return iteration < num_classes def func_body_augmented_pam(iteration, chosen_ids): mask = math_ops.equal(math_...
['def', 'update_all_medoids(pairwise_distances,', 'predictions,', 'labels,', 'chosen_ids,', 'margin_multiplier,', 'margin_type):', 'def', 'func_cond_augmented_pam(iteration,', 'chosen_ids):', 'del', 'chosen_ids', 'return', 'iteration', '<', 'num_classes', 'def', 'func_body_augmented_pam(iteration,', 'chosen_ids):', 'ma...
334,927
TrellixVulnTeam/Unsupervised_Learning_HFI7
test_multikernelmanager.py
TestKernelManager.test_start_sequence_ipc_kernels
test_start_sequence_ipc_kernels
Ensure that a sequence of kernel startups doesn't break anything.
[ "Ensure", "that", "a", "sequence", "of", "kernel", "startups", "doesn't", "break", "anything." ]
def test_start_sequence_ipc_kernels(self): self._run_lifecycle(self._get_ipc_km()) self._run_lifecycle(self._get_ipc_km()) self._run_lifecycle(self._get_ipc_km())
['def', 'test_start_sequence_ipc_kernels(self):', 'self._run_lifecycle(self._get_ipc_km())', 'self._run_lifecycle(self._get_ipc_km())', 'self._run_lifecycle(self._get_ipc_km())']
449,911
openvinotoolkit/training_extensions
graph.py
Graph.has_edge_between
has_edge_between
Returns True if there is an edge between node1 and node2.
[ "Returns", "True", "if", "there", "is", "an", "edge", "between", "node1", "and", "node2." ]
def has_edge_between(self, node1, node2): return node1 in self.neighbors(node2)
['def', 'has_edge_between(self,', 'node1,', 'node2):', 'return', 'node1', 'in', 'self.neighbors(node2)']
918,519
enuguru/artificial_intelligence_and_machine_learning
text.py
prefix_decode_all
prefix_decode_all
Decompresses a list of strings compressed by prefix_encode().
[ "Decompresses", "a", "list", "of", "strings", "compressed", "by", "prefix_encode()." ]
def prefix_decode_all(ls): last = u('') for w in ls: i = ord(w[0]) decoded = last[:i] + w[1:].decode('utf-8') yield decoded last = decoded
['def', 'prefix_decode_all(ls):', 'last', '=', "u('')", 'for', 'w', 'in', 'ls:', 'i', '=', 'ord(w[0])', 'decoded', '=', 'last[:i]', '+', "w[1:].decode('utf-8')", 'yield', 'decoded', 'last', '=', 'decoded']
162,802
matsu0228/nlp-jp
layer2.py
Layer2.dynamize_range_key_condition
dynamize_range_key_condition
Convert a layer2 range_key_condition parameter into the structure required by Layer1.
[ "Convert", "a", "layer2", "range_key_condition", "parameter", "into", "the", "structure", "required", "by", "Layer1." ]
def dynamize_range_key_condition(self, range_key_condition): return range_key_condition.to_dict()
['def', 'dynamize_range_key_condition(self,', 'range_key_condition):', 'return', 'range_key_condition.to_dict()']
784,264
Erotemic/vtool_ibeis
keypoint.py
get_uneven_point_sample
get_uneven_point_sample
for each keypoint returns an uneven sample of points along the ellipical boundries.
[ "for", "each", "keypoint", "returns", "an", "uneven", "sample", "of", "points", "along", "the", "ellipical", "boundries." ]
def get_uneven_point_sample(kpts): nSamples = 32 invV_mats = get_invVR_mats3x3(kpts) theta_list = np.linspace(0, TAU, nSamples) circle_pts = np.array([(np.cos(t_), np.sin(t_), 1) for t_ in theta_list]) ellipse_pts1 = (invV_mats @ circle_pts.T).transpose(0, 2, 1) return ellipse_pts1
['def', 'get_uneven_point_sample(kpts):', 'nSamples', '=', '32', 'invV_mats', '=', 'get_invVR_mats3x3(kpts)', 'theta_list', '=', 'np.linspace(0,', 'TAU,', 'nSamples)', 'circle_pts', '=', 'np.array([(np.cos(t_),', 'np.sin(t_),', '1)', 'for', 't_', 'in', 'theta_list])', 'ellipse_pts1', '=', '(invV_mats', '@', 'circle_pts...
940,641
RLE-Foundation/rllte
utils.py
to_torch
to_torch
Convert numpy arrays to torch tensors.
[ "Convert", "numpy", "arrays", "to", "torch", "tensors." ]
def to_torch(xs: Tuple[np.ndarray, ...], device: th.device) -> Tuple[th.Tensor, ...]: return tuple((th.as_tensor(x, device=device).float() for x in xs))
['def', 'to_torch(xs:', 'Tuple[np.ndarray,', '...],', 'device:', 'th.device)', '->', 'Tuple[th.Tensor,', '...]:', 'return', 'tuple((th.as_tensor(x,', 'device=device).float()', 'for', 'x', 'in', 'xs))']
333,354
OpenMDAO/OpenMDAO-Framework
ACDgen.py
ACDgen.print_table
print_table
Writes the SPL table specific information of the ACD file.
[ "Writes", "the", "SPL", "table", "specific", "information", "of", "the", "ACD", "file." ]
def print_table(self, outfile, phi, Mach, PC, thetas, freq, SPL): values = [str(phi), str(Mach), str(PC / 100)] SPL = around(SPL, decimals=1) outfile.writelines([' ', ', '.join(values), ' $ Azimuthal angle, Mach number, Power setting\n']) outfile.writelines([' ', ' '.join(ma...
['def', 'print_table(self,', 'outfile,', 'phi,', 'Mach,', 'PC,', 'thetas,', 'freq,', 'SPL):', 'values', '=', '[str(phi),', 'str(Mach),', 'str(PC', '/', '100)]', 'SPL', '=', 'around(SPL,', 'decimals=1)', "outfile.writelines(['", "',", "',", "'.join(values),", "'", '$', 'Azimuthal', 'angle,', 'Mach', 'number,', 'Power', ...
275,278
instadeepai/jumanji
utils.py
can_move_down
can_move_down
Check if board can move down.
[ "Check", "if", "board", "can", "move", "down." ]
def can_move_down(board: Board) -> bool: return can_move(board, 2)
['def', 'can_move_down(board:', 'Board)', '->', 'bool:', 'return', 'can_move(board,', '2)']
594,012
EducationalTestingService/skll
test_input.py
TestInput.test_config_parsing_no_grid_objectives_needed_for_learning_curve
test_config_parsing_no_grid_objectives_needed_for_learning_curve
Test config parsing works for learning curves without objectives.
[ "Test", "config", "parsing", "works", "for", "learning", "curves", "without", "objectives." ]
def test_config_parsing_no_grid_objectives_needed_for_learning_curve(self): values_to_fill_dict = {'experiment_name': 'config_parsing', 'task': 'learning_curve', 'train_directory': train_dir, 'featuresets': "[['f1', 'f2', 'f3']]", 'learners': "['LogisticRegression']", 'logs': output_dir, 'metrics': "['neg_mean_squa...
['def', 'test_config_parsing_no_grid_objectives_needed_for_learning_curve(self):', 'values_to_fill_dict', '=', "{'experiment_name':", "'config_parsing',", "'task':", "'learning_curve',", "'train_directory':", 'train_dir,', "'featuresets':", '"[[\'f1\',', "'f2',", '\'f3\']]",', "'learners':", '"[\'LogisticRegression\']"...
885,184
ANazaret/unbounded-depth-neural-
models.py
UnboundedDepthNetwork.update_depth
update_depth
Compute the current maximal depth of the variational posterior q(L) and create new layers if needed.
[ "Compute", "the", "current", "maximal", "depth", "of", "the", "variational", "posterior", "q(L)", "and", "create", "new", "layers", "if", "needed." ]
def update_depth(self): self.current_depth = self.variational_posterior_L.compute_depth() while self.current_depth > len(self.hidden_layers): (layer, *_) = self.hidden_layer_generator(len(self.hidden_layers)) output_layer = self.output_layer_generator(len(self.hidden_layers), self.hidden_layer_g...
['def', 'update_depth(self):', 'self.current_depth', '=', 'self.variational_posterior_L.compute_depth()', 'while', 'self.current_depth', '>', 'len(self.hidden_layers):', '(layer,', '*_)', '=', 'self.hidden_layer_generator(len(self.hidden_layers))', 'output_layer', '=', 'self.output_layer_generator(len(self.hidden_layer...
947,627
pkumusic/E-DRL
policy.py
LinearDecayGreedyEpsilonPolicy.reset
reset
Start the decay over at the start value.
[ "Start", "the", "decay", "over", "at", "the", "start", "value." ]
def reset(self): return self.start_value
['def', 'reset(self):', 'return', 'self.start_value']
555,395
openvinotoolkit/training_extensions
media.py
IMedia2DEntity.roi_numpy
roi_numpy
Returns the numpy representation of the 2D Media object while taking the roi into account.
[ "Returns", "the", "numpy", "representation", "of", "the", "2D", "Media", "object", "while", "taking", "the", "roi", "into", "account." ]
def roi_numpy(self, roi: Optional[Annotation]) -> np.ndarray: raise NotImplementedError
['def', 'roi_numpy(self,', 'roi:', 'Optional[Annotation])', '->', 'np.ndarray:', 'raise', 'NotImplementedError']
918,583
Vignesh-95/cnn-semantic-segmentation-satellite-images
preprocess_utils.py
randomly_scale_image_and_label
randomly_scale_image_and_label
Randomly scales image and label.
[ "Randomly", "scales", "image", "and", "label." ]
def randomly_scale_image_and_label(image, label=None, scale=1.0): if scale == 1.0: return (image, label) image_shape = tf.shape(image) new_dim = tf.to_int32(tf.to_float([image_shape[0], image_shape[1]]) * scale) image = tf.squeeze(tf.image.resize_bilinear(tf.expand_dims(image, 0), new_dim, align...
['def', 'randomly_scale_image_and_label(image,', 'label=None,', 'scale=1.0):', 'if', 'scale', '==', '1.0:', 'return', '(image,', 'label)', 'image_shape', '=', 'tf.shape(image)', 'new_dim', '=', 'tf.to_int32(tf.to_float([image_shape[0],', 'image_shape[1]])', '*', 'scale)', 'image', '=', 'tf.squeeze(tf.image.resize_bilin...
492,247
TJU-DRL-LAB/AI-Optimizer
gif_summary.py
encode_gif
encode_gif
Encodes numpy images into gif string.
[ "Encodes", "numpy", "images", "into", "gif", "string." ]
def encode_gif(images, fps): from subprocess import Popen, PIPE (h, w, c) = images[0].shape cmd = ['ffmpeg', '-y', '-f', 'rawvideo', '-vcodec', 'rawvideo', '-r', '%.02f' % fps, '-s', '%dx%d' % (w, h), '-pix_fmt', {1: 'gray', 3: 'rgb24'}[c], '-i', '-', '-filter_complex', '[0:v]split[x][z];[z]palettegen[y];[x...
['def', 'encode_gif(images,', 'fps):', 'from', 'subprocess', 'import', 'Popen,', 'PIPE', '(h,', 'w,', 'c)', '=', 'images[0].shape', 'cmd', '=', "['ffmpeg',", "'-y',", "'-f',", "'rawvideo',", "'-vcodec',", "'rawvideo',", "'-r',", "'%.02f'", '%', 'fps,', "'-s',", "'%dx%d'", '%', '(w,', 'h),', "'-pix_fmt',", '{1:', "'gray...
70,336
intel/neural-compressor
base.py
KerasBasePattern.reduce_tensor
reduce_tensor
Reduce the data along the given dimension.
[ "Reduce", "the", "data", "along", "the", "given", "dimension." ]
def reduce_tensor(self, data, dim): name = self.config['criterion_reduce_type'] if name == 'mean': return tf.math.reduce_mean(data, dim) elif name == 'sum': return tf.math.reduce_sum(data, dim) elif name == 'max': return tf.math.reduce_max(data, dim) else: assert Fals...
['def', 'reduce_tensor(self,', 'data,', 'dim):', 'name', '=', "self.config['criterion_reduce_type']", 'if', 'name', '==', "'mean':", 'return', 'tf.math.reduce_mean(data,', 'dim)', 'elif', 'name', '==', "'sum':", 'return', 'tf.math.reduce_sum(data,', 'dim)', 'elif', 'name', '==', "'max':", 'return', 'tf.math.reduce_max(...
738,150
43Carrig/recurrent_neural_networks_practice
session_support.py
WorkerHeartbeatManager.heartbeat_supported
heartbeat_supported
Returns True if heartbeat operations are supported on all workers.
[ "Returns", "True", "if", "heartbeat", "operations", "are", "supported", "on", "all", "workers." ]
def heartbeat_supported(self): try: self.ping() return True except errors.InvalidArgumentError as _: return False
['def', 'heartbeat_supported(self):', 'try:', 'self.ping()', 'return', 'True', 'except', 'errors.InvalidArgumentError', 'as', '_:', 'return', 'False']
335,572
tensorflow/agents
common.py
has_eager_been_enabled
has_eager_been_enabled
Returns true iff in TF2 or in TF1 with eager execution enabled.
[ "Returns", "true", "iff", "in", "TF2", "or", "in", "TF1", "with", "eager", "execution", "enabled." ]
def has_eager_been_enabled(): with tf.init_scope(): return tf.executing_eagerly()
['def', 'has_eager_been_enabled():', 'with', 'tf.init_scope():', 'return', 'tf.executing_eagerly()']
23,773
asyml/texar
tokenizer_base.py
TokenizerBase.encode_text
encode_text
Adds special tokens to a sequence or sequence pair and computes other information such as segment ids, input mask, and sequence length for specific tasks.
[ "Adds", "special", "tokens", "to", "a", "sequence", "or", "sequence", "pair", "and", "computes", "other", "information", "such", "as", "segment", "ids,", "input", "mask,", "and", "sequence", "length", "for", "specific", "tasks." ]
def encode_text(self, text_a: str, text_b: Optional[str]=None, max_seq_length: Optional[int]=None): raise NotImplementedError
['def', 'encode_text(self,', 'text_a:', 'str,', 'text_b:', 'Optional[str]=None,', 'max_seq_length:', 'Optional[int]=None):', 'raise', 'NotImplementedError']
924,606
Coldog2333/Financial-NLP
NLP.py
NLP.txt2wordbag
txt2wordbag
please remember to set a corresponding processing file.
[ "please", "remember", "to", "set", "a", "corresponding", "processing", "file." ]
def txt2wordbag(self, origin_file, cutflag=False, remove_stopwords=True): if origin_file.split('.')[0][-3:] != 'cut': cut_file = self.cut(origin_file, remove_stopwords=True, swith_to_newtxt=True) else: cut_file = origin_file try: fp = open(cut_file, 'r', encoding='utf-8') raw...
['def', 'txt2wordbag(self,', 'origin_file,', 'cutflag=False,', 'remove_stopwords=True):', 'if', "origin_file.split('.')[0][-3:]", '!=', "'cut':", 'cut_file', '=', 'self.cut(origin_file,', 'remove_stopwords=True,', 'swith_to_newtxt=True)', 'else:', 'cut_file', '=', 'origin_file', 'try:', 'fp', '=', 'open(cut_file,', "'r...
584,449
devashish-patel/webcam-motion-detector
test_process.py
SubProcessTestCase.setUp
setUp
Make a valid python temp file.
[ "Make", "a", "valid", "python", "temp", "file." ]
def setUp(self): lines = ['from __future__ import print_function', 'import sys', "print('on stdout', end='', file=sys.stdout)", "print('on stderr', end='', file=sys.stderr)", 'sys.stdout.flush()', 'sys.stderr.flush()'] self.mktmp('\n'.join(lines))
['def', 'setUp(self):', 'lines', '=', "['from", '__future__', 'import', "print_function',", "'import", "sys',", '"print(\'on', "stdout',", "end='',", 'file=sys.stdout)",', '"print(\'on', "stderr',", "end='',", 'file=sys.stderr)",', "'sys.stdout.flush()',", "'sys.stderr.flush()']", "self.mktmp('\\n'.join(lines))"]
979,546
zhaocq-nlp/NJUNMT-tf
vocab.py
Vocab.equals
equals
Compares two `Vocab` objects.
[ "Compares", "two", "`Vocab`", "objects." ]
def equals(vocab1, vocab2): if vocab1.vocab_size != vocab2.vocab_size: return False for (key, val) in vocab1.vocab_dict.items(): if key not in vocab2.vocab_dict: return False elif vocab2[key] != val: return False return True
['def', 'equals(vocab1,', 'vocab2):', 'if', 'vocab1.vocab_size', '!=', 'vocab2.vocab_size:', 'return', 'False', 'for', '(key,', 'val)', 'in', 'vocab1.vocab_dict.items():', 'if', 'key', 'not', 'in', 'vocab2.vocab_dict:', 'return', 'False', 'elif', 'vocab2[key]', '!=', 'val:', 'return', 'False', 'return', 'True']
782,811
devashish-patel/webcam-motion-detector
bases.py
Property.themed_default
themed_default
The default, transformed by prepare_value() and the theme overrides.
[ "The", "default,", "transformed", "by", "prepare_value()", "and", "the", "theme", "overrides." ]
def themed_default(self, cls, name, theme_overrides): overrides = theme_overrides if overrides is None or name not in overrides: overrides = cls._overridden_defaults() if name in overrides: default = self._copy_default(overrides[name]) else: default = self._raw_default() retu...
['def', 'themed_default(self,', 'cls,', 'name,', 'theme_overrides):', 'overrides', '=', 'theme_overrides', 'if', 'overrides', 'is', 'None', 'or', 'name', 'not', 'in', 'overrides:', 'overrides', '=', 'cls._overridden_defaults()', 'if', 'name', 'in', 'overrides:', 'default', '=', 'self._copy_default(overrides[name])', 'e...
977,243
yinyunie/ScenePriors
utils.py
is_pointclouds
is_pointclouds
Checks whether the input `pcl` is an instance of `Pointclouds` by checking the existence of `points_padded` and `num_points_per_cloud` functions.
[ "Checks", "whether", "the", "input", "`pcl`", "is", "an", "instance", "of", "`Pointclouds`", "by", "checking", "the", "existence", "of", "`points_padded`", "and", "`num_points_per_cloud`", "functions." ]
def is_pointclouds(pcl: Union[torch.Tensor, 'Pointclouds']) -> bool: return hasattr(pcl, 'points_padded') and hasattr(pcl, 'num_points_per_cloud')
['def', 'is_pointclouds(pcl:', 'Union[torch.Tensor,', "'Pointclouds'])", '->', 'bool:', 'return', 'hasattr(pcl,', "'points_padded')", 'and', 'hasattr(pcl,', "'num_points_per_cloud')"]
329,798
shervinea/enzynet
tools.py
get_class_weights
get_class_weights
Gets class weights for Keras.
[ "Gets", "class", "weights", "for", "Keras." ]
def get_class_weights(dictionary: Dict[Text, int], training_enzymes: Iterator[Text], mode: Text) -> Dict[int, float]: counter = [0 for i in range(constants.N_CLASSES)] for enzyme in training_enzymes: counter[int(dictionary[enzyme]) - 1] += 1 majority = max(counter) class_weights = {i: float(majo...
['def', 'get_class_weights(dictionary:', 'Dict[Text,', 'int],', 'training_enzymes:', 'Iterator[Text],', 'mode:', 'Text)', '->', 'Dict[int,', 'float]:', 'counter', '=', '[0', 'for', 'i', 'in', 'range(constants.N_CLASSES)]', 'for', 'enzyme', 'in', 'training_enzymes:', 'counter[int(dictionary[enzyme])', '-', '1]', '+=', '...
178,222
google-research/tensor2robot
checkpoint_predictor.py
CheckpointPredictor.init_randomly
init_randomly
Initializes model parameters from with random values.
[ "Initializes", "model", "parameters", "from", "with", "random", "values." ]
def init_randomly(self): self._model_was_restored = True logging.info('Initializing model with random weights') self._sess.run(self._global_init_op)
['def', 'init_randomly(self):', 'self._model_was_restored', '=', 'True', "logging.info('Initializing", 'model', 'with', 'random', "weights')", 'self._sess.run(self._global_init_op)']
908,272
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
pydoc.py
HTMLDoc.heading
heading
Format a page heading.
[ "Format", "a", "page", "heading." ]
def heading(self, title, fgcol, bgcol, extras=''): return '\n<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">\n<tr bgcolor="%s">\n<td valign=bottom>&nbsp;<br>\n<font color="%s" face="helvetica, arial">&nbsp;<br>%s</font></td\n><td align=right valign=bottom\n><font color="%s" face="helvet...
['def', 'heading(self,', 'title,', 'fgcol,', 'bgcol,', "extras=''):", 'return', "'\\n<table", 'width="100%%"', 'cellspacing=0', 'cellpadding=2', 'border=0', 'summary="heading">\\n<tr', 'bgcolor="%s">\\n<td', 'valign=bottom>&nbsp;<br>\\n<font', 'color="%s"', 'face="helvetica,', 'arial">&nbsp;<br>%s</font></td\\n><td', '...
429,309
triaquae/triaquae
debug.py
SafeExceptionReporterFilter.get_post_parameters
get_post_parameters
Replaces the values of POST parameters marked as sensitive with stars (*********).
[ "Replaces", "the", "values", "of", "POST", "parameters", "marked", "as", "sensitive", "with", "stars", "(*********)." ]
def get_post_parameters(self, request): if request is None: return {} else: sensitive_post_parameters = getattr(request, 'sensitive_post_parameters', []) if self.is_active(request) and sensitive_post_parameters: cleansed = request.POST.copy() if sensitive_post_par...
['def', 'get_post_parameters(self,', 'request):', 'if', 'request', 'is', 'None:', 'return', '{}', 'else:', 'sensitive_post_parameters', '=', 'getattr(request,', "'sensitive_post_parameters',", '[])', 'if', 'self.is_active(request)', 'and', 'sensitive_post_parameters:', 'cleansed', '=', 'request.POST.copy()', 'if', 'sen...
424,305
google/deepvariant
bed.py
NativeBedReader.iterate
iterate
Returns an iterable of BedRecord protos in the file.
[ "Returns", "an", "iterable", "of", "BedRecord", "protos", "in", "the", "file." ]
def iterate(self): return self._reader.iterate()
['def', 'iterate(self):', 'return', 'self._reader.iterate()']
540,544
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
tree.py
Tree.getType
getType
Return a token type; needed for tree parsing.
[ "Return", "a", "token", "type;", "needed", "for", "tree", "parsing." ]
def getType(self): raise NotImplementedError
['def', 'getType(self):', 'raise', 'NotImplementedError']
16,496
SALT-NLP/Adaptive-Compositional-Modules
tokenization_tapas.py
TapasTokenizer.create_column_token_type_ids_from_sequences
create_column_token_type_ids_from_sequences
Creates the column token type IDs according to the query token IDs and a list of table values.
[ "Creates", "the", "column", "token", "type", "IDs", "according", "to", "the", "query", "token", "IDs", "and", "a", "list", "of", "table", "values." ]
def create_column_token_type_ids_from_sequences(self, query_ids: List[int], table_values: List[TableValue]) -> List[int]: table_column_ids = list(zip(*table_values))[1] if table_values else [] return [0] * (1 + len(query_ids) + 1) + list(table_column_ids)
['def', 'create_column_token_type_ids_from_sequences(self,', 'query_ids:', 'List[int],', 'table_values:', 'List[TableValue])', '->', 'List[int]:', 'table_column_ids', '=', 'list(zip(*table_values))[1]', 'if', 'table_values', 'else', '[]', 'return', '[0]', '*', '(1', '+', 'len(query_ids)', '+', '1)', '+', 'list(table_co...
409,141
open-mmlab/mmdetection3d
image_cross_attention.py
TPVMSDeformableAttention3D.forward
forward
Forward Function of MultiScaleDeformAttention.
[ "Forward", "Function", "of", "MultiScaleDeformAttention." ]
def forward(self, query, key=None, value=None, identity=None, reference_points=None, spatial_shapes=None, level_start_index=None, **kwargs): if value is None: value = query if identity is None: identity = query if not self.batch_first: query = [q.permute(1, 0, 2) for q in query] ...
['def', 'forward(self,', 'query,', 'key=None,', 'value=None,', 'identity=None,', 'reference_points=None,', 'spatial_shapes=None,', 'level_start_index=None,', '**kwargs):', 'if', 'value', 'is', 'None:', 'value', '=', 'query', 'if', 'identity', 'is', 'None:', 'identity', '=', 'query', 'if', 'not', 'self.batch_first:', 'q...
632,470
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
losses.py
add_rotator_mask_loss
add_rotator_mask_loss
Computes the mask loss of deep rotator model.
[ "Computes", "the", "mask", "loss", "of", "deep", "rotator", "model." ]
def add_rotator_mask_loss(inputs, outputs, step_size, weight_scale): batch_size = tf.shape(inputs['images_0'])[0] mask_loss = 0 for k in range(1, step_size + 1): mask_loss += tf.nn.l2_loss(inputs['masks_%d' % k] - outputs['masks_%d' % k]) mask_loss /= tf.to_float(step_size * batch_size) slim...
['def', 'add_rotator_mask_loss(inputs,', 'outputs,', 'step_size,', 'weight_scale):', 'batch_size', '=', "tf.shape(inputs['images_0'])[0]", 'mask_loss', '=', '0', 'for', 'k', 'in', 'range(1,', 'step_size', '+', '1):', 'mask_loss', '+=', "tf.nn.l2_loss(inputs['masks_%d'", '%', 'k]', '-', "outputs['masks_%d'", '%', 'k])',...
109,140
huawei-noah/xingtian
tf_optimizer.py
TFOptimizer.get_real_optimizer
get_real_optimizer
Get real optimizer for faster-rcnn.
[ "Get", "real", "optimizer", "for", "faster-rcnn." ]
def get_real_optimizer(self, global_step=None): if self.optimizer: return (self.optimizer, self.summary_vars) else: if self.type == 'RMSPropOptimizer': learning_rate = self._create_learning_rate(self.lr, global_step=global_step) self.summary_vars.append(learning_rate) ...
['def', 'get_real_optimizer(self,', 'global_step=None):', 'if', 'self.optimizer:', 'return', '(self.optimizer,', 'self.summary_vars)', 'else:', 'if', 'self.type', '==', "'RMSPropOptimizer':", 'learning_rate', '=', 'self._create_learning_rate(self.lr,', 'global_step=global_step)', 'self.summary_vars.append(learning_rate...
963,050
Oporto/CS4341_Artificial_Inteligence
transform_test.py
TransformModuleTest.test_scale__alpha
test_scale__alpha
see if set_alpha information is kept.
[ "see", "if", "set_alpha", "information", "is", "kept." ]
def test_scale__alpha(self): s = pygame.Surface((32, 32)) s.set_alpha(55) self.assertEqual(s.get_alpha(), 55) s = pygame.Surface((32, 32)) s.set_alpha(55) s2 = pygame.transform.scale(s, (64, 64)) s3 = s.copy() self.assertEqual(s.get_alpha(), s3.get_alpha()) self.assertEqual(s.get_alp...
['def', 'test_scale__alpha(self):', 's', '=', 'pygame.Surface((32,', '32))', 's.set_alpha(55)', 'self.assertEqual(s.get_alpha(),', '55)', 's', '=', 'pygame.Surface((32,', '32))', 's.set_alpha(55)', 's2', '=', 'pygame.transform.scale(s,', '(64,', '64))', 's3', '=', 's.copy()', 'self.assertEqual(s.get_alpha(),', 's3.get_...
191,775