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
OctoConsulting/octobot
create_lex_bot.py
create_bot
create_bot
Create Lex bot with all specified intents attached.
[ "Create", "Lex", "bot", "with", "all", "specified", "intents", "attached." ]
def create_bot(bot_name: str, intents_name_version_list: list) -> str: create_bot_response = lex_client.put_bot(name=bot_name, intents=intents_name_version_list, clarificationPrompt={'messages': [{'contentType': 'PlainText', 'content': 'Sorry, can you repeat that?'}], 'maxAttempts': 3, 'responseCard': 'Response car...
['def', 'create_bot(bot_name:', 'str,', 'intents_name_version_list:', 'list)', '->', 'str:', 'create_bot_response', '=', 'lex_client.put_bot(name=bot_name,', 'intents=intents_name_version_list,', "clarificationPrompt={'messages':", "[{'contentType':", "'PlainText',", "'content':", "'Sorry,", 'can', 'you', 'repeat', "th...
249,987
alugupta/ares
nes.py
NES.nes
nes
The attack process of NES.
[ "The", "attack", "process", "of", "NES." ]
def nes(self, x_victim, y_victim, y_target): batchsize = x_victim.shape[0] with torch.no_grad(): self.model.eval() x_victim = x_victim.to(self.device) y_victim = y_victim.to(self.device) if y_target is not None: y_target = y_target.to(self.device) self.model.t...
['def', 'nes(self,', 'x_victim,', 'y_victim,', 'y_target):', 'batchsize', '=', 'x_victim.shape[0]', 'with', 'torch.no_grad():', 'self.model.eval()', 'x_victim', '=', 'x_victim.to(self.device)', 'y_victim', '=', 'y_victim.to(self.device)', 'if', 'y_target', 'is', 'not', 'None:', 'y_target', '=', 'y_target.to(self.device...
401,998
scikit-learn/scikit-learn
test_target_encoder.py
test_constant_target_and_feature
test_constant_target_and_feature
Check edge case where feature and target is constant.
[ "Check", "edge", "case", "where", "feature", "and", "target", "is", "constant." ]
def test_constant_target_and_feature(y, y_mean, smooth): X = np.array([[1] * 20]).T n_samples = X.shape[0] enc = TargetEncoder(cv=2, smooth=smooth, random_state=0) X_trans = enc.fit_transform(X, y) assert_allclose(X_trans, np.repeat([[y_mean]], n_samples, axis=0)) assert enc.encodings_[0][0] == ...
['def', 'test_constant_target_and_feature(y,', 'y_mean,', 'smooth):', 'X', '=', 'np.array([[1]', '*', '20]).T', 'n_samples', '=', 'X.shape[0]', 'enc', '=', 'TargetEncoder(cv=2,', 'smooth=smooth,', 'random_state=0)', 'X_trans', '=', 'enc.fit_transform(X,', 'y)', 'assert_allclose(X_trans,', 'np.repeat([[y_mean]],', 'n_sa...
854,079
onucharles/tensorized-rnn
initializers.py
matrix_with_random_cores
matrix_with_random_cores
Generate a TT-matrix of given shape with N(mean, stddev^2) cores.
[ "Generate", "a", "TT-matrix", "of", "given", "shape", "with", "N(mean,", "stddev^2)", "cores." ]
def matrix_with_random_cores(shape, tt_rank=2, mean=0.0, stddev=1.0, dtype=torch.float32): shape = list(shape) if shape[0] is None: shape[0] = np.ones(len(shape[1]), dtype=int) if shape[1] is None: shape[1] = np.ones(len(shape[0]), dtype=int) shape = np.array(shape) tt_rank = np.arra...
['def', 'matrix_with_random_cores(shape,', 'tt_rank=2,', 'mean=0.0,', 'stddev=1.0,', 'dtype=torch.float32):', 'shape', '=', 'list(shape)', 'if', 'shape[0]', 'is', 'None:', 'shape[0]', '=', 'np.ones(len(shape[1]),', 'dtype=int)', 'if', 'shape[1]', 'is', 'None:', 'shape[1]', '=', 'np.ones(len(shape[0]),', 'dtype=int)', '...
365,990
replit-archive/empythoned
Cookie.py
BaseCookie.output
output
Return a string suitable for HTTP.
[ "Return", "a", "string", "suitable", "for", "HTTP." ]
def output(self, attrs=None, header='Set-Cookie:', sep='\r\n'): result = [] items = self.items() items.sort() for (K, V) in items: result.append(V.output(attrs, header)) return sep.join(result)
['def', 'output(self,', 'attrs=None,', "header='Set-Cookie:',", "sep='\\r\\n'):", 'result', '=', '[]', 'items', '=', 'self.items()', 'items.sort()', 'for', '(K,', 'V)', 'in', 'items:', 'result.append(V.output(attrs,', 'header))', 'return', 'sep.join(result)']
177,168
awslabs/mxnet-lambda
io.py
NDArrayIter.hard_reset
hard_reset
Ignore roll over data and set to start.
[ "Ignore", "roll", "over", "data", "and", "set", "to", "start." ]
def hard_reset(self): self.cursor = -self.batch_size
['def', 'hard_reset(self):', 'self.cursor', '=', '-self.batch_size']
267,049
enuguru/artificial_intelligence_and_machine_
plots.py
CondensedTree.to_numpy
to_numpy
Return a numpy structured array representation of the condensed tree.
[ "Return", "a", "numpy", "structured", "array", "representation", "of", "the", "condensed", "tree." ]
def to_numpy(self): return self._raw_tree.copy()
['def', 'to_numpy(self):', 'return', 'self._raw_tree.copy()']
135,438
eddylau328/fyp-artificial-intelligence-ac-control-device
_helpers.py
metadata_with_prefix
metadata_with_prefix
Create RPC metadata containing a prefix.
[ "Create", "RPC", "metadata", "containing", "a", "prefix." ]
def metadata_with_prefix(prefix, **kw): return [('google-cloud-resource-prefix', prefix)]
['def', 'metadata_with_prefix(prefix,', '**kw):', 'return', "[('google-cloud-resource-prefix',", 'prefix)]']
214,895
devashish-patel/webcam-motion-detector
history.py
HistoryAccessor.init_db
init_db
Connect to the database, and create tables if necessary.
[ "Connect", "to", "the", "database,", "and", "create", "tables", "if", "necessary." ]
def init_db(self): if not self.enabled: self.db = DummyDB() return kwargs = dict(detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES) kwargs.update(self.connection_options) self.db = sqlite3.connect(self.hist_file, **kwargs) self.db.execute('CREATE TABLE IF NOT EXISTS sessi...
['def', 'init_db(self):', 'if', 'not', 'self.enabled:', 'self.db', '=', 'DummyDB()', 'return', 'kwargs', '=', 'dict(detect_types=sqlite3.PARSE_DECLTYPES', '|', 'sqlite3.PARSE_COLNAMES)', 'kwargs.update(self.connection_options)', 'self.db', '=', 'sqlite3.connect(self.hist_file,', '**kwargs)', "self.db.execute('CREATE", ...
978,612
RasaHQ/rasa
rasa_yaml.py
RasaYAMLWriter.dumps
dumps
Turns TrainingData into a string.
[ "Turns", "TrainingData", "into", "a", "string." ]
def dumps(self, training_data: 'TrainingData') -> Text: stream = StringIO() self.dump(stream, training_data) return stream.getvalue()
['def', 'dumps(self,', 'training_data:', "'TrainingData')", '->', 'Text:', 'stream', '=', 'StringIO()', 'self.dump(stream,', 'training_data)', 'return', 'stream.getvalue()']
837,750
Mephisto405/WCMC
metrics.py
MSE
MSE
Mean-squared error between images.
[ "Mean-squared", "error", "between", "images." ]
def MSE(im, ref, reduce=True): return np.square(im - ref).mean() if reduce else np.square(im - ref)
['def', 'MSE(im,', 'ref,', 'reduce=True):', 'return', 'np.square(im', '-', 'ref).mean()', 'if', 'reduce', 'else', 'np.square(im', '-', 'ref)']
373,071
v-sivak/quantum-control-rl
tf_env.py
TFEnvironmentQuantumControl.setup_reward
setup_reward
Setup the reward function based on reward_kwargs.
[ "Setup", "the", "reward", "function", "based", "on", "reward_kwargs." ]
def setup_reward(self, reward_kwargs): try: mode = reward_kwargs.pop('reward_mode') assert mode in ['zero', 'remote'] self.reward_mode = mode except: raise ValueError('reward_mode not specified or not supported.') if mode == 'remote': self.server_socket = reward_kwarg...
['def', 'setup_reward(self,', 'reward_kwargs):', 'try:', 'mode', '=', "reward_kwargs.pop('reward_mode')", 'assert', 'mode', 'in', "['zero',", "'remote']", 'self.reward_mode', '=', 'mode', 'except:', 'raise', "ValueError('reward_mode", 'not', 'specified', 'or', 'not', "supported.')", 'if', 'mode', '==', "'remote':", 'se...
834,384
drprojects/superpoint_transformer
pylogger.py
get_pylogger
get_pylogger
Initializes multi-GPU-friendly python command line logger.
[ "Initializes", "multi-GPU-friendly", "python", "command", "line", "logger." ]
def get_pylogger(name=__name__) -> logging.Logger: logger = logging.getLogger(name) logging_levels = ('debug', 'info', 'warning', 'error', 'exception', 'fatal', 'critical') for level in logging_levels: setattr(logger, level, rank_zero_only(getattr(logger, level))) return logger
['def', 'get_pylogger(name=__name__)', '->', 'logging.Logger:', 'logger', '=', 'logging.getLogger(name)', 'logging_levels', '=', "('debug',", "'info',", "'warning',", "'error',", "'exception',", "'fatal',", "'critical')", 'for', 'level', 'in', 'logging_levels:', 'setattr(logger,', 'level,', 'rank_zero_only(getattr(logg...
880,930
ArdaGunay99/Key_Detection_Unsupervised_Learning
test_constrainedlayout.py
test_constrained_layout23
test_constrained_layout23
Comment in #11035: suptitle used to cause an exception when reusing a figure w/ CL with ``clear=True``.
[ "Comment", "in", "#11035:", "suptitle", "used", "to", "cause", "an", "exception", "when", "reusing", "a", "figure", "w/", "CL", "with", "``clear=True``." ]
def test_constrained_layout23(): for i in range(2): (fig, ax) = plt.subplots(num='123', constrained_layout=True, clear=True) fig.suptitle('Suptitle{}'.format(i))
['def', 'test_constrained_layout23():', 'for', 'i', 'in', 'range(2):', '(fig,', 'ax)', '=', "plt.subplots(num='123',", 'constrained_layout=True,', 'clear=True)', "fig.suptitle('Suptitle{}'.format(i))"]
257,940
PacktPublishing/Hands-On-Artificial--for-Banking
conftest.py
all_boolean_reductions
all_boolean_reductions
Fixture for boolean reduction names.
[ "Fixture", "for", "boolean", "reduction", "names." ]
def all_boolean_reductions(request): return request.param
['def', 'all_boolean_reductions(request):', 'return', 'request.param']
235,978
chainer/chainer
logarithm_1p.py
log1p
log1p
Elementwise natural logarithm plus one function.
[ "Elementwise", "natural", "logarithm", "plus", "one", "function." ]
def log1p(x): return Log1p().apply((x,))[0]
['def', 'log1p(x):', 'return', 'Log1p().apply((x,))[0]']
477,333
caiiiac/Machine-Learning-with-Python
test_voting_classifier.py
test_parallel_predict
test_parallel_predict
Check parallel backend of VotingClassifier on toy dataset.
[ "Check", "parallel", "backend", "of", "VotingClassifier", "on", "toy", "dataset." ]
def test_parallel_predict(): clf1 = LogisticRegression(random_state=123) clf2 = RandomForestClassifier(random_state=123) clf3 = GaussianNB() X = np.array([[-1.1, -1.5], [-1.2, -1.4], [-3.4, -2.2], [1.1, 1.2]]) y = np.array([1, 1, 2, 2]) eclf1 = VotingClassifier(estimators=[('lr', clf1), ('rf', c...
['def', 'test_parallel_predict():', 'clf1', '=', 'LogisticRegression(random_state=123)', 'clf2', '=', 'RandomForestClassifier(random_state=123)', 'clf3', '=', 'GaussianNB()', 'X', '=', 'np.array([[-1.1,', '-1.5],', '[-1.2,', '-1.4],', '[-3.4,', '-2.2],', '[1.1,', '1.2]])', 'y', '=', 'np.array([1,', '1,', '2,', '2])', '...
720,651
flairNLP/flair
anneal_on_plateau.py
AnnealingPlugin.after_evaluation
after_evaluation
Scheduler step of AnnealOnPlateau.
[ "Scheduler", "step", "of", "AnnealOnPlateau." ]
def after_evaluation(self, current_model_is_best, validation_scores, **kw): reduced_learning_rate: bool = self.scheduler.step(*validation_scores) self.store_learning_rate() bad_epochs = self.scheduler.num_bad_epochs if reduced_learning_rate: bad_epochs = self.patience + 1 log.info(f" - {...
['def', 'after_evaluation(self,', 'current_model_is_best,', 'validation_scores,', '**kw):', 'reduced_learning_rate:', 'bool', '=', 'self.scheduler.step(*validation_scores)', 'self.store_learning_rate()', 'bad_epochs', '=', 'self.scheduler.num_bad_epochs', 'if', 'reduced_learning_rate:', 'bad_epochs', '=', 'self.patienc...
584,856
keyonvafa/career-code
utils.py
segments_to_sequence
segments_to_sequence
Concatenate segments into a full sequence.
[ "Concatenate", "segments", "into", "a", "full", "sequence." ]
def segments_to_sequence(segments: List[Tuple[Tensor, Tensor]], time_axis: int) -> Tuple[Tensor, Tensor]: if len(segments) == 1: return segments[0] tensors_to_concat: List[Tensor] = [] lengths_to_stack: List[Tensor] = [] for (tensor, lengths) in segments: tensors_to_concat.append(tensor)...
['def', 'segments_to_sequence(segments:', 'List[Tuple[Tensor,', 'Tensor]],', 'time_axis:', 'int)', '->', 'Tuple[Tensor,', 'Tensor]:', 'if', 'len(segments)', '==', '1:', 'return', 'segments[0]', 'tensors_to_concat:', 'List[Tensor]', '=', '[]', 'lengths_to_stack:', 'List[Tensor]', '=', '[]', 'for', '(tensor,', 'lengths)'...
455,537
mideind/GreynirServer
geo.py
isocode_for_country_name
isocode_for_country_name
Return the ISO 3166-1 alpha-2 code for a country name in the specified language (two-char ISO 639-1).
[ "Return", "the", "ISO", "3166-1", "alpha-2", "code", "for", "a", "country", "name", "in", "the", "specified", "language", "(two-char", "ISO", "639-1)." ]
def isocode_for_country_name(country_name: str, lang: str=ICELANDIC_LANG_ISOCODE) -> Optional[str]: assert len(lang) == 2 lang = lang.lower() if lang not in available_languages(): return None if lang in COUNTRY_NAME_TO_ISOCODE_ADDITIONS: if country_name in COUNTRY_NAME_TO_ISOCODE_ADDITIO...
['def', 'isocode_for_country_name(country_name:', 'str,', 'lang:', 'str=ICELANDIC_LANG_ISOCODE)', '->', 'Optional[str]:', 'assert', 'len(lang)', '==', '2', 'lang', '=', 'lang.lower()', 'if', 'lang', 'not', 'in', 'available_languages():', 'return', 'None', 'if', 'lang', 'in', 'COUNTRY_NAME_TO_ISOCODE_ADDITIONS:', 'if', ...
580,955
rudranil723/mini-main
__init__.py
Stack.back
back
Move the position back and return the current element.
[ "Move", "the", "position", "back", "and", "return", "the", "current", "element." ]
def back(self): if self._pos > 0: self._pos -= 1 return self()
['def', 'back(self):', 'if', 'self._pos', '>', '0:', 'self._pos', '-=', '1', 'return', 'self()']
320,085
OpenMDAO/OpenMDAO-Framework
systems.py
System.set_options
set_options
Sets all user-configurable options for this system and all subsystems.
[ "Sets", "all", "user-configurable", "options", "for", "this", "system", "and", "all", "subsystems." ]
def set_options(self, mode, options): for subsystem in self.subsystems(): subsystem.set_options(mode, options) if not self.is_active(): return self.mode = mode self.options = options if mode in ('forward', 'fd'): self.sol_vec = self.vec['du'] self.rhs_vec = self.vec['...
['def', 'set_options(self,', 'mode,', 'options):', 'for', 'subsystem', 'in', 'self.subsystems():', 'subsystem.set_options(mode,', 'options)', 'if', 'not', 'self.is_active():', 'return', 'self.mode', '=', 'mode', 'self.options', '=', 'options', 'if', 'mode', 'in', "('forward',", "'fd'):", 'self.sol_vec', '=', "self.vec[...
276,083
zihuitang/medical_AI_platform
__init__.py
Misc.winfo_screenmmwidth
winfo_screenmmwidth
Return the number of pixels of the width of the screen of this widget in mm.
[ "Return", "the", "number", "of", "pixels", "of", "the", "width", "of", "the", "screen", "of", "this", "widget", "in", "mm." ]
def winfo_screenmmwidth(self): return self.tk.getint(self.tk.call('winfo', 'screenmmwidth', self._w))
['def', 'winfo_screenmmwidth(self):', 'return', "self.tk.getint(self.tk.call('winfo',", "'screenmmwidth',", 'self._w))']
284,105
kubeflow/pipelines
trtis_client.py
postprocess
postprocess
Post-process results to show classifications.
[ "Post-process", "results", "to", "show", "classifications." ]
def postprocess(results, filenames, batch_size): if len(results) != 1: raise Exception('expected 1 result, got {}'.format(len(results))) batched_result = results[0].batch_classes if len(batched_result) != batch_size: raise Exception('expected {} results, got {}'.format(batch_size, len(batche...
['def', 'postprocess(results,', 'filenames,', 'batch_size):', 'if', 'len(results)', '!=', '1:', 'raise', "Exception('expected", '1', 'result,', 'got', "{}'.format(len(results)))", 'batched_result', '=', 'results[0].batch_classes', 'if', 'len(batched_result)', '!=', 'batch_size:', 'raise', "Exception('expected", '{}', '...
779,761
devashish-patel/webcam-motion-detector
core.py
_Socket.recv
recv
recv, which will only block current greenlet state_changed always fires exactly once (success or fail) at the end of this method.
[ "recv,", "which", "will", "only", "block", "current", "greenlet", "state_changed", "always", "fires", "exactly", "once", "(success", "or", "fail)", "at", "the", "end", "of", "this", "method." ]
def recv(self, flags=0, copy=True, track=False): if flags & zmq.NOBLOCK: try: msg = super(_Socket, self).recv(flags, copy, track) finally: if not self.__in_recv_multipart: self.__state_changed() return msg flags |= zmq.NOBLOCK while True: ...
['def', 'recv(self,', 'flags=0,', 'copy=True,', 'track=False):', 'if', 'flags', '&', 'zmq.NOBLOCK:', 'try:', 'msg', '=', 'super(_Socket,', 'self).recv(flags,', 'copy,', 'track)', 'finally:', 'if', 'not', 'self.__in_recv_multipart:', 'self.__state_changed()', 'return', 'msg', 'flags', '|=', 'zmq.NOBLOCK', 'while', 'True...
985,516
openvinotoolkit/training_extensions
test_action_det_dataset.py
TestOTXActionDetDataset.test_pipeline
test_pipeline
Test RawFrameDecode transform contains otx_dataset.
[ "Test", "RawFrameDecode", "transform", "contains", "otx_dataset." ]
def test_pipeline(self) -> None: dataset = OTXActionDetDataset(self.otx_dataset, self.labels, self.pipeline, fps=1) for transform in dataset.pipeline.transforms: if isinstance(transform, RawFrameDecode): assert transform.otx_dataset == self.otx_dataset
['def', 'test_pipeline(self)', '->', 'None:', 'dataset', '=', 'OTXActionDetDataset(self.otx_dataset,', 'self.labels,', 'self.pipeline,', 'fps=1)', 'for', 'transform', 'in', 'dataset.pipeline.transforms:', 'if', 'isinstance(transform,', 'RawFrameDecode):', 'assert', 'transform.otx_dataset', '==', 'self.otx_dataset']
919,240
arshpreetsingh/quantopian-machinelearning
categorical.py
Categorical.put
put
Replace specific elements in the Categorical with given values.
[ "Replace", "specific", "elements", "in", "the", "Categorical", "with", "given", "values." ]
def put(self, *args, **kwargs): raise NotImplementedError("'put' is not yet implemented for Categorical")
['def', 'put(self,', '*args,', '**kwargs):', 'raise', 'NotImplementedError("\'put\'', 'is', 'not', 'yet', 'implemented', 'for', 'Categorical")']
889,754
mnot/thor
udp.py
UdpEndpoint.send
send
send datagram to host:port.
[ "send", "datagram", "to", "host:port." ]
def send(self, datagram: bytes, host: str, port: int) -> None: try: self.sock.sendto(datagram, (host, port)) except socket.error as why: if why in self._block_errs: pass else: raise
['def', 'send(self,', 'datagram:', 'bytes,', 'host:', 'str,', 'port:', 'int)', '->', 'None:', 'try:', 'self.sock.sendto(datagram,', '(host,', 'port))', 'except', 'socket.error', 'as', 'why:', 'if', 'why', 'in', 'self._block_errs:', 'pass', 'else:', 'raise']
355,127
ryu-ed/SpaceInvaders_Ros
terminal_color.py
enable_ANSI_colors
enable_ANSI_colors
Populate the global module dictionary `ansi` with ANSI escape sequences.
[ "Populate", "the", "global", "module", "dictionary", "`ansi`", "with", "ANSI", "escape", "sequences." ]
def enable_ANSI_colors(): global _ansi color_order = ['black', 'red', 'green', 'yellow', 'blue', 'purple', 'cyan', 'white'] short_colors = {'black': 'k', 'red': 'r', 'green': 'g', 'yellow': 'y', 'blue': 'b', 'purple': 'p', 'cyan': 'c', 'white': 'w'} _ansi = {'escape': '\x1b', 'reset': 0, '|': 0, 'boldon...
['def', 'enable_ANSI_colors():', 'global', '_ansi', 'color_order', '=', "['black',", "'red',", "'green',", "'yellow',", "'blue',", "'purple',", "'cyan',", "'white']", 'short_colors', '=', "{'black':", "'k',", "'red':", "'r',", "'green':", "'g',", "'yellow':", "'y',", "'blue':", "'b',", "'purple':", "'p',", "'cyan':", "...
394,632
rudranil723/mini-main
describe.py
reorder_columns
reorder_columns
Set a convenient order for rows for display.
[ "Set", "a", "convenient", "order", "for", "rows", "for", "display." ]
def reorder_columns(ldesc: Sequence[Series]) -> list[Hashable]: names: list[Hashable] = [] ldesc_indexes = sorted((x.index for x in ldesc), key=len) for idxnames in ldesc_indexes: for name in idxnames: if name not in names: names.append(name) return names
['def', 'reorder_columns(ldesc:', 'Sequence[Series])', '->', 'list[Hashable]:', 'names:', 'list[Hashable]', '=', '[]', 'ldesc_indexes', '=', 'sorted((x.index', 'for', 'x', 'in', 'ldesc),', 'key=len)', 'for', 'idxnames', 'in', 'ldesc_indexes:', 'for', 'name', 'in', 'idxnames:', 'if', 'name', 'not', 'in', 'names:', 'name...
323,296
Ruturaj123/Flowchart-Detection
optimizer.py
_OptimizableVariable.target
target
Returns the optimization target for this variable.
[ "Returns", "the", "optimization", "target", "for", "this", "variable." ]
def target(self): raise NotImplementedError('Calling an abstract method.')
['def', 'target(self):', 'raise', "NotImplementedError('Calling", 'an', 'abstract', "method.')"]
606,528
adamshamsudeen/vision.ai
msvc.py
SystemInfo.VCInstallDir
VCInstallDir
Microsoft Visual C++ directory.
[ "Microsoft", "Visual", "C++", "directory." ]
def VCInstallDir(self): self.VSInstallDir guess_vc = self._guess_vc() or self._guess_vc_legacy() reg_path = os.path.join(self.ri.vc_for_python, '%0.1f' % self.vc_ver) python_vc = self.ri.lookup(reg_path, 'installdir') default_vc = os.path.join(python_vc, 'VC') if python_vc else guess_vc path = s...
['def', 'VCInstallDir(self):', 'self.VSInstallDir', 'guess_vc', '=', 'self._guess_vc()', 'or', 'self._guess_vc_legacy()', 'reg_path', '=', 'os.path.join(self.ri.vc_for_python,', "'%0.1f'", '%', 'self.vc_ver)', 'python_vc', '=', 'self.ri.lookup(reg_path,', "'installdir')", 'default_vc', '=', 'os.path.join(python_vc,', "...
944,097
tslearn-team/tslearn
plot_dtw_custom_metric.py
arc_length
arc_length
Length of the arc between two angles (in rad) on a circle of radius r.
[ "Length", "of", "the", "arc", "between", "two", "angles", "(in", "rad)", "on", "a", "circle", "of", "radius", "r." ]
def arc_length(angle_1, angle_2, r=1.0): theta = np.mod(angle_2 - angle_1, 2 * pi) if theta > pi: theta = theta - 2 * pi L = r * np.abs(theta) return L
['def', 'arc_length(angle_1,', 'angle_2,', 'r=1.0):', 'theta', '=', 'np.mod(angle_2', '-', 'angle_1,', '2', '*', 'pi)', 'if', 'theta', '>', 'pi:', 'theta', '=', 'theta', '-', '2', '*', 'pi', 'L', '=', 'r', '*', 'np.abs(theta)', 'return', 'L']
952,470
facebookresearch/CompilerGym
__init__.py
lli_path
lli_path
Return the path of lli.
[ "Return", "the", "path", "of", "lli." ]
def lli_path() -> Path: return download_llvm_files() / 'bin/lli'
['def', 'lli_path()', '->', 'Path:', 'return', 'download_llvm_files()', '/', "'bin/lli'"]
126,275
awslabs/predictive-maintenance-using--
base.py
IndexOpsMixin.hasnans
hasnans
Return if I have any nans; enables various perf speedups.
[ "Return", "if", "I", "have", "any", "nans;", "enables", "various", "perf", "speedups." ]
def hasnans(self): return bool(isna(self).any())
['def', 'hasnans(self):', 'return', 'bool(isna(self).any())']
823,044
PacktPublishing/Advanced-Deep-Learning-with-Keras
fcn-12.3.1.py
FCN.eval
eval
Evaluate a trained FCN model using mean IoU metric.
[ "Evaluate", "a", "trained", "FCN", "model", "using", "mean", "IoU", "metric." ]
def eval(self): s_iou = 0 s_pla = 0 eps = np.finfo(float).eps for key in self.test_keys: image_path = os.path.join(self.args.data_path, key) image = skimage.img_as_float(imread(image_path)) segmentation = self.segment_objects(image) gt = self.test_dictionary[key] ...
['def', 'eval(self):', 's_iou', '=', '0', 's_pla', '=', '0', 'eps', '=', 'np.finfo(float).eps', 'for', 'key', 'in', 'self.test_keys:', 'image_path', '=', 'os.path.join(self.args.data_path,', 'key)', 'image', '=', 'skimage.img_as_float(imread(image_path))', 'segmentation', '=', 'self.segment_objects(image)', 'gt', '=', ...
396,753
Ruturaj123/Flowchart-Detection
function_test.py
FunctionTest.testControlFlowStrictness
testControlFlowStrictness
Inlined functions must not execute in a untaken control flow branch.
[ "Inlined", "functions", "must", "not", "execute", "in", "a", "untaken", "control", "flow", "branch." ]
def testControlFlowStrictness(self): @function.Defun(dtypes.int32) def AssertFail(x): assert_false = control_flow_ops.Assert(False, [42]) with ops.control_dependencies([assert_false]): return array_ops.identity(x) with ops.device('CPU'): pred = array_ops.placeholder(dtyp...
['def', 'testControlFlowStrictness(self):', '@function.Defun(dtypes.int32)', 'def', 'AssertFail(x):', 'assert_false', '=', 'control_flow_ops.Assert(False,', '[42])', 'with', 'ops.control_dependencies([assert_false]):', 'return', 'array_ops.identity(x)', 'with', "ops.device('CPU'):", 'pred', '=', 'array_ops.placeholder(...
605,356
sunishsheth2009/ChatterBot
test_recfunctions.py
TestStackArrays.test_defaults
test_defaults
Test defaults: no exception raised if keys of defaults are not fields.
[ "Test", "defaults:", "no", "exception", "raised", "if", "keys", "of", "defaults", "are", "not", "fields." ]
def test_defaults(self): (_, _, _, z) = self.data zz = np.array([('a', 10.0, 100.0), ('b', 20.0, 200.0), ('c', 30.0, 300.0)], dtype=[('A', '|S3'), ('B', float), ('C', float)]) defaults = {'A': '???', 'B': -999.0, 'C': -9999.0, 'D': -99999.0} test = stack_arrays((z, zz), defaults=defaults) control = ...
['def', 'test_defaults(self):', '(_,', '_,', '_,', 'z)', '=', 'self.data', 'zz', '=', "np.array([('a',", '10.0,', '100.0),', "('b',", '20.0,', '200.0),', "('c',", '30.0,', '300.0)],', "dtype=[('A',", "'|S3'),", "('B',", 'float),', "('C',", 'float)])', 'defaults', '=', "{'A':", "'???',", "'B':", '-999.0,', "'C':", '-999...
531,543
hugochan/KATE
op_utils.py
calc_ranks
calc_ranks
Given a list of items, return a list(in ndarray type) of ranks.
[ "Given", "a", "list", "of", "items,", "return", "a", "list(in", "ndarray", "type)", "of", "ranks." ]
def calc_ranks(x): n = len(x) index = list(zip(*sorted(list(enumerate(x)), key=lambda d: d[1], reverse=True))[0]) rank = np.zeros(n) rank[index] = range(1, n + 1) return rank
['def', 'calc_ranks(x):', 'n', '=', 'len(x)', 'index', '=', 'list(zip(*sorted(list(enumerate(x)),', 'key=lambda', 'd:', 'd[1],', 'reverse=True))[0])', 'rank', '=', 'np.zeros(n)', 'rank[index]', '=', 'range(1,', 'n', '+', '1)', 'return', 'rank']
594,921
tensorflow/data-validation
stats_util.py
load_stats_tfrecord
load_stats_tfrecord
Loads data statistics proto from TFRecord file.
[ "Loads", "data", "statistics", "proto", "from", "TFRecord", "file." ]
def load_stats_tfrecord(input_path: Text) -> statistics_pb2.DatasetFeatureStatisticsList: it = artifacts_io_impl.get_io_provider('tfrecords').record_iterator_impl([input_path]) result = next(it) try: next(it) raise ValueError('load_stats_tfrecord expects a single record.') except StopIte...
['def', 'load_stats_tfrecord(input_path:', 'Text)', '->', 'statistics_pb2.DatasetFeatureStatisticsList:', 'it', '=', "artifacts_io_impl.get_io_provider('tfrecords').record_iterator_impl([input_path])", 'result', '=', 'next(it)', 'try:', 'next(it)', 'raise', "ValueError('load_stats_tfrecord", 'expects', 'a', 'single', "...
497,654
rudranil723/mini-main
test_lines.py
test_markevery_prop_cycle
test_markevery_prop_cycle
Test that we can set markevery prop_cycle.
[ "Test", "that", "we", "can", "set", "markevery", "prop_cycle." ]
def test_markevery_prop_cycle(fig_test, fig_ref): cases = [None, 8, (30, 8), [16, 24, 30], [0, -1], slice(100, 200, 3), 0.1, 0.3, 1.5, (0.0, 0.1), (0.45, 0.1)] cmap = mpl.colormaps['jet'] colors = cmap(np.linspace(0.2, 0.8, len(cases))) x = np.linspace(-1, 1) y = 5 * x ** 2 axs = fig_ref.add_sub...
['def', 'test_markevery_prop_cycle(fig_test,', 'fig_ref):', 'cases', '=', '[None,', '8,', '(30,', '8),', '[16,', '24,', '30],', '[0,', '-1],', 'slice(100,', '200,', '3),', '0.1,', '0.3,', '1.5,', '(0.0,', '0.1),', '(0.45,', '0.1)]', 'cmap', '=', "mpl.colormaps['jet']", 'colors', '=', 'cmap(np.linspace(0.2,', '0.8,', 'l...
320,287
inseq-team/inseq
serialization.py
json_advanced_dump
json_advanced_dump
Dumps a complex object containing classes and arrays object to a file.
[ "Dumps", "a", "complex", "object", "containing", "classes", "and", "arrays", "object", "to", "a", "file." ]
def json_advanced_dump(obj: EncodableObject, sort_keys: bool=True, encoders: List[Callable]=ENCODE_HOOKS, use_primitives: bool=False, allow_nan: bool=True, ndarray_compact: Optional[bool]=None, compression: bool=False, **jsonkwargs) -> str: if isinstance(obj, str) or hasattr(obj, 'write'): raise ValueError(...
['def', 'json_advanced_dump(obj:', 'EncodableObject,', 'sort_keys:', 'bool=True,', 'encoders:', 'List[Callable]=ENCODE_HOOKS,', 'use_primitives:', 'bool=False,', 'allow_nan:', 'bool=True,', 'ndarray_compact:', 'Optional[bool]=None,', 'compression:', 'bool=False,', '**jsonkwargs)', '->', 'str:', 'if', 'isinstance(obj,',...
613,991
myothida/Supervised-Machine-Learning
test_clipboard.py
test_checked_call_with_bad_call
test_checked_call_with_bad_call
Give CheckCall a function that returns a falsey value and mock get_errno so it returns false so an exception is raised.
[ "Give", "CheckCall", "a", "function", "that", "returns", "a", "falsey", "value", "and", "mock", "get_errno", "so", "it", "returns", "false", "so", "an", "exception", "is", "raised." ]
def test_checked_call_with_bad_call(monkeypatch): def _return_false(): return False monkeypatch.setattr('pandas.io.clipboard.get_errno', lambda : True) msg = f'Error calling {_return_false.__name__} \\(Window Error\\)' with pytest.raises(PyperclipWindowsException, match=msg): CheckedCal...
['def', 'test_checked_call_with_bad_call(monkeypatch):', 'def', '_return_false():', 'return', 'False', "monkeypatch.setattr('pandas.io.clipboard.get_errno',", 'lambda', ':', 'True)', 'msg', '=', "f'Error", 'calling', '{_return_false.__name__}', '\\\\(Window', "Error\\\\)'", 'with', 'pytest.raises(PyperclipWindowsExcept...
443,709
eddylau328/fyp-artificial-intelligence-ac-control-device
client_info.py
ClientInfo.to_user_agent
to_user_agent
Returns the user-agent string for this client info.
[ "Returns", "the", "user-agent", "string", "for", "this", "client", "info." ]
def to_user_agent(self): ua = '' if self.user_agent is not None: ua += '{user_agent} ' ua += 'gl-python/{python_version} ' if self.grpc_version is not None: ua += 'grpc/{grpc_version} ' ua += 'gax/{api_core_version} ' if self.gapic_version is not None: ua += 'gapic/{gapic...
['def', 'to_user_agent(self):', 'ua', '=', "''", 'if', 'self.user_agent', 'is', 'not', 'None:', 'ua', '+=', "'{user_agent}", "'", 'ua', '+=', "'gl-python/{python_version}", "'", 'if', 'self.grpc_version', 'is', 'not', 'None:', 'ua', '+=', "'grpc/{grpc_version}", "'", 'ua', '+=', "'gax/{api_core_version}", "'", 'if', 's...
214,440
Kvatsx/Artificial-Intelligence-Assignments
arffread.py
MetaData.types
types
Return the list of attribute types.
[ "Return", "the", "list", "of", "attribute", "types." ]
def types(self): attr_types = [self._attributes[name][0] for name in self._attrnames] return attr_types
['def', 'types(self):', 'attr_types', '=', '[self._attributes[name][0]', 'for', 'name', 'in', 'self._attrnames]', 'return', 'attr_types']
77,523
navarmn/Elman_neural_network
logger.py
Logger.format
format
Return the formatted representation of the object.
[ "Return", "the", "formatted", "representation", "of", "the", "object." ]
def format(self, obj, indent=0): return pformat(obj, indent=indent, depth=self.depth)
['def', 'format(self,', 'obj,', 'indent=0):', 'return', 'pformat(obj,', 'indent=indent,', 'depth=self.depth)']
175,791
hsouri/BayesianTransferLearning
whitening.py
Whitening2d.forward
forward
Performs whitening using the Cholesky decomposition.
[ "Performs", "whitening", "using", "the", "Cholesky", "decomposition." ]
def forward(self, x: torch.Tensor) -> torch.Tensor: x = x.unsqueeze(2).unsqueeze(3) m = x.mean(0).view(self.output_dim, -1).mean(-1).view(1, -1, 1, 1) xn = x - m T = xn.permute(1, 0, 2, 3).contiguous().view(self.output_dim, -1) f_cov = torch.mm(T, T.permute(1, 0)) / (T.shape[-1] - 1) eye = torch...
['def', 'forward(self,', 'x:', 'torch.Tensor)', '->', 'torch.Tensor:', 'x', '=', 'x.unsqueeze(2).unsqueeze(3)', 'm', '=', 'x.mean(0).view(self.output_dim,', '-1).mean(-1).view(1,', '-1,', '1,', '1)', 'xn', '=', 'x', '-', 'm', 'T', '=', 'xn.permute(1,', '0,', '2,', '3).contiguous().view(self.output_dim,', '-1)', 'f_cov'...
423,051
Alexander-Parker/youtube_nlp
read_preferences.py
_ServerMode.mode
mode
The mode of this read preference instance.
[ "The", "mode", "of", "this", "read", "preference", "instance." ]
def mode(self): return self.__mode
['def', 'mode(self):', 'return', 'self.__mode']
970,596
rudranil723/mini-main
_regex_core.py
parse_group_ref
parse_group_ref
Parses a group reference.
[ "Parses", "a", "group", "reference." ]
def parse_group_ref(source, info): source.expect('<') saved_pos = source.pos name = parse_name(source, True) source.expect('>') if info.is_open_group(name): raise error('cannot refer to an open group', source.string, source.pos) return make_ref_group(info, name, saved_pos)
['def', 'parse_group_ref(source,', 'info):', "source.expect('<')", 'saved_pos', '=', 'source.pos', 'name', '=', 'parse_name(source,', 'True)', "source.expect('>')", 'if', 'info.is_open_group(name):', 'raise', "error('cannot", 'refer', 'to', 'an', 'open', "group',", 'source.string,', 'source.pos)', 'return', 'make_ref_g...
269,812
openvinotoolkit/training_extensions
model.py
ModelEntity.has_xai
has_xai
Get or set the xAI flag.
[ "Get", "or", "set", "the", "xAI", "flag." ]
def has_xai(self) -> float: return self.__has_xai
['def', 'has_xai(self)', '->', 'float:', 'return', 'self.__has_xai']
918,633
ultralytics/xview-yolov3
evaluation.py
safe_divide
safe_divide
Computes the safe division to avoid the divide by zero problem.
[ "Computes", "the", "safe", "division", "to", "avoid", "the", "divide", "by", "zero", "problem." ]
def safe_divide(numerator, denominator): if denominator == 0: return 0 return numerator / denominator
['def', 'safe_divide(numerator,', 'denominator):', 'if', 'denominator', '==', '0:', 'return', '0', 'return', 'numerator', '/', 'denominator']
968,904
he-y/filter-pruning-geometric-median
imagenet_resnet_small.py
resnet152_small
resnet152_small
Constructs a ResNet_small-152 model.
[ "Constructs", "a", "ResNet_small-152", "model." ]
def resnet152_small(pretrained=False, **kwargs): model = ResNet_small(Bottleneck, [3, 8, 36, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet152'])) return model
['def', 'resnet152_small(pretrained=False,', '**kwargs):', 'model', '=', 'ResNet_small(Bottleneck,', '[3,', '8,', '36,', '3],', '**kwargs)', 'if', 'pretrained:', "model.load_state_dict(model_zoo.load_url(model_urls['resnet152']))", 'return', 'model']
210,362
TonyLianLong/VAI-ReinforcementLearning
wrappers.py
MjDataWrapper.efc_JT_rowsuper
efc_JT_rowsuper
number of subsequent rows in supernode T (nv x 1).
[ "number", "of", "subsequent", "rows", "in", "supernode", "T", "(nv", "x", "1)." ]
def efc_JT_rowsuper(self): return util.buf_to_npy(self._ptr.contents.efc_JT_rowsuper, (self._model.nv,))
['def', 'efc_JT_rowsuper(self):', 'return', 'util.buf_to_npy(self._ptr.contents.efc_JT_rowsuper,', '(self._model.nv,))']
440,587
iffiX/machin
checker.py
p_chk_nan
p_chk_nan
Check whether there is any nan element in the parameter.
[ "Check", "whether", "there", "is", "any", "nan", "element", "in", "the", "parameter." ]
def p_chk_nan(counter, _writer, _model, _module, param_name, param_val): check_nan(param_val, param_name + f'(backward_count={counter.get()})')
['def', 'p_chk_nan(counter,', '_writer,', '_model,', '_module,', 'param_name,', 'param_val):', 'check_nan(param_val,', 'param_name', '+', "f'(backward_count={counter.get()})')"]
620,442
rudranil723/mini-main
message.py
Message.ClearExtension
ClearExtension
Clears the contents of a given extension.
[ "Clears", "the", "contents", "of", "a", "given", "extension." ]
def ClearExtension(self, extension_handle): raise NotImplementedError
['def', 'ClearExtension(self,', 'extension_handle):', 'raise', 'NotImplementedError']
318,281
caiiiac/Machine-Learning-with-Python
scale.py
LogitScale.limit_range_for_scale
limit_range_for_scale
Limit the domain to values between 0 and 1 (excluded).
[ "Limit", "the", "domain", "to", "values", "between", "0", "and", "1", "(excluded)." ]
def limit_range_for_scale(self, vmin, vmax, minpos): if not np.isfinite(minpos): minpos = 1e-07 return (minpos if vmin <= 0 else vmin, 1 - minpos if vmax >= 1 else vmax)
['def', 'limit_range_for_scale(self,', 'vmin,', 'vmax,', 'minpos):', 'if', 'not', 'np.isfinite(minpos):', 'minpos', '=', '1e-07', 'return', '(minpos', 'if', 'vmin', '<=', '0', 'else', 'vmin,', '1', '-', 'minpos', 'if', 'vmax', '>=', '1', 'else', 'vmax)']
715,964
instadeepai/Mava
jumanji.py
RwareMultiAgentWrapper.observation_spec
observation_spec
Specification of the observation of the `RobotWarehouse` environment.
[ "Specification", "of", "the", "observation", "of", "the", "`RobotWarehouse`", "environment." ]
def observation_spec(self) -> specs.Spec[Observation]: step_count = specs.BoundedArray((self._env.num_agents,), jnp.int32, [0] * self._env.num_agents, [self._env.time_limit] * self._env.num_agents, 'step_count') return self._env.observation_spec().replace(step_count=step_count)
['def', 'observation_spec(self)', '->', 'specs.Spec[Observation]:', 'step_count', '=', 'specs.BoundedArray((self._env.num_agents,),', 'jnp.int32,', '[0]', '*', 'self._env.num_agents,', '[self._env.time_limit]', '*', 'self._env.num_agents,', "'step_count')", 'return', 'self._env.observation_spec().replace(step_count=ste...
209,902
rudranil723/mini-main
loader_tags.py
do_block
do_block
Define a block that can be overridden by child templates.
[ "Define", "a", "block", "that", "can", "be", "overridden", "by", "child", "templates." ]
def do_block(parser, token): bits = token.contents.split() if len(bits) != 2: raise TemplateSyntaxError("'%s' tag takes only one argument" % bits[0]) block_name = bits[1] try: if block_name in parser.__loaded_blocks: raise TemplateSyntaxError("'%s' tag with name '%s' appears ...
['def', 'do_block(parser,', 'token):', 'bits', '=', 'token.contents.split()', 'if', 'len(bits)', '!=', '2:', 'raise', 'TemplateSyntaxError("\'%s\'', 'tag', 'takes', 'only', 'one', 'argument"', '%', 'bits[0])', 'block_name', '=', 'bits[1]', 'try:', 'if', 'block_name', 'in', 'parser.__loaded_blocks:', 'raise', 'TemplateS...
316,469
RasaHQ/rasa
common.py
update_sanic_log_level
update_sanic_log_level
Set the log level to 'LOG_LEVEL_LIBRARIES' environment variable .
[ "Set", "the", "log", "level", "to", "'LOG_LEVEL_LIBRARIES'", "environment", "variable", "." ]
def update_sanic_log_level(log_file: Optional[Text]=None, use_syslog: Optional[bool]=False, syslog_address: Optional[Text]=None, syslog_port: Optional[int]=None, syslog_protocol: Optional[Text]=None) -> None: from sanic.log import logger, error_logger, access_logger log_level = os.environ.get(ENV_LOG_LEVEL_LIBR...
['def', 'update_sanic_log_level(log_file:', 'Optional[Text]=None,', 'use_syslog:', 'Optional[bool]=False,', 'syslog_address:', 'Optional[Text]=None,', 'syslog_port:', 'Optional[int]=None,', 'syslog_protocol:', 'Optional[Text]=None)', '->', 'None:', 'from', 'sanic.log', 'import', 'logger,', 'error_logger,', 'access_logg...
837,831
seltzerfish/guardyn
gtest_color_test.py
GTestColorTest.testNoEnvVarNoFlag
testNoEnvVarNoFlag
Tests the case when there's neither GTEST_COLOR nor --gtest_color.
[ "Tests", "the", "case", "when", "there's", "neither", "GTEST_COLOR", "nor", "--gtest_color." ]
def testNoEnvVarNoFlag(self): if not IS_WINDOWS: self.assert_(not UsesColor('dumb', None, None)) self.assert_(not UsesColor('emacs', None, None)) self.assert_(not UsesColor('xterm-mono', None, None)) self.assert_(not UsesColor('unknown', None, None)) self.assert_(not UsesColo...
['def', 'testNoEnvVarNoFlag(self):', 'if', 'not', 'IS_WINDOWS:', 'self.assert_(not', "UsesColor('dumb',", 'None,', 'None))', 'self.assert_(not', "UsesColor('emacs',", 'None,', 'None))', 'self.assert_(not', "UsesColor('xterm-mono',", 'None,', 'None))', 'self.assert_(not', "UsesColor('unknown',", 'None,', 'None))', 'self...
572,237
43Carrig/recurrent_neural_networks_practice
function.py
func_graph_from_py_func
func_graph_from_py_func
Returns a `FuncGraph` generated from `python_func`.
[ "Returns", "a", "`FuncGraph`", "generated", "from", "`python_func`." ]
def func_graph_from_py_func(name, python_func, args, kwds, signature=None): func_graph = FuncGraph(name) with func_graph.as_default(), AutomaticControlDependencies() as a: variable_scope.get_variable_scope().set_use_resource(True) if signature is None: func_args = _get_defun_inputs_f...
['def', 'func_graph_from_py_func(name,', 'python_func,', 'args,', 'kwds,', 'signature=None):', 'func_graph', '=', 'FuncGraph(name)', 'with', 'func_graph.as_default(),', 'AutomaticControlDependencies()', 'as', 'a:', 'variable_scope.get_variable_scope().set_use_resource(True)', 'if', 'signature', 'is', 'None:', 'func_arg...
336,141
aws/sagemaker-python-sdk
dataset_builder.py
DatasetBuilder.with_feature_group
with_feature_group
Join FeatureGroup with base.
[ "Join", "FeatureGroup", "with", "base." ]
def with_feature_group(self, feature_group: FeatureGroup, target_feature_name_in_base: str=None, included_feature_names: List[str]=None, feature_name_in_target: str=None, join_comparator: JoinComparatorEnum=JoinComparatorEnum.EQUALS, join_type: JoinTypeEnum=JoinTypeEnum.INNER_JOIN): self._feature_groups_to_be_merge...
['def', 'with_feature_group(self,', 'feature_group:', 'FeatureGroup,', 'target_feature_name_in_base:', 'str=None,', 'included_feature_names:', 'List[str]=None,', 'feature_name_in_target:', 'str=None,', 'join_comparator:', 'JoinComparatorEnum=JoinComparatorEnum.EQUALS,', 'join_type:', 'JoinTypeEnum=JoinTypeEnum.INNER_JO...
830,006
AxeldeRomblay/MLBox
test_stacking_classifer.py
test_fit_transform_stacking_classifier
test_fit_transform_stacking_classifier
Test fit_transform method of StackingClassifier class.
[ "Test", "fit_transform", "method", "of", "StackingClassifier", "class." ]
def test_fit_transform_stacking_classifier(): df_train = pd.read_csv('data_for_tests/clean_train.csv') y_train = pd.read_csv('data_for_tests/clean_target.csv', squeeze=True) stacking_classifier = StackingClassifier() with pytest.raises(ValueError): stacking_classifier.fit_transform(None, y_train...
['def', 'test_fit_transform_stacking_classifier():', 'df_train', '=', "pd.read_csv('data_for_tests/clean_train.csv')", 'y_train', '=', "pd.read_csv('data_for_tests/clean_target.csv',", 'squeeze=True)', 'stacking_classifier', '=', 'StackingClassifier()', 'with', 'pytest.raises(ValueError):', 'stacking_classifier.fit_tra...
630,075
Kvatsx/Artificial-Intelligence-Assignments
texmanager.py
TexManager.get_text_width_height_descent
get_text_width_height_descent
Return width, height and descent of the text.
[ "Return", "width,", "height", "and", "descent", "of", "the", "text." ]
def get_text_width_height_descent(self, tex, fontsize, renderer=None): if tex.strip() == '': return (0, 0, 0) dpi_fraction = renderer.points_to_pixels(1.0) if renderer else 1 if rcParams['text.latex.preview']: basefile = self.get_basefile(tex, fontsize) baselinefile = '%s.baseline' %...
['def', 'get_text_width_height_descent(self,', 'tex,', 'fontsize,', 'renderer=None):', 'if', 'tex.strip()', '==', "'':", 'return', '(0,', '0,', '0)', 'dpi_fraction', '=', 'renderer.points_to_pixels(1.0)', 'if', 'renderer', 'else', '1', 'if', "rcParams['text.latex.preview']:", 'basefile', '=', 'self.get_basefile(tex,', ...
892
OpenMDAO/OpenMDAO-Framework
zone.py
Zone.shape
shape
Coordinate index limits, not including 'ghost/rind' planes.
[ "Coordinate", "index", "limits,", "not", "including", "'ghost/rind'", "planes." ]
def shape(self): return self.grid_coordinates.shape
['def', 'shape(self):', 'return', 'self.grid_coordinates.shape']
275,520
TonyLianLong/VAI-ReinforcementLearning
wrappers.py
MjModelWrapper.skin_bonebindquat
skin_bonebindquat
bind quat of each bone (nskinbone x 4).
[ "bind", "quat", "of", "each", "bone", "(nskinbone", "x", "4)." ]
def skin_bonebindquat(self): return util.buf_to_npy(self._ptr.contents.skin_bonebindquat, (self.nskinbone, 4))
['def', 'skin_bonebindquat(self):', 'return', 'util.buf_to_npy(self._ptr.contents.skin_bonebindquat,', '(self.nskinbone,', '4))']
440,369
microsoft/nlp-recipes
cnndm.py
CNNDMSummarizationDataset
CNNDMSummarizationDataset
Load the CNN/Daily Mail dataset preprocessed by harvardnlp group.
[ "Load", "the", "CNN/Daily", "Mail", "dataset", "preprocessed", "by", "harvardnlp", "group." ]
def CNNDMSummarizationDataset(*args, **kwargs): URLS = ['https://s3.amazonaws.com/opennmt-models/Summary/cnndm.tar.gz'] def _setup_datasets(url, top_n=-1, local_cache_path='.data', prepare_extractive=True): FILE_NAME = 'cnndm.tar.gz' maybe_download(url, FILE_NAME, local_cache_path) data...
['def', 'CNNDMSummarizationDataset(*args,', '**kwargs):', 'URLS', '=', "['https://s3.amazonaws.com/opennmt-models/Summary/cnndm.tar.gz']", 'def', '_setup_datasets(url,', 'top_n=-1,', "local_cache_path='.data',", 'prepare_extractive=True):', 'FILE_NAME', '=', "'cnndm.tar.gz'", 'maybe_download(url,', 'FILE_NAME,', 'local...
731,172
nilearn/nilearn
test_base.py
test_mask_reducer_multiple_image
test_mask_reducer_multiple_image
Mask and reduce 4D images with several values of input arguments.
[ "Mask", "and", "reduce", "4D", "images", "with", "several", "values", "of", "input", "arguments." ]
def test_mask_reducer_multiple_image(data_for_mask_and_reduce, masker, n_components, reduction_ratio, expected_shape_0, shape_3d_default): data = _mask_and_reduce(masker=masker, imgs=data_for_mask_and_reduce, n_components=n_components, reduction_ratio=reduction_ratio) expected_shape = (expected_shape_0, np.prod...
['def', 'test_mask_reducer_multiple_image(data_for_mask_and_reduce,', 'masker,', 'n_components,', 'reduction_ratio,', 'expected_shape_0,', 'shape_3d_default):', 'data', '=', '_mask_and_reduce(masker=masker,', 'imgs=data_for_mask_and_reduce,', 'n_components=n_components,', 'reduction_ratio=reduction_ratio)', 'expected_s...
723,738
rudranil723/mini-main
tz.py
utc
utc
Convert a datetime to UTC.
[ "Convert", "a", "datetime", "to", "UTC." ]
def utc(value): return do_timezone(value, timezone.utc)
['def', 'utc(value):', 'return', 'do_timezone(value,', 'timezone.utc)']
316,517
cackharot/suds-py3
element.py
PrefixNormalizer.refitNodes
refitNodes
Refit (normalize) all of the nodes in the branch.
[ "Refit", "(normalize)", "all", "of", "the", "nodes", "in", "the", "branch." ]
def refitNodes(self): for n in self.branch: if n.prefix is not None: ns = n.namespace() if self.permit(ns): n.prefix = self.prefixes[ns[1]] self.refitAttrs(n)
['def', 'refitNodes(self):', 'for', 'n', 'in', 'self.branch:', 'if', 'n.prefix', 'is', 'not', 'None:', 'ns', '=', 'n.namespace()', 'if', 'self.permit(ns):', 'n.prefix', '=', 'self.prefixes[ns[1]]', 'self.refitAttrs(n)']
360,346
Eric3911/OpenAGI
manifest_utils.py
get_subsegment_dict
get_subsegment_dict
Get subsegment dictionary from manifest file.
[ "Get", "subsegment", "dictionary", "from", "manifest", "file." ]
def get_subsegment_dict(subsegments_manifest_file: str, window: float, shift: float, deci: int) -> Dict[str, dict]: _subsegment_dict = {} with open(subsegments_manifest_file, 'r') as subsegments_manifest: segments = subsegments_manifest.readlines() for segment in segments: segment = ...
['def', 'get_subsegment_dict(subsegments_manifest_file:', 'str,', 'window:', 'float,', 'shift:', 'float,', 'deci:', 'int)', '->', 'Dict[str,', 'dict]:', '_subsegment_dict', '=', '{}', 'with', 'open(subsegments_manifest_file,', "'r')", 'as', 'subsegments_manifest:', 'segments', '=', 'subsegments_manifest.readlines()', '...
272,904
deephyper/deephyper
space.py
Real.update_prior
update_prior
Fit a Kernel Density Estimator to the data to increase density of samples around regions of interest instead of uniform random-sampling.
[ "Fit", "a", "Kernel", "Density", "Estimator", "to", "the", "data", "to", "increase", "density", "of", "samples", "around", "regions", "of", "interest", "instead", "of", "uniform", "random-sampling." ]
def update_prior(self, X, y, q=0.9): X = np.array(X) y = np.array(y) y_ = np.quantile(y, q) X_low = X[y <= y_] try: kde = gaussian_kde(X_low) self._kde = kde except np.linalg.LinAlgError: pass
['def', 'update_prior(self,', 'X,', 'y,', 'q=0.9):', 'X', '=', 'np.array(X)', 'y', '=', 'np.array(y)', 'y_', '=', 'np.quantile(y,', 'q)', 'X_low', '=', 'X[y', '<=', 'y_]', 'try:', 'kde', '=', 'gaussian_kde(X_low)', 'self._kde', '=', 'kde', 'except', 'np.linalg.LinAlgError:', 'pass']
521,038
tangyuhao/DAVIS-2016-Chanllege-Solution
bboxes.py
bboxes_filter_overlap
bboxes_filter_overlap
Filter out bounding boxes based on overlap with reference box [0, 0, 1, 1].
[ "Filter", "out", "bounding", "boxes", "based", "on", "overlap", "with", "reference", "box", "[0,", "0,", "1,", "1]." ]
def bboxes_filter_overlap(labels, bboxes, threshold=0.5, scope=None): with tf.name_scope(scope, 'bboxes_filter', [labels, bboxes]): scores = bboxes_intersection(tf.constant([0, 0, 1, 1], bboxes.dtype), bboxes) mask = scores > threshold labels = tf.boolean_mask(labels, mask) bboxes = ...
['def', 'bboxes_filter_overlap(labels,', 'bboxes,', 'threshold=0.5,', 'scope=None):', 'with', 'tf.name_scope(scope,', "'bboxes_filter',", '[labels,', 'bboxes]):', 'scores', '=', 'bboxes_intersection(tf.constant([0,', '0,', '1,', '1],', 'bboxes.dtype),', 'bboxes)', 'mask', '=', 'scores', '>', 'threshold', 'labels', '=',...
498,388
Alexander-Parker/youtube_nlp
server_selectors.py
secondary_with_tags_server_selector
secondary_with_tags_server_selector
All near-enough secondaries matching the tag sets.
[ "All", "near-enough", "secondaries", "matching", "the", "tag", "sets." ]
def secondary_with_tags_server_selector(tag_sets, selection): return apply_tag_sets(tag_sets, secondary_server_selector(selection))
['def', 'secondary_with_tags_server_selector(tag_sets,', 'selection):', 'return', 'apply_tag_sets(tag_sets,', 'secondary_server_selector(selection))']
970,642
zihuitang/medical_AI_platform
test_buffer.py
randitems
randitems
Return random format, items, item.
[ "Return", "random", "format,", "items,", "item." ]
def randitems(n, obj='ndarray', mode=None, char=None): if mode is None: mode = choice(cap[obj][MODE]) if char is None: char = choice(tuple(fmtdict[mode])) multiplier = choice(cap[obj][MULT]) fmt = mode + '#' + char * int(multiplier if multiplier else 1) items = gen_items(n, fmt, obj)...
['def', 'randitems(n,', "obj='ndarray',", 'mode=None,', 'char=None):', 'if', 'mode', 'is', 'None:', 'mode', '=', 'choice(cap[obj][MODE])', 'if', 'char', 'is', 'None:', 'char', '=', 'choice(tuple(fmtdict[mode]))', 'multiplier', '=', 'choice(cap[obj][MULT])', 'fmt', '=', 'mode', '+', "'#'", '+', 'char', '*', 'int(multipl...
283,222
boostcampaitech2/semantic-segmentation-level2-cv-07
sync_random_size_hook.py
SyncRandomSizeHook.after_train_iter
after_train_iter
Change the dataset output image size.
[ "Change", "the", "dataset", "output", "image", "size." ]
def after_train_iter(self, runner): if self.ratio_range is not None and (runner.iter + 1) % self.interval == 0: tensor = torch.LongTensor(2).to(self.device) if self.rank == 0: size_factor = self.img_scale[1] * 1.0 / self.img_scale[0] size = random.randint(*self.ratio_range) ...
['def', 'after_train_iter(self,', 'runner):', 'if', 'self.ratio_range', 'is', 'not', 'None', 'and', '(runner.iter', '+', '1)', '%', 'self.interval', '==', '0:', 'tensor', '=', 'torch.LongTensor(2).to(self.device)', 'if', 'self.rank', '==', '0:', 'size_factor', '=', 'self.img_scale[1]', '*', '1.0', '/', 'self.img_scale[...
856,866
google-research/scenic
model_utils.py
get_input_token_temporal_dims
get_input_token_temporal_dims
Returns temporal dims of input tokens for each view.
[ "Returns", "temporal", "dims", "of", "input", "tokens", "for", "each", "view." ]
def get_input_token_temporal_dims(num_frames: int, view_configs: Sequence[ml_collections.ConfigDict]) -> List[int]: return [num_frames // view['patches']['size'][2] for view in view_configs]
['def', 'get_input_token_temporal_dims(num_frames:', 'int,', 'view_configs:', 'Sequence[ml_collections.ConfigDict])', '->', 'List[int]:', 'return', '[num_frames', '//', "view['patches']['size'][2]", 'for', 'view', 'in', 'view_configs]']
847,053
wutong8023/CoLL
testing_utils.py
require_soundfile
require_soundfile
Decorator marking a test that requires soundfile These tests are skipped when soundfile isn't installed.
[ "Decorator", "marking", "a", "test", "that", "requires", "soundfile", "These", "tests", "are", "skipped", "when", "soundfile", "isn't", "installed." ]
def require_soundfile(test_case): if not is_soundfile_availble(): return unittest.skip('test requires soundfile')(test_case) else: return test_case
['def', 'require_soundfile(test_case):', 'if', 'not', 'is_soundfile_availble():', 'return', "unittest.skip('test", 'requires', "soundfile')(test_case)", 'else:', 'return', 'test_case']
496,418
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
cygwinccompiler.py
CygwinCCompiler.object_filenames
object_filenames
Adds supports for rc and res files.
[ "Adds", "supports", "for", "rc", "and", "res", "files." ]
def object_filenames(self, source_filenames, strip_dir=0, output_dir=''): if output_dir is None: output_dir = '' obj_names = [] for src_name in source_filenames: (base, ext) = os.path.splitext(os.path.normcase(src_name)) if ext not in self.src_extensions + ['.rc', '.res']: ...
['def', 'object_filenames(self,', 'source_filenames,', 'strip_dir=0,', "output_dir=''):", 'if', 'output_dir', 'is', 'None:', 'output_dir', '=', "''", 'obj_names', '=', '[]', 'for', 'src_name', 'in', 'source_filenames:', '(base,', 'ext)', '=', 'os.path.splitext(os.path.normcase(src_name))', 'if', 'ext', 'not', 'in', 'se...
430,296
scikit-learn/scikit-learn
test_function_transformer.py
test_function_transformer_validate_inverse
test_function_transformer_validate_inverse
Test that function transformer does not reset estimator in `inverse_transform`.
[ "Test", "that", "function", "transformer", "does", "not", "reset", "estimator", "in", "`inverse_transform`." ]
def test_function_transformer_validate_inverse(): def add_constant_feature(X): X_one = np.ones((X.shape[0], 1)) return np.concatenate((X, X_one), axis=1) def inverse_add_constant(X): return X[:, :-1] X = np.array([[1, 2], [3, 4], [3, 4]]) trans = FunctionTransformer(func=add_co...
['def', 'test_function_transformer_validate_inverse():', 'def', 'add_constant_feature(X):', 'X_one', '=', 'np.ones((X.shape[0],', '1))', 'return', 'np.concatenate((X,', 'X_one),', 'axis=1)', 'def', 'inverse_add_constant(X):', 'return', 'X[:,', ':-1]', 'X', '=', 'np.array([[1,', '2],', '[3,', '4],', '[3,', '4]])', 'tran...
854,044
tensorflow/agents
common_test.py
PeriodicallyTest.testPeriodOne
testPeriodOne
Tests that the function is called every time if period == 1.
[ "Tests", "that", "the", "function", "is", "called", "every", "time", "if", "period", "==", "1." ]
def testPeriodOne(self): target = tf.compat.v2.Variable(0) periodic_update = common.periodically(lambda : tf.group(target.assign_add(1)), period=1) self.evaluate(tf.compat.v1.global_variables_initializer()) for desired_value in range(0, 10): result = self.evaluate(target) self.assertEqua...
['def', 'testPeriodOne(self):', 'target', '=', 'tf.compat.v2.Variable(0)', 'periodic_update', '=', 'common.periodically(lambda', ':', 'tf.group(target.assign_add(1)),', 'period=1)', 'self.evaluate(tf.compat.v1.global_variables_initializer())', 'for', 'desired_value', 'in', 'range(0,', '10):', 'result', '=', 'self.evalu...
23,087
011235813/cm3
networks.py
Q_coma_checkers
Q_coma_checkers
Used by COMA for Checkers experiment.
[ "Used", "by", "COMA", "for", "Checkers", "experiment." ]
def Q_coma_checkers(s_grid, s_agents, a_others, g_n, g_others, agent_labels, t_obs, v_obs, f1=4, k1=[3, 5], f2=6, k2=[3, 3], n_actions=5, units=256): n_others = a_others.get_shape().as_list()[1] a_reshaped = tf.reshape(a_others, [-1, n_others * n_actions]) conv_s = convnet_1(s_grid, f1=f1, k1=k1, s1=[1, 1],...
['def', 'Q_coma_checkers(s_grid,', 's_agents,', 'a_others,', 'g_n,', 'g_others,', 'agent_labels,', 't_obs,', 'v_obs,', 'f1=4,', 'k1=[3,', '5],', 'f2=6,', 'k2=[3,', '3],', 'n_actions=5,', 'units=256):', 'n_others', '=', 'a_others.get_shape().as_list()[1]', 'a_reshaped', '=', 'tf.reshape(a_others,', '[-1,', 'n_others', '...
488,610
google-research/scenic
bit_resnet.py
weight_standardize
weight_standardize
Standardize (mean=0, var=1) a weight.
[ "Standardize", "(mean=0,", "var=1)", "a", "weight." ]
def weight_standardize(w: jnp.ndarray, axis: Union[Sequence[int], int], eps: float): w = w - jnp.mean(w, axis=axis, keepdims=True) w = w / jnp.sqrt(jnp.mean(jnp.square(w), axis=axis, keepdims=True) + eps) return w
['def', 'weight_standardize(w:', 'jnp.ndarray,', 'axis:', 'Union[Sequence[int],', 'int],', 'eps:', 'float):', 'w', '=', 'w', '-', 'jnp.mean(w,', 'axis=axis,', 'keepdims=True)', 'w', '=', 'w', '/', 'jnp.sqrt(jnp.mean(jnp.square(w),', 'axis=axis,', 'keepdims=True)', '+', 'eps)', 'return', 'w']
846,501
ryu-ed/SpaceInvaders_Ros
math2html.py
MultiRowFormula.addempty
addempty
Add an empty row.
[ "Add", "an", "empty", "row." ]
def addempty(self): row = self.factory.create(FormulaRow).setalignments(self.alignments) for (index, originalcell) in enumerate(self.rows[-1].contents): cell = row.createcell(index) cell.add(FormulaConstant(u'âÂ\x80Â\x85')) row.add(cell) self.addrow(row)
['def', 'addempty(self):', 'row', '=', 'self.factory.create(FormulaRow).setalignments(self.alignments)', 'for', '(index,', 'originalcell)', 'in', 'enumerate(self.rows[-1].contents):', 'cell', '=', 'row.createcell(index)', "cell.add(FormulaConstant(u'âÂ\\x80Â\\x85'))", 'row.add(cell)', 'self.addrow(row)']
395,321
Speedwagon13/CS-3600-Introduction-to--
__init__.py
Filterer.removeFilter
removeFilter
Remove the specified filter from this handler.
[ "Remove", "the", "specified", "filter", "from", "this", "handler." ]
def removeFilter(self, filter): if filter in self.filters: self.filters.remove(filter)
['def', 'removeFilter(self,', 'filter):', 'if', 'filter', 'in', 'self.filters:', 'self.filters.remove(filter)']
219,512
lbkchen/deep-learning
sdautoencoder.py
SDAutoencoder.get_all_variables
get_all_variables
Returns all trainable variables of the neural network.
[ "Returns", "all", "trainable", "variables", "of", "the", "neural", "network." ]
def get_all_variables(self, additional_vars=None): all_vars = [] for layer in self.hidden_layers: all_vars.extend([layer.get_weight_variable(), layer.get_bias_variable()]) if additional_vars: all_vars.extend(additional_vars) return all_vars
['def', 'get_all_variables(self,', 'additional_vars=None):', 'all_vars', '=', '[]', 'for', 'layer', 'in', 'self.hidden_layers:', 'all_vars.extend([layer.get_weight_variable(),', 'layer.get_bias_variable()])', 'if', 'additional_vars:', 'all_vars.extend(additional_vars)', 'return', 'all_vars']
518,697
kubeflow/pipelines
test_compile_yamls.py
ComponentCompileTest.test_bert_compile
test_bert_compile
Test bert yamls compilation.
[ "Test", "bert", "yamls", "compilation." ]
def test_bert_compile(self): @dsl.pipeline(name='Training pipeline', description='Sample training job test') def pytorch_bert(minio_endpoint=self.minio_endpoint, log_bucket=self.log_bucket, log_dir=f'tensorboard/logs/{dsl.RUN_ID_PLACEHOLDER}', mar_path=f'mar/{dsl.RUN_ID_PLACEHOLDER}/model-store', config_prop_p...
['def', 'test_bert_compile(self):', "@dsl.pipeline(name='Training", "pipeline',", "description='Sample", 'training', 'job', "test')", 'def', 'pytorch_bert(minio_endpoint=self.minio_endpoint,', 'log_bucket=self.log_bucket,', "log_dir=f'tensorboard/logs/{dsl.RUN_ID_PLACEHOLDER}',", "mar_path=f'mar/{dsl.RUN_ID_PLACEHOLDER...
779,637
s3prl/s3prl
utils.py
griffin_lim
griffin_lim
Convert linear spectrogram into waveform using Griffin-Lim.
[ "Convert", "linear", "spectrogram", "into", "waveform", "using", "Griffin-Lim." ]
def griffin_lim(spc, n_fft, n_shift, win_length, window='hann', n_iters=100): assert spc.shape[1] == n_fft // 2 + 1 spc = np.abs(spc.T) y = librosa.griffinlim(S=spc, n_iter=n_iters, hop_length=n_shift, win_length=win_length, window=window, center=True if spc.shape[1] > 1 else False) return y
['def', 'griffin_lim(spc,', 'n_fft,', 'n_shift,', 'win_length,', "window='hann',", 'n_iters=100):', 'assert', 'spc.shape[1]', '==', 'n_fft', '//', '2', '+', '1', 'spc', '=', 'np.abs(spc.T)', 'y', '=', 'librosa.griffinlim(S=spc,', 'n_iter=n_iters,', 'hop_length=n_shift,', 'win_length=win_length,', 'window=window,', 'cen...
327,396
lium-lst/nmtpy
cleanup.py
signal_handler
signal_handler
Let Python call this when SIGINT or SIGTERM caught.
[ "Let", "Python", "call", "this", "when", "SIGINT", "or", "SIGTERM", "caught." ]
def signal_handler(signum, frame): cleanup() sys.exit(0)
['def', 'signal_handler(signum,', 'frame):', 'cleanup()', 'sys.exit(0)']
294,426
Ruturaj123/Flowchart-Detection
array_ops.py
broadcast_dynamic_shape
broadcast_dynamic_shape
Returns the broadcasted dynamic shape between `shape_x` and `shape_y`.
[ "Returns", "the", "broadcasted", "dynamic", "shape", "between", "`shape_x`", "and", "`shape_y`." ]
def broadcast_dynamic_shape(shape_x, shape_y): return gen_array_ops._broadcast_args(shape_x, shape_y)
['def', 'broadcast_dynamic_shape(shape_x,', 'shape_y):', 'return', 'gen_array_ops._broadcast_args(shape_x,', 'shape_y)']
605,710
paulorauber/rl
utils.py
check_no_exclusive_keys
check_no_exclusive_keys
Given a TensorSpec, returns true if there are no exclusive keys.
[ "Given", "a", "TensorSpec,", "returns", "true", "if", "there", "are", "no", "exclusive", "keys." ]
def check_no_exclusive_keys(spec: TensorSpec, recurse: bool=True): if isinstance(spec, LazyStackedCompositeSpec): keys = set(spec.keys()) for inner_td in spec._specs: if recurse and (not check_no_exclusive_keys(inner_td)): return False if set(inner_td.keys()) ...
['def', 'check_no_exclusive_keys(spec:', 'TensorSpec,', 'recurse:', 'bool=True):', 'if', 'isinstance(spec,', 'LazyStackedCompositeSpec):', 'keys', '=', 'set(spec.keys())', 'for', 'inner_td', 'in', 'spec._specs:', 'if', 'recurse', 'and', '(not', 'check_no_exclusive_keys(inner_td)):', 'return', 'False', 'if', 'set(inner_...
858,761
lebrice/Sequoia
environment_test.py
TestContinualSLTestEnvironment.test_gym_interaction_produces_results
test_gym_interaction_produces_results
TODO: Test that when iterating through the env as a dataloader and sending actions produces results.
[ "TODO:", "Test", "that", "when", "iterating", "through", "the", "env", "as", "a", "dataloader", "and", "sending", "actions", "produces", "results." ]
def test_gym_interaction_produces_results(self, no_rewards: bool, base_env: PassiveEnvironment, tmp_path: Path, config: Config): env = self.TestEnvironment(base_env, directory=tmp_path, step_limit=100 // base_env.batch_size, no_rewards=no_rewards) env.config = config done = False obs = env.reset() s...
['def', 'test_gym_interaction_produces_results(self,', 'no_rewards:', 'bool,', 'base_env:', 'PassiveEnvironment,', 'tmp_path:', 'Path,', 'config:', 'Config):', 'env', '=', 'self.TestEnvironment(base_env,', 'directory=tmp_path,', 'step_limit=100', '//', 'base_env.batch_size,', 'no_rewards=no_rewards)', 'env.config', '='...
349,670
deepmind/dm_env
specs.py
StringArray.validate
validate
Checks if value conforms to this spec.
[ "Checks", "if", "value", "conforms", "to", "this", "spec." ]
def validate(self, value): value = np.asarray(value, dtype=object) if value.shape != self.shape: self._fail_validation(_INVALID_SHAPE, self.shape, value.shape) for item in value.flat: if not isinstance(item, self.string_type): self._fail_validation(_INVALID_ELEMENT_TYPE, self.str...
['def', 'validate(self,', 'value):', 'value', '=', 'np.asarray(value,', 'dtype=object)', 'if', 'value.shape', '!=', 'self.shape:', 'self._fail_validation(_INVALID_SHAPE,', 'self.shape,', 'value.shape)', 'for', 'item', 'in', 'value.flat:', 'if', 'not', 'isinstance(item,', 'self.string_type):', 'self._fail_validation(_IN...
166,716
rohanpsingh/LearningHumanoidWalking
robot_interface.py
RobotInterface.get_robot_linmom
get_robot_linmom
Returns linear momentum of robot in world coordinates.
[ "Returns", "linear", "momentum", "of", "robot", "in", "world", "coordinates." ]
def get_robot_linmom(self): sensor_names = [mujoco.mj_id2name(self.model, mujoco.mjtObj.mjOBJ_SENSOR, i) for i in range(self.model.nsensor)] if 'subtreelinvel' not in sensor_names: raise Exception('subtree_linvel sensor not attached.') linvel = self.data.subtree_linvel[1].copy() total_mass = sel...
['def', 'get_robot_linmom(self):', 'sensor_names', '=', '[mujoco.mj_id2name(self.model,', 'mujoco.mjtObj.mjOBJ_SENSOR,', 'i)', 'for', 'i', 'in', 'range(self.model.nsensor)]', 'if', "'subtreelinvel'", 'not', 'in', 'sensor_names:', 'raise', "Exception('subtree_linvel", 'sensor', 'not', "attached.')", 'linvel', '=', 'self...
588,270
QData/deepWordBug
cookies.py
get_cookie_header
get_cookie_header
Produce an appropriate Cookie header string to be sent with `request`, or None.
[ "Produce", "an", "appropriate", "Cookie", "header", "string", "to", "be", "sent", "with", "`request`,", "or", "None." ]
def get_cookie_header(jar, request): r = MockRequest(request) jar.add_cookie_header(r) return r.get_new_headers().get('Cookie')
['def', 'get_cookie_header(jar,', 'request):', 'r', '=', 'MockRequest(request)', 'jar.add_cookie_header(r)', 'return', "r.get_new_headers().get('Cookie')"]
541,445
cjrd/self-supervised-pretraining
chart.py
extract_data_for_mask_loss_from_matches
extract_data_for_mask_loss_from_matches
Extract data for mask loss from instances that contain matched GT and estimated bounding boxes.
[ "Extract", "data", "for", "mask", "loss", "from", "instances", "that", "contain", "matched", "GT", "and", "estimated", "bounding", "boxes." ]
def extract_data_for_mask_loss_from_matches(proposals_targets: Iterable[Instances], estimated_segm: torch.Tensor) -> DataForMaskLoss: data = DataForMaskLoss() masks_gt = [] offset = 0 assert estimated_segm.shape[2] == estimated_segm.shape[3], f'Expected estimated segmentation to have a square shape, but...
['def', 'extract_data_for_mask_loss_from_matches(proposals_targets:', 'Iterable[Instances],', 'estimated_segm:', 'torch.Tensor)', '->', 'DataForMaskLoss:', 'data', '=', 'DataForMaskLoss()', 'masks_gt', '=', '[]', 'offset', '=', '0', 'assert', 'estimated_segm.shape[2]', '==', 'estimated_segm.shape[3],', "f'Expected", 'e...
843,712
alvertogit/bigdata_docker
functions.py
example_function
example_function
Function example that process input data and prints a number.
[ "Function", "example", "that", "process", "input", "data", "and", "prints", "a", "number." ]
def example_function(*args): if len(args) < 1: raise ValueError('Error: required arguments <number>') try: int(args[0]) except ValueError: print('Error: args[0] is not an integer') sys.exit(1) number = int(args[0]) print('Number: {0}'.format(number))
['def', 'example_function(*args):', 'if', 'len(args)', '<', '1:', 'raise', "ValueError('Error:", 'required', 'arguments', "<number>')", 'try:', 'int(args[0])', 'except', 'ValueError:', "print('Error:", 'args[0]', 'is', 'not', 'an', "integer')", 'sys.exit(1)', 'number', '=', 'int(args[0])', "print('Number:", "{0}'.forma...
107,656
openml-labs/gama
test_utilities_generic_paretofront.py
test_pareto_update_unique
test_pareto_update_unique
Creating Pareto front by updating one by one.
[ "Creating", "Pareto", "front", "by", "updating", "one", "by", "one." ]
def test_pareto_update_unique(): list_ = [(1, 2, 3), (3, 2, 1), (0, 5, 0)] pf = ParetoFront() for i in range(len(list_)): pf.update(list_[i]) assert list(pf) == list_[:i + 1]
['def', 'test_pareto_update_unique():', 'list_', '=', '[(1,', '2,', '3),', '(3,', '2,', '1),', '(0,', '5,', '0)]', 'pf', '=', 'ParetoFront()', 'for', 'i', 'in', 'range(len(list_)):', 'pf.update(list_[i])', 'assert', 'list(pf)', '==', 'list_[:i', '+', '1]']
566,257
tomcatmanager/tomcatmanager
mock_server_ssl.py
MockRequestHandlerSSL.get_ssl_connector_ciphers
get_ssl_connector_ciphers
Send the SSL ciphers.
[ "Send", "the", "SSL", "ciphers." ]
def get_ssl_connector_ciphers(self): self.send_text('OK - Connector / SSL Cipher information\nConnector[HTTP/1.1-8080]\n SSL is not enabled for this connector')
['def', 'get_ssl_connector_ciphers(self):', "self.send_text('OK", '-', 'Connector', '/', 'SSL', 'Cipher', 'information\\nConnector[HTTP/1.1-8080]\\n', 'SSL', 'is', 'not', 'enabled', 'for', 'this', "connector')"]
355,664
microsoft/InnerEye-DeepLearning
test_config_helpers.py
test_config_str
test_config_str
Check if dataframe fields are omitted from the string conversion of a config object.
[ "Check", "if", "dataframe", "fields", "are", "omitted", "from", "the", "string", "conversion", "of", "a", "config", "object." ]
def test_config_str() -> None: config = DeepLearningConfig(should_validate=False) df = DataFrame(columns=['foobar'], data=[1.0, 2.0]) config.dataset_data_frame = df s = str(config) assert 'foobar' not in s, f'Incorrect output: {s}'
['def', 'test_config_str()', '->', 'None:', 'config', '=', 'DeepLearningConfig(should_validate=False)', 'df', '=', "DataFrame(columns=['foobar'],", 'data=[1.0,', '2.0])', 'config.dataset_data_frame', '=', 'df', 's', '=', 'str(config)', 'assert', "'foobar'", 'not', 'in', 's,', "f'Incorrect", 'output:', "{s}'"]
613,576