blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d9d32e8144b7c8730f5412f1bd5dfcc533e01dcf | [
"super(EmbeddingLookup, self).__init__()\nself.embedding_dim = embed_dim\nself.vocab_size = vocab_size\nself.use_one_hot_embeddings = use_one_hot_embeddings\ninit_weight = np.random.normal(0, embed_dim ** (-0.5), size=[vocab_size, embed_dim]).astype(np.float32)\ninit_weight[0, :] = 0\nself.embedding_table = Paramet... | <|body_start_0|>
super(EmbeddingLookup, self).__init__()
self.embedding_dim = embed_dim
self.vocab_size = vocab_size
self.use_one_hot_embeddings = use_one_hot_embeddings
init_weight = np.random.normal(0, embed_dim ** (-0.5), size=[vocab_size, embed_dim]).astype(np.float32)
... | Embeddings lookup table with a fixed dictionary and size. | EmbeddingLookup | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmbeddingLookup:
"""Embeddings lookup table with a fixed dictionary and size."""
def __init__(self, vocab_size, embed_dim, use_one_hot_embeddings=False):
"""Embeddings lookup table with a fixed dictionary and size. Args: vocab_size (int): Size of the dictionary of embeddings. embed_d... | stack_v2_sparse_classes_75kplus_train_074300 | 3,125 | permissive | [
{
"docstring": "Embeddings lookup table with a fixed dictionary and size. Args: vocab_size (int): Size of the dictionary of embeddings. embed_dim (int): The size of word embedding. use_one_hot_embeddings (bool): Whether use one-hot embedding. Default: False.",
"name": "__init__",
"signature": "def __ini... | 2 | stack_v2_sparse_classes_30k_val_000110 | Implement the Python class `EmbeddingLookup` described below.
Class description:
Embeddings lookup table with a fixed dictionary and size.
Method signatures and docstrings:
- def __init__(self, vocab_size, embed_dim, use_one_hot_embeddings=False): Embeddings lookup table with a fixed dictionary and size. Args: vocab_... | Implement the Python class `EmbeddingLookup` described below.
Class description:
Embeddings lookup table with a fixed dictionary and size.
Method signatures and docstrings:
- def __init__(self, vocab_size, embed_dim, use_one_hot_embeddings=False): Embeddings lookup table with a fixed dictionary and size. Args: vocab_... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class EmbeddingLookup:
"""Embeddings lookup table with a fixed dictionary and size."""
def __init__(self, vocab_size, embed_dim, use_one_hot_embeddings=False):
"""Embeddings lookup table with a fixed dictionary and size. Args: vocab_size (int): Size of the dictionary of embeddings. embed_d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EmbeddingLookup:
"""Embeddings lookup table with a fixed dictionary and size."""
def __init__(self, vocab_size, embed_dim, use_one_hot_embeddings=False):
"""Embeddings lookup table with a fixed dictionary and size. Args: vocab_size (int): Size of the dictionary of embeddings. embed_dim (int): The... | the_stack_v2_python_sparse | research/nlp/mass/src/transformer/embedding.py | mindspore-ai/models | train | 301 |
9ac30fb308dfb7a8baf4374c2260e35bc0e2e3f8 | [
"self.id_usuario = id_usuario\nself.password = password\nself.session = session",
"usuario = self.session.query(Usuario).filter(Usuario.id_usuario == self.id_usuario, Usuario.password == self.password).first()\nif usuario:\n return usuario.role\nelse:\n return None"
] | <|body_start_0|>
self.id_usuario = id_usuario
self.password = password
self.session = session
<|end_body_0|>
<|body_start_1|>
usuario = self.session.query(Usuario).filter(Usuario.id_usuario == self.id_usuario, Usuario.password == self.password).first()
if usuario:
re... | Esta clase se encarga del logeo de los usuarios que utilizan el sistema | Login | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Login:
"""Esta clase se encarga del logeo de los usuarios que utilizan el sistema"""
def __init__(self, id_usuario, password, session):
"""Constructor de la clase Login :param id_usuario: :param password: :param session: :return:"""
<|body_0|>
def loginValido(self):
... | stack_v2_sparse_classes_75kplus_train_074301 | 1,005 | no_license | [
{
"docstring": "Constructor de la clase Login :param id_usuario: :param password: :param session: :return:",
"name": "__init__",
"signature": "def __init__(self, id_usuario, password, session)"
},
{
"docstring": "Esta funcion retorna el rol correspondiente al usuario (si existe) y no devuelve No... | 2 | null | Implement the Python class `Login` described below.
Class description:
Esta clase se encarga del logeo de los usuarios que utilizan el sistema
Method signatures and docstrings:
- def __init__(self, id_usuario, password, session): Constructor de la clase Login :param id_usuario: :param password: :param session: :retur... | Implement the Python class `Login` described below.
Class description:
Esta clase se encarga del logeo de los usuarios que utilizan el sistema
Method signatures and docstrings:
- def __init__(self, id_usuario, password, session): Constructor de la clase Login :param id_usuario: :param password: :param session: :retur... | dd054271350139e3e7af7ee9f363d3d453a7ef24 | <|skeleton|>
class Login:
"""Esta clase se encarga del logeo de los usuarios que utilizan el sistema"""
def __init__(self, id_usuario, password, session):
"""Constructor de la clase Login :param id_usuario: :param password: :param session: :return:"""
<|body_0|>
def loginValido(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Login:
"""Esta clase se encarga del logeo de los usuarios que utilizan el sistema"""
def __init__(self, id_usuario, password, session):
"""Constructor de la clase Login :param id_usuario: :param password: :param session: :return:"""
self.id_usuario = id_usuario
self.password = pas... | the_stack_v2_python_sparse | login.py | leaLuque/FarmaciaCrisol | train | 0 |
8b0df7d20f56707c689aee8dd639cdc3bbdb362e | [
"super().__init__()\nself.title = title\nself.url = url\nself.pic_url = pic_url",
"if is_not_null_and_blank_str(self.pic_url) and is_not_null_and_blank_str(self.title) and is_not_null_and_blank_str(self.url):\n data = {'title': self.title, 'messageURL': self.url, 'picURL': self.pic_url}\n return data\nelif ... | <|body_start_0|>
super().__init__()
self.title = title
self.url = url
self.pic_url = pic_url
<|end_body_0|>
<|body_start_1|>
if is_not_null_and_blank_str(self.pic_url) and is_not_null_and_blank_str(self.title) and is_not_null_and_blank_str(self.url):
data = {'title':... | ActionCard和FeedCard消息类型中的子控件 | CardItem | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CardItem:
"""ActionCard和FeedCard消息类型中的子控件"""
def __init__(self, title, url, pic_url=None):
"""CardItem初始化 @param title: 子控件名称 @param url: 点击子控件时触发的URL @param pic_url: FeedCard的图片地址,ActionCard时不需要,故默认为None"""
<|body_0|>
def get_data(self):
"""获取CardItem子控件数据(字典) @... | stack_v2_sparse_classes_75kplus_train_074302 | 14,486 | permissive | [
{
"docstring": "CardItem初始化 @param title: 子控件名称 @param url: 点击子控件时触发的URL @param pic_url: FeedCard的图片地址,ActionCard时不需要,故默认为None",
"name": "__init__",
"signature": "def __init__(self, title, url, pic_url=None)"
},
{
"docstring": "获取CardItem子控件数据(字典) @return: 子控件的数据",
"name": "get_data",
"s... | 2 | null | Implement the Python class `CardItem` described below.
Class description:
ActionCard和FeedCard消息类型中的子控件
Method signatures and docstrings:
- def __init__(self, title, url, pic_url=None): CardItem初始化 @param title: 子控件名称 @param url: 点击子控件时触发的URL @param pic_url: FeedCard的图片地址,ActionCard时不需要,故默认为None
- def get_data(self): ... | Implement the Python class `CardItem` described below.
Class description:
ActionCard和FeedCard消息类型中的子控件
Method signatures and docstrings:
- def __init__(self, title, url, pic_url=None): CardItem初始化 @param title: 子控件名称 @param url: 点击子控件时触发的URL @param pic_url: FeedCard的图片地址,ActionCard时不需要,故默认为None
- def get_data(self): ... | 4ba3682468fdd5308e964dc0097860edf8c7da15 | <|skeleton|>
class CardItem:
"""ActionCard和FeedCard消息类型中的子控件"""
def __init__(self, title, url, pic_url=None):
"""CardItem初始化 @param title: 子控件名称 @param url: 点击子控件时触发的URL @param pic_url: FeedCard的图片地址,ActionCard时不需要,故默认为None"""
<|body_0|>
def get_data(self):
"""获取CardItem子控件数据(字典) @... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CardItem:
"""ActionCard和FeedCard消息类型中的子控件"""
def __init__(self, title, url, pic_url=None):
"""CardItem初始化 @param title: 子控件名称 @param url: 点击子控件时触发的URL @param pic_url: FeedCard的图片地址,ActionCard时不需要,故默认为None"""
super().__init__()
self.title = title
self.url = url
self... | the_stack_v2_python_sparse | plugins/dingtalk/dingtalkchatbot/chatbot.py | alerta/alerta-contrib | train | 125 |
056434c2ff18f2bc2fa5425d74609a3bae8fc856 | [
"self.writer = writer\nself.optimizer = optimizer\nself.factor = factor\nself.patience = patience\nself.best = math.inf\nself.num_bad_epochs = 0",
"if self.best > loss:\n self.best = loss\n self.num_bad_epochs = 0\nelse:\n self.num_bad_epochs += 1\nif self.num_bad_epochs > self.patience:\n params = se... | <|body_start_0|>
self.writer = writer
self.optimizer = optimizer
self.factor = factor
self.patience = patience
self.best = math.inf
self.num_bad_epochs = 0
<|end_body_0|>
<|body_start_1|>
if self.best > loss:
self.best = loss
self.num_bad_... | Reduce learning rate when loss has stopped improving. Attributes: writer = [MetricWriter] TensorBoard writer of learning rate optimizer = [Optimizer] optimizer containing the learning rate factor = [float] factor by which the learning rate is reduced patience = [int] number of epochs with no improvement after which the... | ReduceLROnPlateau | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReduceLROnPlateau:
"""Reduce learning rate when loss has stopped improving. Attributes: writer = [MetricWriter] TensorBoard writer of learning rate optimizer = [Optimizer] optimizer containing the learning rate factor = [float] factor by which the learning rate is reduced patience = [int] number ... | stack_v2_sparse_classes_75kplus_train_074303 | 7,467 | no_license | [
{
"docstring": "Initialize the learning rate scheduler. Args: writer = [MetricWriter] TensorBoard writer of learning rate optimizer = [Optimizer] optimizer containing the learning rate factor = [float] factor by which the learning rate is reduced patience = [int] number of epochs with no improvement after which... | 2 | stack_v2_sparse_classes_30k_train_050052 | Implement the Python class `ReduceLROnPlateau` described below.
Class description:
Reduce learning rate when loss has stopped improving. Attributes: writer = [MetricWriter] TensorBoard writer of learning rate optimizer = [Optimizer] optimizer containing the learning rate factor = [float] factor by which the learning r... | Implement the Python class `ReduceLROnPlateau` described below.
Class description:
Reduce learning rate when loss has stopped improving. Attributes: writer = [MetricWriter] TensorBoard writer of learning rate optimizer = [Optimizer] optimizer containing the learning rate factor = [float] factor by which the learning r... | 1514ad396a22dcdc3b0fe9b17974cd384bac97c2 | <|skeleton|>
class ReduceLROnPlateau:
"""Reduce learning rate when loss has stopped improving. Attributes: writer = [MetricWriter] TensorBoard writer of learning rate optimizer = [Optimizer] optimizer containing the learning rate factor = [float] factor by which the learning rate is reduced patience = [int] number ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReduceLROnPlateau:
"""Reduce learning rate when loss has stopped improving. Attributes: writer = [MetricWriter] TensorBoard writer of learning rate optimizer = [Optimizer] optimizer containing the learning rate factor = [float] factor by which the learning rate is reduced patience = [int] number of epochs wit... | the_stack_v2_python_sparse | optim.py | nnistelrooij/MLiP-2020 | train | 0 |
ea2c69a4ff08274eb8599fc2bdd30b9a535cea2a | [
"Parametre.__init__(self, 'affecter', 'affect')\nself.schema = '<nom_matelot>'\nself.tronquer = True\nself.aide_courte = \"change l'affectation d'un matelot\"\nself.aide_longue = \"Cette commande demande à un matelot de changer d'affectation. Le matelot précisé en paramètre voit la salle où vous vous trouvez deveni... | <|body_start_0|>
Parametre.__init__(self, 'affecter', 'affect')
self.schema = '<nom_matelot>'
self.tronquer = True
self.aide_courte = "change l'affectation d'un matelot"
self.aide_longue = "Cette commande demande à un matelot de changer d'affectation. Le matelot précisé en paramè... | Commande 'matelot affecter'. | PrmAffecter | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmAffecter:
"""Commande 'matelot affecter'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Paramet... | stack_v2_sparse_classes_75kplus_train_074304 | 4,078 | permissive | [
{
"docstring": "Constructeur du paramètre",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Interprétation du paramètre",
"name": "interpreter",
"signature": "def interpreter(self, personnage, dic_masques)"
}
] | 2 | stack_v2_sparse_classes_30k_train_036932 | Implement the Python class `PrmAffecter` described below.
Class description:
Commande 'matelot affecter'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre | Implement the Python class `PrmAffecter` described below.
Class description:
Commande 'matelot affecter'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre
<|skeleton|>
class PrmAffecter:
"""Commande 'ma... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmAffecter:
"""Commande 'matelot affecter'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PrmAffecter:
"""Commande 'matelot affecter'."""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, 'affecter', 'affect')
self.schema = '<nom_matelot>'
self.tronquer = True
self.aide_courte = "change l'affectation d'un matelot"
self... | the_stack_v2_python_sparse | src/secondaires/navigation/commandes/matelot/affecter.py | vincent-lg/tsunami | train | 5 |
f268a944b2c05524456aed2f27bb804341611966 | [
"self.cb = cb\nself.configeditor = configeditor\nself.store = gtk.ListStore(str, int)\ngtk.TreeView.__init__(self, self.store)\nrenderer = gtk.CellRendererText()\ncolumn = gtk.TreeViewColumn('Name', renderer, markup=0)\nself.append_column(column)\nself.set_headers_visible(False)\nself.connect('cursor-changed', self... | <|body_start_0|>
self.cb = cb
self.configeditor = configeditor
self.store = gtk.ListStore(str, int)
gtk.TreeView.__init__(self, self.store)
renderer = gtk.CellRendererText()
column = gtk.TreeViewColumn('Name', renderer, markup=0)
self.append_column(column)
... | A treeview control for switching a notebook's tabs. | ListTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListTree:
"""A treeview control for switching a notebook's tabs."""
def __init__(self, cb, configeditor):
"""Constructor. @param cb: An instance of the application class. @type cb: pida.main.Application @param configeditor: The configuration editor that the list is used for. @type co... | stack_v2_sparse_classes_75kplus_train_074305 | 15,563 | no_license | [
{
"docstring": "Constructor. @param cb: An instance of the application class. @type cb: pida.main.Application @param configeditor: The configuration editor that the list is used for. @type configeditor: pida.config.ConfigEditor",
"name": "__init__",
"signature": "def __init__(self, cb, configeditor)"
... | 3 | stack_v2_sparse_classes_30k_test_002707 | Implement the Python class `ListTree` described below.
Class description:
A treeview control for switching a notebook's tabs.
Method signatures and docstrings:
- def __init__(self, cb, configeditor): Constructor. @param cb: An instance of the application class. @type cb: pida.main.Application @param configeditor: The... | Implement the Python class `ListTree` described below.
Class description:
A treeview control for switching a notebook's tabs.
Method signatures and docstrings:
- def __init__(self, cb, configeditor): Constructor. @param cb: An instance of the application class. @type cb: pida.main.Application @param configeditor: The... | 739147ed21a23cab23c2bba98f1c54108f8c2516 | <|skeleton|>
class ListTree:
"""A treeview control for switching a notebook's tabs."""
def __init__(self, cb, configeditor):
"""Constructor. @param cb: An instance of the application class. @type cb: pida.main.Application @param configeditor: The configuration editor that the list is used for. @type co... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ListTree:
"""A treeview control for switching a notebook's tabs."""
def __init__(self, cb, configeditor):
"""Constructor. @param cb: An instance of the application class. @type cb: pida.main.Application @param configeditor: The configuration editor that the list is used for. @type configeditor: p... | the_stack_v2_python_sparse | tags/release-0.2.1/src/configuration/config.py | BackupTheBerlios/pida-svn | train | 1 |
86dc6f0f306a1b21dddce75011bf4840a79c6634 | [
"self.screen_width = 800\nself.screen_height = 600\nself.bg_color = (0, 64, 128)\nself.ship_limit = 2\nself.ship_speed_factor = 2\nself.bullet_width = 3\nself.bullet_height = 15\nself.bullet_speed_factor = 1\nself.bullet_color = (60, 60, 60)\nself.bullets_allowed = 50\nself.alien_speed_factor = 1\nself.fleet_drop_s... | <|body_start_0|>
self.screen_width = 800
self.screen_height = 600
self.bg_color = (0, 64, 128)
self.ship_limit = 2
self.ship_speed_factor = 2
self.bullet_width = 3
self.bullet_height = 15
self.bullet_speed_factor = 1
self.bullet_color = (60, 60, 60... | 存储《外星人入侵》的所有设置的类 | Settings | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Settings:
"""存储《外星人入侵》的所有设置的类"""
def __init__(self):
"""初始化游戏的设置"""
<|body_0|>
def initialize_dynamic_settings(self):
"""初始化随游戏进行而变化的设置"""
<|body_1|>
def increase_speed(self):
"""提高速度设置"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_75kplus_train_074306 | 2,491 | no_license | [
{
"docstring": "初始化游戏的设置",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "初始化随游戏进行而变化的设置",
"name": "initialize_dynamic_settings",
"signature": "def initialize_dynamic_settings(self)"
},
{
"docstring": "提高速度设置",
"name": "increase_speed",
"signatur... | 3 | stack_v2_sparse_classes_30k_val_002985 | Implement the Python class `Settings` described below.
Class description:
存储《外星人入侵》的所有设置的类
Method signatures and docstrings:
- def __init__(self): 初始化游戏的设置
- def initialize_dynamic_settings(self): 初始化随游戏进行而变化的设置
- def increase_speed(self): 提高速度设置 | Implement the Python class `Settings` described below.
Class description:
存储《外星人入侵》的所有设置的类
Method signatures and docstrings:
- def __init__(self): 初始化游戏的设置
- def initialize_dynamic_settings(self): 初始化随游戏进行而变化的设置
- def increase_speed(self): 提高速度设置
<|skeleton|>
class Settings:
"""存储《外星人入侵》的所有设置的类"""
def __ini... | e4b93ac5eb370934109549a5612448e195c6c5ef | <|skeleton|>
class Settings:
"""存储《外星人入侵》的所有设置的类"""
def __init__(self):
"""初始化游戏的设置"""
<|body_0|>
def initialize_dynamic_settings(self):
"""初始化随游戏进行而变化的设置"""
<|body_1|>
def increase_speed(self):
"""提高速度设置"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Settings:
"""存储《外星人入侵》的所有设置的类"""
def __init__(self):
"""初始化游戏的设置"""
self.screen_width = 800
self.screen_height = 600
self.bg_color = (0, 64, 128)
self.ship_limit = 2
self.ship_speed_factor = 2
self.bullet_width = 3
self.bullet_height = 15
... | the_stack_v2_python_sparse | chapter12/settings.py | hongyunshui/learn_python | train | 0 |
6b44378f47e655cdd2e2de840859fccd852eb3df | [
"self._index_name = index_name\nself._data_type = data_type\nfor k, v in self._get_config().items():\n setattr(self, k, v)",
"config_dict = self.CONFIG_REGISTRY.get(self._data_type)\nif not config_dict:\n config_dict = self.DEFAULT_CONFIG\n config_dict['query'] = 'data_type:\"{0}\"'.format(self._data_typ... | <|body_start_0|>
self._index_name = index_name
self._data_type = data_type
for k, v in self._get_config().items():
setattr(self, k, v)
<|end_body_0|>
<|body_start_1|>
config_dict = self.CONFIG_REGISTRY.get(self._data_type)
if not config_dict:
config_dict ... | Configuration for a similarity scorer. | SimilarityScorerConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimilarityScorerConfig:
"""Configuration for a similarity scorer."""
def __init__(self, index_name, data_type):
"""Initializes a similarity scorer config. Args: index_name: OpenSearch index name. data_type: Name of the data_type."""
<|body_0|>
def _get_config(self):
... | stack_v2_sparse_classes_75kplus_train_074307 | 5,064 | permissive | [
{
"docstring": "Initializes a similarity scorer config. Args: index_name: OpenSearch index name. data_type: Name of the data_type.",
"name": "__init__",
"signature": "def __init__(self, index_name, data_type)"
},
{
"docstring": "Get config for supplied data_type. Returns: Dictionary with configu... | 2 | stack_v2_sparse_classes_30k_train_048213 | Implement the Python class `SimilarityScorerConfig` described below.
Class description:
Configuration for a similarity scorer.
Method signatures and docstrings:
- def __init__(self, index_name, data_type): Initializes a similarity scorer config. Args: index_name: OpenSearch index name. data_type: Name of the data_typ... | Implement the Python class `SimilarityScorerConfig` described below.
Class description:
Configuration for a similarity scorer.
Method signatures and docstrings:
- def __init__(self, index_name, data_type): Initializes a similarity scorer config. Args: index_name: OpenSearch index name. data_type: Name of the data_typ... | 24f471b58ca4a87cb053961b5f05c07a544ca7b8 | <|skeleton|>
class SimilarityScorerConfig:
"""Configuration for a similarity scorer."""
def __init__(self, index_name, data_type):
"""Initializes a similarity scorer config. Args: index_name: OpenSearch index name. data_type: Name of the data_type."""
<|body_0|>
def _get_config(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SimilarityScorerConfig:
"""Configuration for a similarity scorer."""
def __init__(self, index_name, data_type):
"""Initializes a similarity scorer config. Args: index_name: OpenSearch index name. data_type: Name of the data_type."""
self._index_name = index_name
self._data_type = ... | the_stack_v2_python_sparse | timesketch/lib/analyzers/similarity_scorer.py | google/timesketch | train | 2,263 |
b62173335183be65b5f41cc1779a5b84b3e2cbfb | [
"super(QRDQN, self).__init__()\nobs_shape, action_shape = (squeeze(obs_shape), squeeze(action_shape))\nif head_hidden_size is None:\n head_hidden_size = encoder_hidden_size_list[-1]\nif isinstance(obs_shape, int) or len(obs_shape) == 1:\n self.encoder = FCEncoder(obs_shape, encoder_hidden_size_list, activatio... | <|body_start_0|>
super(QRDQN, self).__init__()
obs_shape, action_shape = (squeeze(obs_shape), squeeze(action_shape))
if head_hidden_size is None:
head_hidden_size = encoder_hidden_size_list[-1]
if isinstance(obs_shape, int) or len(obs_shape) == 1:
self.encoder = F... | QRDQN | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QRDQN:
def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: Optional[int]=None, head_layer_num: int=1, num_quantiles: int=32, activation: Optional[nn.Module]=nn.ReLU(), norm_type: ... | stack_v2_sparse_classes_75kplus_train_074308 | 30,380 | permissive | [
{
"docstring": "Overview: Init the QRDQN Model according to input arguments. Arguments: - obs_shape (:obj:`Union[int, SequenceType]`): Observation's space. - action_shape (:obj:`Union[int, SequenceType]`): Action's space. - encoder_hidden_size_list (:obj:`SequenceType`): Collection of ``hidden_size`` to pass to... | 2 | stack_v2_sparse_classes_30k_train_025430 | Implement the Python class `QRDQN` described below.
Class description:
Implement the QRDQN class.
Method signatures and docstrings:
- def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: Optional[int]=N... | Implement the Python class `QRDQN` described below.
Class description:
Implement the QRDQN class.
Method signatures and docstrings:
- def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: Optional[int]=N... | eb483fa6e46602d58c8e7d2ca1e566adca28e703 | <|skeleton|>
class QRDQN:
def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: Optional[int]=None, head_layer_num: int=1, num_quantiles: int=32, activation: Optional[nn.Module]=nn.ReLU(), norm_type: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QRDQN:
def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: Optional[int]=None, head_layer_num: int=1, num_quantiles: int=32, activation: Optional[nn.Module]=nn.ReLU(), norm_type: Optional[str]=... | the_stack_v2_python_sparse | ding/model/template/q_learning.py | shengxuesun/DI-engine | train | 1 | |
3ae15b629e43458c0ee4f81804b284b7f08cb9ca | [
"dp = [0] + [float('inf')] * amount\nfor coin in coins:\n for i in range(coin, amount + 1):\n dp[i] = min(dp[i], dp[i - coin] + 1)\nreturn dp[-1] if dp[-1] < float('inf') else -1",
"if not amount:\n return 0\nqueue = deque([(0, 0)])\nvisited = [True] + [False] * amount\nwhile queue:\n totalCoins, ... | <|body_start_0|>
dp = [0] + [float('inf')] * amount
for coin in coins:
for i in range(coin, amount + 1):
dp[i] = min(dp[i], dp[i - coin] + 1)
return dp[-1] if dp[-1] < float('inf') else -1
<|end_body_0|>
<|body_start_1|>
if not amount:
return 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
"""dp[n] stands for the minimum coins we need in order to be summed as n. Then dp[n] = min(dp[n - coins[0]], ..., dp[n - coins[-1]]) + 1. when n = 0, dp[0] = 0 as no coins can form 0 amount."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_074309 | 1,671 | no_license | [
{
"docstring": "dp[n] stands for the minimum coins we need in order to be summed as n. Then dp[n] = min(dp[n - coins[0]], ..., dp[n - coins[-1]]) + 1. when n = 0, dp[0] = 0 as no coins can form 0 amount.",
"name": "coinChange",
"signature": "def coinChange(self, coins: List[int], amount: int) -> int"
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coinChange(self, coins: List[int], amount: int) -> int: dp[n] stands for the minimum coins we need in order to be summed as n. Then dp[n] = min(dp[n - coins[0]], ..., dp[n - ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coinChange(self, coins: List[int], amount: int) -> int: dp[n] stands for the minimum coins we need in order to be summed as n. Then dp[n] = min(dp[n - coins[0]], ..., dp[n - ... | edb870f83f0c4568cce0cacec04ee70cf6b545bf | <|skeleton|>
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
"""dp[n] stands for the minimum coins we need in order to be summed as n. Then dp[n] = min(dp[n - coins[0]], ..., dp[n - coins[-1]]) + 1. when n = 0, dp[0] = 0 as no coins can form 0 amount."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
"""dp[n] stands for the minimum coins we need in order to be summed as n. Then dp[n] = min(dp[n - coins[0]], ..., dp[n - coins[-1]]) + 1. when n = 0, dp[0] = 0 as no coins can form 0 amount."""
dp = [0] + [float('inf')] * am... | the_stack_v2_python_sparse | 2020/coin_change.py | eronekogin/leetcode | train | 0 | |
7ed3280b64944c8ae65bf69e47f47bf6852656a6 | [
"obj.save()\ngenerate_static_list_search_html.delay('list.html')\ngenerate_static_list_search_html.delay('search.html')",
"obj.delete()\ngenerate_static_list_search_html.delay('list.html')\ngenerate_static_list_search_html.delay('search.html')"
] | <|body_start_0|>
obj.save()
generate_static_list_search_html.delay('list.html')
generate_static_list_search_html.delay('search.html')
<|end_body_0|>
<|body_start_1|>
obj.delete()
generate_static_list_search_html.delay('list.html')
generate_static_list_search_html.delay('... | 自定义管理admin站点 -- 商品类别 | GoodsCategoryAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoodsCategoryAdmin:
"""自定义管理admin站点 -- 商品类别"""
def save_model(self, request, obj, form, change):
"""admin后台新增或修改了数据时调用"""
<|body_0|>
def delete_model(self, request, obj):
"""admin后台删除了数据时调用"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
obj.sav... | stack_v2_sparse_classes_75kplus_train_074310 | 3,322 | no_license | [
{
"docstring": "admin后台新增或修改了数据时调用",
"name": "save_model",
"signature": "def save_model(self, request, obj, form, change)"
},
{
"docstring": "admin后台删除了数据时调用",
"name": "delete_model",
"signature": "def delete_model(self, request, obj)"
}
] | 2 | stack_v2_sparse_classes_30k_train_040562 | Implement the Python class `GoodsCategoryAdmin` described below.
Class description:
自定义管理admin站点 -- 商品类别
Method signatures and docstrings:
- def save_model(self, request, obj, form, change): admin后台新增或修改了数据时调用
- def delete_model(self, request, obj): admin后台删除了数据时调用 | Implement the Python class `GoodsCategoryAdmin` described below.
Class description:
自定义管理admin站点 -- 商品类别
Method signatures and docstrings:
- def save_model(self, request, obj, form, change): admin后台新增或修改了数据时调用
- def delete_model(self, request, obj): admin后台删除了数据时调用
<|skeleton|>
class GoodsCategoryAdmin:
"""自定义管理... | c841e7d1aa0616b070b10924f44b2c418f222cd8 | <|skeleton|>
class GoodsCategoryAdmin:
"""自定义管理admin站点 -- 商品类别"""
def save_model(self, request, obj, form, change):
"""admin后台新增或修改了数据时调用"""
<|body_0|>
def delete_model(self, request, obj):
"""admin后台删除了数据时调用"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GoodsCategoryAdmin:
"""自定义管理admin站点 -- 商品类别"""
def save_model(self, request, obj, form, change):
"""admin后台新增或修改了数据时调用"""
obj.save()
generate_static_list_search_html.delay('list.html')
generate_static_list_search_html.delay('search.html')
def delete_model(self, reques... | the_stack_v2_python_sparse | meiduo_mall/meiduo_mall/apps/goods/admin.py | Echo-xie/meiduo_mall | train | 0 |
2c59e8cb77e89ca1c88ab0674cf7592f1bfa622b | [
"first_name, middle_name, last_name = ('', '', '')\nwords = name.split(' ')\nwords_count = len(words)\nif words_count == 0:\n pass\nelif words_count == 1:\n last_name = words[0]\nelse:\n first_name = ' '.join(words[:1])\n middle_name = ' '.join(words[1:-1])\n last_name = words[-1]\nreturn {'first_nam... | <|body_start_0|>
first_name, middle_name, last_name = ('', '', '')
words = name.split(' ')
words_count = len(words)
if words_count == 0:
pass
elif words_count == 1:
last_name = words[0]
else:
first_name = ' '.join(words[:1])
... | ContributorManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContributorManager:
def parse_name(self, name):
"""Assign name parts from a single string. :param name: string containing full name. :return: dict of parsed name parts."""
<|body_0|>
def match_or_create(self, name):
"""Match name to existing contributor or create a n... | stack_v2_sparse_classes_75kplus_train_074311 | 2,386 | permissive | [
{
"docstring": "Assign name parts from a single string. :param name: string containing full name. :return: dict of parsed name parts.",
"name": "parse_name",
"signature": "def parse_name(self, name)"
},
{
"docstring": "Match name to existing contributor or create a new contributor if not matched... | 2 | stack_v2_sparse_classes_30k_train_031348 | Implement the Python class `ContributorManager` described below.
Class description:
Implement the ContributorManager class.
Method signatures and docstrings:
- def parse_name(self, name): Assign name parts from a single string. :param name: string containing full name. :return: dict of parsed name parts.
- def match_... | Implement the Python class `ContributorManager` described below.
Class description:
Implement the ContributorManager class.
Method signatures and docstrings:
- def parse_name(self, name): Assign name parts from a single string. :param name: string containing full name. :return: dict of parsed name parts.
- def match_... | b70cf83c513bff43c3aeee58303a7fb499abde51 | <|skeleton|>
class ContributorManager:
def parse_name(self, name):
"""Assign name parts from a single string. :param name: string containing full name. :return: dict of parsed name parts."""
<|body_0|>
def match_or_create(self, name):
"""Match name to existing contributor or create a n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ContributorManager:
def parse_name(self, name):
"""Assign name parts from a single string. :param name: string containing full name. :return: dict of parsed name parts."""
first_name, middle_name, last_name = ('', '', '')
words = name.split(' ')
words_count = len(words)
... | the_stack_v2_python_sparse | works/managers/contributor.py | pannkotsky/musicworks | train | 0 | |
2b93b82963b491364e16d137460df2b859e7489b | [
"expected_ele = ElementTree.fromstring(expected)\nactual_ele = ElementTree.fromstring(actual)\nself.__compareXMLElements(expected_ele, actual_ele)",
"self.assertEqual(expected.tag, actual.tag, 'Tags should be equivalent: ' + expected.tag)\nif expected.text == None and (not actual.text == None):\n self.fail(\"T... | <|body_start_0|>
expected_ele = ElementTree.fromstring(expected)
actual_ele = ElementTree.fromstring(actual)
self.__compareXMLElements(expected_ele, actual_ele)
<|end_body_0|>
<|body_start_1|>
self.assertEqual(expected.tag, actual.tag, 'Tags should be equivalent: ' + expected.tag)
... | xml_test_case | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class xml_test_case:
def assertEqualXML(self, expected, actual):
"""Compares two XML encoded character strings This helper method does a basic tree comparison between the two XML strings. This includes comparing all nodes in the tree, their associated attributes and text content, and children ... | stack_v2_sparse_classes_75kplus_train_074312 | 4,402 | no_license | [
{
"docstring": "Compares two XML encoded character strings This helper method does a basic tree comparison between the two XML strings. This includes comparing all nodes in the tree, their associated attributes and text content, and children (recursively). If the validation detects any differences, an appropria... | 3 | null | Implement the Python class `xml_test_case` described below.
Class description:
Implement the xml_test_case class.
Method signatures and docstrings:
- def assertEqualXML(self, expected, actual): Compares two XML encoded character strings This helper method does a basic tree comparison between the two XML strings. This... | Implement the Python class `xml_test_case` described below.
Class description:
Implement the xml_test_case class.
Method signatures and docstrings:
- def assertEqualXML(self, expected, actual): Compares two XML encoded character strings This helper method does a basic tree comparison between the two XML strings. This... | 6aa30065560c1d1afb1ef0c17740a606d84d54b5 | <|skeleton|>
class xml_test_case:
def assertEqualXML(self, expected, actual):
"""Compares two XML encoded character strings This helper method does a basic tree comparison between the two XML strings. This includes comparing all nodes in the tree, their associated attributes and text content, and children ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class xml_test_case:
def assertEqualXML(self, expected, actual):
"""Compares two XML encoded character strings This helper method does a basic tree comparison between the two XML strings. This includes comparing all nodes in the tree, their associated attributes and text content, and children (recursively).... | the_stack_v2_python_sparse | unit_tests/xml_test_base.py | ravingrhino/pyjen | train | 0 | |
bf0038de81000093bb0a5f389e9926ad8ccb2421 | [
"super(ClusterData, self).__init__()\nself._data['clusterHandle'] = ''\nself._data['attrConnectionList'].append('bindPreMatrix')\nself._data['attrConnectionList'].append('geomMatrix')",
"glTools.utils.base.verifyNode(cluster, 'cluster')\nself.reset()\nsuper(ClusterData, self).buildData(cluster)\nclsHandle = mc.li... | <|body_start_0|>
super(ClusterData, self).__init__()
self._data['clusterHandle'] = ''
self._data['attrConnectionList'].append('bindPreMatrix')
self._data['attrConnectionList'].append('geomMatrix')
<|end_body_0|>
<|body_start_1|>
glTools.utils.base.verifyNode(cluster, 'cluster')
... | ClusterData class object. | ClusterData | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClusterData:
"""ClusterData class object."""
def __init__(self):
"""ClusterData class initializer."""
<|body_0|>
def buildData(self, cluster):
"""Build ClusterData class data. @param cluster: Cluster deformer to initialize data for @type cluster: str"""
<... | stack_v2_sparse_classes_75kplus_train_074313 | 2,556 | permissive | [
{
"docstring": "ClusterData class initializer.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Build ClusterData class data. @param cluster: Cluster deformer to initialize data for @type cluster: str",
"name": "buildData",
"signature": "def buildData(self, clus... | 3 | stack_v2_sparse_classes_30k_train_030671 | Implement the Python class `ClusterData` described below.
Class description:
ClusterData class object.
Method signatures and docstrings:
- def __init__(self): ClusterData class initializer.
- def buildData(self, cluster): Build ClusterData class data. @param cluster: Cluster deformer to initialize data for @type clus... | Implement the Python class `ClusterData` described below.
Class description:
ClusterData class object.
Method signatures and docstrings:
- def __init__(self): ClusterData class initializer.
- def buildData(self, cluster): Build ClusterData class data. @param cluster: Cluster deformer to initialize data for @type clus... | c512a96c20ba7a4ee93a123690b626bb408a8fcd | <|skeleton|>
class ClusterData:
"""ClusterData class object."""
def __init__(self):
"""ClusterData class initializer."""
<|body_0|>
def buildData(self, cluster):
"""Build ClusterData class data. @param cluster: Cluster deformer to initialize data for @type cluster: str"""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ClusterData:
"""ClusterData class object."""
def __init__(self):
"""ClusterData class initializer."""
super(ClusterData, self).__init__()
self._data['clusterHandle'] = ''
self._data['attrConnectionList'].append('bindPreMatrix')
self._data['attrConnectionList'].appe... | the_stack_v2_python_sparse | data/clusterData.py | rituparna/glTools | train | 0 |
b05c89fdba66c10dbccbcac279ac924066219267 | [
"args = self.get_args.parse_args()\nnum_rows = args.get('rows') or 100\nquery = g.db.query(Match)\nif args.get('server_id'):\n query = query.filter(Match.server_id == args.get('server_id'))\nquery = query.order_by(-Match.match_id)\nquery = query.limit(num_rows)\nrows = query.all()\nret = []\nfor row in rows:\n ... | <|body_start_0|>
args = self.get_args.parse_args()
num_rows = args.get('rows') or 100
query = g.db.query(Match)
if args.get('server_id'):
query = query.filter(Match.server_id == args.get('server_id'))
query = query.order_by(-Match.match_id)
query = query.limit... | UE4 match | MatchesAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MatchesAPI:
"""UE4 match"""
def get(self):
"""This endpoint used by services and clients to fetch recent matches. Dump the DB rows out as json"""
<|body_0|>
def post(self):
"""Register a new battle on the passed in match server. Each match server should always ha... | stack_v2_sparse_classes_75kplus_train_074314 | 24,829 | permissive | [
{
"docstring": "This endpoint used by services and clients to fetch recent matches. Dump the DB rows out as json",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Register a new battle on the passed in match server. Each match server should always have a single battle. A match ser... | 2 | stack_v2_sparse_classes_30k_test_001035 | Implement the Python class `MatchesAPI` described below.
Class description:
UE4 match
Method signatures and docstrings:
- def get(self): This endpoint used by services and clients to fetch recent matches. Dump the DB rows out as json
- def post(self): Register a new battle on the passed in match server. Each match se... | Implement the Python class `MatchesAPI` described below.
Class description:
UE4 match
Method signatures and docstrings:
- def get(self): This endpoint used by services and clients to fetch recent matches. Dump the DB rows out as json
- def post(self): Register a new battle on the passed in match server. Each match se... | 9825cb22b26b577b715f2ce95453363bf90ecc7e | <|skeleton|>
class MatchesAPI:
"""UE4 match"""
def get(self):
"""This endpoint used by services and clients to fetch recent matches. Dump the DB rows out as json"""
<|body_0|>
def post(self):
"""Register a new battle on the passed in match server. Each match server should always ha... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MatchesAPI:
"""UE4 match"""
def get(self):
"""This endpoint used by services and clients to fetch recent matches. Dump the DB rows out as json"""
args = self.get_args.parse_args()
num_rows = args.get('rows') or 100
query = g.db.query(Match)
if args.get('server_id')... | the_stack_v2_python_sparse | driftbase/api/matches.py | dgnorth/drift-base | train | 1 |
1807cd4c53499022753c9d87b4717ca0d4f92e2a | [
"for e in submission.elements.values():\n posed_corners = e.pose.transform_all_from(e.bounds.corners())\n e.posed_bbox = ComputeBbox().from_point_cloud(posed_corners)\nfor e in ground_truth.elements.values():\n posed_corners = e.pose.transform_all_from(e.bounds.corners())\n e.posed_bbox = ComputeBbox().... | <|body_start_0|>
for e in submission.elements.values():
posed_corners = e.pose.transform_all_from(e.bounds.corners())
e.posed_bbox = ComputeBbox().from_point_cloud(posed_corners)
for e in ground_truth.elements.values():
posed_corners = e.pose.transform_all_from(e.boun... | Algorithm to evaluate a submission for the bounding box track. | BBEvaluator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BBEvaluator:
"""Algorithm to evaluate a submission for the bounding box track."""
def __init__(self, submission, ground_truth, settings=None):
"""Constructor. Computes similarity between all elements in the submission and ground_truth and also computes data association caches. Inputs... | stack_v2_sparse_classes_75kplus_train_074315 | 4,356 | permissive | [
{
"docstring": "Constructor. Computes similarity between all elements in the submission and ground_truth and also computes data association caches. Inputs: submission (ProjectScene) - Submitted scene to be evaluated ground_truth (ProjectScene) - The ground truth scene settings (dict) - configuration for the eva... | 3 | stack_v2_sparse_classes_30k_train_037346 | Implement the Python class `BBEvaluator` described below.
Class description:
Algorithm to evaluate a submission for the bounding box track.
Method signatures and docstrings:
- def __init__(self, submission, ground_truth, settings=None): Constructor. Computes similarity between all elements in the submission and groun... | Implement the Python class `BBEvaluator` described below.
Class description:
Algorithm to evaluate a submission for the bounding box track.
Method signatures and docstrings:
- def __init__(self, submission, ground_truth, settings=None): Constructor. Computes similarity between all elements in the submission and groun... | 073811351a7259ccabd145e2307f1656c50552cf | <|skeleton|>
class BBEvaluator:
"""Algorithm to evaluate a submission for the bounding box track."""
def __init__(self, submission, ground_truth, settings=None):
"""Constructor. Computes similarity between all elements in the submission and ground_truth and also computes data association caches. Inputs... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BBEvaluator:
"""Algorithm to evaluate a submission for the bounding box track."""
def __init__(self, submission, ground_truth, settings=None):
"""Constructor. Computes similarity between all elements in the submission and ground_truth and also computes data association caches. Inputs: submission ... | the_stack_v2_python_sparse | sumo/metrics/bb_evaluator.py | RishabhJain2018/sumo-challenge | train | 0 |
9fa04bf2547d02b2edf116c0eaf44a6a2c25a797 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.teleconferenceDeviceScreenSharingQuality'.c... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
try:
mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
except AttributeError:
mapping_value = None
if mapping_value and mapping_value.casefold() ==... | TeleconferenceDeviceVideoQuality | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeleconferenceDeviceVideoQuality:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeleconferenceDeviceVideoQuality:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminat... | stack_v2_sparse_classes_75kplus_train_074316 | 4,180 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: TeleconferenceDeviceVideoQuality",
"name": "create_from_discriminator_value",
"signature": "def create_from_... | 3 | stack_v2_sparse_classes_30k_test_000416 | Implement the Python class `TeleconferenceDeviceVideoQuality` described below.
Class description:
Implement the TeleconferenceDeviceVideoQuality class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeleconferenceDeviceVideoQuality: Creates a new insta... | Implement the Python class `TeleconferenceDeviceVideoQuality` described below.
Class description:
Implement the TeleconferenceDeviceVideoQuality class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeleconferenceDeviceVideoQuality: Creates a new insta... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class TeleconferenceDeviceVideoQuality:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeleconferenceDeviceVideoQuality:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TeleconferenceDeviceVideoQuality:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeleconferenceDeviceVideoQuality:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and c... | the_stack_v2_python_sparse | msgraph/generated/models/teleconference_device_video_quality.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
d64d2b170b59029ddb49b06249288b1c48a35130 | [
"customer = get_a_customer(customer_id)\nif not customer:\n api.abort(404)\nelse:\n return customer",
"data = request.json\ncustomer = update_customer(data=data, id=customer_id)\nif not customer:\n api.abort(404)\nelse:\n return customer",
"customer = delete_a_customer(id=customer_id)\nif not custom... | <|body_start_0|>
customer = get_a_customer(customer_id)
if not customer:
api.abort(404)
else:
return customer
<|end_body_0|>
<|body_start_1|>
data = request.json
customer = update_customer(data=data, id=customer_id)
if not customer:
ap... | Customer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Customer:
def get(self, customer_id):
"""get a customer given its identifier"""
<|body_0|>
def put(self, customer_id):
"""Updates a new Customer"""
<|body_1|>
def delete(self, customer_id):
"""Deletes a new Customer"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_074317 | 1,932 | no_license | [
{
"docstring": "get a customer given its identifier",
"name": "get",
"signature": "def get(self, customer_id)"
},
{
"docstring": "Updates a new Customer",
"name": "put",
"signature": "def put(self, customer_id)"
},
{
"docstring": "Deletes a new Customer",
"name": "delete",
... | 3 | stack_v2_sparse_classes_30k_train_031133 | Implement the Python class `Customer` described below.
Class description:
Implement the Customer class.
Method signatures and docstrings:
- def get(self, customer_id): get a customer given its identifier
- def put(self, customer_id): Updates a new Customer
- def delete(self, customer_id): Deletes a new Customer | Implement the Python class `Customer` described below.
Class description:
Implement the Customer class.
Method signatures and docstrings:
- def get(self, customer_id): get a customer given its identifier
- def put(self, customer_id): Updates a new Customer
- def delete(self, customer_id): Deletes a new Customer
<|sk... | 3f33450a1c556724ff131ccf0f3afeb590b859b8 | <|skeleton|>
class Customer:
def get(self, customer_id):
"""get a customer given its identifier"""
<|body_0|>
def put(self, customer_id):
"""Updates a new Customer"""
<|body_1|>
def delete(self, customer_id):
"""Deletes a new Customer"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Customer:
def get(self, customer_id):
"""get a customer given its identifier"""
customer = get_a_customer(customer_id)
if not customer:
api.abort(404)
else:
return customer
def put(self, customer_id):
"""Updates a new Customer"""
dat... | the_stack_v2_python_sparse | app/main/controller/customer_controller.py | TheJina/orderquick | train | 0 | |
e5ac35471abe7ab422469777481358136a79089f | [
"proxy_ip = IpRedis().random()\nlogger.info('获取了IP: {}'.format(proxy_ip))\nreturn proxy_ip",
"result = IpRedis().delete(ip)\nif result:\n logger.info('删除ip: {}成功'.format(result))\n print('删除ip: {}成功'.format(ip))\nelse:\n print('删除ip: {}失败'.format(ip))"
] | <|body_start_0|>
proxy_ip = IpRedis().random()
logger.info('获取了IP: {}'.format(proxy_ip))
return proxy_ip
<|end_body_0|>
<|body_start_1|>
result = IpRedis().delete(ip)
if result:
logger.info('删除ip: {}成功'.format(result))
print('删除ip: {}成功'.format(ip))
... | IpsPool | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IpsPool:
def get_ip_from_pool(cls):
"""从 IP 池获取 IP,没有 IP 则返回空 str :return:"""
<|body_0|>
def delete_ip(cls, ip):
"""从 IP 池删除失效 IP :param ip: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
proxy_ip = IpRedis().random()
logger.info('... | stack_v2_sparse_classes_75kplus_train_074318 | 2,277 | permissive | [
{
"docstring": "从 IP 池获取 IP,没有 IP 则返回空 str :return:",
"name": "get_ip_from_pool",
"signature": "def get_ip_from_pool(cls)"
},
{
"docstring": "从 IP 池删除失效 IP :param ip: :return:",
"name": "delete_ip",
"signature": "def delete_ip(cls, ip)"
}
] | 2 | stack_v2_sparse_classes_30k_train_047749 | Implement the Python class `IpsPool` described below.
Class description:
Implement the IpsPool class.
Method signatures and docstrings:
- def get_ip_from_pool(cls): 从 IP 池获取 IP,没有 IP 则返回空 str :return:
- def delete_ip(cls, ip): 从 IP 池删除失效 IP :param ip: :return: | Implement the Python class `IpsPool` described below.
Class description:
Implement the IpsPool class.
Method signatures and docstrings:
- def get_ip_from_pool(cls): 从 IP 池获取 IP,没有 IP 则返回空 str :return:
- def delete_ip(cls, ip): 从 IP 池删除失效 IP :param ip: :return:
<|skeleton|>
class IpsPool:
def get_ip_from_pool(cl... | 29ba13905c73081097df9ef646a5c8194eb024be | <|skeleton|>
class IpsPool:
def get_ip_from_pool(cls):
"""从 IP 池获取 IP,没有 IP 则返回空 str :return:"""
<|body_0|>
def delete_ip(cls, ip):
"""从 IP 池删除失效 IP :param ip: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IpsPool:
def get_ip_from_pool(cls):
"""从 IP 池获取 IP,没有 IP 则返回空 str :return:"""
proxy_ip = IpRedis().random()
logger.info('获取了IP: {}'.format(proxy_ip))
return proxy_ip
def delete_ip(cls, ip):
"""从 IP 池删除失效 IP :param ip: :return:"""
result = IpRedis().delete(i... | the_stack_v2_python_sparse | pyspider/helper/ips_pool.py | UoToGK/crawler-pyspider | train | 0 | |
cd1dcc7943b5b0910611c7826539ded39b3590c2 | [
"if self.request.user.is_authenticated and self.request.user.deck.count() > 50:\n try:\n return self.request.user.has_active_subscription or self.request.user.subscription.type.product.attr.access_cards\n except:\n return False\nif not hasattr(self, 'get_object'):\n if self.request.user.is_au... | <|body_start_0|>
if self.request.user.is_authenticated and self.request.user.deck.count() > 50:
try:
return self.request.user.has_active_subscription or self.request.user.subscription.type.product.attr.access_cards
except:
return False
if not hasat... | RevisionPermissionMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RevisionPermissionMixin:
def test_func(self):
"""Check if trial period is over and if user is allowed to access requested object."""
<|body_0|>
def handle_no_permission(self):
"""Ask user to login or to subscribe to a cards plan."""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_75kplus_train_074319 | 26,085 | permissive | [
{
"docstring": "Check if trial period is over and if user is allowed to access requested object.",
"name": "test_func",
"signature": "def test_func(self)"
},
{
"docstring": "Ask user to login or to subscribe to a cards plan.",
"name": "handle_no_permission",
"signature": "def handle_no_p... | 2 | stack_v2_sparse_classes_30k_train_053852 | Implement the Python class `RevisionPermissionMixin` described below.
Class description:
Implement the RevisionPermissionMixin class.
Method signatures and docstrings:
- def test_func(self): Check if trial period is over and if user is allowed to access requested object.
- def handle_no_permission(self): Ask user to ... | Implement the Python class `RevisionPermissionMixin` described below.
Class description:
Implement the RevisionPermissionMixin class.
Method signatures and docstrings:
- def test_func(self): Check if trial period is over and if user is allowed to access requested object.
- def handle_no_permission(self): Ask user to ... | 461de3ba011c0aaed3f0014136c4497b6890d086 | <|skeleton|>
class RevisionPermissionMixin:
def test_func(self):
"""Check if trial period is over and if user is allowed to access requested object."""
<|body_0|>
def handle_no_permission(self):
"""Ask user to login or to subscribe to a cards plan."""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RevisionPermissionMixin:
def test_func(self):
"""Check if trial period is over and if user is allowed to access requested object."""
if self.request.user.is_authenticated and self.request.user.deck.count() > 50:
try:
return self.request.user.has_active_subscription ... | the_stack_v2_python_sparse | blousebrothers/cards/views.py | sladinji/blousebrothers | train | 1 | |
6f3c2e377908ef0ceef8fa0fd5e4e80b19d0cac0 | [
"self.engine = engine\nself.aux_engine = 'simulai.math.products'\nself.engine_module = importlib.import_module(self.engine)\nself.aux_engine_module = importlib.import_module(self.aux_engine)\nself.tokens_module = importlib.import_module('simulai.tokens')\nself.variables = [sympy.Symbol(vv) for vv in variables]\nsel... | <|body_start_0|>
self.engine = engine
self.aux_engine = 'simulai.math.products'
self.engine_module = importlib.import_module(self.engine)
self.aux_engine_module = importlib.import_module(self.aux_engine)
self.tokens_module = importlib.import_module('simulai.tokens')
self.... | FromSymbol2FLambda | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FromSymbol2FLambda:
def __init__(self, engine: str='numpy', variables: List[str]=None) -> None:
"""Initialize a lambda function from a string. Parameters ---------- engine : str, optional The low level engine used, e. g. numpy, torch ... The default value is 'numpy'. variables : list of ... | stack_v2_sparse_classes_75kplus_train_074320 | 5,509 | permissive | [
{
"docstring": "Initialize a lambda function from a string. Parameters ---------- engine : str, optional The low level engine used, e. g. numpy, torch ... The default value is 'numpy'. variables : list of str, optional The list of definition variables. The default value is None. Returns ------- None",
"name... | 5 | stack_v2_sparse_classes_30k_train_005726 | Implement the Python class `FromSymbol2FLambda` described below.
Class description:
Implement the FromSymbol2FLambda class.
Method signatures and docstrings:
- def __init__(self, engine: str='numpy', variables: List[str]=None) -> None: Initialize a lambda function from a string. Parameters ---------- engine : str, op... | Implement the Python class `FromSymbol2FLambda` described below.
Class description:
Implement the FromSymbol2FLambda class.
Method signatures and docstrings:
- def __init__(self, engine: str='numpy', variables: List[str]=None) -> None: Initialize a lambda function from a string. Parameters ---------- engine : str, op... | 55c58ca0096a733559e7cc4f33d57693e75ffa37 | <|skeleton|>
class FromSymbol2FLambda:
def __init__(self, engine: str='numpy', variables: List[str]=None) -> None:
"""Initialize a lambda function from a string. Parameters ---------- engine : str, optional The low level engine used, e. g. numpy, torch ... The default value is 'numpy'. variables : list of ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FromSymbol2FLambda:
def __init__(self, engine: str='numpy', variables: List[str]=None) -> None:
"""Initialize a lambda function from a string. Parameters ---------- engine : str, optional The low level engine used, e. g. numpy, torch ... The default value is 'numpy'. variables : list of str, optional ... | the_stack_v2_python_sparse | simulai/math/expressions.py | IBM/simulai | train | 73 | |
a753668d4d1ff674ca97bbeb4c2d0bddc21d99e2 | [
"if string_param.startswith('$FILE'):\n path = re.findall('\\\\$FILE\\\\{\\\\\"(.*?)\\\\\"\\\\}', string_param)[0]\n base_folder = kwargs.get('base_folder', '.')\n path = ParseTool.get_possible_path(path, base_folder)\n with open(path, 'r') as read_file:\n string_param = ''.join(read_file)\nretur... | <|body_start_0|>
if string_param.startswith('$FILE'):
path = re.findall('\\$FILE\\{\\"(.*?)\\"\\}', string_param)[0]
base_folder = kwargs.get('base_folder', '.')
path = ParseTool.get_possible_path(path, base_folder)
with open(path, 'r') as read_file:
... | Enhanced parsing tools. | ParseTool | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParseTool:
"""Enhanced parsing tools."""
def parse_string_param_if_file(string_param: str, **kwargs):
"""Use $FILE{"data_path"} to load file from "data_path"."""
<|body_0|>
def parse_string_param_if_env(string_param: str, **kwargs):
"""Use $ENV{env_name} to load ... | stack_v2_sparse_classes_75kplus_train_074321 | 16,194 | permissive | [
{
"docstring": "Use $FILE{\"data_path\"} to load file from \"data_path\".",
"name": "parse_string_param_if_file",
"signature": "def parse_string_param_if_file(string_param: str, **kwargs)"
},
{
"docstring": "Use $ENV{env_name} to load environment variable \"env_name\".",
"name": "parse_strin... | 4 | stack_v2_sparse_classes_30k_val_002602 | Implement the Python class `ParseTool` described below.
Class description:
Enhanced parsing tools.
Method signatures and docstrings:
- def parse_string_param_if_file(string_param: str, **kwargs): Use $FILE{"data_path"} to load file from "data_path".
- def parse_string_param_if_env(string_param: str, **kwargs): Use $E... | Implement the Python class `ParseTool` described below.
Class description:
Enhanced parsing tools.
Method signatures and docstrings:
- def parse_string_param_if_file(string_param: str, **kwargs): Use $FILE{"data_path"} to load file from "data_path".
- def parse_string_param_if_env(string_param: str, **kwargs): Use $E... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class ParseTool:
"""Enhanced parsing tools."""
def parse_string_param_if_file(string_param: str, **kwargs):
"""Use $FILE{"data_path"} to load file from "data_path"."""
<|body_0|>
def parse_string_param_if_env(string_param: str, **kwargs):
"""Use $ENV{env_name} to load ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ParseTool:
"""Enhanced parsing tools."""
def parse_string_param_if_file(string_param: str, **kwargs):
"""Use $FILE{"data_path"} to load file from "data_path"."""
if string_param.startswith('$FILE'):
path = re.findall('\\$FILE\\{\\"(.*?)\\"\\}', string_param)[0]
bas... | the_stack_v2_python_sparse | studio/micro-services/dolphinscheduler/dolphinscheduler-python/pydolphinscheduler/src/pydolphinscheduler/core/yaml_process_define.py | alldatacenter/alldata | train | 774 |
45d870d1c4233873b0c27132d6fe55cde4a531f6 | [
"self.assertEqual(NotificationEntry.objects.count(), 0)\nNotificationEntry.notify('test.notification', 1)\nself.assertEqual(NotificationEntry.objects.count(), 1)\ndelta = timedelta(days=1)\nself.assertFalse(NotificationEntry.check_recent('test.notification', 2, delta))\nself.assertFalse(NotificationEntry.check_rece... | <|body_start_0|>
self.assertEqual(NotificationEntry.objects.count(), 0)
NotificationEntry.notify('test.notification', 1)
self.assertEqual(NotificationEntry.objects.count(), 1)
delta = timedelta(days=1)
self.assertFalse(NotificationEntry.check_recent('test.notification', 2, delta)... | Tests for NotificationEntry. | NotificationTest | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NotificationTest:
"""Tests for NotificationEntry."""
def test_check_notification_entries(self):
"""Test that notification entries can be created."""
<|body_0|>
def test_api_list(self):
"""Test list URL."""
<|body_1|>
def test_bulk_delete(self):
... | stack_v2_sparse_classes_75kplus_train_074322 | 42,814 | permissive | [
{
"docstring": "Test that notification entries can be created.",
"name": "test_check_notification_entries",
"signature": "def test_check_notification_entries(self)"
},
{
"docstring": "Test list URL.",
"name": "test_api_list",
"signature": "def test_api_list(self)"
},
{
"docstring... | 3 | stack_v2_sparse_classes_30k_train_021697 | Implement the Python class `NotificationTest` described below.
Class description:
Tests for NotificationEntry.
Method signatures and docstrings:
- def test_check_notification_entries(self): Test that notification entries can be created.
- def test_api_list(self): Test list URL.
- def test_bulk_delete(self): Tests for... | Implement the Python class `NotificationTest` described below.
Class description:
Tests for NotificationEntry.
Method signatures and docstrings:
- def test_check_notification_entries(self): Test that notification entries can be created.
- def test_api_list(self): Test list URL.
- def test_bulk_delete(self): Tests for... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class NotificationTest:
"""Tests for NotificationEntry."""
def test_check_notification_entries(self):
"""Test that notification entries can be created."""
<|body_0|>
def test_api_list(self):
"""Test list URL."""
<|body_1|>
def test_bulk_delete(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NotificationTest:
"""Tests for NotificationEntry."""
def test_check_notification_entries(self):
"""Test that notification entries can be created."""
self.assertEqual(NotificationEntry.objects.count(), 0)
NotificationEntry.notify('test.notification', 1)
self.assertEqual(Not... | the_stack_v2_python_sparse | InvenTree/common/tests.py | inventree/InvenTree | train | 3,077 |
0f4405a277d36b2d0af2825b411b9cdbb7a04a86 | [
"super(GafferSceneTask, self).__init__(*args, **kwargs)\nself.setMetadata('wrapper.name', 'gaffer')\nself.setMetadata('wrapper.options', {})\nself.setMetadata('dispatch.split', True)",
"import Gaffer\nimport GafferDispatch\ncrawlers = self.crawlers()\nscript = Gaffer.ScriptNode()\nscript['fileName'].setValue(self... | <|body_start_0|>
super(GafferSceneTask, self).__init__(*args, **kwargs)
self.setMetadata('wrapper.name', 'gaffer')
self.setMetadata('wrapper.options', {})
self.setMetadata('dispatch.split', True)
<|end_body_0|>
<|body_start_1|>
import Gaffer
import GafferDispatch
... | Executes a gaffer scene by triggering the task nodes. Required options: scene (full path of gaffer scene) All options defined in the task are resolved (in case the value contains a template string) then assigned to gaffer's context. Therefore, you can use it to provide custom data to gaffer. Since the task options are ... | GafferSceneTask | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GafferSceneTask:
"""Executes a gaffer scene by triggering the task nodes. Required options: scene (full path of gaffer scene) All options defined in the task are resolved (in case the value contains a template string) then assigned to gaffer's context. Therefore, you can use it to provide custom ... | stack_v2_sparse_classes_75kplus_train_074323 | 3,016 | permissive | [
{
"docstring": "Create a gaffer template task.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Perform the task.",
"name": "_perform",
"signature": "def _perform(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_023703 | Implement the Python class `GafferSceneTask` described below.
Class description:
Executes a gaffer scene by triggering the task nodes. Required options: scene (full path of gaffer scene) All options defined in the task are resolved (in case the value contains a template string) then assigned to gaffer's context. There... | Implement the Python class `GafferSceneTask` described below.
Class description:
Executes a gaffer scene by triggering the task nodes. Required options: scene (full path of gaffer scene) All options defined in the task are resolved (in case the value contains a template string) then assigned to gaffer's context. There... | 046dbb0c1b4ff20ea5f2e1679f8d89f3089b6aa4 | <|skeleton|>
class GafferSceneTask:
"""Executes a gaffer scene by triggering the task nodes. Required options: scene (full path of gaffer scene) All options defined in the task are resolved (in case the value contains a template string) then assigned to gaffer's context. Therefore, you can use it to provide custom ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GafferSceneTask:
"""Executes a gaffer scene by triggering the task nodes. Required options: scene (full path of gaffer scene) All options defined in the task are resolved (in case the value contains a template string) then assigned to gaffer's context. Therefore, you can use it to provide custom data to gaffe... | the_stack_v2_python_sparse | src/lib/kombi/Task/ImageSequence/GafferSceneTask.py | kombiHQ/kombi | train | 2 |
40a3789a6b1e365ace07d02f1be4908789bc68ab | [
"h = [(t, i) for i, t in enumerate(time)]\nheapify(h)\nt = 0\nwhile totalTrips:\n t, i = heappop(h)\n heappush(h, (t + time[i], i))\n totalTrips -= 1\nreturn t",
"mn = min(time)\nmx = totalTrips * min(time)\n\ndef bisearch(l, r):\n while l <= r:\n m = l + (r - l) // 2\n n = sum((m // t f... | <|body_start_0|>
h = [(t, i) for i, t in enumerate(time)]
heapify(h)
t = 0
while totalTrips:
t, i = heappop(h)
heappush(h, (t + time[i], i))
totalTrips -= 1
return t
<|end_body_0|>
<|body_start_1|>
mn = min(time)
mx = totalTrip... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minimumTime(self, time: List[int], totalTrips: int) -> int:
"""Mar 09, 2023 22:11 TLE"""
<|body_0|>
def minimumTime(self, time: List[int], totalTrips: int) -> int:
"""Mar 09, 2023 22:21"""
<|body_1|>
def minimumTime(self, time: List[int], t... | stack_v2_sparse_classes_75kplus_train_074324 | 3,137 | no_license | [
{
"docstring": "Mar 09, 2023 22:11 TLE",
"name": "minimumTime",
"signature": "def minimumTime(self, time: List[int], totalTrips: int) -> int"
},
{
"docstring": "Mar 09, 2023 22:21",
"name": "minimumTime",
"signature": "def minimumTime(self, time: List[int], totalTrips: int) -> int"
},
... | 3 | stack_v2_sparse_classes_30k_train_021266 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumTime(self, time: List[int], totalTrips: int) -> int: Mar 09, 2023 22:11 TLE
- def minimumTime(self, time: List[int], totalTrips: int) -> int: Mar 09, 2023 22:21
- def ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumTime(self, time: List[int], totalTrips: int) -> int: Mar 09, 2023 22:11 TLE
- def minimumTime(self, time: List[int], totalTrips: int) -> int: Mar 09, 2023 22:21
- def ... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def minimumTime(self, time: List[int], totalTrips: int) -> int:
"""Mar 09, 2023 22:11 TLE"""
<|body_0|>
def minimumTime(self, time: List[int], totalTrips: int) -> int:
"""Mar 09, 2023 22:21"""
<|body_1|>
def minimumTime(self, time: List[int], t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minimumTime(self, time: List[int], totalTrips: int) -> int:
"""Mar 09, 2023 22:11 TLE"""
h = [(t, i) for i, t in enumerate(time)]
heapify(h)
t = 0
while totalTrips:
t, i = heappop(h)
heappush(h, (t + time[i], i))
totalTr... | the_stack_v2_python_sparse | leetcode/solved/2294_Minimum_Time_to_Complete_Trips/solution.py | sungminoh/algorithms | train | 0 | |
c5e0dad4cc0eed51beef649c18f3b2d6113f20b9 | [
"self.n_kernels = n_kernels\nself.n_strides = n_strides\nself.norm_type = normalization\nself.activation_type = activation\nself.kernel_init = tf.random_normal_initializer(0.0, 0.02)",
"activation = Conv2D(filters=n_filters, kernel_size=self.n_kernels, strides=self.n_strides, padding='same', kernel_initializer=se... | <|body_start_0|>
self.n_kernels = n_kernels
self.n_strides = n_strides
self.norm_type = normalization
self.activation_type = activation
self.kernel_init = tf.random_normal_initializer(0.0, 0.02)
<|end_body_0|>
<|body_start_1|>
activation = Conv2D(filters=n_filters, kerne... | Class for the Down Convolution block for Unet. | DownConvBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DownConvBlock:
"""Class for the Down Convolution block for Unet."""
def __init__(self, n_kernels, n_strides, activation, normalization):
"""Initialize the Down Convolution Block. Args: n_kernels (int): Number of kernels for Conv2D. n_strides (int): Stride size. activation (str): Type... | stack_v2_sparse_classes_75kplus_train_074325 | 11,636 | no_license | [
{
"docstring": "Initialize the Down Convolution Block. Args: n_kernels (int): Number of kernels for Conv2D. n_strides (int): Stride size. activation (str): Type of activation layer to use. normalization (str): Type of normalization layer to use.",
"name": "__init__",
"signature": "def __init__(self, n_k... | 2 | stack_v2_sparse_classes_30k_train_020218 | Implement the Python class `DownConvBlock` described below.
Class description:
Class for the Down Convolution block for Unet.
Method signatures and docstrings:
- def __init__(self, n_kernels, n_strides, activation, normalization): Initialize the Down Convolution Block. Args: n_kernels (int): Number of kernels for Con... | Implement the Python class `DownConvBlock` described below.
Class description:
Class for the Down Convolution block for Unet.
Method signatures and docstrings:
- def __init__(self, n_kernels, n_strides, activation, normalization): Initialize the Down Convolution Block. Args: n_kernels (int): Number of kernels for Con... | 1b953d87968dac46ebbc9b1d5c254ea9493ee328 | <|skeleton|>
class DownConvBlock:
"""Class for the Down Convolution block for Unet."""
def __init__(self, n_kernels, n_strides, activation, normalization):
"""Initialize the Down Convolution Block. Args: n_kernels (int): Number of kernels for Conv2D. n_strides (int): Stride size. activation (str): Type... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DownConvBlock:
"""Class for the Down Convolution block for Unet."""
def __init__(self, n_kernels, n_strides, activation, normalization):
"""Initialize the Down Convolution Block. Args: n_kernels (int): Number of kernels for Conv2D. n_strides (int): Stride size. activation (str): Type of activatio... | the_stack_v2_python_sparse | fmlwright/trainer/neural_networks/blocks.py | rgresia-umd/fml-wright | train | 0 |
1244fab3ada0b127f986c03cd2e51191280bb9f2 | [
"if 'icon' not in cls.__cache:\n cls.__cache['icon'] = {}\nif name not in cls.__cache['icon']:\n cls.__cache['icon'][name] = QtGui.QIcon(os.path.join(cls.__resourcesLocation, name))\nreturn cls.__cache['icon'][name]",
"if 'pixmap' not in cls.__cache:\n cls.__cache['pixmap'] = {}\nkey = (name, width, heig... | <|body_start_0|>
if 'icon' not in cls.__cache:
cls.__cache['icon'] = {}
if name not in cls.__cache['icon']:
cls.__cache['icon'][name] = QtGui.QIcon(os.path.join(cls.__resourcesLocation, name))
return cls.__cache['icon'][name]
<|end_body_0|>
<|body_start_1|>
if 'p... | Utility class used to load resources used by the interface. | Resource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Resource:
"""Utility class used to load resources used by the interface."""
def icon(cls, name):
"""Load and return an icon based on the input name."""
<|body_0|>
def pixmap(cls, name, width=None, height=None):
"""Load and return a pixmap based on the input name.... | stack_v2_sparse_classes_75kplus_train_074326 | 2,126 | permissive | [
{
"docstring": "Load and return an icon based on the input name.",
"name": "icon",
"signature": "def icon(cls, name)"
},
{
"docstring": "Load and return a pixmap based on the input name.",
"name": "pixmap",
"signature": "def pixmap(cls, name, width=None, height=None)"
},
{
"docst... | 3 | stack_v2_sparse_classes_30k_train_049377 | Implement the Python class `Resource` described below.
Class description:
Utility class used to load resources used by the interface.
Method signatures and docstrings:
- def icon(cls, name): Load and return an icon based on the input name.
- def pixmap(cls, name, width=None, height=None): Load and return a pixmap bas... | Implement the Python class `Resource` described below.
Class description:
Utility class used to load resources used by the interface.
Method signatures and docstrings:
- def icon(cls, name): Load and return an icon based on the input name.
- def pixmap(cls, name, width=None, height=None): Load and return a pixmap bas... | 046dbb0c1b4ff20ea5f2e1679f8d89f3089b6aa4 | <|skeleton|>
class Resource:
"""Utility class used to load resources used by the interface."""
def icon(cls, name):
"""Load and return an icon based on the input name."""
<|body_0|>
def pixmap(cls, name, width=None, height=None):
"""Load and return a pixmap based on the input name.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Resource:
"""Utility class used to load resources used by the interface."""
def icon(cls, name):
"""Load and return an icon based on the input name."""
if 'icon' not in cls.__cache:
cls.__cache['icon'] = {}
if name not in cls.__cache['icon']:
cls.__cache['i... | the_stack_v2_python_sparse | src/lib/kombiqt/Resource.py | kombiHQ/kombi | train | 2 |
af286d59e275e1d3957c187905950923b3167e3b | [
"goods: List[Stock] = Stock.objects(id=goodid)\nif not goods:\n raise error.StockNotFound(goodid)\nreturn goods[0]",
"if individual:\n return Stock.objects(name__icontains=name, individual=True)\nreturn Stock.objects(name__icontains=name)",
"tags = [tag.strip().lower() for tag in tags]\nif individual:\n ... | <|body_start_0|>
goods: List[Stock] = Stock.objects(id=goodid)
if not goods:
raise error.StockNotFound(goodid)
return goods[0]
<|end_body_0|>
<|body_start_1|>
if individual:
return Stock.objects(name__icontains=name, individual=True)
return Stock.objects(... | 查询相关函数 | Retrieve | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Retrieve:
"""查询相关函数"""
def byid(goodid: ObjectId) -> Stock:
"""根据商品ID查询商品"""
<|body_0|>
def byname(name: str, individual: bool=False) -> List[Stock]:
"""根据名称查找商品"""
<|body_1|>
def bytags(tags: List[str], individual: bool=False) -> List[Stock]:
... | stack_v2_sparse_classes_75kplus_train_074327 | 1,684 | permissive | [
{
"docstring": "根据商品ID查询商品",
"name": "byid",
"signature": "def byid(goodid: ObjectId) -> Stock"
},
{
"docstring": "根据名称查找商品",
"name": "byname",
"signature": "def byname(name: str, individual: bool=False) -> List[Stock]"
},
{
"docstring": "根据标签查找商品",
"name": "bytags",
"sig... | 3 | stack_v2_sparse_classes_30k_train_017176 | Implement the Python class `Retrieve` described below.
Class description:
查询相关函数
Method signatures and docstrings:
- def byid(goodid: ObjectId) -> Stock: 根据商品ID查询商品
- def byname(name: str, individual: bool=False) -> List[Stock]: 根据名称查找商品
- def bytags(tags: List[str], individual: bool=False) -> List[Stock]: 根据标签查找商品 | Implement the Python class `Retrieve` described below.
Class description:
查询相关函数
Method signatures and docstrings:
- def byid(goodid: ObjectId) -> Stock: 根据商品ID查询商品
- def byname(name: str, individual: bool=False) -> List[Stock]: 根据名称查找商品
- def bytags(tags: List[str], individual: bool=False) -> List[Stock]: 根据标签查找商品
... | 79e34f4b8fba8c6fd208b5a3049103dca2064ab5 | <|skeleton|>
class Retrieve:
"""查询相关函数"""
def byid(goodid: ObjectId) -> Stock:
"""根据商品ID查询商品"""
<|body_0|>
def byname(name: str, individual: bool=False) -> List[Stock]:
"""根据名称查找商品"""
<|body_1|>
def bytags(tags: List[str], individual: bool=False) -> List[Stock]:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Retrieve:
"""查询相关函数"""
def byid(goodid: ObjectId) -> Stock:
"""根据商品ID查询商品"""
goods: List[Stock] = Stock.objects(id=goodid)
if not goods:
raise error.StockNotFound(goodid)
return goods[0]
def byname(name: str, individual: bool=False) -> List[Stock]:
... | the_stack_v2_python_sparse | leaf/selling/functions/stock.py | guiqiqi/leaf | train | 122 |
ba805584c4da990698932610b1f9b705b0c1ab8b | [
"super(DepthWiseConv1DBLock, self).__init__()\nself.causal = causal\nself.padding = (kernel - 1) * dilation if causal else padding\nself.conv1d = nn.Conv1d(in_chan, hidden_chan, 1)\nself.dconv1d = nn.Conv1d(hidden_chan, hidden_chan, kernel, dilation=dilation, groups=hidden_chan, padding=self.padding)\nself.res = nn... | <|body_start_0|>
super(DepthWiseConv1DBLock, self).__init__()
self.causal = causal
self.padding = (kernel - 1) * dilation if causal else padding
self.conv1d = nn.Conv1d(in_chan, hidden_chan, 1)
self.dconv1d = nn.Conv1d(hidden_chan, hidden_chan, kernel, dilation=dilation, groups=h... | Depth-Wise 1 Dimensionnal Convolution Block Attributes: causal {bool} -- choose cLN instead of gLN (default: {False}) padding {int} -- padding size conv1d {nn.Module} -- 1 dimensionnal convolution layer dconv1d {nn.Module} -- 1 dimensionnal depth-wise convolution layer res {nn.Module} -- 1 dimensionnal resiudal convolu... | DepthWiseConv1DBLock | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DepthWiseConv1DBLock:
"""Depth-Wise 1 Dimensionnal Convolution Block Attributes: causal {bool} -- choose cLN instead of gLN (default: {False}) padding {int} -- padding size conv1d {nn.Module} -- 1 dimensionnal convolution layer dconv1d {nn.Module} -- 1 dimensionnal depth-wise convolution layer re... | stack_v2_sparse_classes_75kplus_train_074328 | 9,814 | permissive | [
{
"docstring": "Initialization Arguments: in_chan {int} -- input channel size hidden_chan {int} -- hidden channel size kernel {int} -- kernel size padding {int} -- padding size Keyword Arguments: dilation {int} -- dilation factor for altrous conv (default: {1}) causal {bool} -- choose cLN instead of gLN (defaul... | 2 | stack_v2_sparse_classes_30k_train_044140 | Implement the Python class `DepthWiseConv1DBLock` described below.
Class description:
Depth-Wise 1 Dimensionnal Convolution Block Attributes: causal {bool} -- choose cLN instead of gLN (default: {False}) padding {int} -- padding size conv1d {nn.Module} -- 1 dimensionnal convolution layer dconv1d {nn.Module} -- 1 dimen... | Implement the Python class `DepthWiseConv1DBLock` described below.
Class description:
Depth-Wise 1 Dimensionnal Convolution Block Attributes: causal {bool} -- choose cLN instead of gLN (default: {False}) padding {int} -- padding size conv1d {nn.Module} -- 1 dimensionnal convolution layer dconv1d {nn.Module} -- 1 dimen... | 2415502fa8a38d4624b1c71e926f1723bdc8535c | <|skeleton|>
class DepthWiseConv1DBLock:
"""Depth-Wise 1 Dimensionnal Convolution Block Attributes: causal {bool} -- choose cLN instead of gLN (default: {False}) padding {int} -- padding size conv1d {nn.Module} -- 1 dimensionnal convolution layer dconv1d {nn.Module} -- 1 dimensionnal depth-wise convolution layer re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DepthWiseConv1DBLock:
"""Depth-Wise 1 Dimensionnal Convolution Block Attributes: causal {bool} -- choose cLN instead of gLN (default: {False}) padding {int} -- padding size conv1d {nn.Module} -- 1 dimensionnal convolution layer dconv1d {nn.Module} -- 1 dimensionnal depth-wise convolution layer res {nn.Module}... | the_stack_v2_python_sparse | SPK_SP_Master/wass/convtasnet/modules.py | adamwhitakerwilson/speaker_separation | train | 0 |
dfb3cb00901145667477975d43c55445d752eda1 | [
"behavior.Behavior.__init__(self, nodename, ctrlrID)\nself._uses_wp_control = True\nself._last_wp_id = 0\nself.wp_msg = LLA()\nself._wpPublisher = rospy.Publisher('autopilot/payload_waypoint', LLA, tcp_nodelay=True, latch=True, queue_size=1)",
"if wp.alt >= enums.MIN_REL_ALT and wp.alt <= enums.MAX_REL_ALT and (a... | <|body_start_0|>
behavior.Behavior.__init__(self, nodename, ctrlrID)
self._uses_wp_control = True
self._last_wp_id = 0
self.wp_msg = LLA()
self._wpPublisher = rospy.Publisher('autopilot/payload_waypoint', LLA, tcp_nodelay=True, latch=True, queue_size=1)
<|end_body_0|>
<|body_sta... | Abstract class for wrapping a control-order-issuing ACS ROS object Control is implemented through the generation of waypoint commands. Instantiated objects will provide a waypoint publisher that publishes computed waypoints to the appropriate topic. Class member variables: _wpPublisher: publisher object for publishing ... | WaypointBehavior | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WaypointBehavior:
"""Abstract class for wrapping a control-order-issuing ACS ROS object Control is implemented through the generation of waypoint commands. Instantiated objects will provide a waypoint publisher that publishes computed waypoints to the appropriate topic. Class member variables: _w... | stack_v2_sparse_classes_75kplus_train_074329 | 4,100 | no_license | [
{
"docstring": "Class initializer sets up the publisher for the waypoint topic @param nodename: name of the node that the object is contained in @param ctrlrID: identifier (int) for this particular behavior",
"name": "__init__",
"signature": "def __init__(self, nodename, ctrlrID)"
},
{
"docstrin... | 2 | stack_v2_sparse_classes_30k_train_004947 | Implement the Python class `WaypointBehavior` described below.
Class description:
Abstract class for wrapping a control-order-issuing ACS ROS object Control is implemented through the generation of waypoint commands. Instantiated objects will provide a waypoint publisher that publishes computed waypoints to the approp... | Implement the Python class `WaypointBehavior` described below.
Class description:
Abstract class for wrapping a control-order-issuing ACS ROS object Control is implemented through the generation of waypoint commands. Instantiated objects will provide a waypoint publisher that publishes computed waypoints to the approp... | ec2b5c43abed51a37c17bde0c000c2dfbfcbb9b1 | <|skeleton|>
class WaypointBehavior:
"""Abstract class for wrapping a control-order-issuing ACS ROS object Control is implemented through the generation of waypoint commands. Instantiated objects will provide a waypoint publisher that publishes computed waypoints to the appropriate topic. Class member variables: _w... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WaypointBehavior:
"""Abstract class for wrapping a control-order-issuing ACS ROS object Control is implemented through the generation of waypoint commands. Instantiated objects will provide a waypoint publisher that publishes computed waypoints to the appropriate topic. Class member variables: _wpPublisher: p... | the_stack_v2_python_sparse | ap_lib/src/ap_lib/waypoint_behavior.py | jaymonty/autonomy-payload | train | 0 |
9a35ca6278bbf4b2f6d6797d7aa372e0ebdbe3dc | [
"left, right = (0, len(numbers) - 1)\nwhile left < right:\n res = numbers[left] + numbers[right]\n if res == target:\n return [left + 1, right + 1]\n if res < target:\n left += 1\n else:\n right -= 1\nreturn []",
"seen = dict()\nfor i, num in enumerate(numbers):\n diff = target... | <|body_start_0|>
left, right = (0, len(numbers) - 1)
while left < right:
res = numbers[left] + numbers[right]
if res == target:
return [left + 1, right + 1]
if res < target:
left += 1
else:
right -= 1
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
"""Two pointers Time complexity: O(n) Space complexity: O(1)"""
<|body_0|>
def twoSumDictionary(self, numbers: List[int], target: int) -> List[int]:
"""Dictionary Time complexity: O(n) Space co... | stack_v2_sparse_classes_75kplus_train_074330 | 2,239 | permissive | [
{
"docstring": "Two pointers Time complexity: O(n) Space complexity: O(1)",
"name": "twoSum",
"signature": "def twoSum(self, numbers: List[int], target: int) -> List[int]"
},
{
"docstring": "Dictionary Time complexity: O(n) Space complexity: O(n)",
"name": "twoSumDictionary",
"signature"... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, numbers: List[int], target: int) -> List[int]: Two pointers Time complexity: O(n) Space complexity: O(1)
- def twoSumDictionary(self, numbers: List[int], target:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, numbers: List[int], target: int) -> List[int]: Two pointers Time complexity: O(n) Space complexity: O(1)
- def twoSumDictionary(self, numbers: List[int], target:... | 32b0878f63e5edd19a1fbe13bfa4c518a4261e23 | <|skeleton|>
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
"""Two pointers Time complexity: O(n) Space complexity: O(1)"""
<|body_0|>
def twoSumDictionary(self, numbers: List[int], target: int) -> List[int]:
"""Dictionary Time complexity: O(n) Space co... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
"""Two pointers Time complexity: O(n) Space complexity: O(1)"""
left, right = (0, len(numbers) - 1)
while left < right:
res = numbers[left] + numbers[right]
if res == target:
... | the_stack_v2_python_sparse | leetcode/Two Pointers/167. Two Sum II - Input Array Is Sorted.py | danielfsousa/algorithms-solutions | train | 2 | |
6d73fd77b6668fdaafb70f4170c89861535c6f46 | [
"matches = []\nsub_string_parameters = cfn.get_sub_parameters(sub_string)\nfor parameter_name, _ in parameters.items():\n if parameter_name not in sub_string_parameters:\n message = 'Parameter {0} not used in Fn::Sub at {1}'\n matches.append(RuleMatch(tree, message.format(parameter_name, '/'.join(m... | <|body_start_0|>
matches = []
sub_string_parameters = cfn.get_sub_parameters(sub_string)
for parameter_name, _ in parameters.items():
if parameter_name not in sub_string_parameters:
message = 'Parameter {0} not used in Fn::Sub at {1}'
matches.append(Ru... | Check if Sub Parameters are used | SubParametersUsed | [
"MIT-0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubParametersUsed:
"""Check if Sub Parameters are used"""
def _test_parameters(self, cfn, sub_string, parameters, tree):
"""Test if sub parmaeters are in the string"""
<|body_0|>
def match(self, cfn):
"""Check CloudFormation Join"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_75kplus_train_074331 | 2,783 | permissive | [
{
"docstring": "Test if sub parmaeters are in the string",
"name": "_test_parameters",
"signature": "def _test_parameters(self, cfn, sub_string, parameters, tree)"
},
{
"docstring": "Check CloudFormation Join",
"name": "match",
"signature": "def match(self, cfn)"
}
] | 2 | null | Implement the Python class `SubParametersUsed` described below.
Class description:
Check if Sub Parameters are used
Method signatures and docstrings:
- def _test_parameters(self, cfn, sub_string, parameters, tree): Test if sub parmaeters are in the string
- def match(self, cfn): Check CloudFormation Join | Implement the Python class `SubParametersUsed` described below.
Class description:
Check if Sub Parameters are used
Method signatures and docstrings:
- def _test_parameters(self, cfn, sub_string, parameters, tree): Test if sub parmaeters are in the string
- def match(self, cfn): Check CloudFormation Join
<|skeleton|... | 3f5324cfd000e14d9324a242bb7fad528b22a7df | <|skeleton|>
class SubParametersUsed:
"""Check if Sub Parameters are used"""
def _test_parameters(self, cfn, sub_string, parameters, tree):
"""Test if sub parmaeters are in the string"""
<|body_0|>
def match(self, cfn):
"""Check CloudFormation Join"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SubParametersUsed:
"""Check if Sub Parameters are used"""
def _test_parameters(self, cfn, sub_string, parameters, tree):
"""Test if sub parmaeters are in the string"""
matches = []
sub_string_parameters = cfn.get_sub_parameters(sub_string)
for parameter_name, _ in paramete... | the_stack_v2_python_sparse | src/cfnlint/rules/functions/SubParametersUsed.py | jlongtine/cfn-python-lint | train | 1 |
9cd27d35eca5530e414ab946c2e28e904fdf0009 | [
"super(StoreOrderLines, self).__init__(*args, **kwargs)\nself.endpoint = 'ecommerce/stores'\nself.store_id = None\nself.order_id = None\nself.line_id = None",
"self.store_id = store_id\nself.order_id = order_id\nif 'id' not in data:\n raise KeyError('The order line must have an id')\nif 'product_id' not in dat... | <|body_start_0|>
super(StoreOrderLines, self).__init__(*args, **kwargs)
self.endpoint = 'ecommerce/stores'
self.store_id = None
self.order_id = None
self.line_id = None
<|end_body_0|>
<|body_start_1|>
self.store_id = store_id
self.order_id = order_id
if '... | Each Order contains one or more Order Lines, which represent a specific Product Variant that a Customer purchases. | StoreOrderLines | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StoreOrderLines:
"""Each Order contains one or more Order Lines, which represent a specific Product Variant that a Customer purchases."""
def __init__(self, *args, **kwargs):
"""Initialize the endpoint"""
<|body_0|>
def create(self, store_id, order_id, data):
"""... | stack_v2_sparse_classes_75kplus_train_074332 | 5,290 | permissive | [
{
"docstring": "Initialize the endpoint",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Add a new line item to an existing order. :param store_id: The store id. :type store_id: :py:class:`str` :param order_id: The id for the order in a store. :type ord... | 6 | null | Implement the Python class `StoreOrderLines` described below.
Class description:
Each Order contains one or more Order Lines, which represent a specific Product Variant that a Customer purchases.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize the endpoint
- def create(self, store_... | Implement the Python class `StoreOrderLines` described below.
Class description:
Each Order contains one or more Order Lines, which represent a specific Product Variant that a Customer purchases.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize the endpoint
- def create(self, store_... | bf61cd602dc44cbff32fbf6f6dcdd33cf6f782e8 | <|skeleton|>
class StoreOrderLines:
"""Each Order contains one or more Order Lines, which represent a specific Product Variant that a Customer purchases."""
def __init__(self, *args, **kwargs):
"""Initialize the endpoint"""
<|body_0|>
def create(self, store_id, order_id, data):
"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StoreOrderLines:
"""Each Order contains one or more Order Lines, which represent a specific Product Variant that a Customer purchases."""
def __init__(self, *args, **kwargs):
"""Initialize the endpoint"""
super(StoreOrderLines, self).__init__(*args, **kwargs)
self.endpoint = 'ecom... | the_stack_v2_python_sparse | mailchimp3/entities/storeorderlines.py | VingtCinq/python-mailchimp | train | 190 |
9795b15f81cefec10344680afc01b9deb34145b3 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Cloud OS Login API The Cloud OS Login API allows you to manage users and their associated SSH public keys for logging into virtual machines on Google Cloud Platform. | OsLoginServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OsLoginServiceServicer:
"""Cloud OS Login API The Cloud OS Login API allows you to manage users and their associated SSH public keys for logging into virtual machines on Google Cloud Platform."""
def DeletePosixAccount(self, request, context):
"""Deletes a POSIX account."""
<... | stack_v2_sparse_classes_75kplus_train_074333 | 7,621 | permissive | [
{
"docstring": "Deletes a POSIX account.",
"name": "DeletePosixAccount",
"signature": "def DeletePosixAccount(self, request, context)"
},
{
"docstring": "Deletes an SSH public key.",
"name": "DeleteSshPublicKey",
"signature": "def DeleteSshPublicKey(self, request, context)"
},
{
... | 6 | stack_v2_sparse_classes_30k_train_013256 | Implement the Python class `OsLoginServiceServicer` described below.
Class description:
Cloud OS Login API The Cloud OS Login API allows you to manage users and their associated SSH public keys for logging into virtual machines on Google Cloud Platform.
Method signatures and docstrings:
- def DeletePosixAccount(self,... | Implement the Python class `OsLoginServiceServicer` described below.
Class description:
Cloud OS Login API The Cloud OS Login API allows you to manage users and their associated SSH public keys for logging into virtual machines on Google Cloud Platform.
Method signatures and docstrings:
- def DeletePosixAccount(self,... | d897d56bce03d1fda98b79afb08264e51d46c421 | <|skeleton|>
class OsLoginServiceServicer:
"""Cloud OS Login API The Cloud OS Login API allows you to manage users and their associated SSH public keys for logging into virtual machines on Google Cloud Platform."""
def DeletePosixAccount(self, request, context):
"""Deletes a POSIX account."""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OsLoginServiceServicer:
"""Cloud OS Login API The Cloud OS Login API allows you to manage users and their associated SSH public keys for logging into virtual machines on Google Cloud Platform."""
def DeletePosixAccount(self, request, context):
"""Deletes a POSIX account."""
context.set_co... | the_stack_v2_python_sparse | oslogin/google/cloud/oslogin_v1/proto/oslogin_pb2_grpc.py | tswast/google-cloud-python | train | 1 |
a67f9257efdf54a4750b3f5da0adb1a1535ad95b | [
"try:\n path = importlib_resources.files(origin.package) / PosixPath(origin.resource)\n return path.read_text()\nexcept Exception:\n raise TemplateDoesNotExist(origin)",
"resource = f'templates/{template_name}'\nfor extmgr in get_extension_managers():\n for ext in extmgr.get_enabled_extensions():\n ... | <|body_start_0|>
try:
path = importlib_resources.files(origin.package) / PosixPath(origin.resource)
return path.read_text()
except Exception:
raise TemplateDoesNotExist(origin)
<|end_body_0|>
<|body_start_1|>
resource = f'templates/{template_name}'
fo... | Loads templates found within an extension. This will look through all enabled extensions and attempt to fetch the named template under the :file:`templates` directory within the extension's package. This should be added last to the list of template loaders. .. versionadded:: 0.9 | Loader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Loader:
"""Loads templates found within an extension. This will look through all enabled extensions and attempt to fetch the named template under the :file:`templates` directory within the extension's package. This should be added last to the list of template loaders. .. versionadded:: 0.9"""
... | stack_v2_sparse_classes_75kplus_train_074334 | 2,838 | no_license | [
{
"docstring": "Return the contents of a template. Args: origin (ExtensionOrigin): The origin of the template. Returns: str: The resulting template contents. Raises: TemplateDoesNotExist: The template could not be found.",
"name": "get_contents",
"signature": "def get_contents(self, origin: ExtensionOri... | 2 | stack_v2_sparse_classes_30k_train_038770 | Implement the Python class `Loader` described below.
Class description:
Loads templates found within an extension. This will look through all enabled extensions and attempt to fetch the named template under the :file:`templates` directory within the extension's package. This should be added last to the list of templat... | Implement the Python class `Loader` described below.
Class description:
Loads templates found within an extension. This will look through all enabled extensions and attempt to fetch the named template under the :file:`templates` directory within the extension's package. This should be added last to the list of templat... | 99ea69d80a3a393b0da4da3152ef26e808dd8487 | <|skeleton|>
class Loader:
"""Loads templates found within an extension. This will look through all enabled extensions and attempt to fetch the named template under the :file:`templates` directory within the extension's package. This should be added last to the list of template loaders. .. versionadded:: 0.9"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Loader:
"""Loads templates found within an extension. This will look through all enabled extensions and attempt to fetch the named template under the :file:`templates` directory within the extension's package. This should be added last to the list of template loaders. .. versionadded:: 0.9"""
def get_con... | the_stack_v2_python_sparse | djblets/extensions/loaders.py | chipx86/djblets | train | 2 |
8f3e1bd74c61fac0a55c0c19d7e5956116fb0de9 | [
"LPriority = ['', 'auxiliary', 'index', 'punctuation', 'currencySymbol']\nDAlpha = self.D['DAlpha']\nassert all((key in LPriority for key in DAlpha))\nL = []\nfor key in LPriority:\n if key in DAlpha:\n L.append((key, DAlpha[key]))\nreturn L",
"DSymbols = self.D['DSymbols']\nLRtn = []\nfor script1, DScr... | <|body_start_0|>
LPriority = ['', 'auxiliary', 'index', 'punctuation', 'currencySymbol']
DAlpha = self.D['DAlpha']
assert all((key in LPriority for key in DAlpha))
L = []
for key in LPriority:
if key in DAlpha:
L.append((key, DAlpha[key]))
retu... | Alphabets | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Alphabets:
def get_L_alpha(self):
"""Get a list of the alphabet data in a more usable order"""
<|body_0|>
def get_L_symbols(self, exclude_blank=True, len_limit=None):
"""Get any relevant symbols from DSymbols"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_074335 | 1,640 | no_license | [
{
"docstring": "Get a list of the alphabet data in a more usable order",
"name": "get_L_alpha",
"signature": "def get_L_alpha(self)"
},
{
"docstring": "Get any relevant symbols from DSymbols",
"name": "get_L_symbols",
"signature": "def get_L_symbols(self, exclude_blank=True, len_limit=No... | 2 | stack_v2_sparse_classes_30k_train_010114 | Implement the Python class `Alphabets` described below.
Class description:
Implement the Alphabets class.
Method signatures and docstrings:
- def get_L_alpha(self): Get a list of the alphabet data in a more usable order
- def get_L_symbols(self, exclude_blank=True, len_limit=None): Get any relevant symbols from DSymb... | Implement the Python class `Alphabets` described below.
Class description:
Implement the Alphabets class.
Method signatures and docstrings:
- def get_L_alpha(self): Get a list of the alphabet data in a more usable order
- def get_L_symbols(self, exclude_blank=True, len_limit=None): Get any relevant symbols from DSymb... | 58ebdf9982457fc6cd9ea72a674d0619777d9d07 | <|skeleton|>
class Alphabets:
def get_L_alpha(self):
"""Get a list of the alphabet data in a more usable order"""
<|body_0|>
def get_L_symbols(self, exclude_blank=True, len_limit=None):
"""Get any relevant symbols from DSymbols"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Alphabets:
def get_L_alpha(self):
"""Get a list of the alphabet data in a more usable order"""
LPriority = ['', 'auxiliary', 'index', 'punctuation', 'currencySymbol']
DAlpha = self.D['DAlpha']
assert all((key in LPriority for key in DAlpha))
L = []
for key in LP... | the_stack_v2_python_sparse | lang_data/langdata_classes/Alphabets.py | mcyph/lang_data | train | 0 | |
6f97c9fe59b491b3f585e4695249f63f1543559a | [
"super().__init__(n_head, n_feat, dropout_rate)\nself.zero_triu = zero_triu\nself.linear_pos = nn.Linear(n_feat, n_feat, bias=False)\nself.pos_bias_u = nn.Parameter(torch.Tensor(self.h, self.d_k))\nself.pos_bias_v = nn.Parameter(torch.Tensor(self.h, self.d_k))\ntorch.nn.init.xavier_uniform_(self.pos_bias_u)\ntorch.... | <|body_start_0|>
super().__init__(n_head, n_feat, dropout_rate)
self.zero_triu = zero_triu
self.linear_pos = nn.Linear(n_feat, n_feat, bias=False)
self.pos_bias_u = nn.Parameter(torch.Tensor(self.h, self.d_k))
self.pos_bias_v = nn.Parameter(torch.Tensor(self.h, self.d_k))
... | Multi-Head Attention layer with relative position encoding (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): The number of heads. n_feat (int): The number of features. dropout_rate (float): Dropout rate. zero_triu (bool)... | RelPositionMultiHeadedAttention | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelPositionMultiHeadedAttention:
"""Multi-Head Attention layer with relative position encoding (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): The number of heads. n_feat (int): The number of fea... | stack_v2_sparse_classes_75kplus_train_074336 | 11,646 | permissive | [
{
"docstring": "Construct an RelPositionMultiHeadedAttention object.",
"name": "__init__",
"signature": "def __init__(self, n_head, n_feat, dropout_rate, zero_triu=False)"
},
{
"docstring": "Compute relative positional encoding. Args: x (torch.Tensor): Input tensor (batch, head, time1, 2*time1-1... | 3 | stack_v2_sparse_classes_30k_train_020308 | Implement the Python class `RelPositionMultiHeadedAttention` described below.
Class description:
Multi-Head Attention layer with relative position encoding (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): The number of... | Implement the Python class `RelPositionMultiHeadedAttention` described below.
Class description:
Multi-Head Attention layer with relative position encoding (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): The number of... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class RelPositionMultiHeadedAttention:
"""Multi-Head Attention layer with relative position encoding (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): The number of heads. n_feat (int): The number of fea... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RelPositionMultiHeadedAttention:
"""Multi-Head Attention layer with relative position encoding (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): The number of heads. n_feat (int): The number of features. dropou... | the_stack_v2_python_sparse | espnet/nets/pytorch_backend/transformer/attention.py | espnet/espnet | train | 7,242 |
577919043c0f591141055425e96e01912b45715f | [
"sql = self._grammar.compile_table_exists()\ndatabase = self._connection.get_database_name()\ntable = self._connection.get_table_prefix() + table\nreturn len(self._connection.select(sql, [database, table])) > 0",
"sql = self._grammar.compile_column_exists()\ndatabase = self._connection.get_database_name()\ntable ... | <|body_start_0|>
sql = self._grammar.compile_table_exists()
database = self._connection.get_database_name()
table = self._connection.get_table_prefix() + table
return len(self._connection.select(sql, [database, table])) > 0
<|end_body_0|>
<|body_start_1|>
sql = self._grammar.com... | MySQLSchemaBuilder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MySQLSchemaBuilder:
def has_table(self, table):
"""Determine if the given table exists. :param table: The table :type table: str :rtype: bool"""
<|body_0|>
def get_column_listing(self, table):
"""Get the column listing for a given table. :param table: The table :type... | stack_v2_sparse_classes_75kplus_train_074337 | 1,229 | permissive | [
{
"docstring": "Determine if the given table exists. :param table: The table :type table: str :rtype: bool",
"name": "has_table",
"signature": "def has_table(self, table)"
},
{
"docstring": "Get the column listing for a given table. :param table: The table :type table: str :rtype: list",
"na... | 2 | stack_v2_sparse_classes_30k_train_018030 | Implement the Python class `MySQLSchemaBuilder` described below.
Class description:
Implement the MySQLSchemaBuilder class.
Method signatures and docstrings:
- def has_table(self, table): Determine if the given table exists. :param table: The table :type table: str :rtype: bool
- def get_column_listing(self, table): ... | Implement the Python class `MySQLSchemaBuilder` described below.
Class description:
Implement the MySQLSchemaBuilder class.
Method signatures and docstrings:
- def has_table(self, table): Determine if the given table exists. :param table: The table :type table: str :rtype: bool
- def get_column_listing(self, table): ... | 375ffeb9b519ca1ac4cc5be4b61e87c0a82d1be4 | <|skeleton|>
class MySQLSchemaBuilder:
def has_table(self, table):
"""Determine if the given table exists. :param table: The table :type table: str :rtype: bool"""
<|body_0|>
def get_column_listing(self, table):
"""Get the column listing for a given table. :param table: The table :type... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MySQLSchemaBuilder:
def has_table(self, table):
"""Determine if the given table exists. :param table: The table :type table: str :rtype: bool"""
sql = self._grammar.compile_table_exists()
database = self._connection.get_database_name()
table = self._connection.get_table_prefix(... | the_stack_v2_python_sparse | orator/schema/mysql_builder.py | MasoniteFramework/orator | train | 1 | |
f2eeb20aa9fa426b92c637a34bce9d84c9030913 | [
"pygame.sprite.Sprite.__init__(self)\nself.image = image\nself.rect = self.image.get_rect()\nself.row = None\nself.col = None",
"self.row = row\nself.col = col\nself.rect.x = col * BaseTile.WIDTH\nself.rect.y = row * BaseTile.HEIGHT"
] | <|body_start_0|>
pygame.sprite.Sprite.__init__(self)
self.image = image
self.rect = self.image.get_rect()
self.row = None
self.col = None
<|end_body_0|>
<|body_start_1|>
self.row = row
self.col = col
self.rect.x = col * BaseTile.WIDTH
self.rect.y ... | Abstract class providing the base functionality of all game components (tiles) | BaseTile | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseTile:
"""Abstract class providing the base functionality of all game components (tiles)"""
def __init__(self, image):
"""Constructor of the base class :param image: the image of this tile"""
<|body_0|>
def setCoordinates(self, row, col):
"""Sets the coordinat... | stack_v2_sparse_classes_75kplus_train_074338 | 997 | no_license | [
{
"docstring": "Constructor of the base class :param image: the image of this tile",
"name": "__init__",
"signature": "def __init__(self, image)"
},
{
"docstring": "Sets the coordinates calculated by the row and column of this tile :param row: the row in which this tile is stored :param col: the... | 2 | stack_v2_sparse_classes_30k_train_029693 | Implement the Python class `BaseTile` described below.
Class description:
Abstract class providing the base functionality of all game components (tiles)
Method signatures and docstrings:
- def __init__(self, image): Constructor of the base class :param image: the image of this tile
- def setCoordinates(self, row, col... | Implement the Python class `BaseTile` described below.
Class description:
Abstract class providing the base functionality of all game components (tiles)
Method signatures and docstrings:
- def __init__(self, image): Constructor of the base class :param image: the image of this tile
- def setCoordinates(self, row, col... | 29bde2dd56b259cf65429553432f1166c77f1cd5 | <|skeleton|>
class BaseTile:
"""Abstract class providing the base functionality of all game components (tiles)"""
def __init__(self, image):
"""Constructor of the base class :param image: the image of this tile"""
<|body_0|>
def setCoordinates(self, row, col):
"""Sets the coordinat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseTile:
"""Abstract class providing the base functionality of all game components (tiles)"""
def __init__(self, image):
"""Constructor of the base class :param image: the image of this tile"""
pygame.sprite.Sprite.__init__(self)
self.image = image
self.rect = self.image.... | the_stack_v2_python_sparse | source/model/base/BaseTile.py | divid3byzero/zompy | train | 0 |
22b892923124f6f7b7432370b83ad91b0c545419 | [
"super(MaskNet, self).__init__()\nself.prep_block_1 = nn.Sequential(nn.Conv2d(in_channels=in_channels, out_channels=32, kernel_size=3, padding=1), nn.ReLU(), nn.BatchNorm2d(32), nn.Dropout(dropout_rate))\nself.prep_block_2 = nn.Sequential(nn.Conv2d(in_channels=in_channels, out_channels=32, kernel_size=3, padding=1)... | <|body_start_0|>
super(MaskNet, self).__init__()
self.prep_block_1 = nn.Sequential(nn.Conv2d(in_channels=in_channels, out_channels=32, kernel_size=3, padding=1), nn.ReLU(), nn.BatchNorm2d(32), nn.Dropout(dropout_rate))
self.prep_block_2 = nn.Sequential(nn.Conv2d(in_channels=in_channels, out_chan... | MaskNet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaskNet:
def __init__(self, dropout_rate=0.0, in_channels=3):
"""This function instantiates all the model layers."""
<|body_0|>
def forward(self, x):
"""This function defines the forward pass of the model. Args: x: Input. Returns: Model output."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_074339 | 1,855 | permissive | [
{
"docstring": "This function instantiates all the model layers.",
"name": "__init__",
"signature": "def __init__(self, dropout_rate=0.0, in_channels=3)"
},
{
"docstring": "This function defines the forward pass of the model. Args: x: Input. Returns: Model output.",
"name": "forward",
"s... | 2 | stack_v2_sparse_classes_30k_train_025166 | Implement the Python class `MaskNet` described below.
Class description:
Implement the MaskNet class.
Method signatures and docstrings:
- def __init__(self, dropout_rate=0.0, in_channels=3): This function instantiates all the model layers.
- def forward(self, x): This function defines the forward pass of the model. A... | Implement the Python class `MaskNet` described below.
Class description:
Implement the MaskNet class.
Method signatures and docstrings:
- def __init__(self, dropout_rate=0.0, in_channels=3): This function instantiates all the model layers.
- def forward(self, x): This function defines the forward pass of the model. A... | 2eea883c96bf106774ea94464fc16c6baea86a95 | <|skeleton|>
class MaskNet:
def __init__(self, dropout_rate=0.0, in_channels=3):
"""This function instantiates all the model layers."""
<|body_0|>
def forward(self, x):
"""This function defines the forward pass of the model. Args: x: Input. Returns: Model output."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MaskNet:
def __init__(self, dropout_rate=0.0, in_channels=3):
"""This function instantiates all the model layers."""
super(MaskNet, self).__init__()
self.prep_block_1 = nn.Sequential(nn.Conv2d(in_channels=in_channels, out_channels=32, kernel_size=3, padding=1), nn.ReLU(), nn.BatchNorm2... | the_stack_v2_python_sparse | tensornet/model/masknet.py | shan18/Depth-Estimation-Segmentation | train | 7 | |
a027225a268261d7be57c270a5b84973e0b3a403 | [
"activation_counters = network.activation_counters\n_counter = 0\n_size = 0\nfor counter in activation_counters:\n _counter += np.count_nonzero(counter)\n _size += counter.size\nreturn _counter / _size",
"inactivation_counters = network.inactivation_counters\n_counter = 0\n_size = 0\nfor counter in inactiva... | <|body_start_0|>
activation_counters = network.activation_counters
_counter = 0
_size = 0
for counter in activation_counters:
_counter += np.count_nonzero(counter)
_size += counter.size
return _counter / _size
<|end_body_0|>
<|body_start_1|>
inact... | Coverage | [
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Coverage:
def activation_rate(network):
""":type network: Network :rtype: np.ndarray"""
<|body_0|>
def inactivation_rate(network):
""":type network: Network :rtype: np.ndarray"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
activation_counters = net... | stack_v2_sparse_classes_75kplus_train_074340 | 38,616 | permissive | [
{
"docstring": ":type network: Network :rtype: np.ndarray",
"name": "activation_rate",
"signature": "def activation_rate(network)"
},
{
"docstring": ":type network: Network :rtype: np.ndarray",
"name": "inactivation_rate",
"signature": "def inactivation_rate(network)"
}
] | 2 | null | Implement the Python class `Coverage` described below.
Class description:
Implement the Coverage class.
Method signatures and docstrings:
- def activation_rate(network): :type network: Network :rtype: np.ndarray
- def inactivation_rate(network): :type network: Network :rtype: np.ndarray | Implement the Python class `Coverage` described below.
Class description:
Implement the Coverage class.
Method signatures and docstrings:
- def activation_rate(network): :type network: Network :rtype: np.ndarray
- def inactivation_rate(network): :type network: Network :rtype: np.ndarray
<|skeleton|>
class Coverage:
... | 6444a7b4f22faffbfddd2ef2bfcfda5505ff677c | <|skeleton|>
class Coverage:
def activation_rate(network):
""":type network: Network :rtype: np.ndarray"""
<|body_0|>
def inactivation_rate(network):
""":type network: Network :rtype: np.ndarray"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Coverage:
def activation_rate(network):
""":type network: Network :rtype: np.ndarray"""
activation_counters = network.activation_counters
_counter = 0
_size = 0
for counter in activation_counters:
_counter += np.count_nonzero(counter)
_size += co... | the_stack_v2_python_sparse | ait_repository/ait/eval_dnn_coverage_tf1.13_0.1/develop/deep_saucer/neuron_coverage/tensorflow_native/lib/nnutil.py | aistairc/qunomon | train | 17 | |
8d17a3dfdf09ec3331b1ed5b17c29281b53780c3 | [
"test = '6\\n1 5\\n2 6\\n3 7'\nself.assertEqual(calculate(test), '1 2 3')\nself.assertEqual(get_inputs(test), [6, [1, 5], [2, 6], [3, 7]])\ntest = '10\\n1 2\\n1 3\\n1 5'\nself.assertEqual(calculate(test), '2 3 5')\ntest = '6\\n1 3\\n2 2\\n2 2'\nself.assertEqual(calculate(test), '2 2 2')",
"d = Diploma([6, [1, 5],... | <|body_start_0|>
test = '6\n1 5\n2 6\n3 7'
self.assertEqual(calculate(test), '1 2 3')
self.assertEqual(get_inputs(test), [6, [1, 5], [2, 6], [3, 7]])
test = '10\n1 2\n1 3\n1 5'
self.assertEqual(calculate(test), '2 3 5')
test = '6\n1 3\n2 2\n2 2'
self.assertEqual(c... | unitTests | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class unitTests:
def test_sample_tests(self):
"""Quiz sample tests. Add to separate lines"""
<|body_0|>
def test_Diploma_class__basic_functions(self):
"""Diploma class basic functions testing"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
test = '6\n1 5\... | stack_v2_sparse_classes_75kplus_train_074341 | 3,299 | permissive | [
{
"docstring": "Quiz sample tests. Add to separate lines",
"name": "test_sample_tests",
"signature": "def test_sample_tests(self)"
},
{
"docstring": "Diploma class basic functions testing",
"name": "test_Diploma_class__basic_functions",
"signature": "def test_Diploma_class__basic_functio... | 2 | stack_v2_sparse_classes_30k_train_044791 | Implement the Python class `unitTests` described below.
Class description:
Implement the unitTests class.
Method signatures and docstrings:
- def test_sample_tests(self): Quiz sample tests. Add to separate lines
- def test_Diploma_class__basic_functions(self): Diploma class basic functions testing | Implement the Python class `unitTests` described below.
Class description:
Implement the unitTests class.
Method signatures and docstrings:
- def test_sample_tests(self): Quiz sample tests. Add to separate lines
- def test_Diploma_class__basic_functions(self): Diploma class basic functions testing
<|skeleton|>
class... | ae02ea872ca91ef98630cc172a844b82cc56f621 | <|skeleton|>
class unitTests:
def test_sample_tests(self):
"""Quiz sample tests. Add to separate lines"""
<|body_0|>
def test_Diploma_class__basic_functions(self):
"""Diploma class basic functions testing"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class unitTests:
def test_sample_tests(self):
"""Quiz sample tests. Add to separate lines"""
test = '6\n1 5\n2 6\n3 7'
self.assertEqual(calculate(test), '1 2 3')
self.assertEqual(get_inputs(test), [6, [1, 5], [2, 6], [3, 7]])
test = '10\n1 2\n1 3\n1 5'
self.assertEqua... | the_stack_v2_python_sparse | codeforces/557A_diploma.py | snsokolov/contests | train | 1 | |
07f41fdb328d4d9ceffe03f0108a714711a5ddb9 | [
"simulate_insert_data()\ndata = {'name': 'First Deliver', 'backlog': 1, 'order': 1}\nresponse = client.post('/api/backlog/1/stories/', data, format='json')\nself.assertEqual(response.status_code, status.HTTP_201_CREATED)",
"simulate_insert_data()\nresponse = client.get('/api/backlog/1/stories/', format='json')\ns... | <|body_start_0|>
simulate_insert_data()
data = {'name': 'First Deliver', 'backlog': 1, 'order': 1}
response = client.post('/api/backlog/1/stories/', data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
<|end_body_0|>
<|body_start_1|>
simulate_inse... | StoryList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StoryList:
def test_insert_story(self):
"""Insert new story"""
<|body_0|>
def test_story_list(self):
"""Retrieve sotries"""
<|body_1|>
def test_retrieve_story(self):
"""Retrieve story by id"""
<|body_2|>
def test_edit_story_name(self... | stack_v2_sparse_classes_75kplus_train_074342 | 4,419 | no_license | [
{
"docstring": "Insert new story",
"name": "test_insert_story",
"signature": "def test_insert_story(self)"
},
{
"docstring": "Retrieve sotries",
"name": "test_story_list",
"signature": "def test_story_list(self)"
},
{
"docstring": "Retrieve story by id",
"name": "test_retriev... | 5 | stack_v2_sparse_classes_30k_train_028074 | Implement the Python class `StoryList` described below.
Class description:
Implement the StoryList class.
Method signatures and docstrings:
- def test_insert_story(self): Insert new story
- def test_story_list(self): Retrieve sotries
- def test_retrieve_story(self): Retrieve story by id
- def test_edit_story_name(sel... | Implement the Python class `StoryList` described below.
Class description:
Implement the StoryList class.
Method signatures and docstrings:
- def test_insert_story(self): Insert new story
- def test_story_list(self): Retrieve sotries
- def test_retrieve_story(self): Retrieve story by id
- def test_edit_story_name(sel... | 905f071ff963b9bad61610e944b1cef01fc95b33 | <|skeleton|>
class StoryList:
def test_insert_story(self):
"""Insert new story"""
<|body_0|>
def test_story_list(self):
"""Retrieve sotries"""
<|body_1|>
def test_retrieve_story(self):
"""Retrieve story by id"""
<|body_2|>
def test_edit_story_name(self... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StoryList:
def test_insert_story(self):
"""Insert new story"""
simulate_insert_data()
data = {'name': 'First Deliver', 'backlog': 1, 'order': 1}
response = client.post('/api/backlog/1/stories/', data, format='json')
self.assertEqual(response.status_code, status.HTTP_201... | the_stack_v2_python_sparse | backlog/tests.py | rcdigital/kanban-server | train | 0 | |
2fe84bdcae5fc8950307bd933d938cec498485bc | [
"mock_input = MockInputApi()\nmock_input.files = [MockFile('path/One.java', ['new AlertDialog.Builder()']), MockFile('path/Two.java', ['new AlertDialog.Builder(context);'])]\nerrors = PRESUBMIT._CheckAlertDialogBuilder(mock_input, MockOutputApi())\nself.assertEqual(1, len(errors))\nself.assertEqual(2, len(errors[0]... | <|body_start_0|>
mock_input = MockInputApi()
mock_input.files = [MockFile('path/One.java', ['new AlertDialog.Builder()']), MockFile('path/Two.java', ['new AlertDialog.Builder(context);'])]
errors = PRESUBMIT._CheckAlertDialogBuilder(mock_input, MockOutputApi())
self.assertEqual(1, len(er... | Test the _CheckAlertDialogBuilder presubmit check. | CheckAlertDialogBuilder | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckAlertDialogBuilder:
"""Test the _CheckAlertDialogBuilder presubmit check."""
def testTruePositives(self):
"""Examples of when AlertDialog.Builder use is correctly flagged."""
<|body_0|>
def testFalsePositives(self):
"""Examples of when AlertDialog.Builder sh... | stack_v2_sparse_classes_75kplus_train_074343 | 9,227 | permissive | [
{
"docstring": "Examples of when AlertDialog.Builder use is correctly flagged.",
"name": "testTruePositives",
"signature": "def testTruePositives(self)"
},
{
"docstring": "Examples of when AlertDialog.Builder should not be flagged.",
"name": "testFalsePositives",
"signature": "def testFa... | 4 | stack_v2_sparse_classes_30k_train_023627 | Implement the Python class `CheckAlertDialogBuilder` described below.
Class description:
Test the _CheckAlertDialogBuilder presubmit check.
Method signatures and docstrings:
- def testTruePositives(self): Examples of when AlertDialog.Builder use is correctly flagged.
- def testFalsePositives(self): Examples of when A... | Implement the Python class `CheckAlertDialogBuilder` described below.
Class description:
Test the _CheckAlertDialogBuilder presubmit check.
Method signatures and docstrings:
- def testTruePositives(self): Examples of when AlertDialog.Builder use is correctly flagged.
- def testFalsePositives(self): Examples of when A... | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | <|skeleton|>
class CheckAlertDialogBuilder:
"""Test the _CheckAlertDialogBuilder presubmit check."""
def testTruePositives(self):
"""Examples of when AlertDialog.Builder use is correctly flagged."""
<|body_0|>
def testFalsePositives(self):
"""Examples of when AlertDialog.Builder sh... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CheckAlertDialogBuilder:
"""Test the _CheckAlertDialogBuilder presubmit check."""
def testTruePositives(self):
"""Examples of when AlertDialog.Builder use is correctly flagged."""
mock_input = MockInputApi()
mock_input.files = [MockFile('path/One.java', ['new AlertDialog.Builder()... | the_stack_v2_python_sparse | chrome/android/java/src/PRESUBMIT_test.py | chromium/chromium | train | 17,408 |
62f96a6d2ff09586914263ebfbdb2827d8ad5e38 | [
"view = cls.as_view('periodic_incomes')\napp.add_url_rule('/api/budgets/<int:budget_id>/periodic-incomes', defaults={'income_id': None}, view_func=view, methods=['GET'])\napp.add_url_rule('/api/budgets/<int:budget_id>/periodic-incomes', view_func=view, methods=['POST'])\napp.add_url_rule('/api/budget-periodic-incom... | <|body_start_0|>
view = cls.as_view('periodic_incomes')
app.add_url_rule('/api/budgets/<int:budget_id>/periodic-incomes', defaults={'income_id': None}, view_func=view, methods=['GET'])
app.add_url_rule('/api/budgets/<int:budget_id>/periodic-incomes', view_func=view, methods=['POST'])
app... | Periodic income REST resource view | PeriodicIncomesView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PeriodicIncomesView:
"""Periodic income REST resource view"""
def register(cls, app: Flask):
"""Registers routes for this view"""
<|body_0|>
def get(budget_id: Optional[int], income_id: Optional[int]):
"""Gets a specific periodic income or all incomes in the spec... | stack_v2_sparse_classes_75kplus_train_074344 | 17,779 | permissive | [
{
"docstring": "Registers routes for this view",
"name": "register",
"signature": "def register(cls, app: Flask)"
},
{
"docstring": "Gets a specific periodic income or all incomes in the specified budget",
"name": "get",
"signature": "def get(budget_id: Optional[int], income_id: Optional... | 5 | stack_v2_sparse_classes_30k_train_040483 | Implement the Python class `PeriodicIncomesView` described below.
Class description:
Periodic income REST resource view
Method signatures and docstrings:
- def register(cls, app: Flask): Registers routes for this view
- def get(budget_id: Optional[int], income_id: Optional[int]): Gets a specific periodic income or al... | Implement the Python class `PeriodicIncomesView` described below.
Class description:
Periodic income REST resource view
Method signatures and docstrings:
- def register(cls, app: Flask): Registers routes for this view
- def get(budget_id: Optional[int], income_id: Optional[int]): Gets a specific periodic income or al... | 20d992356952542fd79aab69849a04129fa22de2 | <|skeleton|>
class PeriodicIncomesView:
"""Periodic income REST resource view"""
def register(cls, app: Flask):
"""Registers routes for this view"""
<|body_0|>
def get(budget_id: Optional[int], income_id: Optional[int]):
"""Gets a specific periodic income or all incomes in the spec... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PeriodicIncomesView:
"""Periodic income REST resource view"""
def register(cls, app: Flask):
"""Registers routes for this view"""
view = cls.as_view('periodic_incomes')
app.add_url_rule('/api/budgets/<int:budget_id>/periodic-incomes', defaults={'income_id': None}, view_func=view, ... | the_stack_v2_python_sparse | backend/underbudget/views/budgets.py | vimofthevine/underbudget4 | train | 0 |
8dd83da0fd67b0a131220d441fbafda02da776d7 | [
"super(Transformer, self).__init__()\nself.encoder = Encoder(N, dm, h, hidden, input_vocab, max_seq_input, drop_rate)\nself.decoder = Decoder(N, dm, h, hidden, target_vocab, max_seq_target, drop_rate)\nself.linear = tf.keras.layers.Dense(target_vocab)",
"enc_output = self.encoder(inputs, training, encoder_mask)\n... | <|body_start_0|>
super(Transformer, self).__init__()
self.encoder = Encoder(N, dm, h, hidden, input_vocab, max_seq_input, drop_rate)
self.decoder = Decoder(N, dm, h, hidden, target_vocab, max_seq_target, drop_rate)
self.linear = tf.keras.layers.Dense(target_vocab)
<|end_body_0|>
<|body_... | Transformer class for machine translation | Transformer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Transformer:
"""Transformer class for machine translation"""
def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1):
"""Class constructor :param N: number of blocks in the encoder :param dm: dimensionality of the model :param h: ... | stack_v2_sparse_classes_75kplus_train_074345 | 16,008 | no_license | [
{
"docstring": "Class constructor :param N: number of blocks in the encoder :param dm: dimensionality of the model :param h: number of heads :param hidden: number of hidden units in the fully connected layers :param input_vocab: size of the input vocabulary :param target_vocab: size of the target vocabulary :pa... | 2 | stack_v2_sparse_classes_30k_train_047526 | Implement the Python class `Transformer` described below.
Class description:
Transformer class for machine translation
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1): Class constructor :param N: number of blocks in the ... | Implement the Python class `Transformer` described below.
Class description:
Transformer class for machine translation
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1): Class constructor :param N: number of blocks in the ... | f83a60babb1d2a510a4a0e0f58aa3880fd9f93a7 | <|skeleton|>
class Transformer:
"""Transformer class for machine translation"""
def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1):
"""Class constructor :param N: number of blocks in the encoder :param dm: dimensionality of the model :param h: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Transformer:
"""Transformer class for machine translation"""
def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1):
"""Class constructor :param N: number of blocks in the encoder :param dm: dimensionality of the model :param h: number of hea... | the_stack_v2_python_sparse | supervised_learning/0x12-transformer_apps/5-transformer.py | jalondono/holbertonschool-machine_learning | train | 2 |
14c4bc9375274d83f0d9cdd9799505ba24934674 | [
"assert isinstance(output_size, (int, tuple))\nassert isinstance(return_tensor, bool)\nassert isinstance(channel_first, bool)\nassert isinstance(interpolation, int)\nself.output_size = output_size\nself.return_tensor = return_tensor\nself.channel_first = channel_first\nself.interpolation = interpolation",
"if sel... | <|body_start_0|>
assert isinstance(output_size, (int, tuple))
assert isinstance(return_tensor, bool)
assert isinstance(channel_first, bool)
assert isinstance(interpolation, int)
self.output_size = output_size
self.return_tensor = return_tensor
self.channel_first =... | Rescales a collection of images in a given sample, to a specified size. | BatchRescale | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchRescale:
"""Rescales a collection of images in a given sample, to a specified size."""
def __init__(self, output_size, return_tensor=True, channel_first=True, interpolation=cv2.INTER_LANCZOS4):
"""Instantiates a new BatchResize object. Parameters ---------- output_size : int or ... | stack_v2_sparse_classes_75kplus_train_074346 | 14,169 | no_license | [
{
"docstring": "Instantiates a new BatchResize object. Parameters ---------- output_size : int or tuple The output size of the image (height and width). If an integer is passed as input, then the output size of the image is determined by scaling the height and width of the original image. return_tensor : {True,... | 2 | stack_v2_sparse_classes_30k_train_002389 | Implement the Python class `BatchRescale` described below.
Class description:
Rescales a collection of images in a given sample, to a specified size.
Method signatures and docstrings:
- def __init__(self, output_size, return_tensor=True, channel_first=True, interpolation=cv2.INTER_LANCZOS4): Instantiates a new BatchR... | Implement the Python class `BatchRescale` described below.
Class description:
Rescales a collection of images in a given sample, to a specified size.
Method signatures and docstrings:
- def __init__(self, output_size, return_tensor=True, channel_first=True, interpolation=cv2.INTER_LANCZOS4): Instantiates a new BatchR... | a7c30481822ecb945e3ff6ad184d104361a40ed1 | <|skeleton|>
class BatchRescale:
"""Rescales a collection of images in a given sample, to a specified size."""
def __init__(self, output_size, return_tensor=True, channel_first=True, interpolation=cv2.INTER_LANCZOS4):
"""Instantiates a new BatchResize object. Parameters ---------- output_size : int or ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BatchRescale:
"""Rescales a collection of images in a given sample, to a specified size."""
def __init__(self, output_size, return_tensor=True, channel_first=True, interpolation=cv2.INTER_LANCZOS4):
"""Instantiates a new BatchResize object. Parameters ---------- output_size : int or tuple The out... | the_stack_v2_python_sparse | cheapfake/contrib/transforms.py | hu-simon/cheapfake | train | 0 |
52cc72e60050d0cadc5046ccb55c6952a6ca1dbc | [
"self.async_see = async_see\nself.hass = hass\nself.rssi = config['rssi_threshold']\nself.device_types = config['device_types']\nself.host = config['host']\nself.client = client",
"await self.client.update_info(self.host)\ndata = self.hass.data[GOOGLEHOME_DOMAIN][self.host]\ninfo = data.get('info', {})\nconnected... | <|body_start_0|>
self.async_see = async_see
self.hass = hass
self.rssi = config['rssi_threshold']
self.device_types = config['device_types']
self.host = config['host']
self.client = client
<|end_body_0|>
<|body_start_1|>
await self.client.update_info(self.host)
... | This class queries a Google Home unit. | GoogleHomeDeviceScanner | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoogleHomeDeviceScanner:
"""This class queries a Google Home unit."""
def __init__(self, hass, client, config, async_see):
"""Initialize the scanner."""
<|body_0|>
async def async_init(self):
"""Further initialize connection to Google Home."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_074347 | 2,974 | permissive | [
{
"docstring": "Initialize the scanner.",
"name": "__init__",
"signature": "def __init__(self, hass, client, config, async_see)"
},
{
"docstring": "Further initialize connection to Google Home.",
"name": "async_init",
"signature": "async def async_init(self)"
},
{
"docstring": "E... | 3 | stack_v2_sparse_classes_30k_train_047425 | Implement the Python class `GoogleHomeDeviceScanner` described below.
Class description:
This class queries a Google Home unit.
Method signatures and docstrings:
- def __init__(self, hass, client, config, async_see): Initialize the scanner.
- async def async_init(self): Further initialize connection to Google Home.
-... | Implement the Python class `GoogleHomeDeviceScanner` described below.
Class description:
This class queries a Google Home unit.
Method signatures and docstrings:
- def __init__(self, hass, client, config, async_see): Initialize the scanner.
- async def async_init(self): Further initialize connection to Google Home.
-... | 6e414983738d9495eb9e4f858e3e98e9e38869db | <|skeleton|>
class GoogleHomeDeviceScanner:
"""This class queries a Google Home unit."""
def __init__(self, hass, client, config, async_see):
"""Initialize the scanner."""
<|body_0|>
async def async_init(self):
"""Further initialize connection to Google Home."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GoogleHomeDeviceScanner:
"""This class queries a Google Home unit."""
def __init__(self, hass, client, config, async_see):
"""Initialize the scanner."""
self.async_see = async_see
self.hass = hass
self.rssi = config['rssi_threshold']
self.device_types = config['dev... | the_stack_v2_python_sparse | homeassistant/components/googlehome/device_tracker.py | Watemlifts/home-assistant | train | 4 |
0415ca197e2d5b45e7c1a1ca8b861664c81447ea | [
"super(GoogleCloudDiskExportStream, self).__init__(state, name=name, critical=critical)\nself.source_project = None\nself.gcs_output_location = str()\nself.remote_instance_name = None\nself.source_disk_names = []\nself.all_disks = False\nself.source_disks = []\nself.startup_script = str()\nself.boot_image_project =... | <|body_start_0|>
super(GoogleCloudDiskExportStream, self).__init__(state, name=name, critical=critical)
self.source_project = None
self.gcs_output_location = str()
self.remote_instance_name = None
self.source_disk_names = []
self.all_disks = False
self.source_disk... | Google Cloud Platform (GCP) disk bit-stream export. Attributes: source_project (gcp_project.GoogleCloudProject): Source project containing the disk/s to export. gcs_output_location (str): Google Cloud Storage parent bucket/folder path of the exported image. remote_instance_name (str): Instance that needs analysis. sour... | GoogleCloudDiskExportStream | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoogleCloudDiskExportStream:
"""Google Cloud Platform (GCP) disk bit-stream export. Attributes: source_project (gcp_project.GoogleCloudProject): Source project containing the disk/s to export. gcs_output_location (str): Google Cloud Storage parent bucket/folder path of the exported image. remote_... | stack_v2_sparse_classes_75kplus_train_074348 | 9,462 | permissive | [
{
"docstring": "Initializes a Google Cloud Platform (GCP) Disk Export. Args: state (DFTimewolfState): recipe state. name (Optional[str]): The module's runtime name. critical (Optional[bool]): True if the module is critical, which causes the entire recipe to fail if the module encounters an error.",
"name": ... | 4 | null | Implement the Python class `GoogleCloudDiskExportStream` described below.
Class description:
Google Cloud Platform (GCP) disk bit-stream export. Attributes: source_project (gcp_project.GoogleCloudProject): Source project containing the disk/s to export. gcs_output_location (str): Google Cloud Storage parent bucket/fol... | Implement the Python class `GoogleCloudDiskExportStream` described below.
Class description:
Google Cloud Platform (GCP) disk bit-stream export. Attributes: source_project (gcp_project.GoogleCloudProject): Source project containing the disk/s to export. gcs_output_location (str): Google Cloud Storage parent bucket/fol... | bcea85b1ce7a0feb2aa28b5be4fc6ae124e8ca3c | <|skeleton|>
class GoogleCloudDiskExportStream:
"""Google Cloud Platform (GCP) disk bit-stream export. Attributes: source_project (gcp_project.GoogleCloudProject): Source project containing the disk/s to export. gcs_output_location (str): Google Cloud Storage parent bucket/folder path of the exported image. remote_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GoogleCloudDiskExportStream:
"""Google Cloud Platform (GCP) disk bit-stream export. Attributes: source_project (gcp_project.GoogleCloudProject): Source project containing the disk/s to export. gcs_output_location (str): Google Cloud Storage parent bucket/folder path of the exported image. remote_instance_name... | the_stack_v2_python_sparse | dftimewolf/lib/exporters/gce_disk_export_dd.py | log2timeline/dftimewolf | train | 248 |
8cf5f2d249f33c5bf2ee43bee2de57f7c5c4993c | [
"self.aws_kms = aws_kms\nself.azure_kms = azure_kms\nself.cryptsoft_kms = cryptsoft_kms\nself.id = id\nself.key_name = key_name\nself.ownership_context = ownership_context\nself.server_name = server_name\nself.server_type = server_type\nself.usage_type = usage_type\nself.vault_id_list = vault_id_list\nself.view_box... | <|body_start_0|>
self.aws_kms = aws_kms
self.azure_kms = azure_kms
self.cryptsoft_kms = cryptsoft_kms
self.id = id
self.key_name = key_name
self.ownership_context = ownership_context
self.server_name = server_name
self.server_type = server_type
sel... | Implementation of the 'KmsCreateRequestParameters' model. TODO: type description here. Attributes: aws_kms (AwsKmsConfiguration): AWS KMS conifg. azure_kms (AzureKmsConfiguration): Azure KMS config. cryptsoft_kms (CryptsoftKmsConfiguration): Cryptsoft KMS config. id (long|int): The Id of a KMS server. key_name (string)... | KmsCreateRequestParameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KmsCreateRequestParameters:
"""Implementation of the 'KmsCreateRequestParameters' model. TODO: type description here. Attributes: aws_kms (AwsKmsConfiguration): AWS KMS conifg. azure_kms (AzureKmsConfiguration): Azure KMS config. cryptsoft_kms (CryptsoftKmsConfiguration): Cryptsoft KMS config. id... | stack_v2_sparse_classes_75kplus_train_074349 | 5,086 | permissive | [
{
"docstring": "Constructor for the KmsCreateRequestParameters class",
"name": "__init__",
"signature": "def __init__(self, aws_kms=None, azure_kms=None, cryptsoft_kms=None, id=None, key_name=None, ownership_context=None, server_name=None, server_type=None, usage_type=None, vault_id_list=None, view_box_... | 2 | stack_v2_sparse_classes_30k_val_000732 | Implement the Python class `KmsCreateRequestParameters` described below.
Class description:
Implementation of the 'KmsCreateRequestParameters' model. TODO: type description here. Attributes: aws_kms (AwsKmsConfiguration): AWS KMS conifg. azure_kms (AzureKmsConfiguration): Azure KMS config. cryptsoft_kms (CryptsoftKmsC... | Implement the Python class `KmsCreateRequestParameters` described below.
Class description:
Implementation of the 'KmsCreateRequestParameters' model. TODO: type description here. Attributes: aws_kms (AwsKmsConfiguration): AWS KMS conifg. azure_kms (AzureKmsConfiguration): Azure KMS config. cryptsoft_kms (CryptsoftKmsC... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class KmsCreateRequestParameters:
"""Implementation of the 'KmsCreateRequestParameters' model. TODO: type description here. Attributes: aws_kms (AwsKmsConfiguration): AWS KMS conifg. azure_kms (AzureKmsConfiguration): Azure KMS config. cryptsoft_kms (CryptsoftKmsConfiguration): Cryptsoft KMS config. id... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KmsCreateRequestParameters:
"""Implementation of the 'KmsCreateRequestParameters' model. TODO: type description here. Attributes: aws_kms (AwsKmsConfiguration): AWS KMS conifg. azure_kms (AzureKmsConfiguration): Azure KMS config. cryptsoft_kms (CryptsoftKmsConfiguration): Cryptsoft KMS config. id (long|int): ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/kms_create_request_parameters.py | cohesity/management-sdk-python | train | 24 |
514d681b79e1811b3d17e3d565fc98414f59eedf | [
"if not s:\n return False\nss = (s + s)[1:-1]\nreturn ss.find(s) != -1",
"if not s:\n return False\nsub, j = (s[0], 0)\nfor i, c in enumerate(s):\n if c == sub[j % len(sub)]:\n j += 1\n else:\n sub = s[:i + 1]\n j = 0\nreturn len(sub) < len(s) and j % len(sub) == 0",
"if not s:\... | <|body_start_0|>
if not s:
return False
ss = (s + s)[1:-1]
return ss.find(s) != -1
<|end_body_0|>
<|body_start_1|>
if not s:
return False
sub, j = (s[0], 0)
for i, c in enumerate(s):
if c == sub[j % len(sub)]:
j += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def repeatedSubstringPattern(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def repeatedSubstringPattern2(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
def repeatedSubstringPattern3(self, s):
""":type s: str :rtype: bool"""... | stack_v2_sparse_classes_75kplus_train_074350 | 3,316 | no_license | [
{
"docstring": ":type s: str :rtype: bool",
"name": "repeatedSubstringPattern",
"signature": "def repeatedSubstringPattern(self, s)"
},
{
"docstring": ":type s: str :rtype: bool",
"name": "repeatedSubstringPattern2",
"signature": "def repeatedSubstringPattern2(self, s)"
},
{
"doc... | 3 | stack_v2_sparse_classes_30k_train_012249 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def repeatedSubstringPattern(self, s): :type s: str :rtype: bool
- def repeatedSubstringPattern2(self, s): :type s: str :rtype: bool
- def repeatedSubstringPattern3(self, s): :ty... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def repeatedSubstringPattern(self, s): :type s: str :rtype: bool
- def repeatedSubstringPattern2(self, s): :type s: str :rtype: bool
- def repeatedSubstringPattern3(self, s): :ty... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class Solution:
def repeatedSubstringPattern(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def repeatedSubstringPattern2(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
def repeatedSubstringPattern3(self, s):
""":type s: str :rtype: bool"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def repeatedSubstringPattern(self, s):
""":type s: str :rtype: bool"""
if not s:
return False
ss = (s + s)[1:-1]
return ss.find(s) != -1
def repeatedSubstringPattern2(self, s):
""":type s: str :rtype: bool"""
if not s:
retu... | the_stack_v2_python_sparse | code459RepeatedSubstringPattern.py | cybelewang/leetcode-python | train | 0 | |
cce4aa66783c70ed172f79b9d1aadf8f253cec52 | [
"legalMoves = gameState.getLegalActions()\nscores = [self.evaluationFunction(gameState, action) for action in legalMoves]\nbestScore = max(scores)\nbestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]\nchosenIndex = random.choice(bestIndices)\n'Add more of your code here if you want t... | <|body_start_0|>
legalMoves = gameState.getLegalActions()
scores = [self.evaluationFunction(gameState, action) for action in legalMoves]
bestScore = max(scores)
bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]
chosenIndex = random.choice(bestInd... | A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. | ReflexAgent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReflexAgent:
"""A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers."""
def getAction(sel... | stack_v2_sparse_classes_75kplus_train_074351 | 19,430 | no_license | [
{
"docstring": "You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop}",
"... | 2 | null | Implement the Python class `ReflexAgent` described below.
Class description:
A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our me... | Implement the Python class `ReflexAgent` described below.
Class description:
A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our me... | bba0e130afbdf916f269e936766bde38bac4dbc6 | <|skeleton|>
class ReflexAgent:
"""A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers."""
def getAction(sel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReflexAgent:
"""A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers."""
def getAction(self, gameState)... | the_stack_v2_python_sparse | CS565/Project 2/cs465-2-multiagent/multiAgents.py | brandondonato/College-Coursework | train | 0 |
91ed2256d5e7684918185c40e61204051f75266c | [
"for i in range(len(nums)):\n if nums[i] < nums[0]:\n return nums[i]\nreturn nums[0]",
"if len(nums) == 1 or nums[-1] > nums[0]:\n return nums[0]\nleft = 0\nright = len(nums) - 1\nwhile left < right:\n mid = (left + right) // 2\n if nums[mid] > nums[right]:\n left = mid + 1\n elif num... | <|body_start_0|>
for i in range(len(nums)):
if nums[i] < nums[0]:
return nums[i]
return nums[0]
<|end_body_0|>
<|body_start_1|>
if len(nums) == 1 or nums[-1] > nums[0]:
return nums[0]
left = 0
right = len(nums) - 1
while left < rig... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMin1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findMin(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for i in range(len(nums)):
if nums[i] < ... | stack_v2_sparse_classes_75kplus_train_074352 | 1,261 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findMin1",
"signature": "def findMin1(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findMin",
"signature": "def findMin(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016750 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMin1(self, nums): :type nums: List[int] :rtype: int
- def findMin(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMin1(self, nums): :type nums: List[int] :rtype: int
- def findMin(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def findMin1(self, num... | eedf73b5f167025a97f0905d3718b6eab2ee3e09 | <|skeleton|>
class Solution:
def findMin1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findMin(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findMin1(self, nums):
""":type nums: List[int] :rtype: int"""
for i in range(len(nums)):
if nums[i] < nums[0]:
return nums[i]
return nums[0]
def findMin(self, nums):
""":type nums: List[int] :rtype: int"""
if len(nums) == 1... | the_stack_v2_python_sparse | Array/154_Find_Minimum_in_Rotated_Sorted_Array_II.py | xiaomojie/LeetCode | train | 0 | |
017ed110f3be1d577f61cce7835889f908176984 | [
"self.parameters = parameters\nself.sigma_init = sigma_init\nself.Matcher = Matcher\nself.Sigma_guesser = Sigma_guesser\nself.Diagonaliser = Diagonaliser\nself.State_init = State_init",
"state_list = self.State_init(self.Diagonaliser.h0)\nsigma = self.sigma_init\nall_failures = []\nfor p in tqdm(self.parameters):... | <|body_start_0|>
self.parameters = parameters
self.sigma_init = sigma_init
self.Matcher = Matcher
self.Sigma_guesser = Sigma_guesser
self.Diagonaliser = Diagonaliser
self.State_init = State_init
<|end_body_0|>
<|body_start_1|>
state_list = self.State_init(self.Di... | Solver | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solver:
def __init__(self, State_init, Matcher, Sigma_guesser, Diagonaliser, parameters, sigma_init):
"""solver class is a loop which computes eigenvalues and eigenvectors, and calls various plug-in classes to perform logic on the output values. Not intended to be called by a person, the... | stack_v2_sparse_classes_75kplus_train_074353 | 2,805 | permissive | [
{
"docstring": "solver class is a loop which computes eigenvalues and eigenvectors, and calls various plug-in classes to perform logic on the output values. Not intended to be called by a person, the userinterface generates this class. Parameters ----------",
"name": "__init__",
"signature": "def __init... | 3 | stack_v2_sparse_classes_30k_train_043054 | Implement the Python class `Solver` described below.
Class description:
Implement the Solver class.
Method signatures and docstrings:
- def __init__(self, State_init, Matcher, Sigma_guesser, Diagonaliser, parameters, sigma_init): solver class is a loop which computes eigenvalues and eigenvectors, and calls various pl... | Implement the Python class `Solver` described below.
Class description:
Implement the Solver class.
Method signatures and docstrings:
- def __init__(self, State_init, Matcher, Sigma_guesser, Diagonaliser, parameters, sigma_init): solver class is a loop which computes eigenvalues and eigenvectors, and calls various pl... | cdc7e14d61ff33929844ee5d779a18fd64f89f4f | <|skeleton|>
class Solver:
def __init__(self, State_init, Matcher, Sigma_guesser, Diagonaliser, parameters, sigma_init):
"""solver class is a loop which computes eigenvalues and eigenvectors, and calls various plug-in classes to perform logic on the output values. Not intended to be called by a person, the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solver:
def __init__(self, State_init, Matcher, Sigma_guesser, Diagonaliser, parameters, sigma_init):
"""solver class is a loop which computes eigenvalues and eigenvectors, and calls various plug-in classes to perform logic on the output values. Not intended to be called by a person, the userinterface... | the_stack_v2_python_sparse | rydprop/hohi/adiabatic_solver/solver.py | jdrtommey/rydprops | train | 0 | |
ef2e65902e17a63801fc6c2b9bcce475e25531a0 | [
"print_blue('[Open BIDS App Window]')\nbids_layout = BIDSLayout(self.project_info.base_directory)\nsubjects = bids_layout.get_subjects()\nanat_config = os.path.join(self.project_info.base_directory, 'code/', 'ref_anatomical_config.json')\ndmri_config = os.path.join(self.project_info.base_directory, 'code/', 'ref_di... | <|body_start_0|>
print_blue('[Open BIDS App Window]')
bids_layout = BIDSLayout(self.project_info.base_directory)
subjects = bids_layout.get_subjects()
anat_config = os.path.join(self.project_info.base_directory, 'code/', 'ref_anatomical_config.json')
dmri_config = os.path.join(se... | Class that defines the Main window of the Connectome Mapper 3 GUI. Attributes ---------- project_info : cmp.bidsappmanager.project.ProjectInfoUI Instance of :class:`CMP_Project_InfoUI` that represents the processing project anat_pipeline : Instance(HasTraits) Instance of anatomical MRI pipeline UI dmri_pipeline : Insta... | MainWindow | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MainWindow:
"""Class that defines the Main window of the Connectome Mapper 3 GUI. Attributes ---------- project_info : cmp.bidsappmanager.project.ProjectInfoUI Instance of :class:`CMP_Project_InfoUI` that represents the processing project anat_pipeline : Instance(HasTraits) Instance of anatomical... | stack_v2_sparse_classes_75kplus_train_074354 | 10,913 | permissive | [
{
"docstring": "Callback of the \"bidsapp\" button. This displays the BIDS App Interface window.",
"name": "_bidsapp_fired",
"signature": "def _bidsapp_fired(self)"
},
{
"docstring": "Callback of the \"configurator\" button. This displays the Configurator Window.",
"name": "_configurator_fir... | 3 | stack_v2_sparse_classes_30k_train_049372 | Implement the Python class `MainWindow` described below.
Class description:
Class that defines the Main window of the Connectome Mapper 3 GUI. Attributes ---------- project_info : cmp.bidsappmanager.project.ProjectInfoUI Instance of :class:`CMP_Project_InfoUI` that represents the processing project anat_pipeline : Ins... | Implement the Python class `MainWindow` described below.
Class description:
Class that defines the Main window of the Connectome Mapper 3 GUI. Attributes ---------- project_info : cmp.bidsappmanager.project.ProjectInfoUI Instance of :class:`CMP_Project_InfoUI` that represents the processing project anat_pipeline : Ins... | 35cb2ee7be2e73896061359a6cd0a10503fadd42 | <|skeleton|>
class MainWindow:
"""Class that defines the Main window of the Connectome Mapper 3 GUI. Attributes ---------- project_info : cmp.bidsappmanager.project.ProjectInfoUI Instance of :class:`CMP_Project_InfoUI` that represents the processing project anat_pipeline : Instance(HasTraits) Instance of anatomical... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MainWindow:
"""Class that defines the Main window of the Connectome Mapper 3 GUI. Attributes ---------- project_info : cmp.bidsappmanager.project.ProjectInfoUI Instance of :class:`CMP_Project_InfoUI` that represents the processing project anat_pipeline : Instance(HasTraits) Instance of anatomical MRI pipeline... | the_stack_v2_python_sparse | cmp/bidsappmanager/gui/principal.py | jwirsich/connectomemapper3 | train | 0 |
47446ba8f6048656c3d4eec5348c26ca41c57298 | [
"self.USERNAME = 'sebclarke'\nself.PASSWORD = 'password'\nself.driver = webdriver.Chrome()\nsuper(AnonPortalTests, self).setUp()",
"self._accept_cookie_sign_in()\nmy_survey = self._create_public_survey(SURVEY_BASE_NAME)\nself._author_survey(my_survey)\nself.driver.switch_to.window(self.driver.window_handles[0])\n... | <|body_start_0|>
self.USERNAME = 'sebclarke'
self.PASSWORD = 'password'
self.driver = webdriver.Chrome()
super(AnonPortalTests, self).setUp()
<|end_body_0|>
<|body_start_1|>
self._accept_cookie_sign_in()
my_survey = self._create_public_survey(SURVEY_BASE_NAME)
se... | Class containing the tests for the portal side of anonymous use case testing. | AnonPortalTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnonPortalTests:
"""Class containing the tests for the portal side of anonymous use case testing."""
def setUp(self):
"""Set up the test pre-requisites for each test"""
<|body_0|>
def test_login_create_survey(self):
"""Test that we can login, create and join a su... | stack_v2_sparse_classes_75kplus_train_074355 | 7,161 | no_license | [
{
"docstring": "Set up the test pre-requisites for each test",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test that we can login, create and join a survey Saves the created/joined survey as a global so we can make observations to it and check that they exist later",
"... | 3 | null | Implement the Python class `AnonPortalTests` described below.
Class description:
Class containing the tests for the portal side of anonymous use case testing.
Method signatures and docstrings:
- def setUp(self): Set up the test pre-requisites for each test
- def test_login_create_survey(self): Test that we can login,... | Implement the Python class `AnonPortalTests` described below.
Class description:
Class containing the tests for the portal side of anonymous use case testing.
Method signatures and docstrings:
- def setUp(self): Set up the test pre-requisites for each test
- def test_login_create_survey(self): Test that we can login,... | ebc23593c147cfbb9d0e497227294279c29cb895 | <|skeleton|>
class AnonPortalTests:
"""Class containing the tests for the portal side of anonymous use case testing."""
def setUp(self):
"""Set up the test pre-requisites for each test"""
<|body_0|>
def test_login_create_survey(self):
"""Test that we can login, create and join a su... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AnonPortalTests:
"""Class containing the tests for the portal side of anonymous use case testing."""
def setUp(self):
"""Set up the test pre-requisites for each test"""
self.USERNAME = 'sebclarke'
self.PASSWORD = 'password'
self.driver = webdriver.Chrome()
super(An... | the_stack_v2_python_sparse | selenium/cobweb_anon_use_case_tests.py | cobweb-eu/cobweb-system-testing | train | 0 |
6b55a11fecc9a2950ed91f2d989314e55a03c118 | [
"self.model = NN(layer, hidden)\nself.batch_size = batch_size\nself.iteration_num = iteration_num\nself.learning_rate = learning_rate\nif params is not None:\n self.model.load_parameters(params)\ntrain_num = train_num // 2\ntest_num = int(train_num * rate)\nself.train_data, self.train_labels = generate_data(trai... | <|body_start_0|>
self.model = NN(layer, hidden)
self.batch_size = batch_size
self.iteration_num = iteration_num
self.learning_rate = learning_rate
if params is not None:
self.model.load_parameters(params)
train_num = train_num // 2
test_num = int(train... | FNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FNN:
def __init__(self, train_num, rate, layer, hidden, batch_size, train_circle_num, train_r_rate, train_offset, train_start, test_circle_num, test_r_rate, test_offset, test_start, learning_rate=0.1, iteration_num=10, params=None):
"""the init function for FNN Args: train_num (int): the... | stack_v2_sparse_classes_75kplus_train_074356 | 7,324 | no_license | [
{
"docstring": "the init function for FNN Args: train_num (int): the sample number of the train data rate (double): the rate of test data for the train data layer (int): the depth of the FNN hidden (int): the hidden size of the FNN batch_size (int): batch size circle_num (int): the circle number of the spiral r... | 4 | stack_v2_sparse_classes_30k_train_040577 | Implement the Python class `FNN` described below.
Class description:
Implement the FNN class.
Method signatures and docstrings:
- def __init__(self, train_num, rate, layer, hidden, batch_size, train_circle_num, train_r_rate, train_offset, train_start, test_circle_num, test_r_rate, test_offset, test_start, learning_ra... | Implement the Python class `FNN` described below.
Class description:
Implement the FNN class.
Method signatures and docstrings:
- def __init__(self, train_num, rate, layer, hidden, batch_size, train_circle_num, train_r_rate, train_offset, train_start, test_circle_num, test_r_rate, test_offset, test_start, learning_ra... | 3af6918138e3251f9b1c0511d3716e5a33b199aa | <|skeleton|>
class FNN:
def __init__(self, train_num, rate, layer, hidden, batch_size, train_circle_num, train_r_rate, train_offset, train_start, test_circle_num, test_r_rate, test_offset, test_start, learning_rate=0.1, iteration_num=10, params=None):
"""the init function for FNN Args: train_num (int): the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FNN:
def __init__(self, train_num, rate, layer, hidden, batch_size, train_circle_num, train_r_rate, train_offset, train_start, test_circle_num, test_r_rate, test_offset, test_start, learning_rate=0.1, iteration_num=10, params=None):
"""the init function for FNN Args: train_num (int): the sample number... | the_stack_v2_python_sparse | topicABC/src/model.py | 311dada/brain-like-AI-Proj | train | 0 | |
08db45e88733372e62ed979752e2830f4d375942 | [
"context = self.user_context\nfw = context.first\nuse_user = context.batch_user()\nplaces = shareds.dservice.dr_get_place_list_fw(use_user, fw, context.count, lang=context.lang)\nif places:\n print(f'PlaceReader.get_place_list: {len(places)} places {context.direction} \"{places[0].pname}\" – \"{places[-1].pname}... | <|body_start_0|>
context = self.user_context
fw = context.first
use_user = context.batch_user()
places = shareds.dservice.dr_get_place_list_fw(use_user, fw, context.count, lang=context.lang)
if places:
print(f'PlaceReader.get_place_list: {len(places)} places {context.... | Abstracted Place datastore for reading. Data reading class for Place objects with associated data. - Methods return a dict result object {'status':Status, ...} | PlaceReader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlaceReader:
"""Abstracted Place datastore for reading. Data reading class for Place objects with associated data. - Methods return a dict result object {'status':Status, ...}"""
def get_place_list(self):
"""Get a list on PlaceBl objects with nearest heirarchy neighbours. Haetaan pai... | stack_v2_sparse_classes_75kplus_train_074357 | 24,736 | no_license | [
{
"docstring": "Get a list on PlaceBl objects with nearest heirarchy neighbours. Haetaan paikkaluettelo ml. hierarkiassa ylemmät ja alemmat",
"name": "get_place_list",
"signature": "def get_place_list(self)"
},
{
"docstring": "Read the place hierarchy and events connected to this place. Luetaan ... | 3 | stack_v2_sparse_classes_30k_train_011104 | Implement the Python class `PlaceReader` described below.
Class description:
Abstracted Place datastore for reading. Data reading class for Place objects with associated data. - Methods return a dict result object {'status':Status, ...}
Method signatures and docstrings:
- def get_place_list(self): Get a list on Place... | Implement the Python class `PlaceReader` described below.
Class description:
Abstracted Place datastore for reading. Data reading class for Place objects with associated data. - Methods return a dict result object {'status':Status, ...}
Method signatures and docstrings:
- def get_place_list(self): Get a list on Place... | 0f8d6ba035e3cca8dc756531b7cc51029a549a4f | <|skeleton|>
class PlaceReader:
"""Abstracted Place datastore for reading. Data reading class for Place objects with associated data. - Methods return a dict result object {'status':Status, ...}"""
def get_place_list(self):
"""Get a list on PlaceBl objects with nearest heirarchy neighbours. Haetaan pai... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PlaceReader:
"""Abstracted Place datastore for reading. Data reading class for Place objects with associated data. - Methods return a dict result object {'status':Status, ...}"""
def get_place_list(self):
"""Get a list on PlaceBl objects with nearest heirarchy neighbours. Haetaan paikkaluettelo m... | the_stack_v2_python_sparse | bl/place.py | kkujansuu/stk | train | 0 |
558b07b39922f2c8c23731ce7e00bc792a98eb9f | [
"self.maze = maze\nself.visited_cells = [[float('inf') for y in range(self.maze.height)] for x in range(self.maze.width)]\nself.queue = PriorityQueue([Node(maze.player_position, None, 0, self.maze.goal_position.distance_to(maze.player_position))])\nself.continue_solving = True",
"if self.queue.has_items():\n c... | <|body_start_0|>
self.maze = maze
self.visited_cells = [[float('inf') for y in range(self.maze.height)] for x in range(self.maze.width)]
self.queue = PriorityQueue([Node(maze.player_position, None, 0, self.maze.goal_position.distance_to(maze.player_position))])
self.continue_solving = Tr... | Class to implement A* decision making | DecisionHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecisionHandler:
"""Class to implement A* decision making"""
def __init__(self, maze: Maze):
"""Initialises the maze as well as; - Visited cells (list of visited cells to avoid revisiting cells unless a more optimal path to that cell has been found) - Queue (PriorityQueue of nodes to... | stack_v2_sparse_classes_75kplus_train_074358 | 3,784 | permissive | [
{
"docstring": "Initialises the maze as well as; - Visited cells (list of visited cells to avoid revisiting cells unless a more optimal path to that cell has been found) - Queue (PriorityQueue of nodes to process which has the start node and updates over time) - Continue solving (bool of whether to continue sea... | 4 | stack_v2_sparse_classes_30k_train_016901 | Implement the Python class `DecisionHandler` described below.
Class description:
Class to implement A* decision making
Method signatures and docstrings:
- def __init__(self, maze: Maze): Initialises the maze as well as; - Visited cells (list of visited cells to avoid revisiting cells unless a more optimal path to tha... | Implement the Python class `DecisionHandler` described below.
Class description:
Class to implement A* decision making
Method signatures and docstrings:
- def __init__(self, maze: Maze): Initialises the maze as well as; - Visited cells (list of visited cells to avoid revisiting cells unless a more optimal path to tha... | 0131e79654dce37f24f429caee5ee1d45360205d | <|skeleton|>
class DecisionHandler:
"""Class to implement A* decision making"""
def __init__(self, maze: Maze):
"""Initialises the maze as well as; - Visited cells (list of visited cells to avoid revisiting cells unless a more optimal path to that cell has been found) - Queue (PriorityQueue of nodes to... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DecisionHandler:
"""Class to implement A* decision making"""
def __init__(self, maze: Maze):
"""Initialises the maze as well as; - Visited cells (list of visited cells to avoid revisiting cells unless a more optimal path to that cell has been found) - Queue (PriorityQueue of nodes to process whic... | the_stack_v2_python_sparse | astar_logic/decision_handler.py | BenAAndrew/AStar | train | 2 |
a944df114a75c3f72cc6e646e0974c11eab1157a | [
"self.spider = Base_Spider(LgCfg)\nself.first_url = 'https://www.lagou.com/jobs/list_Python?px=new&gx=%E5%85%A8%E8%81%8C&city=%E5%8C%97%E4%BA%AC#order'\n'\\n r = self.spider.get_content(self.first_url)\\n cookies = dict(r.cookies) if not isinstance(r.cookies,dict) else r.cookies\\n cookies = co... | <|body_start_0|>
self.spider = Base_Spider(LgCfg)
self.first_url = 'https://www.lagou.com/jobs/list_Python?px=new&gx=%E5%85%A8%E8%81%8C&city=%E5%8C%97%E4%BA%AC#order'
'\n r = self.spider.get_content(self.first_url)\n cookies = dict(r.cookies) if not isinstance(r.cookies,dict) else ... | LG_Spider | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LG_Spider:
def start_requests(self):
"""the method aims at getting the page number. :return:"""
<|body_0|>
def parse(self, response):
"""crawl related urls.the related url means the title must contains keyword python or web. otherwise,need to exclude these urls. :par... | stack_v2_sparse_classes_75kplus_train_074359 | 4,818 | permissive | [
{
"docstring": "the method aims at getting the page number. :return:",
"name": "start_requests",
"signature": "def start_requests(self)"
},
{
"docstring": "crawl related urls.the related url means the title must contains keyword python or web. otherwise,need to exclude these urls. :param respons... | 3 | stack_v2_sparse_classes_30k_train_051374 | Implement the Python class `LG_Spider` described below.
Class description:
Implement the LG_Spider class.
Method signatures and docstrings:
- def start_requests(self): the method aims at getting the page number. :return:
- def parse(self, response): crawl related urls.the related url means the title must contains key... | Implement the Python class `LG_Spider` described below.
Class description:
Implement the LG_Spider class.
Method signatures and docstrings:
- def start_requests(self): the method aims at getting the page number. :return:
- def parse(self, response): crawl related urls.the related url means the title must contains key... | ffae64974e3dda6828edea88167c6591224b998d | <|skeleton|>
class LG_Spider:
def start_requests(self):
"""the method aims at getting the page number. :return:"""
<|body_0|>
def parse(self, response):
"""crawl related urls.the related url means the title must contains keyword python or web. otherwise,need to exclude these urls. :par... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LG_Spider:
def start_requests(self):
"""the method aims at getting the page number. :return:"""
self.spider = Base_Spider(LgCfg)
self.first_url = 'https://www.lagou.com/jobs/list_Python?px=new&gx=%E5%85%A8%E8%81%8C&city=%E5%8C%97%E4%BA%AC#order'
'\n r = self.spider.get_c... | the_stack_v2_python_sparse | spider/jobspider/spiders/lagou.py | haipersist/webspider | train | 0 | |
dec55fa9365df11da8c439ac816cd2b0f1f4ce10 | [
"robot = self.get_object()\nparts = robot.robot_parts.all().order_by('product__item__name')\nserializer = RobotPartSerializer(parts, many=True, context={'request': request})\nreturn Response(serializer.data)",
"robot = self.get_object()\nrobot_parts = robot.robot_parts.all()\npart_ids = robot_parts.values_list('p... | <|body_start_0|>
robot = self.get_object()
parts = robot.robot_parts.all().order_by('product__item__name')
serializer = RobotPartSerializer(parts, many=True, context={'request': request})
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
robot = self.get_object()
... | API endpoint that allows robots to be viewed or edited. | RobotViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RobotViewSet:
"""API endpoint that allows robots to be viewed or edited."""
def parts_manifest_current(self, request, pk=None):
"""Return a list of all parts currently used by this robot."""
<|body_0|>
def parts_manifest_optimal(self, request, pk=None):
"""Return... | stack_v2_sparse_classes_75kplus_train_074360 | 2,239 | permissive | [
{
"docstring": "Return a list of all parts currently used by this robot.",
"name": "parts_manifest_current",
"signature": "def parts_manifest_current(self, request, pk=None)"
},
{
"docstring": "Return a list of all products used by this robot, optimized such that each product shown is the lowest... | 2 | stack_v2_sparse_classes_30k_train_040662 | Implement the Python class `RobotViewSet` described below.
Class description:
API endpoint that allows robots to be viewed or edited.
Method signatures and docstrings:
- def parts_manifest_current(self, request, pk=None): Return a list of all parts currently used by this robot.
- def parts_manifest_optimal(self, requ... | Implement the Python class `RobotViewSet` described below.
Class description:
API endpoint that allows robots to be viewed or edited.
Method signatures and docstrings:
- def parts_manifest_current(self, request, pk=None): Return a list of all parts currently used by this robot.
- def parts_manifest_optimal(self, requ... | e121100ad5217042397c01e81c6ef9888f3569d6 | <|skeleton|>
class RobotViewSet:
"""API endpoint that allows robots to be viewed or edited."""
def parts_manifest_current(self, request, pk=None):
"""Return a list of all parts currently used by this robot."""
<|body_0|>
def parts_manifest_optimal(self, request, pk=None):
"""Return... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RobotViewSet:
"""API endpoint that allows robots to be viewed or edited."""
def parts_manifest_current(self, request, pk=None):
"""Return a list of all parts currently used by this robot."""
robot = self.get_object()
parts = robot.robot_parts.all().order_by('product__item__name')
... | the_stack_v2_python_sparse | parts_manager/robots/viewsets.py | gunthercox/RobotPartsManager | train | 4 |
d43164f09ede07ec05f89fe9c2dd44c52345f1c4 | [
"super(ScoSessionManager, self).__init__()\nself.getters.update({'cmi_core_lesson_location': 'get_general', 'cmi_core_lesson_status': 'get_general', 'cmi_core_score_max': 'get_general', 'cmi_core_score_min': 'get_general', 'shared_object': 'get_general', 'sco': 'get_foreign_key'})\nself.setters.update({})\nself.my_... | <|body_start_0|>
super(ScoSessionManager, self).__init__()
self.getters.update({'cmi_core_lesson_location': 'get_general', 'cmi_core_lesson_status': 'get_general', 'cmi_core_score_max': 'get_general', 'cmi_core_score_min': 'get_general', 'shared_object': 'get_general', 'sco': 'get_foreign_key'})
... | Manage ScoSessions in the Power Reg system. | ScoSessionManager | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScoSessionManager:
"""Manage ScoSessions in the Power Reg system."""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, assignment):
"""Create a ScoSession :param assignment: foreign key for an Assignment :type assignment: int"""
... | stack_v2_sparse_classes_75kplus_train_074361 | 1,506 | permissive | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Create a ScoSession :param assignment: foreign key for an Assignment :type assignment: int",
"name": "create",
"signature": "def create(self, auth_token, assignment)"
}
] | 2 | stack_v2_sparse_classes_30k_train_045851 | Implement the Python class `ScoSessionManager` described below.
Class description:
Manage ScoSessions in the Power Reg system.
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, assignment): Create a ScoSession :param assignment: foreign key for an Assignment :type assi... | Implement the Python class `ScoSessionManager` described below.
Class description:
Manage ScoSessions in the Power Reg system.
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, assignment): Create a ScoSession :param assignment: foreign key for an Assignment :type assi... | a59457bc37f0501aea1f54d006a6de94ff80511c | <|skeleton|>
class ScoSessionManager:
"""Manage ScoSessions in the Power Reg system."""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, assignment):
"""Create a ScoSession :param assignment: foreign key for an Assignment :type assignment: int"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ScoSessionManager:
"""Manage ScoSessions in the Power Reg system."""
def __init__(self):
"""constructor"""
super(ScoSessionManager, self).__init__()
self.getters.update({'cmi_core_lesson_location': 'get_general', 'cmi_core_lesson_status': 'get_general', 'cmi_core_score_max': 'get_... | the_stack_v2_python_sparse | pr_services/scorm_system/sco_session_manager.py | ninemoreminutes/openassign-server | train | 0 |
4b612ccddcca123d374e51540159ac2215f18f3c | [
"ability = Ability.query.get(id)\nif not ability:\n api.abort(code=404, message='Ability not found')\nreturn {'data': ability.__jsonapi__()}",
"ability = Ability.query.get(id)\ndata = request.get_json()['data']\ntry:\n if len(data['relationships']['groups']['data']) >= 0:\n ability.groups = list((id[... | <|body_start_0|>
ability = Ability.query.get(id)
if not ability:
api.abort(code=404, message='Ability not found')
return {'data': ability.__jsonapi__()}
<|end_body_0|>
<|body_start_1|>
ability = Ability.query.get(id)
data = request.get_json()['data']
try:
... | Abilities | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Abilities:
def get(self, id):
"""Get ability"""
<|body_0|>
def put(self, id):
"""Update ability"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ability = Ability.query.get(id)
if not ability:
api.abort(code=404, message='Ability ... | stack_v2_sparse_classes_75kplus_train_074362 | 46,738 | permissive | [
{
"docstring": "Get ability",
"name": "get",
"signature": "def get(self, id)"
},
{
"docstring": "Update ability",
"name": "put",
"signature": "def put(self, id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018537 | Implement the Python class `Abilities` described below.
Class description:
Implement the Abilities class.
Method signatures and docstrings:
- def get(self, id): Get ability
- def put(self, id): Update ability | Implement the Python class `Abilities` described below.
Class description:
Implement the Abilities class.
Method signatures and docstrings:
- def get(self, id): Get ability
- def put(self, id): Update ability
<|skeleton|>
class Abilities:
def get(self, id):
"""Get ability"""
<|body_0|>
def ... | 3439a2dd0bd527c5d604801fec3a5aac904a72e2 | <|skeleton|>
class Abilities:
def get(self, id):
"""Get ability"""
<|body_0|>
def put(self, id):
"""Update ability"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Abilities:
def get(self, id):
"""Get ability"""
ability = Ability.query.get(id)
if not ability:
api.abort(code=404, message='Ability not found')
return {'data': ability.__jsonapi__()}
def put(self, id):
"""Update ability"""
ability = Ability.que... | the_stack_v2_python_sparse | app/views.py | taidos/lxc-rest | train | 0 | |
1a7b7611e9080abe428b2ffc69036fc923753a64 | [
"super().__init__()\nassert mean.shape == istd.shape\nself.norm_var = norm_var\nself.register_buffer('mean', mean)\nself.register_buffer('istd', istd)",
"x = x - self.mean\nif self.norm_var:\n x = x * self.istd\nreturn x"
] | <|body_start_0|>
super().__init__()
assert mean.shape == istd.shape
self.norm_var = norm_var
self.register_buffer('mean', mean)
self.register_buffer('istd', istd)
<|end_body_0|>
<|body_start_1|>
x = x - self.mean
if self.norm_var:
x = x * self.istd
... | GlobalCMVN | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GlobalCMVN:
def __init__(self, mean: torch.Tensor, istd: torch.Tensor, norm_var: bool=True):
"""Args: mean (torch.Tensor): mean stats istd (torch.Tensor): inverse std, std which is 1.0 / std"""
<|body_0|>
def forward(self, x: torch.Tensor):
"""Args: x (torch.Tensor):... | stack_v2_sparse_classes_75kplus_train_074363 | 992 | permissive | [
{
"docstring": "Args: mean (torch.Tensor): mean stats istd (torch.Tensor): inverse std, std which is 1.0 / std",
"name": "__init__",
"signature": "def __init__(self, mean: torch.Tensor, istd: torch.Tensor, norm_var: bool=True)"
},
{
"docstring": "Args: x (torch.Tensor): (batch, max_len, feat_dim... | 2 | stack_v2_sparse_classes_30k_train_010682 | Implement the Python class `GlobalCMVN` described below.
Class description:
Implement the GlobalCMVN class.
Method signatures and docstrings:
- def __init__(self, mean: torch.Tensor, istd: torch.Tensor, norm_var: bool=True): Args: mean (torch.Tensor): mean stats istd (torch.Tensor): inverse std, std which is 1.0 / st... | Implement the Python class `GlobalCMVN` described below.
Class description:
Implement the GlobalCMVN class.
Method signatures and docstrings:
- def __init__(self, mean: torch.Tensor, istd: torch.Tensor, norm_var: bool=True): Args: mean (torch.Tensor): mean stats istd (torch.Tensor): inverse std, std which is 1.0 / st... | 3bc1fa61cf3ef190872253ee45b7b402c14f3904 | <|skeleton|>
class GlobalCMVN:
def __init__(self, mean: torch.Tensor, istd: torch.Tensor, norm_var: bool=True):
"""Args: mean (torch.Tensor): mean stats istd (torch.Tensor): inverse std, std which is 1.0 / std"""
<|body_0|>
def forward(self, x: torch.Tensor):
"""Args: x (torch.Tensor):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GlobalCMVN:
def __init__(self, mean: torch.Tensor, istd: torch.Tensor, norm_var: bool=True):
"""Args: mean (torch.Tensor): mean stats istd (torch.Tensor): inverse std, std which is 1.0 / std"""
super().__init__()
assert mean.shape == istd.shape
self.norm_var = norm_var
... | the_stack_v2_python_sparse | espnet2/asr/encoder/cmvn.py | ana-kuznetsova/espnet | train | 1 | |
43125d3259fb43e379c618c84efcdd3900264e48 | [
"if numRows == 1 or numRows >= len(s):\n return s\noutput = [''] * numRows\nindex, step = (0, 0)\nfor c in s:\n output[index] += c\n if index == 0:\n step = 1\n elif index == numRows - 1:\n step = -1\n index += step\nreturn ''.join(output)",
"if numRows == 1:\n return s\nstep = 2 *... | <|body_start_0|>
if numRows == 1 or numRows >= len(s):
return s
output = [''] * numRows
index, step = (0, 0)
for c in s:
output[index] += c
if index == 0:
step = 1
elif index == numRows - 1:
step = -1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def convert(self, s, numRows):
""":type s: str :type numRows: int :rtype: str"""
<|body_0|>
def convert(self, s, numRows):
""":type s: str :type numRows: int :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if numRows == 1 or nu... | stack_v2_sparse_classes_75kplus_train_074364 | 1,777 | no_license | [
{
"docstring": ":type s: str :type numRows: int :rtype: str",
"name": "convert",
"signature": "def convert(self, s, numRows)"
},
{
"docstring": ":type s: str :type numRows: int :rtype: str",
"name": "convert",
"signature": "def convert(self, s, numRows)"
}
] | 2 | stack_v2_sparse_classes_30k_train_043694 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def convert(self, s, numRows): :type s: str :type numRows: int :rtype: str
- def convert(self, s, numRows): :type s: str :type numRows: int :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def convert(self, s, numRows): :type s: str :type numRows: int :rtype: str
- def convert(self, s, numRows): :type s: str :type numRows: int :rtype: str
<|skeleton|>
class Soluti... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def convert(self, s, numRows):
""":type s: str :type numRows: int :rtype: str"""
<|body_0|>
def convert(self, s, numRows):
""":type s: str :type numRows: int :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def convert(self, s, numRows):
""":type s: str :type numRows: int :rtype: str"""
if numRows == 1 or numRows >= len(s):
return s
output = [''] * numRows
index, step = (0, 0)
for c in s:
output[index] += c
if index == 0:
... | the_stack_v2_python_sparse | src/lt_6.py | oxhead/CodingYourWay | train | 0 | |
79201e321134880a8eac19cc8165f98b79f9ff7e | [
"key_file = open(pem_path, 'rb')\nprivate_key = RSA.importKey(key_file.read())\nself.__decryptor = PKCS1_v1_5.new(private_key)",
"encrypted_bytes = DataUtils.int2bytes(encrypted_data, 128)\nre = self.__decryptor.decrypt(encrypted_bytes, None)\nreturn DataUtils.bytes2int(re)"
] | <|body_start_0|>
key_file = open(pem_path, 'rb')
private_key = RSA.importKey(key_file.read())
self.__decryptor = PKCS1_v1_5.new(private_key)
<|end_body_0|>
<|body_start_1|>
encrypted_bytes = DataUtils.int2bytes(encrypted_data, 128)
re = self.__decryptor.decrypt(encrypted_bytes, ... | Decryptor based on RSA util. | RSADecryptor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RSADecryptor:
"""Decryptor based on RSA util."""
def __init__(self, pem_path):
"""Init RSADecryptor."""
<|body_0|>
def decrypt(self, encrypted_data):
"""Decrypt encrypted data. Args: encrypted_data: encrypted data represented as integer. Returns: Decrypted data f... | stack_v2_sparse_classes_75kplus_train_074365 | 913 | no_license | [
{
"docstring": "Init RSADecryptor.",
"name": "__init__",
"signature": "def __init__(self, pem_path)"
},
{
"docstring": "Decrypt encrypted data. Args: encrypted_data: encrypted data represented as integer. Returns: Decrypted data from the input encrypted data.",
"name": "decrypt",
"signat... | 2 | stack_v2_sparse_classes_30k_train_019709 | Implement the Python class `RSADecryptor` described below.
Class description:
Decryptor based on RSA util.
Method signatures and docstrings:
- def __init__(self, pem_path): Init RSADecryptor.
- def decrypt(self, encrypted_data): Decrypt encrypted data. Args: encrypted_data: encrypted data represented as integer. Retu... | Implement the Python class `RSADecryptor` described below.
Class description:
Decryptor based on RSA util.
Method signatures and docstrings:
- def __init__(self, pem_path): Init RSADecryptor.
- def decrypt(self, encrypted_data): Decrypt encrypted data. Args: encrypted_data: encrypted data represented as integer. Retu... | 8fa211c55132d290f73d48564cecf6e50c2955da | <|skeleton|>
class RSADecryptor:
"""Decryptor based on RSA util."""
def __init__(self, pem_path):
"""Init RSADecryptor."""
<|body_0|>
def decrypt(self, encrypted_data):
"""Decrypt encrypted data. Args: encrypted_data: encrypted data represented as integer. Returns: Decrypted data f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RSADecryptor:
"""Decryptor based on RSA util."""
def __init__(self, pem_path):
"""Init RSADecryptor."""
key_file = open(pem_path, 'rb')
private_key = RSA.importKey(key_file.read())
self.__decryptor = PKCS1_v1_5.new(private_key)
def decrypt(self, encrypted_data):
... | the_stack_v2_python_sparse | origo-executor/executor/worker/decryptor/rsa_decryptor.py | origolab/origo-executor-example | train | 0 |
b0ae18193055e40a5d1cdedc0db4ad428a7cc9c8 | [
"def error(msg):\n return FetchResponse(status=FetchResponse.Status.ERROR, error_message=msg)\nhash_algo = _HASH_ALGO_MAPPING[request.hash_algo]\nif not impl.is_valid_hash_digest(hash_algo, request.file_hash):\n return error('Invalid hash digest format')\nservice = impl.get_cas_service()\nif service is None o... | <|body_start_0|>
def error(msg):
return FetchResponse(status=FetchResponse.Status.ERROR, error_message=msg)
hash_algo = _HASH_ALGO_MAPPING[request.hash_algo]
if not impl.is_valid_hash_digest(hash_algo, request.file_hash):
return error('Invalid hash digest format')
... | Content addressable storage API. | CASServiceApi | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CASServiceApi:
"""Content addressable storage API."""
def fetch(self, request):
"""Returns a signed URL that can be used to fetch an object."""
<|body_0|>
def begin_upload(self, request):
"""Initiates an upload operation if file is missing. Once initiated the cli... | stack_v2_sparse_classes_75kplus_train_074366 | 8,463 | permissive | [
{
"docstring": "Returns a signed URL that can be used to fetch an object.",
"name": "fetch",
"signature": "def fetch(self, request)"
},
{
"docstring": "Initiates an upload operation if file is missing. Once initiated the client is then responsible for uploading the file to temporary location (re... | 3 | stack_v2_sparse_classes_30k_train_033029 | Implement the Python class `CASServiceApi` described below.
Class description:
Content addressable storage API.
Method signatures and docstrings:
- def fetch(self, request): Returns a signed URL that can be used to fetch an object.
- def begin_upload(self, request): Initiates an upload operation if file is missing. O... | Implement the Python class `CASServiceApi` described below.
Class description:
Content addressable storage API.
Method signatures and docstrings:
- def fetch(self, request): Returns a signed URL that can be used to fetch an object.
- def begin_upload(self, request): Initiates an upload operation if file is missing. O... | 09064105713603f7bf75c772e8354800a1bfa256 | <|skeleton|>
class CASServiceApi:
"""Content addressable storage API."""
def fetch(self, request):
"""Returns a signed URL that can be used to fetch an object."""
<|body_0|>
def begin_upload(self, request):
"""Initiates an upload operation if file is missing. Once initiated the cli... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CASServiceApi:
"""Content addressable storage API."""
def fetch(self, request):
"""Returns a signed URL that can be used to fetch an object."""
def error(msg):
return FetchResponse(status=FetchResponse.Status.ERROR, error_message=msg)
hash_algo = _HASH_ALGO_MAPPING[req... | the_stack_v2_python_sparse | appengine/chrome_infra_packages/cas/api.py | mcgreevy/chromium-infra | train | 1 |
28dc643f5c77e06797f8fc3f9bd49012f14d5607 | [
"if not os.path.exists(path):\n os.mkdir(path)\nelif trash:\n os.system('cp -rf {0} .Trash '.format(path))\n os.system('rm -rf {0} '.format(path))\n os.mkdir(path)\nif clear:\n try:\n os.system('rm -rf .Trash ')\n except:\n pass",
"if is_dir:\n os.system(' cp -rf {0} {1} ;'.f... | <|body_start_0|>
if not os.path.exists(path):
os.mkdir(path)
elif trash:
os.system('cp -rf {0} .Trash '.format(path))
os.system('rm -rf {0} '.format(path))
os.mkdir(path)
if clear:
try:
os.system('rm -rf .Trash ')
... | myTools | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class myTools:
def mkdir(path, trash=False, clear=True):
"""创建文件夹, :param trash: True, 表示,如果存在该文件夹,1、将该文件夹重命名为 .Trash 文件夹 2、在建立该文件夹"""
<|body_0|>
def cp(from_path, to_path, is_dir=False):
"""复制文件 :param from_path: 原文件 :param to_path: 复制后的文件"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus_train_074367 | 10,564 | no_license | [
{
"docstring": "创建文件夹, :param trash: True, 表示,如果存在该文件夹,1、将该文件夹重命名为 .Trash 文件夹 2、在建立该文件夹",
"name": "mkdir",
"signature": "def mkdir(path, trash=False, clear=True)"
},
{
"docstring": "复制文件 :param from_path: 原文件 :param to_path: 复制后的文件",
"name": "cp",
"signature": "def cp(from_path, to_path,... | 2 | stack_v2_sparse_classes_30k_train_037243 | Implement the Python class `myTools` described below.
Class description:
Implement the myTools class.
Method signatures and docstrings:
- def mkdir(path, trash=False, clear=True): 创建文件夹, :param trash: True, 表示,如果存在该文件夹,1、将该文件夹重命名为 .Trash 文件夹 2、在建立该文件夹
- def cp(from_path, to_path, is_dir=False): 复制文件 :param from_path:... | Implement the Python class `myTools` described below.
Class description:
Implement the myTools class.
Method signatures and docstrings:
- def mkdir(path, trash=False, clear=True): 创建文件夹, :param trash: True, 表示,如果存在该文件夹,1、将该文件夹重命名为 .Trash 文件夹 2、在建立该文件夹
- def cp(from_path, to_path, is_dir=False): 复制文件 :param from_path:... | 32ba7b316a4945d062377a3cc37a926aa79b10b9 | <|skeleton|>
class myTools:
def mkdir(path, trash=False, clear=True):
"""创建文件夹, :param trash: True, 表示,如果存在该文件夹,1、将该文件夹重命名为 .Trash 文件夹 2、在建立该文件夹"""
<|body_0|>
def cp(from_path, to_path, is_dir=False):
"""复制文件 :param from_path: 原文件 :param to_path: 复制后的文件"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class myTools:
def mkdir(path, trash=False, clear=True):
"""创建文件夹, :param trash: True, 表示,如果存在该文件夹,1、将该文件夹重命名为 .Trash 文件夹 2、在建立该文件夹"""
if not os.path.exists(path):
os.mkdir(path)
elif trash:
os.system('cp -rf {0} .Trash '.format(path))
os.system('rm -rf {... | the_stack_v2_python_sparse | longgb/Tools/multi/multi.py | longgb246/pythonstudy | train | 20 | |
45032a1c1b69910dcbbce3de9912c217ea8571e5 | [
"self.__exticon = dict()\nself.__exticon['.WAV'] = 'Audio'\nself.__exticon['.WAVE'] = 'Audio'\nfor ext in sppasRW.TRANSCRIPTION_SOFTWARE:\n software = sppasRW.TRANSCRIPTION_SOFTWARE[ext]\n if ext.startswith('.') is False:\n ext = '.' + ext\n self.__exticon[ext.upper()] = software",
"if ext.startsw... | <|body_start_0|>
self.__exticon = dict()
self.__exticon['.WAV'] = 'Audio'
self.__exticon['.WAVE'] = 'Audio'
for ext in sppasRW.TRANSCRIPTION_SOFTWARE:
software = sppasRW.TRANSCRIPTION_SOFTWARE[ext]
if ext.startswith('.') is False:
ext = '.' + ext
... | Represents the link between a file extension and an icon name. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: contact@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Brigitte Bigi All supported file formats of 'anndata' are linked to an icon file. | FileAnnotIcon | [
"GPL-3.0-only",
"GFDL-1.1-or-later",
"GPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileAnnotIcon:
"""Represents the link between a file extension and an icon name. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: contact@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Brigitte Bigi All supported file formats ... | stack_v2_sparse_classes_75kplus_train_074368 | 28,145 | permissive | [
{
"docstring": "Constructor of a FileAnnotIcon. Set the name of the icon for all known extensions of annotations. Create a dictionary linking a file extension to the name of the software it comes from. It is supposed this name is matching an an icon in PNG format.",
"name": "__init__",
"signature": "def... | 2 | stack_v2_sparse_classes_30k_train_050667 | Implement the Python class `FileAnnotIcon` described below.
Class description:
Represents the link between a file extension and an icon name. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: contact@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Br... | Implement the Python class `FileAnnotIcon` described below.
Class description:
Represents the link between a file extension and an icon name. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: contact@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Br... | 3167b65f576abcc27a8767d24c274a04712bd948 | <|skeleton|>
class FileAnnotIcon:
"""Represents the link between a file extension and an icon name. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: contact@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Brigitte Bigi All supported file formats ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FileAnnotIcon:
"""Represents the link between a file extension and an icon name. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: contact@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Brigitte Bigi All supported file formats of 'anndata' ... | the_stack_v2_python_sparse | sppas/sppas/src/ui/phoenix/page_files/filesviewmodel.py | mirfan899/MTTS | train | 0 |
e815645d6e39689ba78afaebadfa98304530f0ee | [
"user = get_current_user()\npagination = user.hash_tags_followed.filter(hash_tag_followers.c.followed_id == user.id).paginate()\nreturn api_success_response(data=[user.as_json() for user in pagination], meta=pagination.meta)",
"user = get_current_user()\nto_follow = HashTag.get_active(entity=hash_tag)\nif to_foll... | <|body_start_0|>
user = get_current_user()
pagination = user.hash_tags_followed.filter(hash_tag_followers.c.followed_id == user.id).paginate()
return api_success_response(data=[user.as_json() for user in pagination], meta=pagination.meta)
<|end_body_0|>
<|body_start_1|>
user = get_curre... | HashTagFollowsView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HashTagFollowsView:
def get(self):
"""Get a list of hash tags being followed"""
<|body_0|>
def put(self, hash_tag):
"""Follow a hash tag"""
<|body_1|>
def delete(self, hash_tag):
"""Unfollow a hash tag"""
<|body_2|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_75kplus_train_074369 | 2,850 | no_license | [
{
"docstring": "Get a list of hash tags being followed",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Follow a hash tag",
"name": "put",
"signature": "def put(self, hash_tag)"
},
{
"docstring": "Unfollow a hash tag",
"name": "delete",
"signature": "def d... | 3 | null | Implement the Python class `HashTagFollowsView` described below.
Class description:
Implement the HashTagFollowsView class.
Method signatures and docstrings:
- def get(self): Get a list of hash tags being followed
- def put(self, hash_tag): Follow a hash tag
- def delete(self, hash_tag): Unfollow a hash tag | Implement the Python class `HashTagFollowsView` described below.
Class description:
Implement the HashTagFollowsView class.
Method signatures and docstrings:
- def get(self): Get a list of hash tags being followed
- def put(self, hash_tag): Follow a hash tag
- def delete(self, hash_tag): Unfollow a hash tag
<|skelet... | 610f3786b4402f9798225d2e97830e527bedc2d0 | <|skeleton|>
class HashTagFollowsView:
def get(self):
"""Get a list of hash tags being followed"""
<|body_0|>
def put(self, hash_tag):
"""Follow a hash tag"""
<|body_1|>
def delete(self, hash_tag):
"""Unfollow a hash tag"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HashTagFollowsView:
def get(self):
"""Get a list of hash tags being followed"""
user = get_current_user()
pagination = user.hash_tags_followed.filter(hash_tag_followers.c.followed_id == user.id).paginate()
return api_success_response(data=[user.as_json() for user in pagination]... | the_stack_v2_python_sparse | modules/follows.py | babatundeladega/social-network-flask-bootstrap | train | 0 | |
c1afdf90d0db0fc5fb91181ddfa5183ea15c1261 | [
"tool = diff_structures.DiffStructures()\nret = tool.Run(DummyOpts(), [])\nself.assertIsNotNone(ret)\nself.assertGreater(ret, 0)\nret = tool.Run(DummyOpts(), ['left'])\nself.assertIsNotNone(ret)\nself.assertGreater(ret, 0)",
"tool = diff_structures.DiffStructures()\nret = tool.Run(DummyOpts(), ['a', 'b', 'c'])\ns... | <|body_start_0|>
tool = diff_structures.DiffStructures()
ret = tool.Run(DummyOpts(), [])
self.assertIsNotNone(ret)
self.assertGreater(ret, 0)
ret = tool.Run(DummyOpts(), ['left'])
self.assertIsNotNone(ret)
self.assertGreater(ret, 0)
<|end_body_0|>
<|body_start_1|... | DiffStructuresUnittest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiffStructuresUnittest:
def testMissingFiles(self):
"""Verify failure w/out file inputs."""
<|body_0|>
def testTooManyArgs(self):
"""Verify failure w/too many inputs."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
tool = diff_structures.DiffStructu... | stack_v2_sparse_classes_75kplus_train_074370 | 1,082 | permissive | [
{
"docstring": "Verify failure w/out file inputs.",
"name": "testMissingFiles",
"signature": "def testMissingFiles(self)"
},
{
"docstring": "Verify failure w/too many inputs.",
"name": "testTooManyArgs",
"signature": "def testTooManyArgs(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012387 | Implement the Python class `DiffStructuresUnittest` described below.
Class description:
Implement the DiffStructuresUnittest class.
Method signatures and docstrings:
- def testMissingFiles(self): Verify failure w/out file inputs.
- def testTooManyArgs(self): Verify failure w/too many inputs. | Implement the Python class `DiffStructuresUnittest` described below.
Class description:
Implement the DiffStructuresUnittest class.
Method signatures and docstrings:
- def testMissingFiles(self): Verify failure w/out file inputs.
- def testTooManyArgs(self): Verify failure w/too many inputs.
<|skeleton|>
class DiffS... | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | <|skeleton|>
class DiffStructuresUnittest:
def testMissingFiles(self):
"""Verify failure w/out file inputs."""
<|body_0|>
def testTooManyArgs(self):
"""Verify failure w/too many inputs."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DiffStructuresUnittest:
def testMissingFiles(self):
"""Verify failure w/out file inputs."""
tool = diff_structures.DiffStructures()
ret = tool.Run(DummyOpts(), [])
self.assertIsNotNone(ret)
self.assertGreater(ret, 0)
ret = tool.Run(DummyOpts(), ['left'])
... | the_stack_v2_python_sparse | tools/grit/grit/tool/diff_structures_unittest.py | chromium/chromium | train | 17,408 | |
904a70e65d34af2744309ad0fb649a5f7c54ce73 | [
"if not root:\n return None\nrootNode = TreeNode(root.val)\nif len(root.children) > 0:\n firstChild = root.children[0]\n rootNode.left = self.encode(firstChild)\ncurr = rootNode.left\nfor i in range(1, len(root.children)):\n curr.right = self.encode(root.children[i])\n curr = curr.right\nreturn rootN... | <|body_start_0|>
if not root:
return None
rootNode = TreeNode(root.val)
if len(root.children) > 0:
firstChild = root.children[0]
rootNode.left = self.encode(firstChild)
curr = rootNode.left
for i in range(1, len(root.children)):
cur... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, root):
"""Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode"""
<|body_0|>
def decode(self, data):
"""Decodes your binary tree to an n-ary tree. :type data: TreeNode :rtype: Node"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_75kplus_train_074371 | 3,222 | no_license | [
{
"docstring": "Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode",
"name": "encode",
"signature": "def encode(self, root)"
},
{
"docstring": "Decodes your binary tree to an n-ary tree. :type data: TreeNode :rtype: Node",
"name": "decode",
"signature": "def decode... | 2 | stack_v2_sparse_classes_30k_train_043213 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, root): Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode
- def decode(self, data): Decodes your binary tree to an n-ary tree. :type data: TreeN... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, root): Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode
- def decode(self, data): Decodes your binary tree to an n-ary tree. :type data: TreeN... | 44765a7d89423b7ec2c159f70b1a6f6e446523c2 | <|skeleton|>
class Codec:
def encode(self, root):
"""Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode"""
<|body_0|>
def decode(self, data):
"""Decodes your binary tree to an n-ary tree. :type data: TreeNode :rtype: Node"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def encode(self, root):
"""Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode"""
if not root:
return None
rootNode = TreeNode(root.val)
if len(root.children) > 0:
firstChild = root.children[0]
rootNode.left = sel... | the_stack_v2_python_sparse | python/_0001_0500/0431_encode-n-ary-tree-to-binary-tree.py | Wang-Yann/LeetCodeMe | train | 0 | |
8b58ce2f1b5a01d3200561af10721fad1b1b04cc | [
"super().__init__()\nself._pokemon = pokemon\nself._name = Text(pokemon.nickname)\nself._name.position = (-self._name.width, 0)\nself.add(self._name, z=1)\nself._level_txt = cocos.sprite.Sprite(pyglet.image.load(PATH + '/assets/img/battle/hud/level.png'))\nself._level_txt.position = (5, -2)\nself.add(self._level_tx... | <|body_start_0|>
super().__init__()
self._pokemon = pokemon
self._name = Text(pokemon.nickname)
self._name.position = (-self._name.width, 0)
self.add(self._name, z=1)
self._level_txt = cocos.sprite.Sprite(pyglet.image.load(PATH + '/assets/img/battle/hud/level.png'))
... | The information about the opponent pokemon: name, level, HP Attributes: - HP_BAR_SIZE: The size in pixels of the HP bar. - HP_UPDATE_DURATION: The time it takes for the HP bar to update. | OpponentHUDLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpponentHUDLayer:
"""The information about the opponent pokemon: name, level, HP Attributes: - HP_BAR_SIZE: The size in pixels of the HP bar. - HP_UPDATE_DURATION: The time it takes for the HP bar to update."""
def __init__(self, pokemon: PokemonModel) -> None:
"""Create a new HUD sh... | stack_v2_sparse_classes_75kplus_train_074372 | 4,187 | no_license | [
{
"docstring": "Create a new HUD showing the opponent pokemon's information. :param pokemon: The opponent pokemon.",
"name": "__init__",
"signature": "def __init__(self, pokemon: PokemonModel) -> None"
},
{
"docstring": "Update the size and the color of the HP bar.",
"name": "update_hp",
... | 3 | stack_v2_sparse_classes_30k_train_008639 | Implement the Python class `OpponentHUDLayer` described below.
Class description:
The information about the opponent pokemon: name, level, HP Attributes: - HP_BAR_SIZE: The size in pixels of the HP bar. - HP_UPDATE_DURATION: The time it takes for the HP bar to update.
Method signatures and docstrings:
- def __init__(... | Implement the Python class `OpponentHUDLayer` described below.
Class description:
The information about the opponent pokemon: name, level, HP Attributes: - HP_BAR_SIZE: The size in pixels of the HP bar. - HP_UPDATE_DURATION: The time it takes for the HP bar to update.
Method signatures and docstrings:
- def __init__(... | dfff995e3e50a8cfa56af73d93de82c427bfa2f5 | <|skeleton|>
class OpponentHUDLayer:
"""The information about the opponent pokemon: name, level, HP Attributes: - HP_BAR_SIZE: The size in pixels of the HP bar. - HP_UPDATE_DURATION: The time it takes for the HP bar to update."""
def __init__(self, pokemon: PokemonModel) -> None:
"""Create a new HUD sh... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OpponentHUDLayer:
"""The information about the opponent pokemon: name, level, HP Attributes: - HP_BAR_SIZE: The size in pixels of the HP bar. - HP_UPDATE_DURATION: The time it takes for the HP bar to update."""
def __init__(self, pokemon: PokemonModel) -> None:
"""Create a new HUD showing the opp... | the_stack_v2_python_sparse | src/views/battle/opponent_hud_layer.py | J-GG/Pymon | train | 0 |
9a634a983a2258a91f2481eedeb2060ac5477e54 | [
"decoded_token = TokenGenerator.decode_token(value)\nif decoded_token is None:\n raise serializers.ValidationError(commons_constant.INVALID_TOKEN)\nreturn decoded_token",
"decoded_token = attr['token']\nself.user = AUTH_USER.objects.filter(email=decoded_token['email']).first()\nif self.user is None:\n raise... | <|body_start_0|>
decoded_token = TokenGenerator.decode_token(value)
if decoded_token is None:
raise serializers.ValidationError(commons_constant.INVALID_TOKEN)
return decoded_token
<|end_body_0|>
<|body_start_1|>
decoded_token = attr['token']
self.user = AUTH_USER.ob... | Serializer for ResetPassword. Require to have a token and new_password. | ResetPasswordSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResetPasswordSerializer:
"""Serializer for ResetPassword. Require to have a token and new_password."""
def validate_token(self, value):
"""Method for validating the token."""
<|body_0|>
def validate(self, attr):
"""Method for validating token provided belongs to ... | stack_v2_sparse_classes_75kplus_train_074373 | 9,332 | no_license | [
{
"docstring": "Method for validating the token.",
"name": "validate_token",
"signature": "def validate_token(self, value)"
},
{
"docstring": "Method for validating token provided belongs to a user or not.",
"name": "validate",
"signature": "def validate(self, attr)"
},
{
"docstr... | 3 | stack_v2_sparse_classes_30k_train_043863 | Implement the Python class `ResetPasswordSerializer` described below.
Class description:
Serializer for ResetPassword. Require to have a token and new_password.
Method signatures and docstrings:
- def validate_token(self, value): Method for validating the token.
- def validate(self, attr): Method for validating token... | Implement the Python class `ResetPasswordSerializer` described below.
Class description:
Serializer for ResetPassword. Require to have a token and new_password.
Method signatures and docstrings:
- def validate_token(self, value): Method for validating the token.
- def validate(self, attr): Method for validating token... | 6bcf64c03f0e47f2c11e5dbbf36c87a0ba8a36e6 | <|skeleton|>
class ResetPasswordSerializer:
"""Serializer for ResetPassword. Require to have a token and new_password."""
def validate_token(self, value):
"""Method for validating the token."""
<|body_0|>
def validate(self, attr):
"""Method for validating token provided belongs to ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResetPasswordSerializer:
"""Serializer for ResetPassword. Require to have a token and new_password."""
def validate_token(self, value):
"""Method for validating the token."""
decoded_token = TokenGenerator.decode_token(value)
if decoded_token is None:
raise serializers... | the_stack_v2_python_sparse | backend/backend/apps/accounts/serializers.py | faizalsha/symptom-checker | train | 0 |
2de27d0e7d6c9c9d98a7cd60b719b7a481c87feb | [
"self.uuid = str(uuid4())\nself.wf_meta = {'wf_uuid': self.uuid, 'wf_name': self.__class__.__name__, 'wf_version': __version__}\nordered_structures = [s for _, s in sorted(zip(energies, magnetic_structures), reverse=False)]\nordered_energies = sorted(energies, reverse=False)\nself.structures = ordered_structures\ns... | <|body_start_0|>
self.uuid = str(uuid4())
self.wf_meta = {'wf_uuid': self.uuid, 'wf_name': self.__class__.__name__, 'wf_version': __version__}
ordered_structures = [s for _, s in sorted(zip(energies, magnetic_structures), reverse=False)]
ordered_energies = sorted(energies, reverse=False)... | ExchangeWF | [
"LicenseRef-scancode-hdf5",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExchangeWF:
def __init__(self, magnetic_structures, energies, default_magmoms=None, db_file=DB_FILE, name='Exchange WF'):
"""Workflow for computing exchange parameters. This workflow takes a set of magnetic orderings and their energies from MagneticOrderingsWF and fits to a classical Hei... | stack_v2_sparse_classes_75kplus_train_074374 | 4,841 | permissive | [
{
"docstring": "Workflow for computing exchange parameters. This workflow takes a set of magnetic orderings and their energies from MagneticOrderingsWF and fits to a classical Heisenberg Hamiltonian to compute exchange parameters. The critical temperature can then be calculated with Monte Carlo. Optionally, onl... | 2 | stack_v2_sparse_classes_30k_train_006863 | Implement the Python class `ExchangeWF` described below.
Class description:
Implement the ExchangeWF class.
Method signatures and docstrings:
- def __init__(self, magnetic_structures, energies, default_magmoms=None, db_file=DB_FILE, name='Exchange WF'): Workflow for computing exchange parameters. This workflow takes ... | Implement the Python class `ExchangeWF` described below.
Class description:
Implement the ExchangeWF class.
Method signatures and docstrings:
- def __init__(self, magnetic_structures, energies, default_magmoms=None, db_file=DB_FILE, name='Exchange WF'): Workflow for computing exchange parameters. This workflow takes ... | f4060e55ae3a22289fde9516ff0e8e4ac1d22190 | <|skeleton|>
class ExchangeWF:
def __init__(self, magnetic_structures, energies, default_magmoms=None, db_file=DB_FILE, name='Exchange WF'):
"""Workflow for computing exchange parameters. This workflow takes a set of magnetic orderings and their energies from MagneticOrderingsWF and fits to a classical Hei... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExchangeWF:
def __init__(self, magnetic_structures, energies, default_magmoms=None, db_file=DB_FILE, name='Exchange WF'):
"""Workflow for computing exchange parameters. This workflow takes a set of magnetic orderings and their energies from MagneticOrderingsWF and fits to a classical Heisenberg Hamilt... | the_stack_v2_python_sparse | atomate/vasp/workflows/base/exchange.py | hackingmaterials/atomate | train | 217 | |
6e25cfa0fe1ee0c922d76a1c21fcdd8c31d02371 | [
"for key, value in self.replacements.items():\n string = string.replace(key, value)\nreturn string",
"if conversions:\n self.replacements.update(conversions)\ntry:\n self.validate(arguments)\n return {self.convert(key): val for key, val in arguments.items()}\nexcept SchemaError as e:\n logger.warni... | <|body_start_0|>
for key, value in self.replacements.items():
string = string.replace(key, value)
return string
<|end_body_0|>
<|body_start_1|>
if conversions:
self.replacements.update(conversions)
try:
self.validate(arguments)
return {sel... | Extends `Schema` adapting it to PA scripts validation strategies. Adds predefined schemata as class variables to be used in scripts' validation schemas as well as `validate_user_input` method which acts as `Schema.validate` but returns a dictionary with converted keys ready to be used as function keyword arguments, e.g... | ScriptSchema | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScriptSchema:
"""Extends `Schema` adapting it to PA scripts validation strategies. Adds predefined schemata as class variables to be used in scripts' validation schemas as well as `validate_user_input` method which acts as `Schema.validate` but returns a dictionary with converted keys ready to be... | stack_v2_sparse_classes_75kplus_train_074375 | 4,382 | permissive | [
{
"docstring": "Removes cli argument notation characters ('--', '<', '>' etc.). :param string: cli argument key to be converted to fit Python argument syntax.",
"name": "convert",
"signature": "def convert(self, string)"
},
{
"docstring": "Calls `Schema.validate` on provided `arguments`. Returns... | 2 | stack_v2_sparse_classes_30k_train_044350 | Implement the Python class `ScriptSchema` described below.
Class description:
Extends `Schema` adapting it to PA scripts validation strategies. Adds predefined schemata as class variables to be used in scripts' validation schemas as well as `validate_user_input` method which acts as `Schema.validate` but returns a dic... | Implement the Python class `ScriptSchema` described below.
Class description:
Extends `Schema` adapting it to PA scripts validation strategies. Adds predefined schemata as class variables to be used in scripts' validation schemas as well as `validate_user_input` method which acts as `Schema.validate` but returns a dic... | dff92d1c5f18f338847b3c371c07a73dd2642957 | <|skeleton|>
class ScriptSchema:
"""Extends `Schema` adapting it to PA scripts validation strategies. Adds predefined schemata as class variables to be used in scripts' validation schemas as well as `validate_user_input` method which acts as `Schema.validate` but returns a dictionary with converted keys ready to be... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ScriptSchema:
"""Extends `Schema` adapting it to PA scripts validation strategies. Adds predefined schemata as class variables to be used in scripts' validation schemas as well as `validate_user_input` method which acts as `Schema.validate` but returns a dictionary with converted keys ready to be used as func... | the_stack_v2_python_sparse | pythonanywhere/scripts_commons.py | pythonanywhere/helper_scripts | train | 34 |
c2238e9fa6aaa593827f8f977f44b5ef64d72779 | [
"flag_seed = False\nif seed is None:\n if dimension is None or n_chains is None:\n raise ValueError('UQpy: Either `seed` or `dimension` and `n_chains` must be provided.')\n flag_seed = True\nself.nsamples = nsamples\nself.nsamples_per_chain = nsamples_per_chain\nsuper().__init__(pdf_target=pdf_target, ... | <|body_start_0|>
flag_seed = False
if seed is None:
if dimension is None or n_chains is None:
raise ValueError('UQpy: Either `seed` or `dimension` and `n_chains` must be provided.')
flag_seed = True
self.nsamples = nsamples
self.nsamples_per_chain ... | Stretch | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Stretch:
def __init__(self, pdf_target: Union[Callable, list[Callable]]=None, log_pdf_target: Union[Callable, list[Callable]]=None, args_target: tuple=None, burn_length: Annotated[int, Is[lambda x: x >= 0]]=0, jump: PositiveInteger=1, dimension: int=None, seed: list=None, save_log_pdf: bool=Fals... | stack_v2_sparse_classes_75kplus_train_074376 | 8,369 | permissive | [
{
"docstring": "Affine-invariant sampler with Stretch moves, parallel implementation. :cite:`Stretch1` :cite:`Stretch2` :param pdf_target: Target density function from which to draw random samples. Either `pdf_target` or `log_pdf_target` must be provided (the latter should be preferred for better numerical stab... | 2 | stack_v2_sparse_classes_30k_train_053578 | Implement the Python class `Stretch` described below.
Class description:
Implement the Stretch class.
Method signatures and docstrings:
- def __init__(self, pdf_target: Union[Callable, list[Callable]]=None, log_pdf_target: Union[Callable, list[Callable]]=None, args_target: tuple=None, burn_length: Annotated[int, Is[l... | Implement the Python class `Stretch` described below.
Class description:
Implement the Stretch class.
Method signatures and docstrings:
- def __init__(self, pdf_target: Union[Callable, list[Callable]]=None, log_pdf_target: Union[Callable, list[Callable]]=None, args_target: tuple=None, burn_length: Annotated[int, Is[l... | 9e98a6279aa5a2ec2d6d4c61226c34712547bcc6 | <|skeleton|>
class Stretch:
def __init__(self, pdf_target: Union[Callable, list[Callable]]=None, log_pdf_target: Union[Callable, list[Callable]]=None, args_target: tuple=None, burn_length: Annotated[int, Is[lambda x: x >= 0]]=0, jump: PositiveInteger=1, dimension: int=None, seed: list=None, save_log_pdf: bool=Fals... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Stretch:
def __init__(self, pdf_target: Union[Callable, list[Callable]]=None, log_pdf_target: Union[Callable, list[Callable]]=None, args_target: tuple=None, burn_length: Annotated[int, Is[lambda x: x >= 0]]=0, jump: PositiveInteger=1, dimension: int=None, seed: list=None, save_log_pdf: bool=False, concatenate... | the_stack_v2_python_sparse | src/UQpy/sampling/mcmc/Stretch.py | SURGroup/UQpy | train | 215 | |
7b28e7e044957305f0979dc8cbe2a06ec8c7f8c2 | [
"self._hass = hass\nself._client = client\nself._config = config",
"if not self._hass.config.is_allowed_path(path):\n _LOGGER.error('Path does not exist or is not allowed: %s', path)\n return\nparsed_url = urlparse(path)\nfilename = os.path.basename(parsed_url.path)\ntry:\n await self._client.files_uploa... | <|body_start_0|>
self._hass = hass
self._client = client
self._config = config
<|end_body_0|>
<|body_start_1|>
if not self._hass.config.is_allowed_path(path):
_LOGGER.error('Path does not exist or is not allowed: %s', path)
return
parsed_url = urlparse(pa... | Define the Slack notification logic. | SlackNotificationService | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SlackNotificationService:
"""Define the Slack notification logic."""
def __init__(self, hass: HomeAssistant, client: WebClient, config: dict[str, str]) -> None:
"""Initialize."""
<|body_0|>
async def _async_send_local_file_message(self, path: str, targets: list[str], mes... | stack_v2_sparse_classes_75kplus_train_074377 | 9,238 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, client: WebClient, config: dict[str, str]) -> None"
},
{
"docstring": "Upload a local file (with message) to Slack.",
"name": "_async_send_local_file_message",
"signature": "async def ... | 5 | stack_v2_sparse_classes_30k_train_050779 | Implement the Python class `SlackNotificationService` described below.
Class description:
Define the Slack notification logic.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, client: WebClient, config: dict[str, str]) -> None: Initialize.
- async def _async_send_local_file_message(self, pa... | Implement the Python class `SlackNotificationService` described below.
Class description:
Define the Slack notification logic.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, client: WebClient, config: dict[str, str]) -> None: Initialize.
- async def _async_send_local_file_message(self, pa... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class SlackNotificationService:
"""Define the Slack notification logic."""
def __init__(self, hass: HomeAssistant, client: WebClient, config: dict[str, str]) -> None:
"""Initialize."""
<|body_0|>
async def _async_send_local_file_message(self, path: str, targets: list[str], mes... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SlackNotificationService:
"""Define the Slack notification logic."""
def __init__(self, hass: HomeAssistant, client: WebClient, config: dict[str, str]) -> None:
"""Initialize."""
self._hass = hass
self._client = client
self._config = config
async def _async_send_local... | the_stack_v2_python_sparse | homeassistant/components/slack/notify.py | home-assistant/core | train | 35,501 |
241d332c73dfc3d4cb9922b38484cb9b922e9cf6 | [
"output_types = output_types or ['pdf']\nfor t in output_types:\n t = t.replace('.', '')\n f_out = dot_filename.replace('.dot', '.' + t)\n exec_str = 'dot -T%s %s -o %s' % (t, dot_filename, f_out)\n os.system(exec_str)",
"from Cheetah.Template import Template\nif not component.is_flat() and flatten:\n... | <|body_start_0|>
output_types = output_types or ['pdf']
for t in output_types:
t = t.replace('.', '')
f_out = dot_filename.replace('.dot', '.' + t)
exec_str = 'dot -T%s %s -o %s' % (t, dot_filename, f_out)
os.system(exec_str)
<|end_body_0|>
<|body_start_1... | Dot Writer docstring | DotWriter | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DotWriter:
"""Dot Writer docstring"""
def build(cls, dot_filename, output_types=None):
"""Runs the commandline tool, ``dot`` on a filename to produce output figures. :params dot_filename: The filename of the .dot file. :params output_types: The types of output that should be produced... | stack_v2_sparse_classes_75kplus_train_074378 | 4,675 | permissive | [
{
"docstring": "Runs the commandline tool, ``dot`` on a filename to produce output figures. :params dot_filename: The filename of the .dot file. :params output_types: The types of output that should be produced, by default 'pdf' will be produced. This should be a list, for example, ['svg','pdf','png']",
"na... | 2 | stack_v2_sparse_classes_30k_train_037079 | Implement the Python class `DotWriter` described below.
Class description:
Dot Writer docstring
Method signatures and docstrings:
- def build(cls, dot_filename, output_types=None): Runs the commandline tool, ``dot`` on a filename to produce output figures. :params dot_filename: The filename of the .dot file. :params ... | Implement the Python class `DotWriter` described below.
Class description:
Dot Writer docstring
Method signatures and docstrings:
- def build(cls, dot_filename, output_types=None): Runs the commandline tool, ``dot`` on a filename to produce output figures. :params dot_filename: The filename of the .dot file. :params ... | 941ceb72e6cd26c55fd03f0029f84ab75ad18485 | <|skeleton|>
class DotWriter:
"""Dot Writer docstring"""
def build(cls, dot_filename, output_types=None):
"""Runs the commandline tool, ``dot`` on a filename to produce output figures. :params dot_filename: The filename of the .dot file. :params output_types: The types of output that should be produced... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DotWriter:
"""Dot Writer docstring"""
def build(cls, dot_filename, output_types=None):
"""Runs the commandline tool, ``dot`` on a filename to produce output figures. :params dot_filename: The filename of the .dot file. :params output_types: The types of output that should be produced, by default ... | the_stack_v2_python_sparse | lib9ml/python/nineml/abstraction_layer/dynamics/writers/dot_writer.py | iraikov/nineml | train | 0 |
97fab2085144f93753681216868ab482ff6191d2 | [
"super().__init__()\nself._level = level\nself._floor_type = floor_type\nself.image = pygame.Surface((width, height), pygame.SRCALPHA)\nself._visualize(width, height)\nself.rect = self.image.get_rect()\nself.rect.x = x_coordinate\nself.rect.y = y_coordinate",
"self.rect.x -= self._level.speed\nif self.rect.right ... | <|body_start_0|>
super().__init__()
self._level = level
self._floor_type = floor_type
self.image = pygame.Surface((width, height), pygame.SRCALPHA)
self._visualize(width, height)
self.rect = self.image.get_rect()
self.rect.x = x_coordinate
self.rect.y = y_... | A class to represent floor object at the game level. Attributes: level: Level object x_coordinate: Spawn location at the x-axis. y_coordinate: Spawn location at the y-axis. width: Width of the floor object. heigth: Heigth of the floor object. floor_type: Type of the floor (normal floor, lava or goal) | Floor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Floor:
"""A class to represent floor object at the game level. Attributes: level: Level object x_coordinate: Spawn location at the x-axis. y_coordinate: Spawn location at the y-axis. width: Width of the floor object. heigth: Heigth of the floor object. floor_type: Type of the floor (normal floor,... | stack_v2_sparse_classes_75kplus_train_074379 | 2,357 | no_license | [
{
"docstring": "Constructs all the necessary attributes for the floor object. Args: level (Level): Level object x_coordinate (int): Spawn location at the x-axis. y_coordinate (int): Spawn location at the y-axis. width (int): Width of the floor object. height (int): Heigth of the floor object. floor_type (str): ... | 3 | stack_v2_sparse_classes_30k_train_048870 | Implement the Python class `Floor` described below.
Class description:
A class to represent floor object at the game level. Attributes: level: Level object x_coordinate: Spawn location at the x-axis. y_coordinate: Spawn location at the y-axis. width: Width of the floor object. heigth: Heigth of the floor object. floor... | Implement the Python class `Floor` described below.
Class description:
A class to represent floor object at the game level. Attributes: level: Level object x_coordinate: Spawn location at the x-axis. y_coordinate: Spawn location at the y-axis. width: Width of the floor object. heigth: Heigth of the floor object. floor... | 29cd15dddff620de068a479595a5cb9aba855343 | <|skeleton|>
class Floor:
"""A class to represent floor object at the game level. Attributes: level: Level object x_coordinate: Spawn location at the x-axis. y_coordinate: Spawn location at the y-axis. width: Width of the floor object. heigth: Heigth of the floor object. floor_type: Type of the floor (normal floor,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Floor:
"""A class to represent floor object at the game level. Attributes: level: Level object x_coordinate: Spawn location at the x-axis. y_coordinate: Spawn location at the y-axis. width: Width of the floor object. heigth: Heigth of the floor object. floor_type: Type of the floor (normal floor, lava or goal... | the_stack_v2_python_sparse | src/entities/floor.py | TopiasHarjunpaa/ot-harjoitustyo | train | 0 |
5fcc93f62f623a0c0d673c583ba7cb802eb87c17 | [
"app = App.get_running_app()\ntry:\n app.backend.login(self.ids.email.text, self.ids.password.text)\n app.show(Home, True)\nexcept BackEndError as e:\n Alert(title='Login Error', text=e.error)\nexcept Exception as e:\n Alert(title='Login Error', text='Unexpected error: ' + str(e))",
"app = App.get_run... | <|body_start_0|>
app = App.get_running_app()
try:
app.backend.login(self.ids.email.text, self.ids.password.text)
app.show(Home, True)
except BackEndError as e:
Alert(title='Login Error', text=e.error)
except Exception as e:
Alert(title='Log... | Represent the screen to login | Login | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Login:
"""Represent the screen to login"""
def login(self):
"""Called when you click "Login" button on login screen to login to the back-end server."""
<|body_0|>
def register(self):
"""Called when you click "Register" button on login screen to register a new use... | stack_v2_sparse_classes_75kplus_train_074380 | 1,302 | no_license | [
{
"docstring": "Called when you click \"Login\" button on login screen to login to the back-end server.",
"name": "login",
"signature": "def login(self)"
},
{
"docstring": "Called when you click \"Register\" button on login screen to register a new user account on the back-end server.",
"nam... | 2 | stack_v2_sparse_classes_30k_train_047696 | Implement the Python class `Login` described below.
Class description:
Represent the screen to login
Method signatures and docstrings:
- def login(self): Called when you click "Login" button on login screen to login to the back-end server.
- def register(self): Called when you click "Register" button on login screen ... | Implement the Python class `Login` described below.
Class description:
Represent the screen to login
Method signatures and docstrings:
- def login(self): Called when you click "Login" button on login screen to login to the back-end server.
- def register(self): Called when you click "Register" button on login screen ... | d986e3b802b349f7c27c97fdebf7f084dc95fdde | <|skeleton|>
class Login:
"""Represent the screen to login"""
def login(self):
"""Called when you click "Login" button on login screen to login to the back-end server."""
<|body_0|>
def register(self):
"""Called when you click "Register" button on login screen to register a new use... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Login:
"""Represent the screen to login"""
def login(self):
"""Called when you click "Login" button on login screen to login to the back-end server."""
app = App.get_running_app()
try:
app.backend.login(self.ids.email.text, self.ids.password.text)
app.show(... | the_stack_v2_python_sparse | ui/login.py | Salemalbarqi3090/online_travel_distribution | train | 0 |
df1ef78c6479f5da68addb41e3f82c2f3815efa1 | [
"if not v:\n raise InvalidOrderData(order_id='order_id is required')\nif type(v) != int:\n raise InvalidOrderData(order_id='order_id must be integer')\nif v < 0 or v > 9223372036854775807:\n raise InvalidOrderData(order_id='order_id out of allowed range')\nreturn v",
"if not v:\n raise InvalidOrderDat... | <|body_start_0|>
if not v:
raise InvalidOrderData(order_id='order_id is required')
if type(v) != int:
raise InvalidOrderData(order_id='order_id must be integer')
if v < 0 or v > 9223372036854775807:
raise InvalidOrderData(order_id='order_id out of allowed rang... | Структура данных, описывающая заказ | OrderDataModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrderDataModel:
"""Структура данных, описывающая заказ"""
def validate_order_id(cls, v: int) -> int:
"""Валидирует order_id заказа"""
<|body_0|>
def validate_region(cls, v):
"""Валидирует регион заказа"""
<|body_1|>
def validate_weight(cls, v):
... | stack_v2_sparse_classes_75kplus_train_074381 | 8,762 | no_license | [
{
"docstring": "Валидирует order_id заказа",
"name": "validate_order_id",
"signature": "def validate_order_id(cls, v: int) -> int"
},
{
"docstring": "Валидирует регион заказа",
"name": "validate_region",
"signature": "def validate_region(cls, v)"
},
{
"docstring": "Валидирует вес... | 5 | stack_v2_sparse_classes_30k_train_020807 | Implement the Python class `OrderDataModel` described below.
Class description:
Структура данных, описывающая заказ
Method signatures and docstrings:
- def validate_order_id(cls, v: int) -> int: Валидирует order_id заказа
- def validate_region(cls, v): Валидирует регион заказа
- def validate_weight(cls, v): Валидируе... | Implement the Python class `OrderDataModel` described below.
Class description:
Структура данных, описывающая заказ
Method signatures and docstrings:
- def validate_order_id(cls, v: int) -> int: Валидирует order_id заказа
- def validate_region(cls, v): Валидирует регион заказа
- def validate_weight(cls, v): Валидируе... | f1a908e5d6b30b826c38d24c52a721764f056fde | <|skeleton|>
class OrderDataModel:
"""Структура данных, описывающая заказ"""
def validate_order_id(cls, v: int) -> int:
"""Валидирует order_id заказа"""
<|body_0|>
def validate_region(cls, v):
"""Валидирует регион заказа"""
<|body_1|>
def validate_weight(cls, v):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OrderDataModel:
"""Структура данных, описывающая заказ"""
def validate_order_id(cls, v: int) -> int:
"""Валидирует order_id заказа"""
if not v:
raise InvalidOrderData(order_id='order_id is required')
if type(v) != int:
raise InvalidOrderData(order_id='order... | the_stack_v2_python_sparse | candyapi/orders/validators.py | IntAlgambra/candyapi | train | 0 |
4689b40169794da478ec817348311458accd8d6e | [
"self.prefix = IPNetwork(prefix)\nself.origin = origin\nself.max_len = max_len if max_len else self.prefix.prefixlen",
"assert isinstance(prefix, IPNetwork), 'Convert to IPNetwork'\nif prefix in self.prefix:\n length = True if prefix.prefixlen <= self.max_len else False\n correct_origin = True if origin == ... | <|body_start_0|>
self.prefix = IPNetwork(prefix)
self.origin = origin
self.max_len = max_len if max_len else self.prefix.prefixlen
<|end_body_0|>
<|body_start_1|>
assert isinstance(prefix, IPNetwork), 'Convert to IPNetwork'
if prefix in self.prefix:
length = True if ... | Stores information for a ROA | ROA | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ROA:
"""Stores information for a ROA"""
def __init__(self, prefix: IPNetwork, origin: int, max_len=None):
"""Inits prefix, origin, and max length max length defaults to prefix length if not specified"""
<|body_0|>
def check_validity(self, prefix: IPNetwork, origin: int):... | stack_v2_sparse_classes_75kplus_train_074382 | 1,955 | permissive | [
{
"docstring": "Inits prefix, origin, and max length max length defaults to prefix length if not specified",
"name": "__init__",
"signature": "def __init__(self, prefix: IPNetwork, origin: int, max_len=None)"
},
{
"docstring": "Checks the validity of an announcement",
"name": "check_validity... | 2 | null | Implement the Python class `ROA` described below.
Class description:
Stores information for a ROA
Method signatures and docstrings:
- def __init__(self, prefix: IPNetwork, origin: int, max_len=None): Inits prefix, origin, and max length max length defaults to prefix length if not specified
- def check_validity(self, ... | Implement the Python class `ROA` described below.
Class description:
Stores information for a ROA
Method signatures and docstrings:
- def __init__(self, prefix: IPNetwork, origin: int, max_len=None): Inits prefix, origin, and max length max length defaults to prefix length if not specified
- def check_validity(self, ... | 91c92584b31bd128d818c7fee86c738367c0712e | <|skeleton|>
class ROA:
"""Stores information for a ROA"""
def __init__(self, prefix: IPNetwork, origin: int, max_len=None):
"""Inits prefix, origin, and max length max length defaults to prefix length if not specified"""
<|body_0|>
def check_validity(self, prefix: IPNetwork, origin: int):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ROA:
"""Stores information for a ROA"""
def __init__(self, prefix: IPNetwork, origin: int, max_len=None):
"""Inits prefix, origin, and max length max length defaults to prefix length if not specified"""
self.prefix = IPNetwork(prefix)
self.origin = origin
self.max_len = ma... | the_stack_v2_python_sparse | lib_bgp_data/simulations/simulator/attacks/roa.py | jfuruness/lib_bgp_data | train | 16 |
9d86156c656d1752e59effa6df5f3ca6a53a678d | [
"errors = ''\ntry:\n id = int(parameters[0])\n text = parameters[1]\n chuice_a = parameters[2]\n choice_b = parameters[3]\n choice_c = parameters[4]\n correct_choice = parameters[5]\n difficulty = parameters[6]\nexcept ValueError as ve:\n errors += 'Invalid id input number !\\n'\ndifficulty ... | <|body_start_0|>
errors = ''
try:
id = int(parameters[0])
text = parameters[1]
chuice_a = parameters[2]
choice_b = parameters[3]
choice_c = parameters[4]
correct_choice = parameters[5]
difficulty = parameters[6]
... | Validator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Validator:
def validate_question(self, parameters):
"""This function determines whether the parameters are suitable for creating a question. Input : parameters, a list of parameters that are checked Output : error if the parameters are not right"""
<|body_0|>
def validate_qu... | stack_v2_sparse_classes_75kplus_train_074383 | 1,986 | no_license | [
{
"docstring": "This function determines whether the parameters are suitable for creating a question. Input : parameters, a list of parameters that are checked Output : error if the parameters are not right",
"name": "validate_question",
"signature": "def validate_question(self, parameters)"
},
{
... | 3 | null | Implement the Python class `Validator` described below.
Class description:
Implement the Validator class.
Method signatures and docstrings:
- def validate_question(self, parameters): This function determines whether the parameters are suitable for creating a question. Input : parameters, a list of parameters that are... | Implement the Python class `Validator` described below.
Class description:
Implement the Validator class.
Method signatures and docstrings:
- def validate_question(self, parameters): This function determines whether the parameters are suitable for creating a question. Input : parameters, a list of parameters that are... | ca6269864e5ade872cb5522a3ceb94a206e207b3 | <|skeleton|>
class Validator:
def validate_question(self, parameters):
"""This function determines whether the parameters are suitable for creating a question. Input : parameters, a list of parameters that are checked Output : error if the parameters are not right"""
<|body_0|>
def validate_qu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Validator:
def validate_question(self, parameters):
"""This function determines whether the parameters are suitable for creating a question. Input : parameters, a list of parameters that are checked Output : error if the parameters are not right"""
errors = ''
try:
id = int... | the_stack_v2_python_sparse | 1st semester/Fundamentals-of-programming/PracticalExam/validation.py | toadereandreas/Babes-Bolyai-University | train | 0 | |
edba1402e44e984f36352b564538403c60656216 | [
"from collections import Counter\ncounter = Counter(nums)\ni = 0\nfor color in range(3):\n for _ in range(counter[color]):\n nums[i] = color\n i += 1",
"\"\"\"https://leetcode.com/problems/sort-colors/discuss/26481/Python-O(n)-1-pass-in-place-solution-with-explanation\"\"\"\nn = len(nums)\nl, r =... | <|body_start_0|>
from collections import Counter
counter = Counter(nums)
i = 0
for color in range(3):
for _ in range(counter[color]):
nums[i] = color
i += 1
<|end_body_0|>
<|body_start_1|>
"""https://leetcode.com/problems/sort-colors/d... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""Counting Sort, Time: O(n), Space: O(n)"""
<|body_0|>
def sortColors(self, nums: List[int]) -> None:
"""Two Pointer, Time: O(n), Space: O(1)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
f... | stack_v2_sparse_classes_75kplus_train_074384 | 1,275 | no_license | [
{
"docstring": "Counting Sort, Time: O(n), Space: O(n)",
"name": "sortColors",
"signature": "def sortColors(self, nums: List[int]) -> None"
},
{
"docstring": "Two Pointer, Time: O(n), Space: O(1)",
"name": "sortColors",
"signature": "def sortColors(self, nums: List[int]) -> None"
}
] | 2 | stack_v2_sparse_classes_30k_val_002831 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums: List[int]) -> None: Counting Sort, Time: O(n), Space: O(n)
- def sortColors(self, nums: List[int]) -> None: Two Pointer, Time: O(n), Space: O(1) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums: List[int]) -> None: Counting Sort, Time: O(n), Space: O(n)
- def sortColors(self, nums: List[int]) -> None: Two Pointer, Time: O(n), Space: O(1)
<|ske... | 72136e3487d239f5b37e2d6393e034262a6bf599 | <|skeleton|>
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""Counting Sort, Time: O(n), Space: O(n)"""
<|body_0|>
def sortColors(self, nums: List[int]) -> None:
"""Two Pointer, Time: O(n), Space: O(1)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def sortColors(self, nums: List[int]) -> None:
"""Counting Sort, Time: O(n), Space: O(n)"""
from collections import Counter
counter = Counter(nums)
i = 0
for color in range(3):
for _ in range(counter[color]):
nums[i] = color
... | the_stack_v2_python_sparse | python/75-Sort Colors.py | cwza/leetcode | train | 0 | |
c8068d0ab8a223be465cb8e95794b74ddb0dd317 | [
"ride = get_ride_by_id(ride_id)\nif ride:\n return (ride, HTTPStatus.OK)\nreturn ({'msg': f'Ride \"{ride_id}\" Not found', 'action': 'View all rides', 'link': url_for('api_bp.ride_rides_resource')}, HTTPStatus.NOT_FOUND)",
"ride = get_ride_by_id(ride_id)\nif ride:\n if ride.created_by == current_user.id:\n ... | <|body_start_0|>
ride = get_ride_by_id(ride_id)
if ride:
return (ride, HTTPStatus.OK)
return ({'msg': f'Ride "{ride_id}" Not found', 'action': 'View all rides', 'link': url_for('api_bp.ride_rides_resource')}, HTTPStatus.NOT_FOUND)
<|end_body_0|>
<|body_start_1|>
ride = get_r... | Handle Operation on a ride | RideResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RideResource:
"""Handle Operation on a ride"""
def get(self, ride_id):
"""View a ride"""
<|body_0|>
def put(self, ride_id):
"""Update a ride"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ride = get_ride_by_id(ride_id)
if ride:
... | stack_v2_sparse_classes_75kplus_train_074385 | 4,289 | permissive | [
{
"docstring": "View a ride",
"name": "get",
"signature": "def get(self, ride_id)"
},
{
"docstring": "Update a ride",
"name": "put",
"signature": "def put(self, ride_id)"
}
] | 2 | null | Implement the Python class `RideResource` described below.
Class description:
Handle Operation on a ride
Method signatures and docstrings:
- def get(self, ride_id): View a ride
- def put(self, ride_id): Update a ride | Implement the Python class `RideResource` described below.
Class description:
Handle Operation on a ride
Method signatures and docstrings:
- def get(self, ride_id): View a ride
- def put(self, ride_id): Update a ride
<|skeleton|>
class RideResource:
"""Handle Operation on a ride"""
def get(self, ride_id):
... | 4831094d973fc1abcd3d83e697a84fe5336e8827 | <|skeleton|>
class RideResource:
"""Handle Operation on a ride"""
def get(self, ride_id):
"""View a ride"""
<|body_0|>
def put(self, ride_id):
"""Update a ride"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RideResource:
"""Handle Operation on a ride"""
def get(self, ride_id):
"""View a ride"""
ride = get_ride_by_id(ride_id)
if ride:
return (ride, HTTPStatus.OK)
return ({'msg': f'Ride "{ride_id}" Not found', 'action': 'View all rides', 'link': url_for('api_bp.ride... | the_stack_v2_python_sparse | app/api_BP/ns_ride.py | Xerrex/rmw-API | train | 0 |
89797a12399b63f28d171ec3f3da1a651fe01d28 | [
"super().__init__(model_config)\nself.pipelines = pipelines\nself.aggregation_type = ensemble_aggregation_type",
"inference_pipelines = []\nfor pipeline_id, path in enumerate(paths_to_checkpoint):\n pipeline = ScalarInferencePipeline.create_from_checkpoint(path, config, pipeline_id)\n if pipeline:\n ... | <|body_start_0|>
super().__init__(model_config)
self.pipelines = pipelines
self.aggregation_type = ensemble_aggregation_type
<|end_body_0|>
<|body_start_1|>
inference_pipelines = []
for pipeline_id, path in enumerate(paths_to_checkpoint):
pipeline = ScalarInferencePi... | Pipeline for inference from an ensemble model on classification tasks. This pipeline creates models from multiple checkpoints and aggregates the predictions across models. | ScalarEnsemblePipeline | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScalarEnsemblePipeline:
"""Pipeline for inference from an ensemble model on classification tasks. This pipeline creates models from multiple checkpoints and aggregates the predictions across models."""
def __init__(self, pipelines: List[ScalarInferencePipeline], model_config: ScalarModelBase... | stack_v2_sparse_classes_75kplus_train_074386 | 9,301 | permissive | [
{
"docstring": ":param pipelines: A set of inference pipelines, one for each recovered checkpoint. :param model_config: Model configuration information. :param ensemble_aggregation_type: Type of aggregation to perform on the model outputs. :return:",
"name": "__init__",
"signature": "def __init__(self, ... | 4 | stack_v2_sparse_classes_30k_train_032472 | Implement the Python class `ScalarEnsemblePipeline` described below.
Class description:
Pipeline for inference from an ensemble model on classification tasks. This pipeline creates models from multiple checkpoints and aggregates the predictions across models.
Method signatures and docstrings:
- def __init__(self, pip... | Implement the Python class `ScalarEnsemblePipeline` described below.
Class description:
Pipeline for inference from an ensemble model on classification tasks. This pipeline creates models from multiple checkpoints and aggregates the predictions across models.
Method signatures and docstrings:
- def __init__(self, pip... | 2877002d50d3a34d80f647c18cb561025d9066cc | <|skeleton|>
class ScalarEnsemblePipeline:
"""Pipeline for inference from an ensemble model on classification tasks. This pipeline creates models from multiple checkpoints and aggregates the predictions across models."""
def __init__(self, pipelines: List[ScalarInferencePipeline], model_config: ScalarModelBase... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ScalarEnsemblePipeline:
"""Pipeline for inference from an ensemble model on classification tasks. This pipeline creates models from multiple checkpoints and aggregates the predictions across models."""
def __init__(self, pipelines: List[ScalarInferencePipeline], model_config: ScalarModelBase, ensemble_ag... | the_stack_v2_python_sparse | InnerEye/ML/pipelines/scalar_inference.py | microsoft/InnerEye-DeepLearning | train | 511 |
098599617ef2409f798cb63be7728e36d6a792d7 | [
"self.sv_dim = sv_dim\nself.meas_dim = meas_dim\nself._init_matrices(1)\nself.q_mat = numpy.eye(self.sv_dim)\nself.r_mat = numpy.eye(self.meas_dim)\nself.update = update\nself.update_jacobian = update_jacobian\nself.measure = measure\nself.measure_jacobian = measure_jacobian\nself.seed = seed",
"self.sv_sv_matsh ... | <|body_start_0|>
self.sv_dim = sv_dim
self.meas_dim = meas_dim
self._init_matrices(1)
self.q_mat = numpy.eye(self.sv_dim)
self.r_mat = numpy.eye(self.meas_dim)
self.update = update
self.update_jacobian = update_jacobian
self.measure = measure
self.... | A class that defines a general extended Kalman filter. Attributes ---------- sv_dim : The dimension of the state vector meas_dim : The dimension of the measurement vector q_mat : The process noise covariance matrix r_mat : The measurement noise covariance matrix xhat : The a posteriori state estimate p_mat : The estima... | KalmanFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KalmanFilter:
"""A class that defines a general extended Kalman filter. Attributes ---------- sv_dim : The dimension of the state vector meas_dim : The dimension of the measurement vector q_mat : The process noise covariance matrix r_mat : The measurement noise covariance matrix xhat : The a post... | stack_v2_sparse_classes_75kplus_train_074387 | 4,175 | no_license | [
{
"docstring": "Initializes the class. Arguments --------- sv_dim : The dimension of the state vector meas_dim : The dimension of the measurement vector update : A callback function for estimating the next state vector jacobian : A callback function for estimating the Jacobian of the update function",
"name... | 3 | stack_v2_sparse_classes_30k_train_005130 | Implement the Python class `KalmanFilter` described below.
Class description:
A class that defines a general extended Kalman filter. Attributes ---------- sv_dim : The dimension of the state vector meas_dim : The dimension of the measurement vector q_mat : The process noise covariance matrix r_mat : The measurement no... | Implement the Python class `KalmanFilter` described below.
Class description:
A class that defines a general extended Kalman filter. Attributes ---------- sv_dim : The dimension of the state vector meas_dim : The dimension of the measurement vector q_mat : The process noise covariance matrix r_mat : The measurement no... | 8809d26c8659a02cabe4735df732b6f0a4d647bf | <|skeleton|>
class KalmanFilter:
"""A class that defines a general extended Kalman filter. Attributes ---------- sv_dim : The dimension of the state vector meas_dim : The dimension of the measurement vector q_mat : The process noise covariance matrix r_mat : The measurement noise covariance matrix xhat : The a post... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KalmanFilter:
"""A class that defines a general extended Kalman filter. Attributes ---------- sv_dim : The dimension of the state vector meas_dim : The dimension of the measurement vector q_mat : The process noise covariance matrix r_mat : The measurement noise covariance matrix xhat : The a posteriori state ... | the_stack_v2_python_sparse | pytpc/kalman.py | ATTPC/pytpc | train | 1 |
14165d4a176f68e92a49041bc698699b36d6cf21 | [
"mock_condition = mock.Mock(spec=threading.Condition)()\n\ndef _fetch_data():\n \"\"\"Generator that returns 3 data items.\"\"\"\n self.assertEqual(0, mock_condition.wait.call_count)\n for i in (1, 2, 3):\n yield i\n self.assertEqual(0, mock_condition.wait.call_count)\n yield None\n moc... | <|body_start_0|>
mock_condition = mock.Mock(spec=threading.Condition)()
def _fetch_data():
"""Generator that returns 3 data items."""
self.assertEqual(0, mock_condition.wait.call_count)
for i in (1, 2, 3):
yield i
self.assertEqual(0, m... | Test DataFetcher. | DataFetcherTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataFetcherTest:
"""Test DataFetcher."""
def test_data_fetcher(self):
"""Retrieve and ensure the fetch does not wait for available data."""
<|body_0|>
def test_error_propagation(self):
"""Ensure get() raises the exception returned by the generator."""
<|b... | stack_v2_sparse_classes_75kplus_train_074388 | 3,287 | permissive | [
{
"docstring": "Retrieve and ensure the fetch does not wait for available data.",
"name": "test_data_fetcher",
"signature": "def test_data_fetcher(self)"
},
{
"docstring": "Ensure get() raises the exception returned by the generator.",
"name": "test_error_propagation",
"signature": "def ... | 3 | stack_v2_sparse_classes_30k_train_022617 | Implement the Python class `DataFetcherTest` described below.
Class description:
Test DataFetcher.
Method signatures and docstrings:
- def test_data_fetcher(self): Retrieve and ensure the fetch does not wait for available data.
- def test_error_propagation(self): Ensure get() raises the exception returned by the gene... | Implement the Python class `DataFetcherTest` described below.
Class description:
Test DataFetcher.
Method signatures and docstrings:
- def test_data_fetcher(self): Retrieve and ensure the fetch does not wait for available data.
- def test_error_propagation(self): Ensure get() raises the exception returned by the gene... | 26ab377a6853463b2efce40970e54d44b91e79ca | <|skeleton|>
class DataFetcherTest:
"""Test DataFetcher."""
def test_data_fetcher(self):
"""Retrieve and ensure the fetch does not wait for available data."""
<|body_0|>
def test_error_propagation(self):
"""Ensure get() raises the exception returned by the generator."""
<|b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataFetcherTest:
"""Test DataFetcher."""
def test_data_fetcher(self):
"""Retrieve and ensure the fetch does not wait for available data."""
mock_condition = mock.Mock(spec=threading.Condition)()
def _fetch_data():
"""Generator that returns 3 data items."""
... | the_stack_v2_python_sparse | service/learner/data_fetcher_test.py | stewartmiles/falken | train | 1 |
f812fc54c1a8012015538edaa45955f2bb97d5c1 | [
"logging.info('Validando os dados para criação do usuário.')\nif 'name' not in data.keys() or not data['name']:\n raise ParseError('O nome é obrigatório.')\nif 'email' not in data.keys() or not data['email']:\n raise ParseError('O email é obrigatório.')\nif 'password' not in data.keys():\n raise ParseError... | <|body_start_0|>
logging.info('Validando os dados para criação do usuário.')
if 'name' not in data.keys() or not data['name']:
raise ParseError('O nome é obrigatório.')
if 'email' not in data.keys() or not data['email']:
raise ParseError('O email é obrigatório.')
... | O serializer para registrar um novo usuário | UserRegisterSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserRegisterSerializer:
"""O serializer para registrar um novo usuário"""
def validate(self, data):
"""Valide se existe outro usuário com o mesmo endereço de email e verifique se a senha não corresponde."""
<|body_0|>
def create(self, validated_data):
"""Cria e r... | stack_v2_sparse_classes_75kplus_train_074389 | 6,258 | no_license | [
{
"docstring": "Valide se existe outro usuário com o mesmo endereço de email e verifique se a senha não corresponde.",
"name": "validate",
"signature": "def validate(self, data)"
},
{
"docstring": "Cria e retorna um novo usuário",
"name": "create",
"signature": "def create(self, validate... | 2 | null | Implement the Python class `UserRegisterSerializer` described below.
Class description:
O serializer para registrar um novo usuário
Method signatures and docstrings:
- def validate(self, data): Valide se existe outro usuário com o mesmo endereço de email e verifique se a senha não corresponde.
- def create(self, vali... | Implement the Python class `UserRegisterSerializer` described below.
Class description:
O serializer para registrar um novo usuário
Method signatures and docstrings:
- def validate(self, data): Valide se existe outro usuário com o mesmo endereço de email e verifique se a senha não corresponde.
- def create(self, vali... | 3a8009b17518384c269dfee3c8fe44cbe2567cc0 | <|skeleton|>
class UserRegisterSerializer:
"""O serializer para registrar um novo usuário"""
def validate(self, data):
"""Valide se existe outro usuário com o mesmo endereço de email e verifique se a senha não corresponde."""
<|body_0|>
def create(self, validated_data):
"""Cria e r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserRegisterSerializer:
"""O serializer para registrar um novo usuário"""
def validate(self, data):
"""Valide se existe outro usuário com o mesmo endereço de email e verifique se a senha não corresponde."""
logging.info('Validando os dados para criação do usuário.')
if 'name' not ... | the_stack_v2_python_sparse | project/accounts/serializers.py | VWApplications/VWAlmaAPI | train | 1 |
ce3a4430eea64981771268019c3ccb62efaccd17 | [
"self.rects = rects\nself.weight = [0]\nself.s = 0\nfor rect in rects:\n area = (rect[2] - rect[0] + 1) * (rect[3] - rect[1] + 1)\n self.s += area\n self.weight.append(self.s)",
"randomFromArea = randint(1, self.s)\nl = 0\nr = len(self.weight) - 1\nwhile l < r:\n mid = l + r >> 1\n if self.weight[m... | <|body_start_0|>
self.rects = rects
self.weight = [0]
self.s = 0
for rect in rects:
area = (rect[2] - rect[0] + 1) * (rect[3] - rect[1] + 1)
self.s += area
self.weight.append(self.s)
<|end_body_0|>
<|body_start_1|>
randomFromArea = randint(1, ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
<|body_0|>
def pick(self):
""":rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.rects = rects
self.weight = [0]
self.s = 0
for rect ... | stack_v2_sparse_classes_75kplus_train_074390 | 2,163 | no_license | [
{
"docstring": ":type rects: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, rects)"
},
{
"docstring": ":rtype: List[int]",
"name": "pick",
"signature": "def pick(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011053 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, rects): :type rects: List[List[int]]
- def pick(self): :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, rects): :type rects: List[List[int]]
- def pick(self): :rtype: List[int]
<|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: ... | 819fbc523f3b33742333b6b39b72337a24a26f7a | <|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
<|body_0|>
def pick(self):
""":rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
self.rects = rects
self.weight = [0]
self.s = 0
for rect in rects:
area = (rect[2] - rect[0] + 1) * (rect[3] - rect[1] + 1)
self.s += area
self.weight.append(self... | the_stack_v2_python_sparse | leetcode/Random/497m. 非重叠矩形中的随机点(合并随机,二分查找).py | Andrewlearning/Leetcoding | train | 1 | |
38d3fb1b28d9c6d9d5ebe8e0d1e78c4b29730b71 | [
"self.credentials = credentials\nself.host_address = host_address\nself.host_type = host_type",
"if dictionary is None:\n return None\ncredentials = cohesity_management_sdk.models.credentials.Credentials.from_dictionary(dictionary.get('credentials')) if dictionary.get('credentials') else None\nhost_address = d... | <|body_start_0|>
self.credentials = credentials
self.host_address = host_address
self.host_type = host_type
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
credentials = cohesity_management_sdk.models.credentials.Credentials.from_dictionary(diction... | Implementation of the 'RemoteHostConnectorParams' model. TODO: type description here. Attributes: credentials (Credentials): Credentials that will be used to login to the remote host. For env of type kLinux, it is expected that user has setup the password-less access to the remote host. So only username field MUST be s... | RemoteHostConnectorParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RemoteHostConnectorParams:
"""Implementation of the 'RemoteHostConnectorParams' model. TODO: type description here. Attributes: credentials (Credentials): Credentials that will be used to login to the remote host. For env of type kLinux, it is expected that user has setup the password-less access... | stack_v2_sparse_classes_75kplus_train_074391 | 2,331 | permissive | [
{
"docstring": "Constructor for the RemoteHostConnectorParams class",
"name": "__init__",
"signature": "def __init__(self, credentials=None, host_address=None, host_type=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary repr... | 2 | stack_v2_sparse_classes_30k_train_045015 | Implement the Python class `RemoteHostConnectorParams` described below.
Class description:
Implementation of the 'RemoteHostConnectorParams' model. TODO: type description here. Attributes: credentials (Credentials): Credentials that will be used to login to the remote host. For env of type kLinux, it is expected that ... | Implement the Python class `RemoteHostConnectorParams` described below.
Class description:
Implementation of the 'RemoteHostConnectorParams' model. TODO: type description here. Attributes: credentials (Credentials): Credentials that will be used to login to the remote host. For env of type kLinux, it is expected that ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RemoteHostConnectorParams:
"""Implementation of the 'RemoteHostConnectorParams' model. TODO: type description here. Attributes: credentials (Credentials): Credentials that will be used to login to the remote host. For env of type kLinux, it is expected that user has setup the password-less access... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RemoteHostConnectorParams:
"""Implementation of the 'RemoteHostConnectorParams' model. TODO: type description here. Attributes: credentials (Credentials): Credentials that will be used to login to the remote host. For env of type kLinux, it is expected that user has setup the password-less access to the remot... | the_stack_v2_python_sparse | cohesity_management_sdk/models/remote_host_connector_params.py | cohesity/management-sdk-python | train | 24 |
5733999d4b86225b12dfd80042180415e535018e | [
"ans = bal = 0\nfor symbol in S:\n bal += 1 if symbol == '(' else -1\n if bal == -1:\n ans += 1\n bal += 1\nreturn ans + bal",
"while '()' in S:\n S = S.replace('()', '')\nreturn len(S)"
] | <|body_start_0|>
ans = bal = 0
for symbol in S:
bal += 1 if symbol == '(' else -1
if bal == -1:
ans += 1
bal += 1
return ans + bal
<|end_body_0|>
<|body_start_1|>
while '()' in S:
S = S.replace('()', '')
return ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minAddToMakeValid(self, S):
"""解法1:利用)不能再匹配成功的原理,用bal计数balance当前的结果。 比较技巧性的解法,bal维持一个balance,一直在-1,0,n之间浮动 symobol = '('则+1,=')'则-1, bal=0,代表目前凑对成功, bal=-1代表目前剩余一个')',此时就ans+=1,把这个多余的')'计数到最后结果,因为)不可能再匹配成功了,且bal+=1置为0 bal=n,代表剩余n个'(',还有希望匹配成功。"""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus_train_074392 | 1,364 | no_license | [
{
"docstring": "解法1:利用)不能再匹配成功的原理,用bal计数balance当前的结果。 比较技巧性的解法,bal维持一个balance,一直在-1,0,n之间浮动 symobol = '('则+1,=')'则-1, bal=0,代表目前凑对成功, bal=-1代表目前剩余一个')',此时就ans+=1,把这个多余的')'计数到最后结果,因为)不可能再匹配成功了,且bal+=1置为0 bal=n,代表剩余n个'(',还有希望匹配成功。",
"name": "minAddToMakeValid",
"signature": "def minAddToMakeValid(self, S)... | 2 | stack_v2_sparse_classes_30k_train_013566 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minAddToMakeValid(self, S): 解法1:利用)不能再匹配成功的原理,用bal计数balance当前的结果。 比较技巧性的解法,bal维持一个balance,一直在-1,0,n之间浮动 symobol = '('则+1,=')'则-1, bal=0,代表目前凑对成功, bal=-1代表目前剩余一个')',此时就ans+=1,... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minAddToMakeValid(self, S): 解法1:利用)不能再匹配成功的原理,用bal计数balance当前的结果。 比较技巧性的解法,bal维持一个balance,一直在-1,0,n之间浮动 symobol = '('则+1,=')'则-1, bal=0,代表目前凑对成功, bal=-1代表目前剩余一个')',此时就ans+=1,... | 18c06a96bb14688e4a1d5fb6baf235a6b53bd3ae | <|skeleton|>
class Solution:
def minAddToMakeValid(self, S):
"""解法1:利用)不能再匹配成功的原理,用bal计数balance当前的结果。 比较技巧性的解法,bal维持一个balance,一直在-1,0,n之间浮动 symobol = '('则+1,=')'则-1, bal=0,代表目前凑对成功, bal=-1代表目前剩余一个')',此时就ans+=1,把这个多余的')'计数到最后结果,因为)不可能再匹配成功了,且bal+=1置为0 bal=n,代表剩余n个'(',还有希望匹配成功。"""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minAddToMakeValid(self, S):
"""解法1:利用)不能再匹配成功的原理,用bal计数balance当前的结果。 比较技巧性的解法,bal维持一个balance,一直在-1,0,n之间浮动 symobol = '('则+1,=')'则-1, bal=0,代表目前凑对成功, bal=-1代表目前剩余一个')',此时就ans+=1,把这个多余的')'计数到最后结果,因为)不可能再匹配成功了,且bal+=1置为0 bal=n,代表剩余n个'(',还有希望匹配成功。"""
ans = bal = 0
for symbol ... | the_stack_v2_python_sparse | medium/others/minimum-add-to-make-parentheses-valid.py | congyingTech/Basic-Algorithm | train | 10 | |
b2f6e58d895a19def2996ab382859efbe147bb33 | [
"res = []\ncount = 1\nfor _ in range(n):\n res.append(count)\n if count * 10 <= n:\n count *= 10\n else:\n if count >= n:\n count //= 10\n count += 1\n while count % 10 == 0:\n count //= 10\nreturn res",
"res = [x for x in range(1, n + 1)]\nres = sorted(r... | <|body_start_0|>
res = []
count = 1
for _ in range(n):
res.append(count)
if count * 10 <= n:
count *= 10
else:
if count >= n:
count //= 10
count += 1
while count % 10 == 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lexicalOrder(self, n):
""":type n: int :rtype: List[int]"""
<|body_0|>
def lexicalOrder2(self, n):
""":type n: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = []
count = 1
for _ in range(n):
... | stack_v2_sparse_classes_75kplus_train_074393 | 1,262 | no_license | [
{
"docstring": ":type n: int :rtype: List[int]",
"name": "lexicalOrder",
"signature": "def lexicalOrder(self, n)"
},
{
"docstring": ":type n: int :rtype: List[int]",
"name": "lexicalOrder2",
"signature": "def lexicalOrder2(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001244 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lexicalOrder(self, n): :type n: int :rtype: List[int]
- def lexicalOrder2(self, n): :type n: int :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lexicalOrder(self, n): :type n: int :rtype: List[int]
- def lexicalOrder2(self, n): :type n: int :rtype: List[int]
<|skeleton|>
class Solution:
def lexicalOrder(self, n... | 8595b04cf5a024c2cd8a97f750d890a818568401 | <|skeleton|>
class Solution:
def lexicalOrder(self, n):
""":type n: int :rtype: List[int]"""
<|body_0|>
def lexicalOrder2(self, n):
""":type n: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def lexicalOrder(self, n):
""":type n: int :rtype: List[int]"""
res = []
count = 1
for _ in range(n):
res.append(count)
if count * 10 <= n:
count *= 10
else:
if count >= n:
count /... | the_stack_v2_python_sparse | python/386.lexicographical-numbers.py | tainenko/Leetcode2019 | train | 5 | |
a96019a7ab745e4adaddd29519ebac4605054970 | [
"self.parent = parent\ncontent = Frame(0.75 * inch, 0.5 * inch, parent.document.pagesize[0] - 1.25 * inch, parent.document.pagesize[1] - 1.5 * inch)\nPageTemplate.__init__(self, 'MyTemplate', [content])\nself.logo = self.getImageFromZODB('logo')",
"try:\n logo = getattr(self.parent.context, name)\nexcept Attri... | <|body_start_0|>
self.parent = parent
content = Frame(0.75 * inch, 0.5 * inch, parent.document.pagesize[0] - 1.25 * inch, parent.document.pagesize[1] - 1.5 * inch)
PageTemplate.__init__(self, 'MyTemplate', [content])
self.logo = self.getImageFromZODB('logo')
<|end_body_0|>
<|body_start_... | Our own page template. | MyPageTemplate | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyPageTemplate:
"""Our own page template."""
def __init__(self, parent):
"""Initialise our page template."""
<|body_0|>
def getImageFromZODB(self, name):
"""Retrieves an Image from the ZODB, converts it to PIL, and makes it 0.75 inch high."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_074394 | 6,791 | permissive | [
{
"docstring": "Initialise our page template.",
"name": "__init__",
"signature": "def __init__(self, parent)"
},
{
"docstring": "Retrieves an Image from the ZODB, converts it to PIL, and makes it 0.75 inch high.",
"name": "getImageFromZODB",
"signature": "def getImageFromZODB(self, name)... | 3 | stack_v2_sparse_classes_30k_train_008109 | Implement the Python class `MyPageTemplate` described below.
Class description:
Our own page template.
Method signatures and docstrings:
- def __init__(self, parent): Initialise our page template.
- def getImageFromZODB(self, name): Retrieves an Image from the ZODB, converts it to PIL, and makes it 0.75 inch high.
- ... | Implement the Python class `MyPageTemplate` described below.
Class description:
Our own page template.
Method signatures and docstrings:
- def __init__(self, parent): Initialise our page template.
- def getImageFromZODB(self, name): Retrieves an Image from the ZODB, converts it to PIL, and makes it 0.75 inch high.
- ... | c28aa50e2d6d3451b47e114094a86c03c87d4c50 | <|skeleton|>
class MyPageTemplate:
"""Our own page template."""
def __init__(self, parent):
"""Initialise our page template."""
<|body_0|>
def getImageFromZODB(self, name):
"""Retrieves an Image from the ZODB, converts it to PIL, and makes it 0.75 inch high."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyPageTemplate:
"""Our own page template."""
def __init__(self, parent):
"""Initialise our page template."""
self.parent = parent
content = Frame(0.75 * inch, 0.5 * inch, parent.document.pagesize[0] - 1.25 * inch, parent.document.pagesize[1] - 1.5 * inch)
PageTemplate.__in... | the_stack_v2_python_sparse | demos/rlzope/rlzope.py | MrBitBucket/reportlab-mirror | train | 64 |
451d606904da780e8a2734d472907bf84574007e | [
"if self._listeners is None:\n self._listeners = weakref.WeakValueDictionary()\nself._listeners[id(listener)] = listener",
"if self._listeners is None:\n return\nwith suppress(KeyError):\n del self._listeners[id(listener)]",
"if self._listeners is None:\n return\nmethod_name = f'_update_{notificatio... | <|body_start_0|>
if self._listeners is None:
self._listeners = weakref.WeakValueDictionary()
self._listeners[id(listener)] = listener
<|end_body_0|>
<|body_start_1|>
if self._listeners is None:
return
with suppress(KeyError):
del self._listeners[id(li... | Mixin class that provides services by which objects can register listeners to changes on that object. All methods provided by this class are underscored, since this is intended for internal use to communicate between classes in a generic way, and is not machinery that should be exposed to users of the classes involved.... | NotifierMixin | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NotifierMixin:
"""Mixin class that provides services by which objects can register listeners to changes on that object. All methods provided by this class are underscored, since this is intended for internal use to communicate between classes in a generic way, and is not machinery that should be ... | stack_v2_sparse_classes_75kplus_train_074395 | 29,904 | permissive | [
{
"docstring": "Add an object to the list of listeners to notify of changes to this object. This adds a weakref to the list of listeners that is removed from the listeners list when the listener has no other references to it.",
"name": "_add_listener",
"signature": "def _add_listener(self, listener)"
... | 4 | stack_v2_sparse_classes_30k_train_019773 | Implement the Python class `NotifierMixin` described below.
Class description:
Mixin class that provides services by which objects can register listeners to changes on that object. All methods provided by this class are underscored, since this is intended for internal use to communicate between classes in a generic wa... | Implement the Python class `NotifierMixin` described below.
Class description:
Mixin class that provides services by which objects can register listeners to changes on that object. All methods provided by this class are underscored, since this is intended for internal use to communicate between classes in a generic wa... | 53188c39a23c33b72df5850ec59e31886f84e29d | <|skeleton|>
class NotifierMixin:
"""Mixin class that provides services by which objects can register listeners to changes on that object. All methods provided by this class are underscored, since this is intended for internal use to communicate between classes in a generic way, and is not machinery that should be ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NotifierMixin:
"""Mixin class that provides services by which objects can register listeners to changes on that object. All methods provided by this class are underscored, since this is intended for internal use to communicate between classes in a generic way, and is not machinery that should be exposed to us... | the_stack_v2_python_sparse | astropy/io/fits/util.py | astropy/astropy | train | 3,922 |
5f3882d3e15fd0a2f828de5e6fe2e802e6baeaaa | [
"inputs = [x.strip('[]\"\\n') for x in sys_stdin]\na = [self.cast(x) for x in inputs[0].split(',')]\nreturn a",
"if x.lower() == 'null':\n return None\nelse:\n return int(x)"
] | <|body_start_0|>
inputs = [x.strip('[]"\n') for x in sys_stdin]
a = [self.cast(x) for x in inputs[0].split(',')]
return a
<|end_body_0|>
<|body_start_1|>
if x.lower() == 'null':
return None
else:
return int(x)
<|end_body_1|>
| Input | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Input:
def stdin(self, sys_stdin):
"""Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: array of input integer values :rtype: list[int or None]"""
<|body_0|>
def cast(self, x):
"""Converts string values to integer or None values. :pa... | stack_v2_sparse_classes_75kplus_train_074396 | 2,776 | permissive | [
{
"docstring": "Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: array of input integer values :rtype: list[int or None]",
"name": "stdin",
"signature": "def stdin(self, sys_stdin)"
},
{
"docstring": "Converts string values to integer or None values. :param str... | 2 | null | Implement the Python class `Input` described below.
Class description:
Implement the Input class.
Method signatures and docstrings:
- def stdin(self, sys_stdin): Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: array of input integer values :rtype: list[int or None]
- def cast(self,... | Implement the Python class `Input` described below.
Class description:
Implement the Input class.
Method signatures and docstrings:
- def stdin(self, sys_stdin): Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: array of input integer values :rtype: list[int or None]
- def cast(self,... | 69f90877c5466927e8b081c4268cbcda074813ec | <|skeleton|>
class Input:
def stdin(self, sys_stdin):
"""Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: array of input integer values :rtype: list[int or None]"""
<|body_0|>
def cast(self, x):
"""Converts string values to integer or None values. :pa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Input:
def stdin(self, sys_stdin):
"""Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: array of input integer values :rtype: list[int or None]"""
inputs = [x.strip('[]"\n') for x in sys_stdin]
a = [self.cast(x) for x in inputs[0].split(',')]
r... | the_stack_v2_python_sparse | 0654_maximum_binary_tree/python_source.py | arthurdysart/LeetCode | train | 0 | |
7bf28cf37c57d261303e688cbac8385dcf8c6dc7 | [
"super(Timer, self).__init__()\nself._msg = msg\nself._start = time.time()\nself._last = self._start",
"if msg is not None:\n self._msg = msg\ncurr_time = time.time()\nself._last = curr_time\nif not only_last:\n self._start = curr_time",
"end = time.time()\ncost = end - self._start\nreturn cost",
"end =... | <|body_start_0|>
super(Timer, self).__init__()
self._msg = msg
self._start = time.time()
self._last = self._start
<|end_body_0|>
<|body_start_1|>
if msg is not None:
self._msg = msg
curr_time = time.time()
self._last = curr_time
if not only_la... | Stat Cost Time | Timer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Timer:
"""Stat Cost Time"""
def __init__(self, msg=''):
"""init of class Args: msg (TYPE): Default is """""
<|body_0|>
def reset(self, only_last=False, msg=None):
"""reset all setting Args: msg (TYPE): Default is None Returns: TODO Raises: NULL"""
<|body_... | stack_v2_sparse_classes_75kplus_train_074397 | 4,088 | permissive | [
{
"docstring": "init of class Args: msg (TYPE): Default is \"\"",
"name": "__init__",
"signature": "def __init__(self, msg='')"
},
{
"docstring": "reset all setting Args: msg (TYPE): Default is None Returns: TODO Raises: NULL",
"name": "reset",
"signature": "def reset(self, only_last=Fal... | 5 | null | Implement the Python class `Timer` described below.
Class description:
Stat Cost Time
Method signatures and docstrings:
- def __init__(self, msg=''): init of class Args: msg (TYPE): Default is ""
- def reset(self, only_last=False, msg=None): reset all setting Args: msg (TYPE): Default is None Returns: TODO Raises: NU... | Implement the Python class `Timer` described below.
Class description:
Stat Cost Time
Method signatures and docstrings:
- def __init__(self, msg=''): init of class Args: msg (TYPE): Default is ""
- def reset(self, only_last=False, msg=None): reset all setting Args: msg (TYPE): Default is None Returns: TODO Raises: NU... | b8ec015fa9e16c0a879c619ee1f2aab8a393c7bd | <|skeleton|>
class Timer:
"""Stat Cost Time"""
def __init__(self, msg=''):
"""init of class Args: msg (TYPE): Default is """""
<|body_0|>
def reset(self, only_last=False, msg=None):
"""reset all setting Args: msg (TYPE): Default is None Returns: TODO Raises: NULL"""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Timer:
"""Stat Cost Time"""
def __init__(self, msg=''):
"""init of class Args: msg (TYPE): Default is """""
super(Timer, self).__init__()
self._msg = msg
self._start = time.time()
self._last = self._start
def reset(self, only_last=False, msg=None):
"""... | the_stack_v2_python_sparse | NLP/Text2SQL-BASELINE/text2sql/utils/utils.py | sserdoubleh/Research | train | 10 |
57998053c305a12dea390ed3fc15ddb538d1dff9 | [
"part1 = volumePartition(7, VolumeOffset(3, 1, 5))\npart2 = volumePartition(7, VolumeOffset(3, 2, 5))\npart3 = volumePartition(8, VolumeOffset(3, 1, 5))\nself.assertEqual(hash(part1), hash(part2))\nself.assertNotEqual(hash(part1), hash(part3))",
"part1 = volumePartition(7, VolumeOffset(3, 1, 5))\npart2 = volumePa... | <|body_start_0|>
part1 = volumePartition(7, VolumeOffset(3, 1, 5))
part2 = volumePartition(7, VolumeOffset(3, 2, 5))
part3 = volumePartition(8, VolumeOffset(3, 1, 5))
self.assertEqual(hash(part1), hash(part2))
self.assertNotEqual(hash(part1), hash(part3))
<|end_body_0|>
<|body_s... | TestVolumePartition | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestVolumePartition:
def test_partitionhash(self):
"""Check hashing function for volumePartition."""
<|body_0|>
def test_partitioneq(self):
"""Check equivalence function for volumePartition."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
part1 = vo... | stack_v2_sparse_classes_75kplus_train_074398 | 6,793 | permissive | [
{
"docstring": "Check hashing function for volumePartition.",
"name": "test_partitionhash",
"signature": "def test_partitionhash(self)"
},
{
"docstring": "Check equivalence function for volumePartition.",
"name": "test_partitioneq",
"signature": "def test_partitioneq(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_042143 | Implement the Python class `TestVolumePartition` described below.
Class description:
Implement the TestVolumePartition class.
Method signatures and docstrings:
- def test_partitionhash(self): Check hashing function for volumePartition.
- def test_partitioneq(self): Check equivalence function for volumePartition. | Implement the Python class `TestVolumePartition` described below.
Class description:
Implement the TestVolumePartition class.
Method signatures and docstrings:
- def test_partitionhash(self): Check hashing function for volumePartition.
- def test_partitioneq(self): Check equivalence function for volumePartition.
<|s... | 14b271b150508ad247347898c0b1ac7365931b05 | <|skeleton|>
class TestVolumePartition:
def test_partitionhash(self):
"""Check hashing function for volumePartition."""
<|body_0|>
def test_partitioneq(self):
"""Check equivalence function for volumePartition."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestVolumePartition:
def test_partitionhash(self):
"""Check hashing function for volumePartition."""
part1 = volumePartition(7, VolumeOffset(3, 1, 5))
part2 = volumePartition(7, VolumeOffset(3, 2, 5))
part3 = volumePartition(8, VolumeOffset(3, 1, 5))
self.assertEqual(ha... | the_stack_v2_python_sparse | obsolete/unit_tests/io_util/test_partitionSchema.py | janelia-flyem/flyemflows | train | 1 | |
0c9d3577f0bf02059c18bc1910f37ba4ad2276cf | [
"super().__init__(clip_duration)\nself._stride = stride if stride is not None else clip_duration\nself._eps = eps\nself._backpad_last = backpad_last\nassert self._stride > 0 and self._stride <= clip_duration, f'stride must be >0 and <= clip_duration ({clip_duration})'",
"clip_start = max(last_clip_time - max(0, s... | <|body_start_0|>
super().__init__(clip_duration)
self._stride = stride if stride is not None else clip_duration
self._eps = eps
self._backpad_last = backpad_last
assert self._stride > 0 and self._stride <= clip_duration, f'stride must be >0 and <= clip_duration ({clip_duration})'... | Evenly splits the video into clips of size clip_duration. | UniformClipSampler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UniformClipSampler:
"""Evenly splits the video into clips of size clip_duration."""
def __init__(self, clip_duration: float, stride: Optional[float]=None, backpad_last: bool=False, eps: float=1e-06):
"""Args: clip_duration (float): The length of the clip to sample (in seconds) stride... | stack_v2_sparse_classes_75kplus_train_074399 | 9,223 | permissive | [
{
"docstring": "Args: clip_duration (float): The length of the clip to sample (in seconds) stride (float, optional): The amount of seconds to offset the next clip by default value of None is equivalent to no stride => stride == clip_duration eps (float): Epsilon for floating point comparisons. Used to check the... | 3 | stack_v2_sparse_classes_30k_train_024672 | Implement the Python class `UniformClipSampler` described below.
Class description:
Evenly splits the video into clips of size clip_duration.
Method signatures and docstrings:
- def __init__(self, clip_duration: float, stride: Optional[float]=None, backpad_last: bool=False, eps: float=1e-06): Args: clip_duration (flo... | Implement the Python class `UniformClipSampler` described below.
Class description:
Evenly splits the video into clips of size clip_duration.
Method signatures and docstrings:
- def __init__(self, clip_duration: float, stride: Optional[float]=None, backpad_last: bool=False, eps: float=1e-06): Args: clip_duration (flo... | 16f2abf2f8aa174915316007622bbb260215dee8 | <|skeleton|>
class UniformClipSampler:
"""Evenly splits the video into clips of size clip_duration."""
def __init__(self, clip_duration: float, stride: Optional[float]=None, backpad_last: bool=False, eps: float=1e-06):
"""Args: clip_duration (float): The length of the clip to sample (in seconds) stride... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UniformClipSampler:
"""Evenly splits the video into clips of size clip_duration."""
def __init__(self, clip_duration: float, stride: Optional[float]=None, backpad_last: bool=False, eps: float=1e-06):
"""Args: clip_duration (float): The length of the clip to sample (in seconds) stride (float, opti... | the_stack_v2_python_sparse | pytorchvideo/data/clip_sampling.py | xchani/pytorchvideo | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.