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 |
|---|---|---|---|---|---|---|---|---|
wandb/wandb | util.py | make_artifact_name_safe | make_artifact_name_safe | Make an artifact name safe for use in artifacts. | [
"Make",
"an",
"artifact",
"name",
"safe",
"for",
"use",
"in",
"artifacts."
] | def make_artifact_name_safe(name: str) -> str:
cleaned = re.sub('[^a-zA-Z0-9_\\-.]', '_', name)
if len(cleaned) <= 128:
return cleaned
return re.sub('(^.{63}).*(.{63}$)', '\\g<1>..\\g<2>', cleaned) | ['def', 'make_artifact_name_safe(name:', 'str)', '->', 'str:', 'cleaned', '=', "re.sub('[^a-zA-Z0-9_\\\\-.]',", "'_',", 'name)', 'if', 'len(cleaned)', '<=', '128:', 'return', 'cleaned', 'return', "re.sub('(^.{63}).*(.{63}$)',", "'\\\\g<1>..\\\\g<2>',", 'cleaned)'] | 941,414 |
gunthercox/ChatterBot | tagged.py | TaggedCorpusView.read_block | read_block | Reads one paragraph at a time. | [
"Reads",
"one",
"paragraph",
"at",
"a",
"time."
] | def read_block(self, stream):
block = []
for para_str in self._para_block_reader(stream):
para = []
for sent_str in self._sent_tokenizer.tokenize(para_str):
sent = [str2tuple(s, self._sep) for s in self._word_tokenizer.tokenize(sent_str)]
if self._tag_mapping_function:
... | ['def', 'read_block(self,', 'stream):', 'block', '=', '[]', 'for', 'para_str', 'in', 'self._para_block_reader(stream):', 'para', '=', '[]', 'for', 'sent_str', 'in', 'self._sent_tokenizer.tokenize(para_str):', 'sent', '=', '[str2tuple(s,', 'self._sep)', 'for', 's', 'in', 'self._word_tokenizer.tokenize(sent_str)]', 'if',... | 530,134 |
xiongfengyan/gcnn | models.py | gcnn.build_graph | build_graph | Build the computational graph of the model. | [
"Build",
"the",
"computational",
"graph",
"of",
"the",
"model."
] | def build_graph(self, Vs, As):
self.graph = tf.Graph()
with self.graph.as_default():
with tf.name_scope('inputs'):
self.ph_vertices = tf.placeholder(tf.float32, (self.batch_size, As, Vs), 'vertices')
self.ph_adjacencies = tf.placeholder(tf.float32, (self.batch_size, As, As), 'adj... | ['def', 'build_graph(self,', 'Vs,', 'As):', 'self.graph', '=', 'tf.Graph()', 'with', 'self.graph.as_default():', 'with', "tf.name_scope('inputs'):", 'self.ph_vertices', '=', 'tf.placeholder(tf.float32,', '(self.batch_size,', 'As,', 'Vs),', "'vertices')", 'self.ph_adjacencies', '=', 'tf.placeholder(tf.float32,', '(self.... | 201,357 |
RasaHQ/rasa | emulator.py | Emulator.normalise_response_json | normalise_response_json | Transform response JSON to target format. | [
"Transform",
"response",
"JSON",
"to",
"target",
"format."
] | def normalise_response_json(self, data: Dict[Text, Any]) -> Dict[Text, Any]:
raise NotImplementedError | ['def', 'normalise_response_json(self,', 'data:', 'Dict[Text,', 'Any])', '->', 'Dict[Text,', 'Any]:', 'raise', 'NotImplementedError'] | 837,188 |
nancheng58/Self-supervised-learning-for-Sequential-Recommender-Systems | abstract_recommender.py | AbstractRecommender.predict | predict | Predict the scores between users and items. | [
"Predict",
"the",
"scores",
"between",
"users",
"and",
"items."
] | def predict(self, interaction):
raise NotImplementedError | ['def', 'predict(self,', 'interaction):', 'raise', 'NotImplementedError'] | 341,864 |
Alexander-Parker/youtube_nlp | common.py | validate_is_callable_or_none | validate_is_callable_or_none | Validates that 'value' is a callable. | [
"Validates",
"that",
"'value'",
"is",
"a",
"callable."
] | def validate_is_callable_or_none(option, value):
if value is None:
return value
if not callable(value):
raise ValueError('%s must be a callable' % (option,))
return value | ['def', 'validate_is_callable_or_none(option,', 'value):', 'if', 'value', 'is', 'None:', 'return', 'value', 'if', 'not', 'callable(value):', 'raise', "ValueError('%s", 'must', 'be', 'a', "callable'", '%', '(option,))', 'return', 'value'] | 970,381 |
zihuitang/medical_AI_platform | cookiejar.py | CookiePolicy.path_return_ok | path_return_ok | Return false if cookies should not be returned, given cookie path. | [
"Return",
"false",
"if",
"cookies",
"should",
"not",
"be",
"returned,",
"given",
"cookie",
"path."
] | def path_return_ok(self, path, request):
return True | ['def', 'path_return_ok(self,', 'path,', 'request):', 'return', 'True'] | 282,615 |
intel/neural-compressor | metric.py | MAE.update | update | Add the predictions and labels. | [
"Add",
"the",
"predictions",
"and",
"labels."
] | def update(self, preds, labels, sample_weight=None):
(preds, labels) = _shape_validate(preds, labels)
self.label_list.extend(labels)
self.pred_list.extend(preds) | ['def', 'update(self,', 'preds,', 'labels,', 'sample_weight=None):', '(preds,', 'labels)', '=', '_shape_validate(preds,', 'labels)', 'self.label_list.extend(labels)', 'self.pred_list.extend(preds)'] | 738,560 |
ZumoLabs/zpy | image.py | seg_to_annotations | seg_to_annotations | Convert a segmentation image into bounding boxes and polygon segmentations. | [
"Convert",
"a",
"segmentation",
"image",
"into",
"bounding",
"boxes",
"and",
"polygon",
"segmentations."
] | def seg_to_annotations(image_path: Union[Path, str], remove_salt: bool=True, rle_segmentations: bool=False, float_annotations: bool=False, max_categories: int=1000) -> List[Dict]:
log.info(f'Extracting annotations from segmentation: {image_path}')
image_path = zpy.files.verify_path(image_path, make=False)
i... | ['def', 'seg_to_annotations(image_path:', 'Union[Path,', 'str],', 'remove_salt:', 'bool=True,', 'rle_segmentations:', 'bool=False,', 'float_annotations:', 'bool=False,', 'max_categories:', 'int=1000)', '->', 'List[Dict]:', "log.info(f'Extracting", 'annotations', 'from', 'segmentation:', "{image_path}')", 'image_path', ... | 972,045 |
dojoteef/dvae | dataloader.py | Dataset.image_size | image_size | Return the image size of the images in the dataset. | [
"Return",
"the",
"image",
"size",
"of",
"the",
"images",
"in",
"the",
"dataset."
] | def image_size(self):
return self.train.images.shape[1:3] | ['def', 'image_size(self):', 'return', 'self.train.images.shape[1:3]'] | 554,977 |
matsu0228/nlp-jp | iterable.py | get_dynamic_array_instance | get_dynamic_array_instance | Used for set() and list() instances. | [
"Used",
"for",
"set()",
"and",
"list()",
"instances."
] | def get_dynamic_array_instance(instance):
if not settings.dynamic_array_additions:
return instance.var_args
ai = _ArrayInstance(instance)
from jedi.evaluate import param
return param.ValuesArguments([[ai]]) | ['def', 'get_dynamic_array_instance(instance):', 'if', 'not', 'settings.dynamic_array_additions:', 'return', 'instance.var_args', 'ai', '=', '_ArrayInstance(instance)', 'from', 'jedi.evaluate', 'import', 'param', 'return', 'param.ValuesArguments([[ai]])'] | 787,713 |
berlius/artificial-intelligence | util.py | build_module | build_module | Compile and import a f2py module, built from the given files. | [
"Compile",
"and",
"import",
"a",
"f2py",
"module,",
"built",
"from",
"the",
"given",
"files."
] | def build_module(source_files, options=[], skip=[], only=[], module_name=None):
code = 'import sys; sys.path = %s; import numpy.f2py as f2py2e; f2py2e.main()' % repr(sys.path)
d = get_module_dir()
dst_sources = []
for fn in source_files:
if not os.path.isfile(fn):
raise RuntimeError(... | ['def', 'build_module(source_files,', 'options=[],', 'skip=[],', 'only=[],', 'module_name=None):', 'code', '=', "'import", 'sys;', 'sys.path', '=', '%s;', 'import', 'numpy.f2py', 'as', 'f2py2e;', "f2py2e.main()'", '%', 'repr(sys.path)', 'd', '=', 'get_module_dir()', 'dst_sources', '=', '[]', 'for', 'fn', 'in', 'source_... | 169,024 |
PacktPublishing/Hands-On-Artificial--for-Banking | msvc.py | SystemInfo.FSharpInstallDir | FSharpInstallDir | Microsoft Visual F# directory. | [
"Microsoft",
"Visual",
"F#",
"directory."
] | def FSharpInstallDir(self):
path = '%0.1f\\Setup\\F#' % self.vc_ver
path = os.path.join(self.ri.visualstudio, path)
return self.ri.lookup(path, 'productdir') or '' | ['def', 'FSharpInstallDir(self):', 'path', '=', "'%0.1f\\\\Setup\\\\F#'", '%', 'self.vc_ver', 'path', '=', 'os.path.join(self.ri.visualstudio,', 'path)', 'return', 'self.ri.lookup(path,', "'productdir')", 'or', "''"] | 203,708 |
RasaHQ/rasa | readerwriter.py | TrainingDataReader.reads | reads | Reads TrainingData from a string. | [
"Reads",
"TrainingData",
"from",
"a",
"string."
] | def reads(self, s: Text, **kwargs: Any) -> 'TrainingData':
raise NotImplementedError | ['def', 'reads(self,', 's:', 'Text,', '**kwargs:', 'Any)', '->', "'TrainingData':", 'raise', 'NotImplementedError'] | 837,756 |
vmware-archive/salt-contrib | octopus_tentacle_test.py | OctopusTentacleTestCase.test_set_squid | test_set_squid | Test - Manage the SQUID of the provided instance. | [
"Test",
"-",
"Manage",
"the",
"SQUID",
"of",
"the",
"provided",
"instance."
] | def test_set_squid(self):
mock_cmd = MagicMock(return_value={'retcode': 0})
with patch.dict(octopus_tentacle.__salt__, {'cmd.run_all': mock_cmd}):
self.assertTrue(octopus_tentacle.set_squid()) | ['def', 'test_set_squid(self):', 'mock_cmd', '=', "MagicMock(return_value={'retcode':", '0})', 'with', 'patch.dict(octopus_tentacle.__salt__,', "{'cmd.run_all':", 'mock_cmd}):', 'self.assertTrue(octopus_tentacle.set_squid())'] | 328,957 |
43Carrig/recurrent_neural_networks_practice | traceable_stack.py | TraceableStack.push_obj | push_obj | Add object to the stack and record its filename and line information. | [
"Add",
"object",
"to",
"the",
"stack",
"and",
"record",
"its",
"filename",
"and",
"line",
"information."
] | def push_obj(self, obj, offset=0):
traceable_obj = TraceableObject(obj)
self._stack.append(traceable_obj)
return traceable_obj.set_filename_and_line_from_caller(offset + 1) | ['def', 'push_obj(self,', 'obj,', 'offset=0):', 'traceable_obj', '=', 'TraceableObject(obj)', 'self._stack.append(traceable_obj)', 'return', 'traceable_obj.set_filename_and_line_from_caller(offset', '+', '1)'] | 336,641 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | __init__.py | LoggerAdapter.debug | debug | Delegate a debug call to the underlying logger. | [
"Delegate",
"a",
"debug",
"call",
"to",
"the",
"underlying",
"logger."
] | def debug(self, msg, *args, **kwargs):
self.log(DEBUG, msg, *args, **kwargs) | ['def', 'debug(self,', 'msg,', '*args,', '**kwargs):', 'self.log(DEBUG,', 'msg,', '*args,', '**kwargs)'] | 431,224 |
simoncadman/CUPS-Cloud-Print | client.py | OAuth2Credentials.apply | apply | Add the authorization to the headers. | [
"Add",
"the",
"authorization",
"to",
"the",
"headers."
] | def apply(self, headers):
headers['Authorization'] = 'Bearer ' + self.access_token | ['def', 'apply(self,', 'headers):', "headers['Authorization']", '=', "'Bearer", "'", '+', 'self.access_token'] | 197,430 |
Ruturaj123/Flowchart-Detection | base.py | load_boston | load_boston | Load Boston housing dataset. | [
"Load",
"Boston",
"housing",
"dataset."
] | def load_boston(data_path=None):
if data_path is None:
module_path = path.dirname(__file__)
data_path = path.join(module_path, 'data', 'boston_house_prices.csv')
return load_csv_with_header(data_path, target_dtype=np.float, features_dtype=np.float) | ['def', 'load_boston(data_path=None):', 'if', 'data_path', 'is', 'None:', 'module_path', '=', 'path.dirname(__file__)', 'data_path', '=', 'path.join(module_path,', "'data',", "'boston_house_prices.csv')", 'return', 'load_csv_with_header(data_path,', 'target_dtype=np.float,', 'features_dtype=np.float)'] | 603,818 |
enuguru/artificial_intelligence_and_machine_ | packaging.py | append_text_list | append_text_list | Append a separated list to possibly existing value. | [
"Append",
"a",
"separated",
"list",
"to",
"possibly",
"existing",
"value."
] | def append_text_list(config, key, text_list):
new_value = []
current_value = config.get(key, '')
if current_value:
new_value.append(current_value)
new_value.extend(text_list)
config[key] = '\n'.join(new_value) | ['def', 'append_text_list(config,', 'key,', 'text_list):', 'new_value', '=', '[]', 'current_value', '=', 'config.get(key,', "'')", 'if', 'current_value:', 'new_value.append(current_value)', 'new_value.extend(text_list)', 'config[key]', '=', "'\\n'.join(new_value)"] | 130,518 |
secretflow/secretflow | scaler.py | MinMaxScaler.fit | fit | Compute the minimum and maximum for later scaling. | [
"Compute",
"the",
"minimum",
"and",
"maximum",
"for",
"later",
"scaling."
] | def fit(self, df: Union[HDataFrame, VDataFrame, MixDataFrame]):
self._check_dataframe(df)
min_max = pd.concat([df.min().to_frame(name='min').transpose(), df.max().to_frame(name='max').transpose()])
self._scaler = SkMinMaxScaler()
self._scaler.fit(min_max)
self._columns = df.columns | ['def', 'fit(self,', 'df:', 'Union[HDataFrame,', 'VDataFrame,', 'MixDataFrame]):', 'self._check_dataframe(df)', 'min_max', '=', "pd.concat([df.min().to_frame(name='min').transpose(),", "df.max().to_frame(name='max').transpose()])", 'self._scaler', '=', 'SkMinMaxScaler()', 'self._scaler.fit(min_max)', 'self._columns', '... | 856,595 |
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform | globals.py | pop_context | pop_context | Removes the top level from the stack. | [
"Removes",
"the",
"top",
"level",
"from",
"the",
"stack."
] | def pop_context():
_local.stack.pop() | ['def', 'pop_context():', '_local.stack.pop()'] | 101,877 |
man805/Diffusion-Video-Autoencoders | nn.py | conv_nd | conv_nd | Create a 1D, 2D, or 3D convolution module. | [
"Create",
"a",
"1D,",
"2D,",
"or",
"3D",
"convolution",
"module."
] | def conv_nd(dims, *args, **kwargs):
if dims == 1:
return nn.Conv1d(*args, **kwargs)
elif dims == 2:
return nn.Conv2d(*args, **kwargs)
elif dims == 3:
return nn.Conv3d(*args, **kwargs)
raise ValueError(f'unsupported dimensions: {dims}') | ['def', 'conv_nd(dims,', '*args,', '**kwargs):', 'if', 'dims', '==', '1:', 'return', 'nn.Conv1d(*args,', '**kwargs)', 'elif', 'dims', '==', '2:', 'return', 'nn.Conv2d(*args,', '**kwargs)', 'elif', 'dims', '==', '3:', 'return', 'nn.Conv3d(*args,', '**kwargs)', 'raise', "ValueError(f'unsupported", 'dimensions:', "{dims}'... | 551,749 |
flavioschneider/rl-transfer- | _functions.py | rollout | rollout | Sample a single episode of the agent in the environment. | [
"Sample",
"a",
"single",
"episode",
"of",
"the",
"agent",
"in",
"the",
"environment."
] | def rollout(env, agent, *, max_episode_length=np.inf, animated=False, pause_per_frame=None, deterministic=False):
env_steps = []
agent_infos = []
observations = []
(last_obs, episode_infos) = env.reset()
agent.reset()
episode_length = 0
if animated:
env.visualize()
while episode_... | ['def', 'rollout(env,', 'agent,', '*,', 'max_episode_length=np.inf,', 'animated=False,', 'pause_per_frame=None,', 'deterministic=False):', 'env_steps', '=', '[]', 'agent_infos', '=', '[]', 'observations', '=', '[]', '(last_obs,', 'episode_infos)', '=', 'env.reset()', 'agent.reset()', 'episode_length', '=', '0', 'if', '... | 860,993 |
mideind/GreynirServer | tnttagger.py | FreqDist.freq | freq | Return the frequency of a given sample. | [
"Return",
"the",
"frequency",
"of",
"a",
"given",
"sample."
] | def freq(self, sample: str) -> float:
n = self.N()
if n == 0:
return 0
return self.get(sample, 0) / n | ['def', 'freq(self,', 'sample:', 'str)', '->', 'float:', 'n', '=', 'self.N()', 'if', 'n', '==', '0:', 'return', '0', 'return', 'self.get(sample,', '0)', '/', 'n'] | 581,022 |
TonyLianLong/VAI-ReinforcementLearning | quadruped.py | Physics.toe_positions | toe_positions | Returns toe positions in egocentric frame. | [
"Returns",
"toe",
"positions",
"in",
"egocentric",
"frame."
] | def toe_positions(self):
torso_frame = self.named.data.xmat['torso'].reshape(3, 3)
torso_pos = self.named.data.xpos['torso']
torso_to_toe = self.named.data.xpos[_TOES] - torso_pos
return torso_to_toe.dot(torso_frame) | ['def', 'toe_positions(self):', 'torso_frame', '=', "self.named.data.xmat['torso'].reshape(3,", '3)', 'torso_pos', '=', "self.named.data.xpos['torso']", 'torso_to_toe', '=', 'self.named.data.xpos[_TOES]', '-', 'torso_pos', 'return', 'torso_to_toe.dot(torso_frame)'] | 440,948 |
Honkl/general-ai | game2048.py | Game2048.init_process | init_process | Initializes a new 2048 game. | [
"Initializes",
"a",
"new",
"2048",
"game."
] | def init_process(self):
spec = importlib.util.spec_from_file_location('Game', GAME2048_PY_PATH)
game_2048 = importlib.util.module_from_spec(spec)
spec.loader.exec_module(game_2048)
self.game = game_2048.Game(self.rng.randint(0, 2 ** 30))
state = self.game.get_state()
return (state, self.phase) | ['def', 'init_process(self):', 'spec', '=', "importlib.util.spec_from_file_location('Game',", 'GAME2048_PY_PATH)', 'game_2048', '=', 'importlib.util.module_from_spec(spec)', 'spec.loader.exec_module(game_2048)', 'self.game', '=', 'game_2048.Game(self.rng.randint(0,', '2', '**', '30))', 'state', '=', 'self.game.get_stat... | 202,247 |
klickmal/ContextNet | audio_encoder.py | AudioEncoder.forward | forward | Forward propagate a `inputs` for audio encoder. | [
"Forward",
"propagate",
"a",
"`inputs`",
"for",
"audio",
"encoder."
] | def forward(self, inputs: Tensor, input_lengths: Tensor) -> Tuple[Tensor, Tensor]:
output = inputs.transpose(1, 2)
output_lengths = input_lengths
for block in self.blocks:
(output, output_lengths) = block(output, output_lengths)
return (output.transpose(1, 2), output_lengths) | ['def', 'forward(self,', 'inputs:', 'Tensor,', 'input_lengths:', 'Tensor)', '->', 'Tuple[Tensor,', 'Tensor]:', 'output', '=', 'inputs.transpose(1,', '2)', 'output_lengths', '=', 'input_lengths', 'for', 'block', 'in', 'self.blocks:', '(output,', 'output_lengths)', '=', 'block(output,', 'output_lengths)', 'return', '(out... | 136,359 |
rlworkgroup/garage | _functions.py | torch_to_np | torch_to_np | Convert PyTorch tensors to numpy arrays. | [
"Convert",
"PyTorch",
"tensors",
"to",
"numpy",
"arrays."
] | def torch_to_np(tensors):
value_out = tuple((v.cpu().numpy() for v in tensors))
return value_out | ['def', 'torch_to_np(tensors):', 'value_out', '=', 'tuple((v.cpu().numpy()', 'for', 'v', 'in', 'tensors))', 'return', 'value_out'] | 200,736 |
google/deepvariant | vcf.py | NativeVcfReader.c_reader | c_reader | Returns the underlying C++ reader. | [
"Returns",
"the",
"underlying",
"C++",
"reader."
] | def c_reader(self):
return self._reader | ['def', 'c_reader(self):', 'return', 'self._reader'] | 540,606 |
weimin17/Object-Detection_HelmetDetection | models.py | small_decoder | small_decoder | Decodes the codes to a fixed output size. | [
"Decodes",
"the",
"codes",
"to",
"a",
"fixed",
"output",
"size."
] | def small_decoder(codes, height, width, channels, batch_norm_params=None, weight_decay=0.0):
with slim.arg_scope([slim.conv2d, slim.fully_connected], weights_regularizer=slim.l2_regularizer(weight_decay), activation_fn=tf.nn.relu, normalizer_fn=slim.batch_norm, normalizer_params=batch_norm_params):
net = sl... | ['def', 'small_decoder(codes,', 'height,', 'width,', 'channels,', 'batch_norm_params=None,', 'weight_decay=0.0):', 'with', 'slim.arg_scope([slim.conv2d,', 'slim.fully_connected],', 'weights_regularizer=slim.l2_regularizer(weight_decay),', 'activation_fn=tf.nn.relu,', 'normalizer_fn=slim.batch_norm,', 'normalizer_params... | 749,883 |
tensorflow/agents | train_utils_test.py | TrainUtilsTest.test_wait_for_predicate_instant_false | test_wait_for_predicate_instant_false | Tests predicate returning False on first call. | [
"Tests",
"predicate",
"returning",
"False",
"on",
"first",
"call."
] | def test_wait_for_predicate_instant_false(self):
predicate_mock = mock.MagicMock(side_effect=[False])
train_utils.wait_for_predicate(predicate_mock, num_retries=10)
self.assertEqual(predicate_mock.call_count, 1) | ['def', 'test_wait_for_predicate_instant_false(self):', 'predicate_mock', '=', 'mock.MagicMock(side_effect=[False])', 'train_utils.wait_for_predicate(predicate_mock,', 'num_retries=10)', 'self.assertEqual(predicate_mock.call_count,', '1)'] | 23,746 |
replit-archive/empythoned | __init__.py | Handler.setFormatter | setFormatter | Set the formatter for this handler. | [
"Set",
"the",
"formatter",
"for",
"this",
"handler."
] | def setFormatter(self, fmt):
self.formatter = fmt | ['def', 'setFormatter(self,', 'fmt):', 'self.formatter', '=', 'fmt'] | 177,721 |
instadeepai/jumanji | utils_spawn.py | spawn_agent | spawn_agent | Spawn an agent (robot) at a given position and direction. | [
"Spawn",
"an",
"agent",
"(robot)",
"at",
"a",
"given",
"position",
"and",
"direction."
] | def spawn_agent(agent_coordinates: chex.Array, direction: chex.Array) -> chex.Array:
(x, y) = agent_coordinates
agent_pos = Position(x=x, y=y)
agent = Agent(position=agent_pos, direction=direction, is_carrying=0)
return agent | ['def', 'spawn_agent(agent_coordinates:', 'chex.Array,', 'direction:', 'chex.Array)', '->', 'chex.Array:', '(x,', 'y)', '=', 'agent_coordinates', 'agent_pos', '=', 'Position(x=x,', 'y=y)', 'agent', '=', 'Agent(position=agent_pos,', 'direction=direction,', 'is_carrying=0)', 'return', 'agent'] | 594,492 |
carbonati/variational-zoo | ops.py | compute_on_off_diag | compute_on_off_diag | Computes the on and off diagonal of a tensor. | [
"Computes",
"the",
"on",
"and",
"off",
"diagonal",
"of",
"a",
"tensor."
] | def compute_on_off_diag(cov_matrix):
diag = tf.linalg.diag_part(cov_matrix)
off_diag = cov_matrix - tf.linalg.diag(diag)
return (diag, off_diag) | ['def', 'compute_on_off_diag(cov_matrix):', 'diag', '=', 'tf.linalg.diag_part(cov_matrix)', 'off_diag', '=', 'cov_matrix', '-', 'tf.linalg.diag(diag)', 'return', '(diag,', 'off_diag)'] | 379,241 |
ManifoldFR/recvis-project | evaluate_h36m.py | get_data | get_data | Read preprocessed image from tfrecords. | [
"Read",
"preprocessed",
"image",
"from",
"tfrecords."
] | def get_data(seq_name, config):
global sess
if sess is None:
sess = tf.Session()
tf_path = join(expanduser(config.tfh36m_dir), 'test', seq_name + '.tfrecord')
(images, kps, gt3ds) = read_images_from_tfrecords(tf_path, img_size=config.img_size, sess=sess)
return (images, gt3ds) | ['def', 'get_data(seq_name,', 'config):', 'global', 'sess', 'if', 'sess', 'is', 'None:', 'sess', '=', 'tf.Session()', 'tf_path', '=', 'join(expanduser(config.tfh36m_dir),', "'test',", 'seq_name', '+', "'.tfrecord')", '(images,', 'kps,', 'gt3ds)', '=', 'read_images_from_tfrecords(tf_path,', 'img_size=config.img_size,', ... | 832,447 |
open-mmlab/mmcv | image.py | imshow_bboxes | imshow_bboxes | Draw bboxes on an image. | [
"Draw",
"bboxes",
"on",
"an",
"image."
] | def imshow_bboxes(img: Union[str, np.ndarray], bboxes: Union[list, np.ndarray], colors: ColorType='green', top_k: int=-1, thickness: int=1, show: bool=True, win_name: str='', wait_time: int=0, out_file: Optional[str]=None):
img = imread(img)
img = np.ascontiguousarray(img)
if isinstance(bboxes, np.ndarray):... | ['def', 'imshow_bboxes(img:', 'Union[str,', 'np.ndarray],', 'bboxes:', 'Union[list,', 'np.ndarray],', 'colors:', "ColorType='green',", 'top_k:', 'int=-1,', 'thickness:', 'int=1,', 'show:', 'bool=True,', 'win_name:', "str='',", 'wait_time:', 'int=0,', 'out_file:', 'Optional[str]=None):', 'img', '=', 'imread(img)', 'img'... | 631,625 |
Kvatsx/Artificial-Intelligence-Assignments | __init__.py | detect_hooks | detect_hooks | Returns True if the import hooks are installed, False if not. | [
"Returns",
"True",
"if",
"the",
"import",
"hooks",
"are",
"installed,",
"False",
"if",
"not."
] | def detect_hooks():
flog.debug('Detecting hooks ...')
present = any([hasattr(hook, 'RENAMER') for hook in sys.meta_path])
if present:
flog.debug('Detected.')
else:
flog.debug('Not detected.')
return present | ['def', 'detect_hooks():', "flog.debug('Detecting", 'hooks', "...')", 'present', '=', 'any([hasattr(hook,', "'RENAMER')", 'for', 'hook', 'in', 'sys.meta_path])', 'if', 'present:', "flog.debug('Detected.')", 'else:', "flog.debug('Not", "detected.')", 'return', 'present'] | 37,152 |
AboudyKreidieh/h-baselines | test_envs.py | TestEfficientHRLAntEnvironments.test_ant_four_rooms | test_ant_four_rooms | Validate the functionality of the AntFourRooms environment. | [
"Validate",
"the",
"functionality",
"of",
"the",
"AntFourRooms",
"environment."
] | def test_ant_four_rooms(self):
env = AntFourRooms(use_contexts=True, context_range=[0, 0])
env.reset()
np.testing.assert_almost_equal(env.action_space.low, np.array([-30.0, -30.0, -30.0, -30.0, -30.0, -30.0, -30.0, -30.0]))
np.testing.assert_almost_equal(env.action_space.high, np.array([30.0, 30.0, 30.0... | ['def', 'test_ant_four_rooms(self):', 'env', '=', 'AntFourRooms(use_contexts=True,', 'context_range=[0,', '0])', 'env.reset()', 'np.testing.assert_almost_equal(env.action_space.low,', 'np.array([-30.0,', '-30.0,', '-30.0,', '-30.0,', '-30.0,', '-30.0,', '-30.0,', '-30.0]))', 'np.testing.assert_almost_equal(env.action_s... | 574,039 |
xiaoaleiBLUE/computer_vision | text_dataflow.py | get_batch_train_dataflow | get_batch_train_dataflow | Tensorpack batch text dataflow. | [
"Tensorpack",
"batch",
"text",
"dataflow."
] | def get_batch_train_dataflow(roidbs, batch_size):
batched_roidbs = []
batch = []
for (i, d) in enumerate(roidbs):
if i % batch_size == 0:
if len(batch) == batch_size:
batched_roidbs.append(batch)
batch = []
batch.append(d)
def preprocess(roidb_bat... | ['def', 'get_batch_train_dataflow(roidbs,', 'batch_size):', 'batched_roidbs', '=', '[]', 'batch', '=', '[]', 'for', '(i,', 'd)', 'in', 'enumerate(roidbs):', 'if', 'i', '%', 'batch_size', '==', '0:', 'if', 'len(batch)', '==', 'batch_size:', 'batched_roidbs.append(batch)', 'batch', '=', '[]', 'batch.append(d)', 'def', 'p... | 501,488 |
ternaus/kaggle_dstl_submission | visualize.py | plot_image | plot_image | Plot get_images(imageId)[image_key] on axis/fig Optional: select which channels of the image are used (used for sixteen_band/ images) Parameters ---------- img_key : str, {'3', 'P', 'N', 'A'} See get_images for description. | [
"Plot",
"get_images(imageId)[image_key]",
"on",
"axis/fig",
"Optional:",
"select",
"which",
"channels",
"of",
"the",
"image",
"are",
"used",
"(used",
"for",
"sixteen_band/",
"images)",
"Parameters",
"----------",
"img_key",
":",
"str,",
"{'3',",
"'P',",
"'N',",
"'A'... | def plot_image(fig, ax, imageId, img_key, selected_channels=None):
images = get_images(imageId, img_key)
img = images[img_key]
title_suffix = ''
if selected_channels is not None:
img = img[selected_channels]
title_suffix = ' (' + ','.join([repr(i) for i in selected_channels]) + ')'
i... | ['def', 'plot_image(fig,', 'ax,', 'imageId,', 'img_key,', 'selected_channels=None):', 'images', '=', 'get_images(imageId,', 'img_key)', 'img', '=', 'images[img_key]', 'title_suffix', '=', "''", 'if', 'selected_channels', 'is', 'not', 'None:', 'img', '=', 'img[selected_channels]', 'title_suffix', '=', "'", "('", '+', "'... | 247,258 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | tix.py | Tree.open | open | Open the entry given by entryPath if its mode is open. | [
"Open",
"the",
"entry",
"given",
"by",
"entryPath",
"if",
"its",
"mode",
"is",
"open."
] | def open(self, entrypath):
self.tk.call(self._w, 'open', entrypath) | ['def', 'open(self,', 'entrypath):', 'self.tk.call(self._w,', "'open',", 'entrypath)'] | 376,643 |
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform | test.py | EnvironBuilder.args | args | The URL arguments as :class:`MultiDict`. | [
"The",
"URL",
"arguments",
"as",
":class:`MultiDict`."
] | def args(self):
if self._query_string is not None:
raise AttributeError('a query string is defined')
if self._args is None:
self._args = MultiDict()
return self._args | ['def', 'args(self):', 'if', 'self._query_string', 'is', 'not', 'None:', 'raise', "AttributeError('a", 'query', 'string', 'is', "defined')", 'if', 'self._args', 'is', 'None:', 'self._args', '=', 'MultiDict()', 'return', 'self._args'] | 84,946 |
facebookresearch/CompilerGym | llvm.py | non_validatable_cbench_uri | non_validatable_cbench_uri | Enumerate the names of benchmarks whose semantics cannot be validated. | [
"Enumerate",
"the",
"names",
"of",
"benchmarks",
"whose",
"semantics",
"cannot",
"be",
"validated."
] | def non_validatable_cbench_uri(request) -> str:
yield request.param | ['def', 'non_validatable_cbench_uri(request)', '->', 'str:', 'yield', 'request.param'] | 125,974 |
dibyaghosh/gcsl | configurable_test.py | TestConfigurable.test_set_config_kwargs | test_set_config_kwargs | Tests overriding a config with kwargs. | [
"Tests",
"overriding",
"a",
"config",
"with",
"kwargs."
] | def test_set_config_kwargs(self):
TEST_CONFIGS[DummyWithConfig] = {'a': 4, 'c': 5}
d = DummyWithConfig(a=7)
self.assertEqual(d.a, 7)
self.assertEqual(d.b, 2)
self.assertEqual(d.c, 5) | ['def', 'test_set_config_kwargs(self):', 'TEST_CONFIGS[DummyWithConfig]', '=', "{'a':", '4,', "'c':", '5}', 'd', '=', 'DummyWithConfig(a=7)', 'self.assertEqual(d.a,', '7)', 'self.assertEqual(d.b,', '2)', 'self.assertEqual(d.c,', '5)'] | 202,084 |
aws/sagemaker-python-sdk | entities.py | _LocalPipelineExecution.update_execution_failure | update_execution_failure | Mark execution as failed. | [
"Mark",
"execution",
"as",
"failed."
] | def update_execution_failure(self, step_name, failure_message):
self.status = _LocalExecutionStatus.FAILED.value
self.failure_reason = f"Step '{step_name}' failed with message: {failure_message}"
self.last_modified_time = datetime.datetime.now().timestamp()
print(f"Pipeline execution {self.pipeline_exec... | ['def', 'update_execution_failure(self,', 'step_name,', 'failure_message):', 'self.status', '=', '_LocalExecutionStatus.FAILED.value', 'self.failure_reason', '=', 'f"Step', "'{step_name}'", 'failed', 'with', 'message:', '{failure_message}"', 'self.last_modified_time', '=', 'datetime.datetime.now().timestamp()', 'print(... | 830,314 |
PacktPublishing/Hands-On-Artificial--for-Banking | _fortran.py | get_g77_abi_wrappers | get_g77_abi_wrappers | Returns file names of source files containing Fortran ABI wrapper routines. | [
"Returns",
"file",
"names",
"of",
"source",
"files",
"containing",
"Fortran",
"ABI",
"wrapper",
"routines."
] | def get_g77_abi_wrappers(info):
wrapper_sources = []
path = os.path.abspath(os.path.dirname(__file__))
if needs_g77_abi_wrapper(info):
wrapper_sources += [os.path.join(path, 'src', 'wrap_g77_abi_f.f'), os.path.join(path, 'src', 'wrap_g77_abi_c.c')]
else:
wrapper_sources += [os.path.join(... | ['def', 'get_g77_abi_wrappers(info):', 'wrapper_sources', '=', '[]', 'path', '=', 'os.path.abspath(os.path.dirname(__file__))', 'if', 'needs_g77_abi_wrapper(info):', 'wrapper_sources', '+=', '[os.path.join(path,', "'src',", "'wrap_g77_abi_f.f'),", 'os.path.join(path,', "'src',", "'wrap_g77_abi_c.c')]", 'else:', 'wrappe... | 203,614 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | pydoc.py | TextDoc.docroutine | docroutine | Produce text documentation for a function or method object. | [
"Produce",
"text",
"documentation",
"for",
"a",
"function",
"or",
"method",
"object."
] | def docroutine(self, object, name=None, mod=None, cl=None):
realname = object.__name__
name = name or realname
note = ''
skipdocs = 0
if _is_bound_method(object):
imclass = object.__self__.__class__
if cl:
if imclass is not cl:
note = ' from ' + classname(... | ['def', 'docroutine(self,', 'object,', 'name=None,', 'mod=None,', 'cl=None):', 'realname', '=', 'object.__name__', 'name', '=', 'name', 'or', 'realname', 'note', '=', "''", 'skipdocs', '=', '0', 'if', '_is_bound_method(object):', 'imclass', '=', 'object.__self__.__class__', 'if', 'cl:', 'if', 'imclass', 'is', 'not', 'c... | 429,336 |
bachiraoun/fullrmc | DistanceConstraints.py | _DistanceConstraint.typePairsIndex | typePairsIndex | Numpy array look up for type pairs index. | [
"Numpy",
"array",
"look",
"up",
"for",
"type",
"pairs",
"index."
] | def typePairsIndex(self):
return self.__typePairsIndex | ['def', 'typePairsIndex(self):', 'return', 'self.__typePairsIndex'] | 213,546 |
lucylow/En_francais_si_vous_plait- | data_utils.py | collect_filtered | collect_filtered | Similar to :func:`filter` but collects filtered elements in ``filtered``. | [
"Similar",
"to",
":func:`filter`",
"but",
"collects",
"filtered",
"elements",
"in",
"``filtered``."
] | def collect_filtered(function, iterable, filtered):
for el in iterable:
if function(el):
yield el
else:
filtered.append(el) | ['def', 'collect_filtered(function,', 'iterable,', 'filtered):', 'for', 'el', 'in', 'iterable:', 'if', 'function(el):', 'yield', 'el', 'else:', 'filtered.append(el)'] | 562,387 |
facebookresearch/sylph-few-shot-detection | few_shot_rcnn.py | FewShotGeneralizedRCNN.forward | forward | Forward for base detector's training and inference and meta-learning's training stage. | [
"Forward",
"for",
"base",
"detector's",
"training",
"and",
"inference",
"and",
"meta-learning's",
"training",
"stage."
] | def forward(self, batched_inputs: List[Dict[str, Any]]):
if not self.episodic_learning:
return self.forward_base_detector(batched_inputs)
if self.training:
return self.forward_few_shot_detector_training(batched_inputs)
else:
raise NotImplementedError('Episodic learning inferrence for... | ['def', 'forward(self,', 'batched_inputs:', 'List[Dict[str,', 'Any]]):', 'if', 'not', 'self.episodic_learning:', 'return', 'self.forward_base_detector(batched_inputs)', 'if', 'self.training:', 'return', 'self.forward_few_shot_detector_training(batched_inputs)', 'else:', 'raise', "NotImplementedError('Episodic", 'learni... | 905,840 |
IIM-TTIJ/MVA2023SmallObjectDetection4SpottingBirds | coco_panoptic.py | CocoPanopticDataset.evaluate | evaluate | Evaluation in COCO Panoptic protocol. | [
"Evaluation",
"in",
"COCO",
"Panoptic",
"protocol."
] | def evaluate(self, results, metric='PQ', logger=None, jsonfile_prefix=None, classwise=False, nproc=32, **kwargs):
metrics = metric if isinstance(metric, list) else [metric]
metrics = ['PQ' if metric == 'pq' else metric for metric in metrics]
allowed_metrics = ['PQ', 'bbox', 'segm', 'proposal']
for metri... | ['def', 'evaluate(self,', 'results,', "metric='PQ',", 'logger=None,', 'jsonfile_prefix=None,', 'classwise=False,', 'nproc=32,', '**kwargs):', 'metrics', '=', 'metric', 'if', 'isinstance(metric,', 'list)', 'else', '[metric]', 'metrics', '=', "['PQ'", 'if', 'metric', '==', "'pq'", 'else', 'metric', 'for', 'metric', 'in',... | 650,738 |
LeighWeston86/multilayer_perceptron | cost_functions.py | MeanSquaredError.unit | unit | Computes the total cost. | [
"Computes",
"the",
"total",
"cost."
] | def unit(self, prediction, label, derivative=False):
if not derivative:
return (label.T - prediction) ** 2 / 2
return prediction - label.T | ['def', 'unit(self,', 'prediction,', 'label,', 'derivative=False):', 'if', 'not', 'derivative:', 'return', '(label.T', '-', 'prediction)', '**', '2', '/', '2', 'return', 'prediction', '-', 'label.T'] | 643,585 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | colors.py | color_string_to_rgb | color_string_to_rgb | Convert color string to a list of RBG integers. | [
"Convert",
"color",
"string",
"to",
"a",
"list",
"of",
"RBG",
"integers."
] | def color_string_to_rgb(color):
return [*map(int, color.split(','))] | ['def', 'color_string_to_rgb(color):', 'return', '[*map(int,', "color.split(','))]"] | 18,010 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | ptn_rotator.py | bilinear | bilinear | Define the bilinear transformation layer. | [
"Define",
"the",
"bilinear",
"transformation",
"layer."
] | def bilinear(input_x, input_y, output_size):
shape_x = input_x.get_shape().as_list()
shape_y = input_y.get_shape().as_list()
weights_initializer = tf.truncated_normal_initializer(stddev=0.02, seed=1)
biases_initializer = tf.constant_initializer(0.0)
matrix = tf.get_variable('Matrix', [shape_x[1], sh... | ['def', 'bilinear(input_x,', 'input_y,', 'output_size):', 'shape_x', '=', 'input_x.get_shape().as_list()', 'shape_y', '=', 'input_y.get_shape().as_list()', 'weights_initializer', '=', 'tf.truncated_normal_initializer(stddev=0.02,', 'seed=1)', 'biases_initializer', '=', 'tf.constant_initializer(0.0)', 'matrix', '=', "tf... | 109,337 |
EducationalTestingService/skll | test_output.py | TestOutput.test_learning_curve_output | test_learning_curve_output | Test learning curve output for experiment with metrics option. | [
"Test",
"learning",
"curve",
"output",
"for",
"experiment",
"with",
"metrics",
"option."
] | def test_learning_curve_output(self):
self.make_learning_curve_data()
config_template_path = config_dir / 'test_learning_curve.template.cfg'
config_path = fill_in_config_paths(config_template_path)
run_configuration(config_path, quiet=True, local=True)
outprefix = 'test_learning_curve'
output_ts... | ['def', 'test_learning_curve_output(self):', 'self.make_learning_curve_data()', 'config_template_path', '=', 'config_dir', '/', "'test_learning_curve.template.cfg'", 'config_path', '=', 'fill_in_config_paths(config_template_path)', 'run_configuration(config_path,', 'quiet=True,', 'local=True)', 'outprefix', '=', "'test... | 885,219 |
AboudyKreidieh/h-baselines | train.py | create_feedforward_parser | create_feedforward_parser | Add the feedforward policy hyperparameters to the parser. | [
"Add",
"the",
"feedforward",
"policy",
"hyperparameters",
"to",
"the",
"parser."
] | def create_feedforward_parser(parser):
parser.add_argument('--l2_penalty', type=float, default=FEEDFORWARD_PARAMS['l2_penalty'], help='L2 regularization penalty. This is applied to the policy network.')
parser.add_argument('--model_params:model_type', type=str, default=FEEDFORWARD_PARAMS['model_params']['model_... | ['def', 'create_feedforward_parser(parser):', "parser.add_argument('--l2_penalty',", 'type=float,', "default=FEEDFORWARD_PARAMS['l2_penalty'],", "help='L2", 'regularization', 'penalty.', 'This', 'is', 'applied', 'to', 'the', 'policy', "network.')", "parser.add_argument('--model_params:model_type',", 'type=str,', "defau... | 574,019 |
yandexdataschool/AgentNet | test_attention.py | test_attention_2d | test_attention_2d | Almost a copy-paste of previous test, but this time attention is applied to an image instead of a 1d sequence. | [
"Almost",
"a",
"copy-paste",
"of",
"previous",
"test,",
"but",
"this",
"time",
"attention",
"is",
"applied",
"to",
"an",
"image",
"instead",
"of",
"a",
"1d",
"sequence."
] | def test_attention_2d():
class step:
image = InputLayer((None, 3, 24, 24), name='placeholder for 24x24 image (to be attended)')
prev_gru = InputLayer((None, 15), name='gru prev state (15 units)')
(n_channels, width, height) = image.output_shape[1:]
image_chunks = reshape(dimshuffle(... | ['def', 'test_attention_2d():', 'class', 'step:', 'image', '=', 'InputLayer((None,', '3,', '24,', '24),', "name='placeholder", 'for', '24x24', 'image', '(to', 'be', "attended)')", 'prev_gru', '=', 'InputLayer((None,', '15),', "name='gru", 'prev', 'state', '(15', "units)')", '(n_channels,', 'width,', 'height)', '=', 'im... | 22,436 |
ivanmontero/autobot | modeling_tf_transfo_xl.py | TFTransfoXLLMHeadModel.get_output_embeddings | get_output_embeddings | Double-check if you are using adaptive softmax. | [
"Double-check",
"if",
"you",
"are",
"using",
"adaptive",
"softmax."
] | def get_output_embeddings(self):
if len(self.crit.out_layers) > 0:
return self.crit.out_layers[-1]
return None | ['def', 'get_output_embeddings(self):', 'if', 'len(self.crit.out_layers)', '>', '0:', 'return', 'self.crit.out_layers[-1]', 'return', 'None'] | 418,115 |
matsu0228/nlp-jp | precedence.py | calculate_children | calculate_children | Calculate a list of children with operators. | [
"Calculate",
"a",
"list",
"of",
"children",
"with",
"operators."
] | def calculate_children(evaluator, context, children):
iterator = iter(children)
types = context.eval_node(next(iterator))
for operator in iterator:
right = next(iterator)
if operator.type == 'comp_op':
operator = ' '.join((c.value for c in operator.children))
if operator ... | ['def', 'calculate_children(evaluator,', 'context,', 'children):', 'iterator', '=', 'iter(children)', 'types', '=', 'context.eval_node(next(iterator))', 'for', 'operator', 'in', 'iterator:', 'right', '=', 'next(iterator)', 'if', 'operator.type', '==', "'comp_op':", 'operator', '=', "'", "'.join((c.value", 'for', 'c', '... | 787,722 |
salesforce/CodeRL | testing_utils.py | require_faiss | require_faiss | Decorator marking a test that requires faiss. | [
"Decorator",
"marking",
"a",
"test",
"that",
"requires",
"faiss."
] | def require_faiss(test_case):
if not is_faiss_available():
return unittest.skip('test requires `faiss`')(test_case)
else:
return test_case | ['def', 'require_faiss(test_case):', 'if', 'not', 'is_faiss_available():', 'return', "unittest.skip('test", 'requires', "`faiss`')(test_case)", 'else:', 'return', 'test_case'] | 494,113 |
zackmcnulty/CSE_446-Machine_Learning | backend_bases.py | NavigationToolbar2.release_zoom | release_zoom | Callback for mouse button release in zoom to rect mode. | [
"Callback",
"for",
"mouse",
"button",
"release",
"in",
"zoom",
"to",
"rect",
"mode."
] | def release_zoom(self, event):
for zoom_id in self._ids_zoom:
self.canvas.mpl_disconnect(zoom_id)
self._ids_zoom = []
self.remove_rubberband()
if not self._xypress:
return
last_a = []
for cur_xypress in self._xypress:
(x, y) = (event.x, event.y)
(lastx, lasty, a, ... | ['def', 'release_zoom(self,', 'event):', 'for', 'zoom_id', 'in', 'self._ids_zoom:', 'self.canvas.mpl_disconnect(zoom_id)', 'self._ids_zoom', '=', '[]', 'self.remove_rubberband()', 'if', 'not', 'self._xypress:', 'return', 'last_a', '=', '[]', 'for', 'cur_xypress', 'in', 'self._xypress:', '(x,', 'y)', '=', '(event.x,', '... | 194,094 |
microsoft/nni | storage.py | _DistilStorage.get_uids | get_uids | Get uid list of recorded distillation labels. | [
"Get",
"uid",
"list",
"of",
"recorded",
"distillation",
"labels."
] | def get_uids(self) -> List[str]:
raise NotImplementedError() | ['def', 'get_uids(self)', '->', 'List[str]:', 'raise', 'NotImplementedError()'] | 728,604 |
nilearn/nilearn | test_plot_anat.py | test_plot_anat_MNI | test_plot_anat_MNI | Tests for plot_anat with MNI template. | [
"Tests",
"for",
"plot_anat",
"with",
"MNI",
"template."
] | def test_plot_anat_MNI(anat_img, display_mode, tmp_path):
slicer = plot_anat(anat_img=anat_img, display_mode=display_mode)
filename = tmp_path / 'test.png'
slicer.savefig(filename)
plt.close() | ['def', 'test_plot_anat_MNI(anat_img,', 'display_mode,', 'tmp_path):', 'slicer', '=', 'plot_anat(anat_img=anat_img,', 'display_mode=display_mode)', 'filename', '=', 'tmp_path', '/', "'test.png'", 'slicer.savefig(filename)', 'plt.close()'] | 724,149 |
kubeflow/pipelines | entrypoint_utils.py | get_output_artifacts | get_output_artifacts | Gets the output artifacts from function signature and provided URIs. | [
"Gets",
"the",
"output",
"artifacts",
"from",
"function",
"signature",
"and",
"provided",
"URIs."
] | def get_output_artifacts(fn: Callable, output_uris: Dict[str, str]) -> Dict[str, artifact.Artifact]:
spec = _python_op._extract_component_interface(fn)
result = {}
for output in spec.outputs:
if getattr(output, '_passing_style', None) == _python_op.OutputArtifact:
type_name = getattr(out... | ['def', 'get_output_artifacts(fn:', 'Callable,', 'output_uris:', 'Dict[str,', 'str])', '->', 'Dict[str,', 'artifact.Artifact]:', 'spec', '=', '_python_op._extract_component_interface(fn)', 'result', '=', '{}', 'for', 'output', 'in', 'spec.outputs:', 'if', 'getattr(output,', "'_passing_style',", 'None)', '==', '_python_... | 780,062 |
Eric3911/OpenAGI | waveflow.py | WaveFlow.forward | forward | Probability density estimation of random variable x given the condition. | [
"Probability",
"density",
"estimation",
"of",
"random",
"variable",
"x",
"given",
"the",
"condition."
] | def forward(self, x, condition):
(x, condition) = self._trim(x, condition)
x = paddle.unsqueeze(paddle.transpose(fold(x, self.n_group), [0, 2, 1]), 1)
condition = paddle.transpose(fold(condition, self.n_group), [0, 1, 3, 2])
logs_list = []
for (i, layer) in enumerate(self):
(x, (logs, b)) = ... | ['def', 'forward(self,', 'x,', 'condition):', '(x,', 'condition)', '=', 'self._trim(x,', 'condition)', 'x', '=', 'paddle.unsqueeze(paddle.transpose(fold(x,', 'self.n_group),', '[0,', '2,', '1]),', '1)', 'condition', '=', 'paddle.transpose(fold(condition,', 'self.n_group),', '[0,', '1,', '3,', '2])', 'logs_list', '=', '... | 251,724 |
43Carrig/recurrent_neural_networks_practice | variable_scope.py | VariableScope.get_variable | get_variable | Gets an existing variable with this name or create a new one. | [
"Gets",
"an",
"existing",
"variable",
"with",
"this",
"name",
"or",
"create",
"a",
"new",
"one."
] | def get_variable(self, var_store, name, shape=None, dtype=None, initializer=None, regularizer=None, reuse=None, trainable=None, collections=None, caching_device=None, partitioner=None, validate_shape=True, use_resource=None, custom_getter=None, constraint=None, synchronization=VariableSynchronization.AUTO, aggregation=... | ['def', 'get_variable(self,', 'var_store,', 'name,', 'shape=None,', 'dtype=None,', 'initializer=None,', 'regularizer=None,', 'reuse=None,', 'trainable=None,', 'collections=None,', 'caching_device=None,', 'partitioner=None,', 'validate_shape=True,', 'use_resource=None,', 'custom_getter=None,', 'constraint=None,', 'synch... | 339,144 |
keyonvafa/career-code | pretrained.py | get_model | get_model | Load local model package or torchhub pre-trained model. | [
"Load",
"local",
"model",
"package",
"or",
"torchhub",
"pre-trained",
"model."
] | def get_model(args):
if args.model_path:
logger.info('Loading model from %s', args.model_path)
pkg = torch.load(args.model_path)
model = deserialize_model(pkg)
elif args.dns64:
logger.info('Loading pre-trained real time H=64 model trained on DNS.')
model = dns64()
eli... | ['def', 'get_model(args):', 'if', 'args.model_path:', "logger.info('Loading", 'model', 'from', "%s',", 'args.model_path)', 'pkg', '=', 'torch.load(args.model_path)', 'model', '=', 'deserialize_model(pkg)', 'elif', 'args.dns64:', "logger.info('Loading", 'pre-trained', 'real', 'time', 'H=64', 'model', 'trained', 'on', "D... | 455,008 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | rollout.py | Rollout.add | add | Add the next timestep to this rollout. | [
"Add",
"the",
"next",
"timestep",
"to",
"this",
"rollout."
] | def add(self, state, action, reward, value=0.0, terminated=False):
if self.terminated:
raise ValueError('Trying to add timestep to an already terminal rollout.')
self.states += [state]
self.actions += [action]
self.rewards += [reward]
self.values += [value]
self.terminated = terminated
... | ['def', 'add(self,', 'state,', 'action,', 'reward,', 'value=0.0,', 'terminated=False):', 'if', 'self.terminated:', 'raise', "ValueError('Trying", 'to', 'add', 'timestep', 'to', 'an', 'already', 'terminal', "rollout.')", 'self.states', '+=', '[state]', 'self.actions', '+=', '[action]', 'self.rewards', '+=', '[reward]', ... | 46,292 |
adamshamsudeen/vision.ai | __init__.py | get_default_cache | get_default_cache | Return the ``PYTHON_EGG_CACHE`` environment variable or a platform-relevant user cache dir for an app named "Python-Eggs". | [
"Return",
"the",
"``PYTHON_EGG_CACHE``",
"environment",
"variable",
"or",
"a",
"platform-relevant",
"user",
"cache",
"dir",
"for",
"an",
"app",
"named",
"\"Python-Eggs\"."
] | def get_default_cache():
return os.environ.get('PYTHON_EGG_CACHE') or appdirs.user_cache_dir(appname='Python-Eggs') | ['def', 'get_default_cache():', 'return', "os.environ.get('PYTHON_EGG_CACHE')", 'or', "appdirs.user_cache_dir(appname='Python-Eggs')"] | 943,684 |
instadeepai/jumanji | maze_generation.py | chambers_remaining | chambers_remaining | Check if there is any chamber remaining to split. | [
"Check",
"if",
"there",
"is",
"any",
"chamber",
"remaining",
"to",
"split."
] | def chambers_remaining(state: MazeGenerationState) -> int:
return ~empty_stack(state.chambers) | ['def', 'chambers_remaining(state:', 'MazeGenerationState)', '->', 'int:', 'return', '~empty_stack(state.chambers)'] | 593,978 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | common_video.py | encode_to_shape | encode_to_shape | Encode the given tensor to given image shape. | [
"Encode",
"the",
"given",
"tensor",
"to",
"given",
"image",
"shape."
] | def encode_to_shape(inputs, shape, scope):
with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):
(w, h) = (shape[1], shape[2])
x = inputs
x = tf.contrib.layers.flatten(x)
x = tfl.dense(x, w * h, activation=None, name='enc_dense')
x = tf.reshape(x, (-1, w, h, 1))
return ... | ['def', 'encode_to_shape(inputs,', 'shape,', 'scope):', 'with', 'tf.variable_scope(scope,', 'reuse=tf.AUTO_REUSE):', '(w,', 'h)', '=', '(shape[1],', 'shape[2])', 'x', '=', 'inputs', 'x', '=', 'tf.contrib.layers.flatten(x)', 'x', '=', 'tfl.dense(x,', 'w', '*', 'h,', 'activation=None,', "name='enc_dense')", 'x', '=', 'tf... | 965,366 |
devashish-patel/webcam-motion-detector | containers.py | WindowRenderInfo.content_height | content_height | The full height of the user control. | [
"The",
"full",
"height",
"of",
"the",
"user",
"control."
] | def content_height(self):
return self.ui_content.line_count | ['def', 'content_height(self):', 'return', 'self.ui_content.line_count'] | 983,994 |
43Carrig/recurrent_neural_networks_practice | curses_widgets.py | CursesNavigationHistory.render | render | Render the rich text content of the single-line navigation bar. | [
"Render",
"the",
"rich",
"text",
"content",
"of",
"the",
"single-line",
"navigation",
"bar."
] | def render(self, max_length, backward_command, forward_command, latest_command_attribute='black_on_white', old_command_attribute='magenta_on_white'):
output = RL('| ')
output += RL(self.BACK_ARROW_TEXT, debugger_cli_common.MenuItem(None, backward_command) if self.can_go_back() else None)
output += RL(' ')
... | ['def', 'render(self,', 'max_length,', 'backward_command,', 'forward_command,', "latest_command_attribute='black_on_white',", "old_command_attribute='magenta_on_white'):", 'output', '=', "RL('|", "')", 'output', '+=', 'RL(self.BACK_ARROW_TEXT,', 'debugger_cli_common.MenuItem(None,', 'backward_command)', 'if', 'self.can... | 335,874 |
microsoft/InnerEye-DeepLearning | test_scalar_dataset.py | test_dataset_traverse_dirs | test_dataset_traverse_dirs | Test dataset loading when the dataset file only contains file name stems, not full paths. | [
"Test",
"dataset",
"loading",
"when",
"the",
"dataset",
"file",
"only",
"contains",
"file",
"name",
"stems,",
"not",
"full",
"paths."
] | def test_dataset_traverse_dirs(test_output_dirs: OutputFolderForTests, center_crop_size: Optional[TupleInt3]) -> None:
source_folder = str(full_ml_test_data_path() / 'classification_data')
target_folder = str(Path(test_output_dirs.make_sub_dir('foo')) / 'bar')
shutil.copytree(source_folder, target_folder)
... | ['def', 'test_dataset_traverse_dirs(test_output_dirs:', 'OutputFolderForTests,', 'center_crop_size:', 'Optional[TupleInt3])', '->', 'None:', 'source_folder', '=', 'str(full_ml_test_data_path()', '/', "'classification_data')", 'target_folder', '=', "str(Path(test_output_dirs.make_sub_dir('foo'))", '/', "'bar')", 'shutil... | 613,676 |
TonyLianLong/VAI-ReinforcementLearning | entity.py | Observables.disable_all | disable_all | Disable all observables of this entity. | [
"Disable",
"all",
"observables",
"of",
"this",
"entity."
] | def disable_all(self):
for obs in self._observables.values():
obs.enabled = False | ['def', 'disable_all(self):', 'for', 'obs', 'in', 'self._observables.values():', 'obs.enabled', '=', 'False'] | 439,847 |
gunthercox/ChatterBot | scoping.py | ScopedSession.remove | remove | Dispose of the current contextual session. | [
"Dispose",
"of",
"the",
"current",
"contextual",
"session."
] | def remove(self):
if self.registry.has():
self.registry().close()
self.registry.clear() | ['def', 'remove(self):', 'if', 'self.registry.has():', 'self.registry().close()', 'self.registry.clear()'] | 534,684 |
facebookresearch/CompilerGym | gcc_env.py | GccEnv.obj_hash | obj_hash | Get a hash of the object code. | [
"Get",
"a",
"hash",
"of",
"the",
"object",
"code."
] | def obj_hash(self) -> str:
return self.observation['obj_hash'] | ['def', 'obj_hash(self)', '->', 'str:', 'return', "self.observation['obj_hash']"] | 125,465 |
guxm2021/ALT_SpeechBrain | PLDA_LDA.py | StatObject_SB.get_total_covariance_stat1 | get_total_covariance_stat1 | Compute and return the total covariance matrix of the first-order statistics. | [
"Compute",
"and",
"return",
"the",
"total",
"covariance",
"matrix",
"of",
"the",
"first-order",
"statistics."
] | def get_total_covariance_stat1(self):
C = self.stat1 - self.stat1.mean(axis=0)
return numpy.dot(C.transpose(), C) / self.stat1.shape[0] | ['def', 'get_total_covariance_stat1(self):', 'C', '=', 'self.stat1', '-', 'self.stat1.mean(axis=0)', 'return', 'numpy.dot(C.transpose(),', 'C)', '/', 'self.stat1.shape[0]'] | 415,832 |
matsu0228/nlp-jp | keywords.py | imitate_pydoc | imitate_pydoc | It's not possible to get the pydoc's without starting the annoying pager stuff. | [
"It's",
"not",
"possible",
"to",
"get",
"the",
"pydoc's",
"without",
"starting",
"the",
"annoying",
"pager",
"stuff."
] | def imitate_pydoc(string):
if pydoc_topics is None:
return ''
string = str(string)
h = pydoc.help
with common.ignored(KeyError):
string = h.symbols[string]
(string, _, related) = string.partition(' ')
get_target = lambda s: h.topics.get(s, h.keywords.get(s))
while isinsta... | ['def', 'imitate_pydoc(string):', 'if', 'pydoc_topics', 'is', 'None:', 'return', "''", 'string', '=', 'str(string)', 'h', '=', 'pydoc.help', 'with', 'common.ignored(KeyError):', 'string', '=', 'h.symbols[string]', '(string,', '_,', 'related)', '=', "string.partition('", "')", 'get_target', '=', 'lambda', 's:', 'h.topic... | 787,683 |
zihuitang/medical_AI_platform | pydoc.py | visiblename | visiblename | Decide whether to show documentation on a variable. | [
"Decide",
"whether",
"to",
"show",
"documentation",
"on",
"a",
"variable."
] | def visiblename(name, all=None, obj=None):
if name in {'__author__', '__builtins__', '__cached__', '__credits__', '__date__', '__doc__', '__file__', '__spec__', '__loader__', '__module__', '__name__', '__package__', '__path__', '__qualname__', '__slots__', '__version__'}:
return 0
if name.startswith('__... | ['def', 'visiblename(name,', 'all=None,', 'obj=None):', 'if', 'name', 'in', "{'__author__',", "'__builtins__',", "'__cached__',", "'__credits__',", "'__date__',", "'__doc__',", "'__file__',", "'__spec__',", "'__loader__',", "'__module__',", "'__name__',", "'__package__',", "'__path__',", "'__qualname__',", "'__slots__'... | 281,186 |
intel/neural-compressor | util.py | match_datatype_pattern | match_datatype_pattern | Check the datatype pattern. | [
"Check",
"the",
"datatype",
"pattern."
] | def match_datatype_pattern(datatype, pattern=None):
import re
if not pattern:
pattern = '(uint|int)([1-8])'
match = re.match(pattern, datatype)
return match | ['def', 'match_datatype_pattern(datatype,', 'pattern=None):', 'import', 're', 'if', 'not', 'pattern:', 'pattern', '=', "'(uint|int)([1-8])'", 'match', '=', 're.match(pattern,', 'datatype)', 'return', 'match'] | 737,910 |
ziplab/SAQ | preresnet.py | preresnet110 | preresnet110 | Constructs a PreResNet-110 model. | [
"Constructs",
"a",
"PreResNet-110",
"model."
] | def preresnet110(**kwargs):
model = PreResNet(depth=110, **kwargs)
return model | ['def', 'preresnet110(**kwargs):', 'model', '=', 'PreResNet(depth=110,', '**kwargs)', 'return', 'model'] | 845,533 |
chainer/chainer | convolution_2d.py | Convolution2D.forward | forward | Applies the convolution layer. | [
"Applies",
"the",
"convolution",
"layer."
] | def forward(self, x):
x = chainer.as_variable(x)
assert x.layout == self.x_layout
if self.W.raw_array is None:
(_, c, _, _) = memory_layouts.get_semantic_shape(x, assumed_layout=self.x_layout)
self._initialize_params(c)
return convolution_2d.convolution_2d(x, self.W, self.b, self.stride,... | ['def', 'forward(self,', 'x):', 'x', '=', 'chainer.as_variable(x)', 'assert', 'x.layout', '==', 'self.x_layout', 'if', 'self.W.raw_array', 'is', 'None:', '(_,', 'c,', '_,', '_)', '=', 'memory_layouts.get_semantic_shape(x,', 'assumed_layout=self.x_layout)', 'self._initialize_params(c)', 'return', 'convolution_2d.convolu... | 477,423 |
kubeflow/pipelines | recurring_run.py | create | create | Create a recurring run. | [
"Create",
"a",
"recurring",
"run."
] | def create(ctx: click.Context, job_name: str, experiment_id: Optional[str]=None, experiment_name: Optional[str]=None, catchup: Optional[bool]=None, cron_expression: Optional[str]=None, enabled: Optional[bool]=None, description: Optional[str]=None, enable_caching: Optional[bool]=None, end_time: Optional[str]=None, inter... | ['def', 'create(ctx:', 'click.Context,', 'job_name:', 'str,', 'experiment_id:', 'Optional[str]=None,', 'experiment_name:', 'Optional[str]=None,', 'catchup:', 'Optional[bool]=None,', 'cron_expression:', 'Optional[str]=None,', 'enabled:', 'Optional[bool]=None,', 'description:', 'Optional[str]=None,', 'enable_caching:', '... | 779,845 |
MahmoudAshraf97/AutoencoderCompression | LPIPS.py | ensure_lpips_weights_exist | ensure_lpips_weights_exist | Downloads weights if needed. | [
"Downloads",
"weights",
"if",
"needed."
] | def ensure_lpips_weights_exist(weight_path_out):
if os.path.isfile(weight_path_out):
return
print('Downloading LPIPS weights:', _LPIPS_URL, '->', weight_path_out)
urllib.request.urlretrieve(_LPIPS_URL, weight_path_out)
if not os.path.isfile(weight_path_out):
raise ValueError(f'Failed to ... | ['def', 'ensure_lpips_weights_exist(weight_path_out):', 'if', 'os.path.isfile(weight_path_out):', 'return', "print('Downloading", 'LPIPS', "weights:',", '_LPIPS_URL,', "'->',", 'weight_path_out)', 'urllib.request.urlretrieve(_LPIPS_URL,', 'weight_path_out)', 'if', 'not', 'os.path.isfile(weight_path_out):', 'raise', "Va... | 419,487 |
descendant-ai/functime | conversion.py | df_to_ndarray | df_to_ndarray | Zero-copy spill-to-disk Polars DataFrame to numpy ndarray. | [
"Zero-copy",
"spill-to-disk",
"Polars",
"DataFrame",
"to",
"numpy",
"ndarray."
] | def df_to_ndarray(df: pl.DataFrame, n_groups: Optional[int]=None) -> np.ndarray:
columns = df.columns
df = df.select(pl.all().cast(pl.Float32))
chunks = (df.shape[0], 1)
if n_groups:
chunks = (n_groups, df.shape[1])
with tempfile.TemporaryDirectory() as tempdir:
timestamp = datetime.... | ['def', 'df_to_ndarray(df:', 'pl.DataFrame,', 'n_groups:', 'Optional[int]=None)', '->', 'np.ndarray:', 'columns', '=', 'df.columns', 'df', '=', 'df.select(pl.all().cast(pl.Float32))', 'chunks', '=', '(df.shape[0],', '1)', 'if', 'n_groups:', 'chunks', '=', '(n_groups,', 'df.shape[1])', 'with', 'tempfile.TemporaryDirecto... | 565,560 |
MycroftAI/mycroft-core | api.py | EnclosureAPI.system_blink | system_blink | The 'eyes' should blink the given number of times. | [
"The",
"'eyes'",
"should",
"blink",
"the",
"given",
"number",
"of",
"times."
] | def system_blink(self, times):
self.bus.emit(Message('enclosure.system.blink', {'times': times}, context={'destination': ['enclosure']})) | ['def', 'system_blink(self,', 'times):', "self.bus.emit(Message('enclosure.system.blink',", "{'times':", 'times},', "context={'destination':", "['enclosure']}))"] | 290,349 |
NoGameNoLife00/mybolg | atom.py | AtomFeed.to_string | to_string | Convert the feed into a string. | [
"Convert",
"the",
"feed",
"into",
"a",
"string."
] | def to_string(self):
return u''.join(self.generate()) | ['def', 'to_string(self):', 'return', "u''.join(self.generate())"] | 290,036 |
openvinotoolkit/training_extensions | progress.py | ProgressCallback.on_train_start | on_train_start | Store max epochs and current epoch from trainer. | [
"Store",
"max",
"epochs",
"and",
"current",
"epoch",
"from",
"trainer."
] | def on_train_start(self, trainer, pl_module):
super().on_train_start(trainer, pl_module)
self.current_epoch = trainer.current_epoch
self.max_epochs = trainer.max_epochs
self._reset_progress() | ['def', 'on_train_start(self,', 'trainer,', 'pl_module):', 'super().on_train_start(trainer,', 'pl_module)', 'self.current_epoch', '=', 'trainer.current_epoch', 'self.max_epochs', '=', 'trainer.max_epochs', 'self._reset_progress()'] | 903,906 |
enuguru/artificial_intelligence_and_machine_ | xmlreport.py | rate | rate | Return the fraction of `hit`/`num`, as a string. | [
"Return",
"the",
"fraction",
"of",
"`hit`/`num`,",
"as",
"a",
"string."
] | def rate(hit, num):
if num == 0:
return '1'
else:
return '%.4g' % (float(hit) / num) | ['def', 'rate(hit,', 'num):', 'if', 'num', '==', '0:', 'return', "'1'", 'else:', 'return', "'%.4g'", '%', '(float(hit)', '/', 'num)'] | 148,002 |
PacktPublishing/Hands-On-Artificial--for-Banking | test.py | EnvironBuilder.base_url | base_url | The base URL is used to extract the URL scheme, host name, port, and root path. | [
"The",
"base",
"URL",
"is",
"used",
"to",
"extract",
"the",
"URL",
"scheme,",
"host",
"name,",
"port,",
"and",
"root",
"path."
] | def base_url(self):
return self._make_base_url(self.url_scheme, self.host, self.script_root) | ['def', 'base_url(self):', 'return', 'self._make_base_url(self.url_scheme,', 'self.host,', 'self.script_root)'] | 204,925 |
43Carrig/recurrent_neural_networks_practice | test_util.py | NCHWToNHWC | NCHWToNHWC | Converts the input from the NCHW format to NHWC. | [
"Converts",
"the",
"input",
"from",
"the",
"NCHW",
"format",
"to",
"NHWC."
] | def NCHWToNHWC(input_tensor):
new_axes = {4: [0, 2, 3, 1], 5: [0, 2, 3, 4, 1]}
if isinstance(input_tensor, ops.Tensor):
ndims = input_tensor.shape.ndims
return array_ops.transpose(input_tensor, new_axes[ndims])
else:
ndims = len(input_tensor)
return [input_tensor[a] for a in ... | ['def', 'NCHWToNHWC(input_tensor):', 'new_axes', '=', '{4:', '[0,', '2,', '3,', '1],', '5:', '[0,', '2,', '3,', '4,', '1]}', 'if', 'isinstance(input_tensor,', 'ops.Tensor):', 'ndims', '=', 'input_tensor.shape.ndims', 'return', 'array_ops.transpose(input_tensor,', 'new_axes[ndims])', 'else:', 'ndims', '=', 'len(input_te... | 336,595 |
ilya16/MultINN | multinn.py | MultINN.generators | generators | The list of the MultINN Generators. | [
"The",
"list",
"of",
"the",
"MultINN",
"Generators."
] | def generators(self):
return self._model.generators | ['def', 'generators(self):', 'return', 'self._model.generators'] | 644,286 |
deepmind/dm_control | walker.py | PlanarWalker.get_observation | get_observation | Returns an observation of body orientations, height and velocites. | [
"Returns",
"an",
"observation",
"of",
"body",
"orientations,",
"height",
"and",
"velocites."
] | def get_observation(self, physics):
obs = collections.OrderedDict()
obs['orientations'] = physics.orientations()
obs['height'] = physics.torso_height()
obs['velocity'] = physics.velocity()
return obs | ['def', 'get_observation(self,', 'physics):', 'obs', '=', 'collections.OrderedDict()', "obs['orientations']", '=', 'physics.orientations()', "obs['height']", '=', 'physics.torso_height()', "obs['velocity']", '=', 'physics.velocity()', 'return', 'obs'] | 166,498 |
gibranfp/P300-CNNT | cross_subject_UCNN1.py | evaluate_cross_subject_model | evaluate_cross_subject_model | Trains and evaluates the modified CNN1 for each subject in the P300 Speller database using random cross validation. | [
"Trains",
"and",
"evaluates",
"the",
"modified",
"CNN1",
"for",
"each",
"subject",
"in",
"the",
"P300",
"Speller",
"database",
"using",
"random",
"cross",
"validation."
] | def evaluate_cross_subject_model(data, labels, modelpath):
n_sub = data.shape[0]
n_ex_sub = data.shape[1]
n_samples = data.shape[2]
n_channels = data.shape[3]
aucs = np.zeros(n_sub)
data = data.reshape((n_sub * n_ex_sub, n_samples, n_channels))
labels = labels.reshape(n_sub * n_ex_sub)
g... | ['def', 'evaluate_cross_subject_model(data,', 'labels,', 'modelpath):', 'n_sub', '=', 'data.shape[0]', 'n_ex_sub', '=', 'data.shape[1]', 'n_samples', '=', 'data.shape[2]', 'n_channels', '=', 'data.shape[3]', 'aucs', '=', 'np.zeros(n_sub)', 'data', '=', 'data.reshape((n_sub', '*', 'n_ex_sub,', 'n_samples,', 'n_channels)... | 253,730 |
replit-archive/empythoned | test_io.py | SignalsTest.check_interrupted_write_retry | check_interrupted_write_retry | Check that a buffered write, when it gets interrupted (either returning a partial result or EINTR), properly invokes the signal handler and retries if the latter returned successfully. | [
"Check",
"that",
"a",
"buffered",
"write,",
"when",
"it",
"gets",
"interrupted",
"(either",
"returning",
"a",
"partial",
"result",
"or",
"EINTR),",
"properly",
"invokes",
"the",
"signal",
"handler",
"and",
"retries",
"if",
"the",
"latter",
"returned",
"successfu... | def check_interrupted_write_retry(self, item, **fdopen_kwargs):
select = support.import_module('select')
N = 1024 * 1024
(r, w) = os.pipe()
fdopen_kwargs['closefd'] = False
read_results = []
write_finished = False
def _read():
while not write_finished:
while r in select.... | ['def', 'check_interrupted_write_retry(self,', 'item,', '**fdopen_kwargs):', 'select', '=', "support.import_module('select')", 'N', '=', '1024', '*', '1024', '(r,', 'w)', '=', 'os.pipe()', "fdopen_kwargs['closefd']", '=', 'False', 'read_results', '=', '[]', 'write_finished', '=', 'False', 'def', '_read():', 'while', 'n... | 176,994 |
IndicoDataSolutions/Enso | grid_search.py | GridSearch.predict | predict | Predict results on test set based on current internal model. | [
"Predict",
"results",
"on",
"test",
"set",
"based",
"on",
"current",
"internal",
"model."
] | def predict(self, X, **kwargs):
labels = self.best_model.classes_
probabilities = self.best_model.predict_proba(X)
return pd.DataFrame({label: probabilities[:, i] for (i, label) in enumerate(labels)}) | ['def', 'predict(self,', 'X,', '**kwargs):', 'labels', '=', 'self.best_model.classes_', 'probabilities', '=', 'self.best_model.predict_proba(X)', 'return', 'pd.DataFrame({label:', 'probabilities[:,', 'i]', 'for', '(i,', 'label)', 'in', 'enumerate(labels)})'] | 562,247 |
ryu-ed/SpaceInvaders_Ros | surface_test.py | SurfaceTypeTest.test_get_bytesize | test_get_bytesize | Ensure a surface's bit and byte sizes can be retrieved. | [
"Ensure",
"a",
"surface's",
"bit",
"and",
"byte",
"sizes",
"can",
"be",
"retrieved."
] | def test_get_bytesize(self):
depth = 32
depth_bytes = 4
s1 = pygame.Surface((32, 32), pygame.SRCALPHA, depth)
self.assertEqual(s1.get_bytesize(), depth_bytes)
self.assertEqual(s1.get_bitsize(), depth) | ['def', 'test_get_bytesize(self):', 'depth', '=', '32', 'depth_bytes', '=', '4', 's1', '=', 'pygame.Surface((32,', '32),', 'pygame.SRCALPHA,', 'depth)', 'self.assertEqual(s1.get_bytesize(),', 'depth_bytes)', 'self.assertEqual(s1.get_bitsize(),', 'depth)'] | 369,169 |
TonyLianLong/VAI-ReinforcementLearning | wrappers.py | MjDataWrapper.xipos | xipos | Cartesian position of body com (nbody x 3). | [
"Cartesian",
"position",
"of",
"body",
"com",
"(nbody",
"x",
"3)."
] | def xipos(self):
return util.buf_to_npy(self._ptr.contents.xipos, (self._model.nbody, 3)) | ['def', 'xipos(self):', 'return', 'util.buf_to_npy(self._ptr.contents.xipos,', '(self._model.nbody,', '3))'] | 440,547 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.