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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2a473d3de066cdd7e0971f68adccf452ccf14c8f | [
"if not embed_items:\n embed_items = {}\nif not field_items:\n field_items = {}\nenumerated_data: enumerate = enumerate(sorted_data)\ndata_embed: Embed = await initialize_embed(**embed_items)\nfor counter, contents in enumerated_data:\n embed_items.update({'page_number': counter // DiscordConstant.MAX_EMBE... | <|body_start_0|>
if not embed_items:
embed_items = {}
if not field_items:
field_items = {}
enumerated_data: enumerate = enumerate(sorted_data)
data_embed: Embed = await initialize_embed(**embed_items)
for counter, contents in enumerated_data:
e... | This class is a mix-in that contains helper methods for creating embeds. It also contains two template methods for fashioning the overall Embed objects. | Embedder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Embedder:
"""This class is a mix-in that contains helper methods for creating embeds. It also contains two template methods for fashioning the overall Embed objects."""
async def embed(destination_channel: TextChannel, sorted_data: List[Any], initialize_embed: Callable, initialize_field: Cal... | stack_v2_sparse_classes_75kplus_train_067500 | 5,507 | no_license | [
{
"docstring": "This method produces Discord Embeds of varying kinds and sends them to a given channel. It accepts functions to produce the overall Embed and its fields for data sets of varying sizes, taking two optional dictionaries to add to each function's customization. :param TextChannel destination_channe... | 3 | stack_v2_sparse_classes_30k_val_001885 | Implement the Python class `Embedder` described below.
Class description:
This class is a mix-in that contains helper methods for creating embeds. It also contains two template methods for fashioning the overall Embed objects.
Method signatures and docstrings:
- async def embed(destination_channel: TextChannel, sorte... | Implement the Python class `Embedder` described below.
Class description:
This class is a mix-in that contains helper methods for creating embeds. It also contains two template methods for fashioning the overall Embed objects.
Method signatures and docstrings:
- async def embed(destination_channel: TextChannel, sorte... | d8c2dc4a9aa21d5861f465b5cc4b02df44df0360 | <|skeleton|>
class Embedder:
"""This class is a mix-in that contains helper methods for creating embeds. It also contains two template methods for fashioning the overall Embed objects."""
async def embed(destination_channel: TextChannel, sorted_data: List[Any], initialize_embed: Callable, initialize_field: Cal... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Embedder:
"""This class is a mix-in that contains helper methods for creating embeds. It also contains two template methods for fashioning the overall Embed objects."""
async def embed(destination_channel: TextChannel, sorted_data: List[Any], initialize_embed: Callable, initialize_field: Callable, embed_... | the_stack_v2_python_sparse | Bot/Cogs/Helpers/embedder.py | Mythologos/Smorg | train | 0 |
2e207a2e04ca9743aa32fdc2bd3ade823c896893 | [
"print('重写创建方法', validated_data)\ninstance = Category.objects.create(**validated_data)\nprint('创建模型实例', instance)\nreturn instance",
"print('重写更新方法', validated_data, instance.name)\ninstance.name = validated_data.get('name', instance.name)\nprint(instance.name)\ninstance.save()\nreturn instance"
] | <|body_start_0|>
print('重写创建方法', validated_data)
instance = Category.objects.create(**validated_data)
print('创建模型实例', instance)
return instance
<|end_body_0|>
<|body_start_1|>
print('重写更新方法', validated_data, instance.name)
instance.name = validated_data.get('name', insta... | 序列化类 决定了模型序列化细节 | CategorySerizlizer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CategorySerizlizer:
"""序列化类 决定了模型序列化细节"""
def create(self, validated_data):
"""通过重写create方法 来定义模型创建方式 :param validated_data: :return:"""
<|body_0|>
def update(self, instance, validated_data):
"""通过重写update,来定义模型的更新方法 :param instance: 更改之前的实例 :param validated_data... | stack_v2_sparse_classes_75kplus_train_067501 | 7,088 | no_license | [
{
"docstring": "通过重写create方法 来定义模型创建方式 :param validated_data: :return:",
"name": "create",
"signature": "def create(self, validated_data)"
},
{
"docstring": "通过重写update,来定义模型的更新方法 :param instance: 更改之前的实例 :param validated_data: 更改参数 :return: 返回的新实例",
"name": "update",
"signature": "def u... | 2 | stack_v2_sparse_classes_30k_train_040600 | Implement the Python class `CategorySerizlizer` described below.
Class description:
序列化类 决定了模型序列化细节
Method signatures and docstrings:
- def create(self, validated_data): 通过重写create方法 来定义模型创建方式 :param validated_data: :return:
- def update(self, instance, validated_data): 通过重写update,来定义模型的更新方法 :param instance: 更改之前的实例 ... | Implement the Python class `CategorySerizlizer` described below.
Class description:
序列化类 决定了模型序列化细节
Method signatures and docstrings:
- def create(self, validated_data): 通过重写create方法 来定义模型创建方式 :param validated_data: :return:
- def update(self, instance, validated_data): 通过重写update,来定义模型的更新方法 :param instance: 更改之前的实例 ... | 80eb5175cd0e5b3c6c5e2ebb906bb78d9a8f9e0d | <|skeleton|>
class CategorySerizlizer:
"""序列化类 决定了模型序列化细节"""
def create(self, validated_data):
"""通过重写create方法 来定义模型创建方式 :param validated_data: :return:"""
<|body_0|>
def update(self, instance, validated_data):
"""通过重写update,来定义模型的更新方法 :param instance: 更改之前的实例 :param validated_data... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CategorySerizlizer:
"""序列化类 决定了模型序列化细节"""
def create(self, validated_data):
"""通过重写create方法 来定义模型创建方式 :param validated_data: :return:"""
print('重写创建方法', validated_data)
instance = Category.objects.create(**validated_data)
print('创建模型实例', instance)
return instance
... | the_stack_v2_python_sparse | end/shop-end/drfend/shop/serializers.py | 1987617587/lsh_py | train | 2 |
bafdf0eb0c2fca1f94e12fa8d402918d12a7326b | [
"try:\n return Parametros.objects.first()\nexcept Parametros.DoesNotExist:\n raise Http404",
"parametros = self.get_object()\ninstrucao_normativa_url = parametros.instrucao_normativa.url\nlog.info(f'Url da instrução normativa: {instrucao_normativa_url}')\nreturn Response(instrucao_normativa_url)"
] | <|body_start_0|>
try:
return Parametros.objects.first()
except Parametros.DoesNotExist:
raise Http404
<|end_body_0|>
<|body_start_1|>
parametros = self.get_object()
instrucao_normativa_url = parametros.instrucao_normativa.url
log.info(f'Url da instrução n... | InstrucaoNormativaViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstrucaoNormativaViewSet:
def get_object(self):
"""Busca o objeto do modelo Parametros Raises: Http404: Quando objeto não encontrado Returns: Parametros (Parametros): Instância do objeto parâmetros."""
<|body_0|>
def list(self, request, *args, **kwargs):
"""Busca o ... | stack_v2_sparse_classes_75kplus_train_067502 | 1,186 | permissive | [
{
"docstring": "Busca o objeto do modelo Parametros Raises: Http404: Quando objeto não encontrado Returns: Parametros (Parametros): Instância do objeto parâmetros.",
"name": "get_object",
"signature": "def get_object(self)"
},
{
"docstring": "Busca o arquivo do edital e suas informações Raises: ... | 2 | stack_v2_sparse_classes_30k_train_026958 | Implement the Python class `InstrucaoNormativaViewSet` described below.
Class description:
Implement the InstrucaoNormativaViewSet class.
Method signatures and docstrings:
- def get_object(self): Busca o objeto do modelo Parametros Raises: Http404: Quando objeto não encontrado Returns: Parametros (Parametros): Instân... | Implement the Python class `InstrucaoNormativaViewSet` described below.
Class description:
Implement the InstrucaoNormativaViewSet class.
Method signatures and docstrings:
- def get_object(self): Busca o objeto do modelo Parametros Raises: Http404: Quando objeto não encontrado Returns: Parametros (Parametros): Instân... | bf8e0dc21ebc55554466d8de6608a047a59cc3e9 | <|skeleton|>
class InstrucaoNormativaViewSet:
def get_object(self):
"""Busca o objeto do modelo Parametros Raises: Http404: Quando objeto não encontrado Returns: Parametros (Parametros): Instância do objeto parâmetros."""
<|body_0|>
def list(self, request, *args, **kwargs):
"""Busca o ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InstrucaoNormativaViewSet:
def get_object(self):
"""Busca o objeto do modelo Parametros Raises: Http404: Quando objeto não encontrado Returns: Parametros (Parametros): Instância do objeto parâmetros."""
try:
return Parametros.objects.first()
except Parametros.DoesNotExist:
... | the_stack_v2_python_sparse | sme_uniforme_apps/core/api/viewsets/instrucao_normativa_viewset.py | prefeiturasp/SME-PortalUniforme-BackEnd | train | 0 | |
08c81fd7270cd9009174940fdd52eca0a21da6e2 | [
"for session in sessions:\n if sessions['id'] == id:\n return sessions\napi.abort(404)",
"for session in sessions:\n if sessions['id'] == id:\n return sessions\napi.abort(404)",
"for session in sessions:\n if sessions['id'] == id:\n return sessions\napi.abort(404)"
] | <|body_start_0|>
for session in sessions:
if sessions['id'] == id:
return sessions
api.abort(404)
<|end_body_0|>
<|body_start_1|>
for session in sessions:
if sessions['id'] == id:
return sessions
api.abort(404)
<|end_body_1|>
<|bo... | Session | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Session:
def get(self, id):
"""Fetch a session given its identifier"""
<|body_0|>
def post(self, id):
"""Fetch a session given its identifier"""
<|body_1|>
def delete(self, id):
"""Fetch a session given its identifier"""
<|body_2|>
<|end... | stack_v2_sparse_classes_75kplus_train_067503 | 949 | no_license | [
{
"docstring": "Fetch a session given its identifier",
"name": "get",
"signature": "def get(self, id)"
},
{
"docstring": "Fetch a session given its identifier",
"name": "post",
"signature": "def post(self, id)"
},
{
"docstring": "Fetch a session given its identifier",
"name":... | 3 | stack_v2_sparse_classes_30k_train_017030 | Implement the Python class `Session` described below.
Class description:
Implement the Session class.
Method signatures and docstrings:
- def get(self, id): Fetch a session given its identifier
- def post(self, id): Fetch a session given its identifier
- def delete(self, id): Fetch a session given its identifier | Implement the Python class `Session` described below.
Class description:
Implement the Session class.
Method signatures and docstrings:
- def get(self, id): Fetch a session given its identifier
- def post(self, id): Fetch a session given its identifier
- def delete(self, id): Fetch a session given its identifier
<|s... | bc0f80e2f1b139bff0538863c86f2e88d477061e | <|skeleton|>
class Session:
def get(self, id):
"""Fetch a session given its identifier"""
<|body_0|>
def post(self, id):
"""Fetch a session given its identifier"""
<|body_1|>
def delete(self, id):
"""Fetch a session given its identifier"""
<|body_2|>
<|end... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Session:
def get(self, id):
"""Fetch a session given its identifier"""
for session in sessions:
if sessions['id'] == id:
return sessions
api.abort(404)
def post(self, id):
"""Fetch a session given its identifier"""
for session in session... | the_stack_v2_python_sparse | resources/sessions.py | daehan0226/fun_english_server | train | 0 | |
2fa81bb3514bbc455389a7aaf696449b16aec231 | [
"rel_path = 'data/' + location + '/LinkTable.txt'\nabs_path = os.path.join(os.path.dirname(__file__), rel_path)\nwith open(abs_path, 'w') as f:\n for key, value in data.items():\n element = (key, value)\n f.writelines(str(element))\n f.write('\\n')\nf.close()",
"rel_path = 'data/' + locati... | <|body_start_0|>
rel_path = 'data/' + location + '/LinkTable.txt'
abs_path = os.path.join(os.path.dirname(__file__), rel_path)
with open(abs_path, 'w') as f:
for key, value in data.items():
element = (key, value)
f.writelines(str(element))
... | Export | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Export:
def export_link_table(location, data):
"""Export the link table :param location: :param data: :return:"""
<|body_0|>
def export_dimension_data(location, dimension, data):
"""Export the dimension data :param location: :param dimension: :param data: :return:"""... | stack_v2_sparse_classes_75kplus_train_067504 | 1,667 | no_license | [
{
"docstring": "Export the link table :param location: :param data: :return:",
"name": "export_link_table",
"signature": "def export_link_table(location, data)"
},
{
"docstring": "Export the dimension data :param location: :param dimension: :param data: :return:",
"name": "export_dimension_d... | 3 | stack_v2_sparse_classes_30k_train_027063 | Implement the Python class `Export` described below.
Class description:
Implement the Export class.
Method signatures and docstrings:
- def export_link_table(location, data): Export the link table :param location: :param data: :return:
- def export_dimension_data(location, dimension, data): Export the dimension data ... | Implement the Python class `Export` described below.
Class description:
Implement the Export class.
Method signatures and docstrings:
- def export_link_table(location, data): Export the link table :param location: :param data: :return:
- def export_dimension_data(location, dimension, data): Export the dimension data ... | 7a3b8830ec0ec7c701b8c555c894d5a2497dd1a1 | <|skeleton|>
class Export:
def export_link_table(location, data):
"""Export the link table :param location: :param data: :return:"""
<|body_0|>
def export_dimension_data(location, dimension, data):
"""Export the dimension data :param location: :param dimension: :param data: :return:"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Export:
def export_link_table(location, data):
"""Export the link table :param location: :param data: :return:"""
rel_path = 'data/' + location + '/LinkTable.txt'
abs_path = os.path.join(os.path.dirname(__file__), rel_path)
with open(abs_path, 'w') as f:
for key, va... | the_stack_v2_python_sparse | Export.py | CppbetterC/A-Star | train | 0 | |
50ad28afd8c58e3201116786ee55065a5a5c0674 | [
"df_work = df.drop('idle_time', 'start_time', 'end_time')\ndf_avg = df_work.groupBy('user_name').agg(sqlFun.from_unixtime(sqlFun.avg(sqlFun.unix_timestamp('working_hour')), 'hh:mm:ss').alias('avg_time'))\ndf_avg_hours = df_avg.withColumn('avg_hour', (hour(df_avg['avg_time']) * 3600 + minute(df_avg['avg_time']) * 60... | <|body_start_0|>
df_work = df.drop('idle_time', 'start_time', 'end_time')
df_avg = df_work.groupBy('user_name').agg(sqlFun.from_unixtime(sqlFun.avg(sqlFun.unix_timestamp('working_hour')), 'hh:mm:ss').alias('avg_time'))
df_avg_hours = df_avg.withColumn('avg_hour', (hour(df_avg['avg_time']) * 3600... | SparkQuery | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparkQuery:
def high_avg_working_users(self, df):
"""Find average working hours for each users. And then find who is working more then total average hour."""
<|body_0|>
def lowest_avg_working_user(self, df):
"""Find average working hours for each users. And then find... | stack_v2_sparse_classes_75kplus_train_067505 | 6,521 | no_license | [
{
"docstring": "Find average working hours for each users. And then find who is working more then total average hour.",
"name": "high_avg_working_users",
"signature": "def high_avg_working_users(self, df)"
},
{
"docstring": "Find average working hours for each users. And then find who is working... | 6 | stack_v2_sparse_classes_30k_train_050986 | Implement the Python class `SparkQuery` described below.
Class description:
Implement the SparkQuery class.
Method signatures and docstrings:
- def high_avg_working_users(self, df): Find average working hours for each users. And then find who is working more then total average hour.
- def lowest_avg_working_user(self... | Implement the Python class `SparkQuery` described below.
Class description:
Implement the SparkQuery class.
Method signatures and docstrings:
- def high_avg_working_users(self, df): Find average working hours for each users. And then find who is working more then total average hour.
- def lowest_avg_working_user(self... | 913ca78b3cdb22feba106d63f25cff4ebd29bbc7 | <|skeleton|>
class SparkQuery:
def high_avg_working_users(self, df):
"""Find average working hours for each users. And then find who is working more then total average hour."""
<|body_0|>
def lowest_avg_working_user(self, df):
"""Find average working hours for each users. And then find... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SparkQuery:
def high_avg_working_users(self, df):
"""Find average working hours for each users. And then find who is working more then total average hour."""
df_work = df.drop('idle_time', 'start_time', 'end_time')
df_avg = df_work.groupBy('user_name').agg(sqlFun.from_unixtime(sqlFun.a... | the_stack_v2_python_sparse | PySpark/Queries.py | shivamgupta7/Hadoop | train | 0 | |
d167e2411b83e8ece389bea2cf3c5fb26144b095 | [
"dt = {'dt': {'dtype': numpy.int_}, 'critic_score': {'dtype': numpy.int_}}\nall_params = self.add_critic_params(params=dt, override_params=override_params)\nreturn all_params",
"if self.critic is not None:\n critic_states = self.critic.calculate(batch_size=batch_size, model_states=model_states, **kwargs)\n ... | <|body_start_0|>
dt = {'dt': {'dtype': numpy.int_}, 'critic_score': {'dtype': numpy.int_}}
all_params = self.add_critic_params(params=dt, override_params=override_params)
return all_params
<|end_body_0|>
<|body_start_1|>
if self.critic is not None:
critic_states = self.criti... | Model class that allows to sample actions meant to be applied a different number of time steps. In order to account for the target number of time steps it incorporates in the `dt` attribute, that will represent the number of times that the calculated action should be applied. This model is not meant to be instantiated ... | _DtModel | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _DtModel:
"""Model class that allows to sample actions meant to be applied a different number of time steps. In order to account for the target number of time steps it incorporates in the `dt` attribute, that will represent the number of times that the calculated action should be applied. This mo... | stack_v2_sparse_classes_75kplus_train_067506 | 18,253 | permissive | [
{
"docstring": "Return the dictionary with the parameters to create a new `DiscreteUniform` model. Args: override_params: The :class:`Critic` parameters will override the :class:`Model` parameters if they both have parameters with the same name. Returns: dict containing the parameters of both the :class:`Model`... | 2 | stack_v2_sparse_classes_30k_train_009012 | Implement the Python class `_DtModel` described below.
Class description:
Model class that allows to sample actions meant to be applied a different number of time steps. In order to account for the target number of time steps it incorporates in the `dt` attribute, that will represent the number of times that the calcu... | Implement the Python class `_DtModel` described below.
Class description:
Model class that allows to sample actions meant to be applied a different number of time steps. In order to account for the target number of time steps it incorporates in the `dt` attribute, that will represent the number of times that the calcu... | 5e69c50e5b220859d65406d803086406b50a8e78 | <|skeleton|>
class _DtModel:
"""Model class that allows to sample actions meant to be applied a different number of time steps. In order to account for the target number of time steps it incorporates in the `dt` attribute, that will represent the number of times that the calculated action should be applied. This mo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _DtModel:
"""Model class that allows to sample actions meant to be applied a different number of time steps. In order to account for the target number of time steps it incorporates in the `dt` attribute, that will represent the number of times that the calculated action should be applied. This model is not me... | the_stack_v2_python_sparse | fragile/core/models.py | sergio-hcsoft/fragile-1 | train | 0 |
a2bc12321e5148fbc36ff0b5038bf657180e1f50 | [
"super(ContextualCell_v1, self).__init__()\nself._ops = ops.MoudleList()\nself._pos = []\nself._collect_inds = [0]\nself._pools = ['x']\nfor ind, op in enumerate(config):\n if ind == 0:\n pos = 0\n op_id = op\n self._collect_inds.remove(pos)\n op_name = op_names[op_id]\n self._... | <|body_start_0|>
super(ContextualCell_v1, self).__init__()
self._ops = ops.MoudleList()
self._pos = []
self._collect_inds = [0]
self._pools = ['x']
for ind, op in enumerate(config):
if ind == 0:
pos = 0
op_id = op
... | New contextual cell design. | ContextualCell_v1 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContextualCell_v1:
"""New contextual cell design."""
def __init__(self, op_names, config, inp, repeats=1, concat=False):
"""Construct ContextualCell_v1 class. :param op_names: list of operation indices :param config: list of config numbers :param inp: input channel :param repeats: nu... | stack_v2_sparse_classes_75kplus_train_067507 | 10,880 | permissive | [
{
"docstring": "Construct ContextualCell_v1 class. :param op_names: list of operation indices :param config: list of config numbers :param inp: input channel :param repeats: number of repeated times :param concat: concat the result if set to True, otherwise add the result",
"name": "__init__",
"signatur... | 2 | null | Implement the Python class `ContextualCell_v1` described below.
Class description:
New contextual cell design.
Method signatures and docstrings:
- def __init__(self, op_names, config, inp, repeats=1, concat=False): Construct ContextualCell_v1 class. :param op_names: list of operation indices :param config: list of co... | Implement the Python class `ContextualCell_v1` described below.
Class description:
New contextual cell design.
Method signatures and docstrings:
- def __init__(self, op_names, config, inp, repeats=1, concat=False): Construct ContextualCell_v1 class. :param op_names: list of operation indices :param config: list of co... | e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04 | <|skeleton|>
class ContextualCell_v1:
"""New contextual cell design."""
def __init__(self, op_names, config, inp, repeats=1, concat=False):
"""Construct ContextualCell_v1 class. :param op_names: list of operation indices :param config: list of config numbers :param inp: input channel :param repeats: nu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ContextualCell_v1:
"""New contextual cell design."""
def __init__(self, op_names, config, inp, repeats=1, concat=False):
"""Construct ContextualCell_v1 class. :param op_names: list of operation indices :param config: list of config numbers :param inp: input channel :param repeats: number of repea... | the_stack_v2_python_sparse | zeus/modules/operators/cell.py | huawei-noah/xingtian | train | 308 |
5716b5f02e9f550df441f371313598e695e5933e | [
"if request.user.is_authenticated:\n buses = UserBusNumber.objects.filter(bus_number_user=request.user)\n buses = list(buses)\n buses_list = [{'bus_number': bus.bus_number, 'start_point': bus.start_point, 'end_point': bus.end_point} for bus in buses]\n json_file = {'user_bus_list': buses_list, 'res': 1}... | <|body_start_0|>
if request.user.is_authenticated:
buses = UserBusNumber.objects.filter(bus_number_user=request.user)
buses = list(buses)
buses_list = [{'bus_number': bus.bus_number, 'start_point': bus.start_point, 'end_point': bus.end_point} for bus in buses]
jso... | store the favorite bus numbers of user | FavoriteBusNumberView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FavoriteBusNumberView:
"""store the favorite bus numbers of user"""
def get(self, request):
"""return the user's favortie bus list"""
<|body_0|>
def post(self, request):
"""add new bus information"""
<|body_1|>
def delete(self, request):
"""r... | stack_v2_sparse_classes_75kplus_train_067508 | 28,206 | no_license | [
{
"docstring": "return the user's favortie bus list",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "add new bus information",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "remove the bus number from the favorite list",
"na... | 3 | stack_v2_sparse_classes_30k_val_000078 | Implement the Python class `FavoriteBusNumberView` described below.
Class description:
store the favorite bus numbers of user
Method signatures and docstrings:
- def get(self, request): return the user's favortie bus list
- def post(self, request): add new bus information
- def delete(self, request): remove the bus n... | Implement the Python class `FavoriteBusNumberView` described below.
Class description:
store the favorite bus numbers of user
Method signatures and docstrings:
- def get(self, request): return the user's favortie bus list
- def post(self, request): add new bus information
- def delete(self, request): remove the bus n... | 5efeebedd4695ef9d904beb707a1538ba049b187 | <|skeleton|>
class FavoriteBusNumberView:
"""store the favorite bus numbers of user"""
def get(self, request):
"""return the user's favortie bus list"""
<|body_0|>
def post(self, request):
"""add new bus information"""
<|body_1|>
def delete(self, request):
"""r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FavoriteBusNumberView:
"""store the favorite bus numbers of user"""
def get(self, request):
"""return the user's favortie bus list"""
if request.user.is_authenticated:
buses = UserBusNumber.objects.filter(bus_number_user=request.user)
buses = list(buses)
... | the_stack_v2_python_sparse | dbbus/apps/user/views.py | mofiebiger/DublinBus | train | 1 |
2ea96482745dcc4cfd6c3417777055c6044370f7 | [
"self.host = host\nself.port = port\nself.verbose = verbose\nself.opts = opts\nself.flags = flags\nself.connect()",
"context = zmq.Context()\npuller = context.socket(zmq.PULL)\nfor opt in self.opts:\n puller.setsockopt(opt, 1)\nprint('Puller: tcp://{0}:{1}'.format(self.host, self.port))\npuller.bind('tcp://{0}... | <|body_start_0|>
self.host = host
self.port = port
self.verbose = verbose
self.opts = opts
self.flags = flags
self.connect()
<|end_body_0|>
<|body_start_1|>
context = zmq.Context()
puller = context.socket(zmq.PULL)
for opt in self.opts:
... | ZMQPullBind | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZMQPullBind:
def __init__(self, host, port, opts=[], flags=0, verbose=False):
"""create a Default ZMQ Pull socket"""
<|body_0|>
def connect(self):
"""open ZMQ pull socket return receiver object"""
<|body_1|>
def receive(self):
"""receive and retu... | stack_v2_sparse_classes_75kplus_train_067509 | 12,974 | no_license | [
{
"docstring": "create a Default ZMQ Pull socket",
"name": "__init__",
"signature": "def __init__(self, host, port, opts=[], flags=0, verbose=False)"
},
{
"docstring": "open ZMQ pull socket return receiver object",
"name": "connect",
"signature": "def connect(self)"
},
{
"docstri... | 4 | stack_v2_sparse_classes_30k_train_016926 | Implement the Python class `ZMQPullBind` described below.
Class description:
Implement the ZMQPullBind class.
Method signatures and docstrings:
- def __init__(self, host, port, opts=[], flags=0, verbose=False): create a Default ZMQ Pull socket
- def connect(self): open ZMQ pull socket return receiver object
- def rec... | Implement the Python class `ZMQPullBind` described below.
Class description:
Implement the ZMQPullBind class.
Method signatures and docstrings:
- def __init__(self, host, port, opts=[], flags=0, verbose=False): create a Default ZMQ Pull socket
- def connect(self): open ZMQ pull socket return receiver object
- def rec... | 55041e6947b888242ff01cb18bd5f1ee4c4c8f28 | <|skeleton|>
class ZMQPullBind:
def __init__(self, host, port, opts=[], flags=0, verbose=False):
"""create a Default ZMQ Pull socket"""
<|body_0|>
def connect(self):
"""open ZMQ pull socket return receiver object"""
<|body_1|>
def receive(self):
"""receive and retu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ZMQPullBind:
def __init__(self, host, port, opts=[], flags=0, verbose=False):
"""create a Default ZMQ Pull socket"""
self.host = host
self.port = port
self.verbose = verbose
self.opts = opts
self.flags = flags
self.connect()
def connect(self):
... | the_stack_v2_python_sparse | NPC/gui/ZmqSockets.py | coquellen/NanoPeakCell | train | 6 | |
7d0ae7d93e5380e1380bc54c0889f08eacc8c1a0 | [
"super(DuelingHead, self).__init__()\nself.A = [fc_block(hidden_dim, hidden_dim, activation=activation, norm_type=norm_type) for _ in range(a_layer_num)]\nself.V = [fc_block(hidden_dim, hidden_dim, activation=activation, norm_type=norm_type) for _ in range(v_layer_num)]\nself.A += fc_block(hidden_dim, action_dim, a... | <|body_start_0|>
super(DuelingHead, self).__init__()
self.A = [fc_block(hidden_dim, hidden_dim, activation=activation, norm_type=norm_type) for _ in range(a_layer_num)]
self.V = [fc_block(hidden_dim, hidden_dim, activation=activation, norm_type=norm_type) for _ in range(v_layer_num)]
sel... | Overview: The Dueling head used in models. Notes: Dueling head is one of the three most major improvements in DQN algorithm. The paper introducing \\ this improvement `Dueling Network Architectures for Deep Reinforcement Learning` was published \\ by Google in 2016. You can view the original paper on <https://arxiv.org... | DuelingHead | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DuelingHead:
"""Overview: The Dueling head used in models. Notes: Dueling head is one of the three most major improvements in DQN algorithm. The paper introducing \\ this improvement `Dueling Network Architectures for Deep Reinforcement Learning` was published \\ by Google in 2016. You can view t... | stack_v2_sparse_classes_75kplus_train_067510 | 2,805 | permissive | [
{
"docstring": "Overview: Init the DuelingHead according to arguments. Arguments: - hidden_dim (:obj:`int`): the hidden_dim used before connected to DuelingHead - action_dim (:obj:`int`): the num of actions - a_layer_num (:obj:`int`): the num of fc_block used in the network to compute action output - v_layer_nu... | 2 | stack_v2_sparse_classes_30k_train_014515 | Implement the Python class `DuelingHead` described below.
Class description:
Overview: The Dueling head used in models. Notes: Dueling head is one of the three most major improvements in DQN algorithm. The paper introducing \\ this improvement `Dueling Network Architectures for Deep Reinforcement Learning` was publish... | Implement the Python class `DuelingHead` described below.
Class description:
Overview: The Dueling head used in models. Notes: Dueling head is one of the three most major improvements in DQN algorithm. The paper introducing \\ this improvement `Dueling Network Architectures for Deep Reinforcement Learning` was publish... | 09d507c412235a2f0cf9c0b3485ec9ed15fb6421 | <|skeleton|>
class DuelingHead:
"""Overview: The Dueling head used in models. Notes: Dueling head is one of the three most major improvements in DQN algorithm. The paper introducing \\ this improvement `Dueling Network Architectures for Deep Reinforcement Learning` was published \\ by Google in 2016. You can view t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DuelingHead:
"""Overview: The Dueling head used in models. Notes: Dueling head is one of the three most major improvements in DQN algorithm. The paper introducing \\ this improvement `Dueling Network Architectures for Deep Reinforcement Learning` was published \\ by Google in 2016. You can view the original p... | the_stack_v2_python_sparse | ctools/model/common_arch/dueling.py | LFhase/DI-star | train | 1 |
3061909c4c74cab050b2e0b677ff81c80f6008a7 | [
"if not stream:\n return ()\nif os.path.isfile(stream):\n return yaml.load(codecs.open(stream, 'rb', encoding=coding))\nelse:\n return yaml.load(stream)",
"if not stream:\n return ()\nif os.path.isfile(stream):\n return yaml.load_all(codecs.open(stream, 'rb', encoding=coding))\nelse:\n return ya... | <|body_start_0|>
if not stream:
return ()
if os.path.isfile(stream):
return yaml.load(codecs.open(stream, 'rb', encoding=coding))
else:
return yaml.load(stream)
<|end_body_0|>
<|body_start_1|>
if not stream:
return ()
if os.path.is... | Yaml | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Yaml:
def load(self, stream, coding='utf-8'):
"""Load one section Parameter: steam --> a yaml file or yaml string coding --> yaml file's coding Usage: stream = u''' - {case_id: 1001, element_info: id/login_account_input, find_type: id, operate_type: type, test_intr: 用户名, text: admin} - {... | stack_v2_sparse_classes_75kplus_train_067511 | 4,040 | permissive | [
{
"docstring": "Load one section Parameter: steam --> a yaml file or yaml string coding --> yaml file's coding Usage: stream = u''' - {case_id: 1001, element_info: id/login_account_input, find_type: id, operate_type: type, test_intr: 用户名, text: admin} - {case_id: 1002, element_info: id/login_password_input, fin... | 4 | null | Implement the Python class `Yaml` described below.
Class description:
Implement the Yaml class.
Method signatures and docstrings:
- def load(self, stream, coding='utf-8'): Load one section Parameter: steam --> a yaml file or yaml string coding --> yaml file's coding Usage: stream = u''' - {case_id: 1001, element_info... | Implement the Python class `Yaml` described below.
Class description:
Implement the Yaml class.
Method signatures and docstrings:
- def load(self, stream, coding='utf-8'): Load one section Parameter: steam --> a yaml file or yaml string coding --> yaml file's coding Usage: stream = u''' - {case_id: 1001, element_info... | 1fad443ddcd42e56d632084517e56139ed788b54 | <|skeleton|>
class Yaml:
def load(self, stream, coding='utf-8'):
"""Load one section Parameter: steam --> a yaml file or yaml string coding --> yaml file's coding Usage: stream = u''' - {case_id: 1001, element_info: id/login_account_input, find_type: id, operate_type: type, test_intr: 用户名, text: admin} - {... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Yaml:
def load(self, stream, coding='utf-8'):
"""Load one section Parameter: steam --> a yaml file or yaml string coding --> yaml file's coding Usage: stream = u''' - {case_id: 1001, element_info: id/login_account_input, find_type: id, operate_type: type, test_intr: 用户名, text: admin} - {case_id: 1002,... | the_stack_v2_python_sparse | rock4/common/ext/datafile/yamlparser.py | RockFeng0/rock4automation | train | 5 | |
55fd842a2d81e946e73428538f8ff2bfeb5b511b | [
"for output in self.outputs:\n if output.type in {'stdout', 'stderr'}:\n stream = getattr(self, output.type)\n if stream == path:\n return output.id\n elif output.type == 'File':\n glob = output.outputBinding.glob\n if glob.startswith('$(inputs.'):\n input_id ... | <|body_start_0|>
for output in self.outputs:
if output.type in {'stdout', 'stderr'}:
stream = getattr(self, output.type)
if stream == path:
return output.id
elif output.type == 'File':
glob = output.outputBinding.glob
... | Represent a command line tool. | CommandLineTool | [
"Apache-2.0",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommandLineTool:
"""Represent a command line tool."""
def get_output_id(self, path):
"""Return an id of the matching path from default values."""
<|body_0|>
def to_argv(self, job=None):
"""Generate arguments for system call."""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus_train_067512 | 15,381 | permissive | [
{
"docstring": "Return an id of the matching path from default values.",
"name": "get_output_id",
"signature": "def get_output_id(self, path)"
},
{
"docstring": "Generate arguments for system call.",
"name": "to_argv",
"signature": "def to_argv(self, job=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_051262 | Implement the Python class `CommandLineTool` described below.
Class description:
Represent a command line tool.
Method signatures and docstrings:
- def get_output_id(self, path): Return an id of the matching path from default values.
- def to_argv(self, job=None): Generate arguments for system call. | Implement the Python class `CommandLineTool` described below.
Class description:
Represent a command line tool.
Method signatures and docstrings:
- def get_output_id(self, path): Return an id of the matching path from default values.
- def to_argv(self, job=None): Generate arguments for system call.
<|skeleton|>
cla... | 36ae4282f2da3eaf444674784b82a5d8a1e0e59c | <|skeleton|>
class CommandLineTool:
"""Represent a command line tool."""
def get_output_id(self, path):
"""Return an id of the matching path from default values."""
<|body_0|>
def to_argv(self, job=None):
"""Generate arguments for system call."""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CommandLineTool:
"""Represent a command line tool."""
def get_output_id(self, path):
"""Return an id of the matching path from default values."""
for output in self.outputs:
if output.type in {'stdout', 'stderr'}:
stream = getattr(self, output.type)
... | the_stack_v2_python_sparse | renku/models/cwl/command_line_tool.py | leafty/renku-python | train | 0 |
54665fbcdba82834b7b18d0f2e6ee9e7fb7efb87 | [
"result = ''\nfor key in ('event', 'id', 'timestamp', 'data'):\n value = obj.get(key, None)\n if not value:\n continue\n if key == 'data':\n value = json.dumps(value, separators=(',', ':'))\n result += f'{key}: {value}\\n'\nresult += '\\n'\nreturn result",
"obj = {}\nfor line in s.split(... | <|body_start_0|>
result = ''
for key in ('event', 'id', 'timestamp', 'data'):
value = obj.get(key, None)
if not value:
continue
if key == 'data':
value = json.dumps(value, separators=(',', ':'))
result += f'{key}: {value}\n'... | A helper class for serializing and deserializing objects to server side events message format. The server side event message is UTF-8 text data separated by a pair of newline characters. | _SSERenderer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _SSERenderer:
"""A helper class for serializing and deserializing objects to server side events message format. The server side event message is UTF-8 text data separated by a pair of newline characters."""
def dumps(obj: Dict[str, Any], *_args, **_kwargs) -> str:
"""Encodes input ob... | stack_v2_sparse_classes_75kplus_train_067513 | 27,773 | permissive | [
{
"docstring": "Encodes input object into text string. Args: obj: Object to be serialized. Returns: Text string in format: {key}: {value}\\\\n ... \\\\n",
"name": "dumps",
"signature": "def dumps(obj: Dict[str, Any], *_args, **_kwargs) -> str"
},
{
"docstring": "Decodes input text string into di... | 2 | null | Implement the Python class `_SSERenderer` described below.
Class description:
A helper class for serializing and deserializing objects to server side events message format. The server side event message is UTF-8 text data separated by a pair of newline characters.
Method signatures and docstrings:
- def dumps(obj: Di... | Implement the Python class `_SSERenderer` described below.
Class description:
A helper class for serializing and deserializing objects to server side events message format. The server side event message is UTF-8 text data separated by a pair of newline characters.
Method signatures and docstrings:
- def dumps(obj: Di... | c784c321b801cfa74a25d92d41f31c1ae3e0ac3e | <|skeleton|>
class _SSERenderer:
"""A helper class for serializing and deserializing objects to server side events message format. The server side event message is UTF-8 text data separated by a pair of newline characters."""
def dumps(obj: Dict[str, Any], *_args, **_kwargs) -> str:
"""Encodes input ob... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _SSERenderer:
"""A helper class for serializing and deserializing objects to server side events message format. The server side event message is UTF-8 text data separated by a pair of newline characters."""
def dumps(obj: Dict[str, Any], *_args, **_kwargs) -> str:
"""Encodes input object into tex... | the_stack_v2_python_sparse | floq/client/schemas.py | 00mjk/floq-client | train | 0 |
47bc50a52113c89c0d57476926e0ef4ab57772e9 | [
"super(Net, self).__init__()\nself.in_channel = 16\nself.field_conv = FieldConv(edge_length=0.03, filter_sample_number=64, center_number=16 ** 3, in_channels=1, out_channels=self.in_channel, feature_is_sdf=True)\nself.num_class = options.model.out_channel\nself.sa1 = PointNetSetAbstraction(npoint=512, radius=0.2, n... | <|body_start_0|>
super(Net, self).__init__()
self.in_channel = 16
self.field_conv = FieldConv(edge_length=0.03, filter_sample_number=64, center_number=16 ** 3, in_channels=1, out_channels=self.in_channel, feature_is_sdf=True)
self.num_class = options.model.out_channel
self.sa1 = ... | The PointNet++ classification model. | Net | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Net:
"""The PointNet++ classification model."""
def __init__(self, options: EasyDict):
"""The initialization function. Args: options: The options to define the model."""
<|body_0|>
def forward(self, batch: dict) -> dict:
"""The forward function. Args: batch: The ... | stack_v2_sparse_classes_75kplus_train_067514 | 8,021 | permissive | [
{
"docstring": "The initialization function. Args: options: The options to define the model.",
"name": "__init__",
"signature": "def __init__(self, options: EasyDict)"
},
{
"docstring": "The forward function. Args: batch: The input batch. \"xyz_sdf\": The input point cloud concatenated with sign... | 2 | null | Implement the Python class `Net` described below.
Class description:
The PointNet++ classification model.
Method signatures and docstrings:
- def __init__(self, options: EasyDict): The initialization function. Args: options: The options to define the model.
- def forward(self, batch: dict) -> dict: The forward functi... | Implement the Python class `Net` described below.
Class description:
The PointNet++ classification model.
Method signatures and docstrings:
- def __init__(self, options: EasyDict): The initialization function. Args: options: The options to define the model.
- def forward(self, batch: dict) -> dict: The forward functi... | ca88df568a6f2143dcb85d22c005fce4562a7523 | <|skeleton|>
class Net:
"""The PointNet++ classification model."""
def __init__(self, options: EasyDict):
"""The initialization function. Args: options: The options to define the model."""
<|body_0|>
def forward(self, batch: dict) -> dict:
"""The forward function. Args: batch: The ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Net:
"""The PointNet++ classification model."""
def __init__(self, options: EasyDict):
"""The initialization function. Args: options: The options to define the model."""
super(Net, self).__init__()
self.in_channel = 16
self.field_conv = FieldConv(edge_length=0.03, filter_s... | the_stack_v2_python_sparse | SDFConv/code/models/pointnet2_field_conv_sparse.py | zshyang/FieldConvolution | train | 1 |
f3c256d047465e7604f3a03fac3c020a85360d74 | [
"self.socket_type = zmq.PUSH\nself.bind_host = 'tcp://{0}:{1}'.format(*bind_host_tuple)\nself.context = None\nself.socket = None\nself.bound = False",
"self.context = zmq.Context()\nself.socket = self.context.socket(self.socket_type)\nself.socket.bind(self.bind_host)\nself.bound = True",
"if not self.bound:\n ... | <|body_start_0|>
self.socket_type = zmq.PUSH
self.bind_host = 'tcp://{0}:{1}'.format(*bind_host_tuple)
self.context = None
self.socket = None
self.bound = False
<|end_body_0|>
<|body_start_1|>
self.context = zmq.Context()
self.socket = self.context.socket(self.so... | ZeroMQCaster allows for messages to be sent downstream by pushing messages over a zmq socket to downstream clients. If multiple clients connect to this PUSH socket the messages will be load balanced evenly across the clients. | ZeroMQCaster | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZeroMQCaster:
"""ZeroMQCaster allows for messages to be sent downstream by pushing messages over a zmq socket to downstream clients. If multiple clients connect to this PUSH socket the messages will be load balanced evenly across the clients."""
def __init__(self, bind_host_tuple):
"... | stack_v2_sparse_classes_75kplus_train_067515 | 6,508 | permissive | [
{
"docstring": "Creates an instance of the ZeroMQCaster. A zmq PUSH socket is created and is bound to the specified host:port. :param bind_host_tuple: (host, port), for example ('127.0.0.1', '5000')",
"name": "__init__",
"signature": "def __init__(self, bind_host_tuple)"
},
{
"docstring": "Bind ... | 4 | stack_v2_sparse_classes_30k_train_022521 | Implement the Python class `ZeroMQCaster` described below.
Class description:
ZeroMQCaster allows for messages to be sent downstream by pushing messages over a zmq socket to downstream clients. If multiple clients connect to this PUSH socket the messages will be load balanced evenly across the clients.
Method signatu... | Implement the Python class `ZeroMQCaster` described below.
Class description:
ZeroMQCaster allows for messages to be sent downstream by pushing messages over a zmq socket to downstream clients. If multiple clients connect to this PUSH socket the messages will be load balanced evenly across the clients.
Method signatu... | 1df9efe33ead702d0f53dfc227b5da385ba9cf23 | <|skeleton|>
class ZeroMQCaster:
"""ZeroMQCaster allows for messages to be sent downstream by pushing messages over a zmq socket to downstream clients. If multiple clients connect to this PUSH socket the messages will be load balanced evenly across the clients."""
def __init__(self, bind_host_tuple):
"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ZeroMQCaster:
"""ZeroMQCaster allows for messages to be sent downstream by pushing messages over a zmq socket to downstream clients. If multiple clients connect to this PUSH socket the messages will be load balanced evenly across the clients."""
def __init__(self, bind_host_tuple):
"""Creates an ... | the_stack_v2_python_sparse | meniscus/transport.py | priestd09/meniscus | train | 0 |
45b535e9651401875563e04fd2f08e4e2247175d | [
"self.logger = Log()\nself.logger.info('########################### TestWalletOpen START ###########################')\nconfig = ReadYaml(FileUtil.getProjectObsPath() + '/config/config.yaml').getValue()\napp_package = config['appPackage_chezhu']\napp_activity = config['appActivity_chezhu']\nself.db = DbOperation()\... | <|body_start_0|>
self.logger = Log()
self.logger.info('########################### TestWalletOpen START ###########################')
config = ReadYaml(FileUtil.getProjectObsPath() + '/config/config.yaml').getValue()
app_package = config['appPackage_chezhu']
app_activity = config... | 凯京车主APP 开通钱包 | TestWalletOpen | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestWalletOpen:
"""凯京车主APP 开通钱包"""
def setUp(self):
"""前置条件准备"""
<|body_0|>
def tearDown(self):
"""测试环境重置"""
<|body_1|>
def test_bvt_wallet_open(self):
"""开通司机钱包"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
self.logger = ... | stack_v2_sparse_classes_75kplus_train_067516 | 2,299 | no_license | [
{
"docstring": "前置条件准备",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "测试环境重置",
"name": "tearDown",
"signature": "def tearDown(self)"
},
{
"docstring": "开通司机钱包",
"name": "test_bvt_wallet_open",
"signature": "def test_bvt_wallet_open(self)"
}
] | 3 | stack_v2_sparse_classes_30k_train_001447 | Implement the Python class `TestWalletOpen` described below.
Class description:
凯京车主APP 开通钱包
Method signatures and docstrings:
- def setUp(self): 前置条件准备
- def tearDown(self): 测试环境重置
- def test_bvt_wallet_open(self): 开通司机钱包 | Implement the Python class `TestWalletOpen` described below.
Class description:
凯京车主APP 开通钱包
Method signatures and docstrings:
- def setUp(self): 前置条件准备
- def tearDown(self): 测试环境重置
- def test_bvt_wallet_open(self): 开通司机钱包
<|skeleton|>
class TestWalletOpen:
"""凯京车主APP 开通钱包"""
def setUp(self):
"""前置条... | 4112ee34827a68289ba95a30518c4b1ecf38a3b2 | <|skeleton|>
class TestWalletOpen:
"""凯京车主APP 开通钱包"""
def setUp(self):
"""前置条件准备"""
<|body_0|>
def tearDown(self):
"""测试环境重置"""
<|body_1|>
def test_bvt_wallet_open(self):
"""开通司机钱包"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestWalletOpen:
"""凯京车主APP 开通钱包"""
def setUp(self):
"""前置条件准备"""
self.logger = Log()
self.logger.info('########################### TestWalletOpen START ###########################')
config = ReadYaml(FileUtil.getProjectObsPath() + '/config/config.yaml').getValue()
... | the_stack_v2_python_sparse | BVT/chezhuAPP/driver_unregister/test_case/test_wallet_open_chezhu.py | penny1205/AppUI | train | 0 |
3e6f8a18241237e3f1b51c73682ebc15375de653 | [
"Block.__init__(self, scenario, args)\nif self.language is None:\n raise LoadingException('Language must be defined!')",
"aroot = zone.atree\nsent = ' '.join([a.form for a in aroot.get_descendants(ordered=True) if a.form and (not re.match('^(#[A-Z]|[A-Z]{3}$)', a.form))])\nsent = re.sub(' ([“,.?:;])', '\\\\1',... | <|body_start_0|>
Block.__init__(self, scenario, args)
if self.language is None:
raise LoadingException('Language must be defined!')
<|end_body_0|>
<|body_start_1|>
aroot = zone.atree
sent = ' '.join([a.form for a in aroot.get_descendants(ordered=True) if a.form and (not re.m... | Detokenize the sentence, spread whitespace correctly. | ConcatenateTokens | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConcatenateTokens:
"""Detokenize the sentence, spread whitespace correctly."""
def __init__(self, scenario, args):
"""Constructor, checking the argument values"""
<|body_0|>
def process_zone(self, zone):
"""Detokenize the sentence and assign the result to the sen... | stack_v2_sparse_classes_75kplus_train_067517 | 1,588 | permissive | [
{
"docstring": "Constructor, checking the argument values",
"name": "__init__",
"signature": "def __init__(self, scenario, args)"
},
{
"docstring": "Detokenize the sentence and assign the result to the sentence attribute of the current zone.",
"name": "process_zone",
"signature": "def pr... | 2 | stack_v2_sparse_classes_30k_train_048319 | Implement the Python class `ConcatenateTokens` described below.
Class description:
Detokenize the sentence, spread whitespace correctly.
Method signatures and docstrings:
- def __init__(self, scenario, args): Constructor, checking the argument values
- def process_zone(self, zone): Detokenize the sentence and assign ... | Implement the Python class `ConcatenateTokens` described below.
Class description:
Detokenize the sentence, spread whitespace correctly.
Method signatures and docstrings:
- def __init__(self, scenario, args): Constructor, checking the argument values
- def process_zone(self, zone): Detokenize the sentence and assign ... | 73af644ec35c8a1cd0c37cd478c2afc1db717e0b | <|skeleton|>
class ConcatenateTokens:
"""Detokenize the sentence, spread whitespace correctly."""
def __init__(self, scenario, args):
"""Constructor, checking the argument values"""
<|body_0|>
def process_zone(self, zone):
"""Detokenize the sentence and assign the result to the sen... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConcatenateTokens:
"""Detokenize the sentence, spread whitespace correctly."""
def __init__(self, scenario, args):
"""Constructor, checking the argument values"""
Block.__init__(self, scenario, args)
if self.language is None:
raise LoadingException('Language must be de... | the_stack_v2_python_sparse | alex/components/nlg/tectotpl/block/a2w/cs/concatenatetokens.py | oplatek/alex | train | 0 |
01cda23f1541d885ff24899f2d840e19b88284b3 | [
"result = []\nfor i in range(0, len(nums) + 1):\n result += self.combinationSolo(nums, i)\nreturn result",
"nums = sorted(nums)\nif k == 0:\n return [[]]\nelif k == len(nums):\n return [nums]\nelif k == 1:\n result = []\n for i in nums:\n if [i] not in result:\n result.append([i])... | <|body_start_0|>
result = []
for i in range(0, len(nums) + 1):
result += self.combinationSolo(nums, i)
return result
<|end_body_0|>
<|body_start_1|>
nums = sorted(nums)
if k == 0:
return [[]]
elif k == len(nums):
return [nums]
... | Solution_A | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution_A:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
"""With the help from the combinationSolo from Leetcode LC077 use tuple and set to remove repeat and convert back to list"""
<|body_0|>
def combinationSolo(self, nums: List[int], k: int) -> List[List[i... | stack_v2_sparse_classes_75kplus_train_067518 | 4,175 | permissive | [
{
"docstring": "With the help from the combinationSolo from Leetcode LC077 use tuple and set to remove repeat and convert back to list",
"name": "subsetsWithDup",
"signature": "def subsetsWithDup(self, nums: List[int]) -> List[List[int]]"
},
{
"docstring": "Helper for A1, refer to LC077, modify ... | 2 | stack_v2_sparse_classes_30k_train_007530 | Implement the Python class `Solution_A` described below.
Class description:
Implement the Solution_A class.
Method signatures and docstrings:
- def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: With the help from the combinationSolo from Leetcode LC077 use tuple and set to remove repeat and convert back t... | Implement the Python class `Solution_A` described below.
Class description:
Implement the Solution_A class.
Method signatures and docstrings:
- def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: With the help from the combinationSolo from Leetcode LC077 use tuple and set to remove repeat and convert back t... | 143422321cbc3715ca08f6c3af8f960a55887ced | <|skeleton|>
class Solution_A:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
"""With the help from the combinationSolo from Leetcode LC077 use tuple and set to remove repeat and convert back to list"""
<|body_0|>
def combinationSolo(self, nums: List[int], k: int) -> List[List[i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution_A:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
"""With the help from the combinationSolo from Leetcode LC077 use tuple and set to remove repeat and convert back to list"""
result = []
for i in range(0, len(nums) + 1):
result += self.combinationSol... | the_stack_v2_python_sparse | LeetCode/LC090_subsets_ii.py | jxie0755/Learning_Python | train | 0 | |
7f426579407da607b82c55f4364af81a247877bc | [
"self.num = num\nself.color = color\nself.especial = especial\nself.tipo = self.tipo()",
"if self.tipo == 'Comodin' or self.tipo == 'Propia':\n if self.color:\n return \"'{}, {}'\".format(self.especial, self.color)\n return \"'{}'\".format(self.especial)\nelif self.tipo == 'Especial':\n return \"'... | <|body_start_0|>
self.num = num
self.color = color
self.especial = especial
self.tipo = self.tipo()
<|end_body_0|>
<|body_start_1|>
if self.tipo == 'Comodin' or self.tipo == 'Propia':
if self.color:
return "'{}, {}'".format(self.especial, self.color)
... | Modelo de representación de una carta | Carta | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Carta:
"""Modelo de representación de una carta"""
def __init__(self, num, color, especial):
"""Crea una carta; num tiene que ser un valor numérico y, junto color y especial strings."""
<|body_0|>
def __repr__(self):
"""Representación formal de una cadena de text... | stack_v2_sparse_classes_75kplus_train_067519 | 1,787 | permissive | [
{
"docstring": "Crea una carta; num tiene que ser un valor numérico y, junto color y especial strings.",
"name": "__init__",
"signature": "def __init__(self, num, color, especial)"
},
{
"docstring": "Representación formal de una cadena de texto.",
"name": "__repr__",
"signature": "def __... | 4 | stack_v2_sparse_classes_30k_test_001787 | Implement the Python class `Carta` described below.
Class description:
Modelo de representación de una carta
Method signatures and docstrings:
- def __init__(self, num, color, especial): Crea una carta; num tiene que ser un valor numérico y, junto color y especial strings.
- def __repr__(self): Representación formal ... | Implement the Python class `Carta` described below.
Class description:
Modelo de representación de una carta
Method signatures and docstrings:
- def __init__(self, num, color, especial): Crea una carta; num tiene que ser un valor numérico y, junto color y especial strings.
- def __repr__(self): Representación formal ... | 8900604873195df9e902ead6bcb67723a8b654c8 | <|skeleton|>
class Carta:
"""Modelo de representación de una carta"""
def __init__(self, num, color, especial):
"""Crea una carta; num tiene que ser un valor numérico y, junto color y especial strings."""
<|body_0|>
def __repr__(self):
"""Representación formal de una cadena de text... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Carta:
"""Modelo de representación de una carta"""
def __init__(self, num, color, especial):
"""Crea una carta; num tiene que ser un valor numérico y, junto color y especial strings."""
self.num = num
self.color = color
self.especial = especial
self.tipo = self.tip... | the_stack_v2_python_sparse | TPs/TP3/Trabajo Practico 3/Carta.py | FdelMazo/7540rw-Algo1 | train | 1 |
a0ca8a4f4d1f0ecbd62fdaa3635f7b7135b48449 | [
"email_claim = Config.get_OIDC_email_claim()\nself._assert_required_token_parameters([email_claim])\nreturn self.token[email_claim]",
"from ..security import assert_authorized_email\nassert_authorized_email(emails, self.token)\nreturn"
] | <|body_start_0|>
email_claim = Config.get_OIDC_email_claim()
self._assert_required_token_parameters([email_claim])
return self.token[email_claim]
<|end_body_0|>
<|body_start_1|>
from ..security import assert_authorized_email
assert_authorized_email(emails, self.token)
re... | Mixin: add a token_email attribute, based on email token claim set in DSS config. Includes verification methods. | TokenEmailMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TokenEmailMixin:
"""Mixin: add a token_email attribute, based on email token claim set in DSS config. Includes verification methods."""
def token_email(self):
"""Property for the user's JWT email claim"""
<|body_0|>
def _assert_authorized_email(self, emails):
"""... | stack_v2_sparse_classes_75kplus_train_067520 | 4,756 | permissive | [
{
"docstring": "Property for the user's JWT email claim",
"name": "token_email",
"signature": "def token_email(self)"
},
{
"docstring": "Verify user JWT token email matches specified emails",
"name": "_assert_authorized_email",
"signature": "def _assert_authorized_email(self, emails)"
... | 2 | stack_v2_sparse_classes_30k_train_009172 | Implement the Python class `TokenEmailMixin` described below.
Class description:
Mixin: add a token_email attribute, based on email token claim set in DSS config. Includes verification methods.
Method signatures and docstrings:
- def token_email(self): Property for the user's JWT email claim
- def _assert_authorized_... | Implement the Python class `TokenEmailMixin` described below.
Class description:
Mixin: add a token_email attribute, based on email token claim set in DSS config. Includes verification methods.
Method signatures and docstrings:
- def token_email(self): Property for the user's JWT email claim
- def _assert_authorized_... | fa96624a09c7ac1595fcd6fbabd31e551382b757 | <|skeleton|>
class TokenEmailMixin:
"""Mixin: add a token_email attribute, based on email token claim set in DSS config. Includes verification methods."""
def token_email(self):
"""Property for the user's JWT email claim"""
<|body_0|>
def _assert_authorized_email(self, emails):
"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TokenEmailMixin:
"""Mixin: add a token_email attribute, based on email token claim set in DSS config. Includes verification methods."""
def token_email(self):
"""Property for the user's JWT email claim"""
email_claim = Config.get_OIDC_email_claim()
self._assert_required_token_para... | the_stack_v2_python_sparse | dss/util/auth/authorize.py | charlesreid1acom/data-store | train | 0 |
19a783a67decbe5521a90b06ffcf91226b3b88d2 | [
"if not cls._instance:\n cls._instance = RedisAppStatus()\nreturn cls._instance",
"options = _load_redis_options()\nout = ''\nerr = ''\ntry:\n if 'requirepass' in options:\n LOG.info(_('Password is set running ping with password'))\n out, err = utils.execute_with_timeout(system.REDIS_CLI, '-a'... | <|body_start_0|>
if not cls._instance:
cls._instance = RedisAppStatus()
return cls._instance
<|end_body_0|>
<|body_start_1|>
options = _load_redis_options()
out = ''
err = ''
try:
if 'requirepass' in options:
LOG.info(_('Password i... | Handles all of the status updating for the redis guest agent. | RedisAppStatus | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RedisAppStatus:
"""Handles all of the status updating for the redis guest agent."""
def get(cls):
"""Gets an instance of the RedisAppStatus class."""
<|body_0|>
def _get_actual_db_status(self):
"""Gets the actual status of the Redis instance First it attempts to ... | stack_v2_sparse_classes_75kplus_train_067521 | 10,076 | permissive | [
{
"docstring": "Gets an instance of the RedisAppStatus class.",
"name": "get",
"signature": "def get(cls)"
},
{
"docstring": "Gets the actual status of the Redis instance First it attempts to make a connection to the redis instance by making a PING request. If PING does not return PONG we do a p... | 2 | stack_v2_sparse_classes_30k_train_038155 | Implement the Python class `RedisAppStatus` described below.
Class description:
Handles all of the status updating for the redis guest agent.
Method signatures and docstrings:
- def get(cls): Gets an instance of the RedisAppStatus class.
- def _get_actual_db_status(self): Gets the actual status of the Redis instance ... | Implement the Python class `RedisAppStatus` described below.
Class description:
Handles all of the status updating for the redis guest agent.
Method signatures and docstrings:
- def get(cls): Gets an instance of the RedisAppStatus class.
- def _get_actual_db_status(self): Gets the actual status of the Redis instance ... | 8f200b73719b36a7ab2f8d651e46a8b6b55c9a77 | <|skeleton|>
class RedisAppStatus:
"""Handles all of the status updating for the redis guest agent."""
def get(cls):
"""Gets an instance of the RedisAppStatus class."""
<|body_0|>
def _get_actual_db_status(self):
"""Gets the actual status of the Redis instance First it attempts to ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RedisAppStatus:
"""Handles all of the status updating for the redis guest agent."""
def get(cls):
"""Gets an instance of the RedisAppStatus class."""
if not cls._instance:
cls._instance = RedisAppStatus()
return cls._instance
def _get_actual_db_status(self):
... | the_stack_v2_python_sparse | trove/guestagent/datastore/redis/service.py | NeCTAR-RC/trove | train | 1 |
e5f6ec6c126de1d00c12403813602f347ae208a2 | [
"if not num or len(num) <= 2:\n return False\nfor i in range(0, len(num) // 2 + 1):\n a = self.str2num(num, 0, i + 1)\n if a == -1:\n continue\n for j in range(i + 1, (len(num) - i - 1) // 2 + 1 + i):\n b = self.str2num(num, i + 1, j + 1)\n if self.dfs(num, j + 1, a, b, i + 1, j - i... | <|body_start_0|>
if not num or len(num) <= 2:
return False
for i in range(0, len(num) // 2 + 1):
a = self.str2num(num, 0, i + 1)
if a == -1:
continue
for j in range(i + 1, (len(num) - i - 1) // 2 + 1 + i):
b = self.str2num(n... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isAdditiveNumber(self, num):
""":type num: str :rtype: bool"""
<|body_0|>
def dfs(self, s, index, a, b, aBitCount, bBitCount):
"""对字符串从索引开始的部分判断 :param s:str,判断的字符串 :param index:int,新的字符串开始的索引 :param a:int,第一个加数 :param b:int,第二个加数 :param aBitCount:int,a... | stack_v2_sparse_classes_75kplus_train_067522 | 3,636 | no_license | [
{
"docstring": ":type num: str :rtype: bool",
"name": "isAdditiveNumber",
"signature": "def isAdditiveNumber(self, num)"
},
{
"docstring": "对字符串从索引开始的部分判断 :param s:str,判断的字符串 :param index:int,新的字符串开始的索引 :param a:int,第一个加数 :param b:int,第二个加数 :param aBitCount:int,a的位数 :param bBitCount:int,b的位数 :re... | 3 | stack_v2_sparse_classes_30k_train_030544 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isAdditiveNumber(self, num): :type num: str :rtype: bool
- def dfs(self, s, index, a, b, aBitCount, bBitCount): 对字符串从索引开始的部分判断 :param s:str,判断的字符串 :param index:int,新的字符串开始的索引... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isAdditiveNumber(self, num): :type num: str :rtype: bool
- def dfs(self, s, index, a, b, aBitCount, bBitCount): 对字符串从索引开始的部分判断 :param s:str,判断的字符串 :param index:int,新的字符串开始的索引... | 807ba32ed7802b756e93dfe44264dac5bb9317a0 | <|skeleton|>
class Solution:
def isAdditiveNumber(self, num):
""":type num: str :rtype: bool"""
<|body_0|>
def dfs(self, s, index, a, b, aBitCount, bBitCount):
"""对字符串从索引开始的部分判断 :param s:str,判断的字符串 :param index:int,新的字符串开始的索引 :param a:int,第一个加数 :param b:int,第二个加数 :param aBitCount:int,a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isAdditiveNumber(self, num):
""":type num: str :rtype: bool"""
if not num or len(num) <= 2:
return False
for i in range(0, len(num) // 2 + 1):
a = self.str2num(num, 0, i + 1)
if a == -1:
continue
for j in ran... | the_stack_v2_python_sparse | num301_400/num301_310/num306.py | guozhaoxin/leetcode | train | 0 | |
86703bf05c75ca8cba2a6f44db20958236fd794f | [
"try:\n type = request.args.get('type', type=int)\n page = request.args.get('page', 1, type=int)\n page_num = request.args.get('page_num', 6, type=int)\nexcept:\n return {'code': RET.PARAMERR, 'msg': error_map[RET.PARAMERR]}\nif type == 1:\n history = db.session.query(ChatFriend, User).outerjoin(User... | <|body_start_0|>
try:
type = request.args.get('type', type=int)
page = request.args.get('page', 1, type=int)
page_num = request.args.get('page_num', 6, type=int)
except:
return {'code': RET.PARAMERR, 'msg': error_map[RET.PARAMERR]}
if type == 1:
... | FriendCheckView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FriendCheckView:
def get(self):
"""获取好友审核列表"""
<|body_0|>
def post(self):
"""好友审核"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
type = request.args.get('type', type=int)
page = request.args.get('page', 1, type=int)
... | stack_v2_sparse_classes_75kplus_train_067523 | 10,925 | no_license | [
{
"docstring": "获取好友审核列表",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "好友审核",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_026986 | Implement the Python class `FriendCheckView` described below.
Class description:
Implement the FriendCheckView class.
Method signatures and docstrings:
- def get(self): 获取好友审核列表
- def post(self): 好友审核 | Implement the Python class `FriendCheckView` described below.
Class description:
Implement the FriendCheckView class.
Method signatures and docstrings:
- def get(self): 获取好友审核列表
- def post(self): 好友审核
<|skeleton|>
class FriendCheckView:
def get(self):
"""获取好友审核列表"""
<|body_0|>
def post(self... | f969cf63a3b6e4292d8c280f2bf1e7ae83a0d220 | <|skeleton|>
class FriendCheckView:
def get(self):
"""获取好友审核列表"""
<|body_0|>
def post(self):
"""好友审核"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FriendCheckView:
def get(self):
"""获取好友审核列表"""
try:
type = request.args.get('type', type=int)
page = request.args.get('page', 1, type=int)
page_num = request.args.get('page_num', 6, type=int)
except:
return {'code': RET.PARAMERR, 'msg': e... | the_stack_v2_python_sparse | c_chat_server/api/v1/friend.py | jangocheng/Cchat | train | 0 | |
39255a3d8392da612585cfe906bde3a5b5e04bfd | [
"if RestClient.__instance is not None:\n raise Exception('A singleton class cannot be initialized twice')\nself.__connection = http.client.HTTPConnection(os.getenv('AUTH_SERVER_HOST', '127.0.0.1'), os.getenv('AUTH_SERVER_PORT', 1234))",
"if RestClient.__instance is None:\n RestClient.__instance = RestClient... | <|body_start_0|>
if RestClient.__instance is not None:
raise Exception('A singleton class cannot be initialized twice')
self.__connection = http.client.HTTPConnection(os.getenv('AUTH_SERVER_HOST', '127.0.0.1'), os.getenv('AUTH_SERVER_PORT', 1234))
<|end_body_0|>
<|body_start_1|>
if ... | Singleton REST client to interact with the authentication server. --- This class is responsible of interfacing the authentication server as another data source, via a REST API presentation layer in the authentication server. Note: Uses the AUTH_SERVER_HOST and AUTH_SERVER_PORT environment variables to open the connecti... | RestClient | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestClient:
"""Singleton REST client to interact with the authentication server. --- This class is responsible of interfacing the authentication server as another data source, via a REST API presentation layer in the authentication server. Note: Uses the AUTH_SERVER_HOST and AUTH_SERVER_PORT envi... | stack_v2_sparse_classes_75kplus_train_067524 | 3,698 | permissive | [
{
"docstring": "Constructor method. --- Do NOT use this method. Use instance() instead.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Singleton instance access method. --- Do NOT use the constructor. Use this method instead. Returns: The singleton instance of this cl... | 5 | stack_v2_sparse_classes_30k_train_037200 | Implement the Python class `RestClient` described below.
Class description:
Singleton REST client to interact with the authentication server. --- This class is responsible of interfacing the authentication server as another data source, via a REST API presentation layer in the authentication server. Note: Uses the AUT... | Implement the Python class `RestClient` described below.
Class description:
Singleton REST client to interact with the authentication server. --- This class is responsible of interfacing the authentication server as another data source, via a REST API presentation layer in the authentication server. Note: Uses the AUT... | 7c3fc38823478054499e233dd36b8b4430d3f3d3 | <|skeleton|>
class RestClient:
"""Singleton REST client to interact with the authentication server. --- This class is responsible of interfacing the authentication server as another data source, via a REST API presentation layer in the authentication server. Note: Uses the AUTH_SERVER_HOST and AUTH_SERVER_PORT envi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RestClient:
"""Singleton REST client to interact with the authentication server. --- This class is responsible of interfacing the authentication server as another data source, via a REST API presentation layer in the authentication server. Note: Uses the AUTH_SERVER_HOST and AUTH_SERVER_PORT environment varia... | the_stack_v2_python_sparse | src/components/game-server/lib/data/auth/restclient.py | rorik/UBU-DMS | train | 0 |
9099bec8b50df6444fe1e5fa5f9ffd2e4a1bca1b | [
"if level is not None:\n self._target_level = level\nif self._target_level and self._target_level == self._deep_level:\n desc = {'type': self.__class__.__name__}\n desc.update(self.desc)\n return desc\ndesc = {'modules': [], 'type': self.__class__.__name__}\nif self._losses:\n desc['loss'] = self._lo... | <|body_start_0|>
if level is not None:
self._target_level = level
if self._target_level and self._target_level == self._deep_level:
desc = {'type': self.__class__.__name__}
desc.update(self.desc)
return desc
desc = {'modules': [], 'type': self.__cl... | Seriablizable Module class. | ModuleSerializable | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModuleSerializable:
"""Seriablizable Module class."""
def to_desc(self, level=None):
"""Convert Module to desc dict. :param level: Specifies witch level to convert. all conversions are performed as default."""
<|body_0|>
def update_from_desc(self, desc):
"""Updat... | stack_v2_sparse_classes_75kplus_train_067525 | 7,315 | permissive | [
{
"docstring": "Convert Module to desc dict. :param level: Specifies witch level to convert. all conversions are performed as default.",
"name": "to_desc",
"signature": "def to_desc(self, level=None)"
},
{
"docstring": "Update desc according to desc.",
"name": "update_from_desc",
"signat... | 3 | stack_v2_sparse_classes_30k_train_050579 | Implement the Python class `ModuleSerializable` described below.
Class description:
Seriablizable Module class.
Method signatures and docstrings:
- def to_desc(self, level=None): Convert Module to desc dict. :param level: Specifies witch level to convert. all conversions are performed as default.
- def update_from_de... | Implement the Python class `ModuleSerializable` described below.
Class description:
Seriablizable Module class.
Method signatures and docstrings:
- def to_desc(self, level=None): Convert Module to desc dict. :param level: Specifies witch level to convert. all conversions are performed as default.
- def update_from_de... | e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04 | <|skeleton|>
class ModuleSerializable:
"""Seriablizable Module class."""
def to_desc(self, level=None):
"""Convert Module to desc dict. :param level: Specifies witch level to convert. all conversions are performed as default."""
<|body_0|>
def update_from_desc(self, desc):
"""Updat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ModuleSerializable:
"""Seriablizable Module class."""
def to_desc(self, level=None):
"""Convert Module to desc dict. :param level: Specifies witch level to convert. all conversions are performed as default."""
if level is not None:
self._target_level = level
if self._t... | the_stack_v2_python_sparse | zeus/modules/operators/functions/serializable.py | huawei-noah/xingtian | train | 308 |
7439333ec8e426a8b049722f099e1e21260bcbce | [
"assert peer.id is not None\nif peer.id in self:\n raise ValueError('Peer has already been added')\nself[peer.id] = peer",
"assert peer.id is not None\nif peer.id not in self:\n self.add(peer)\n return peer\nelse:\n current = self[peer.id]\n current.merge(peer)\n return current",
"assert peer.... | <|body_start_0|>
assert peer.id is not None
if peer.id in self:
raise ValueError('Peer has already been added')
self[peer.id] = peer
<|end_body_0|>
<|body_start_1|>
assert peer.id is not None
if peer.id not in self:
self.add(peer)
return peer
... | PeerStorage is used to store all known peers in memory. It is a dict of peer objects, and peers can be retrieved by their `peer.id`. | PeerStorage | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PeerStorage:
"""PeerStorage is used to store all known peers in memory. It is a dict of peer objects, and peers can be retrieved by their `peer.id`."""
def add(self, peer: PeerId) -> None:
"""Add a new peer to the storage. Raises a `ValueError` if the peer has already been added."""
... | stack_v2_sparse_classes_75kplus_train_067526 | 1,737 | permissive | [
{
"docstring": "Add a new peer to the storage. Raises a `ValueError` if the peer has already been added.",
"name": "add",
"signature": "def add(self, peer: PeerId) -> None"
},
{
"docstring": "Add a peer to the storage if it has not been added yet. Otherwise, merge the current peer with the given... | 3 | stack_v2_sparse_classes_30k_train_009108 | Implement the Python class `PeerStorage` described below.
Class description:
PeerStorage is used to store all known peers in memory. It is a dict of peer objects, and peers can be retrieved by their `peer.id`.
Method signatures and docstrings:
- def add(self, peer: PeerId) -> None: Add a new peer to the storage. Rais... | Implement the Python class `PeerStorage` described below.
Class description:
PeerStorage is used to store all known peers in memory. It is a dict of peer objects, and peers can be retrieved by their `peer.id`.
Method signatures and docstrings:
- def add(self, peer: PeerId) -> None: Add a new peer to the storage. Rais... | 78229b7c99365229a7a806a4660d17234c0b2a9a | <|skeleton|>
class PeerStorage:
"""PeerStorage is used to store all known peers in memory. It is a dict of peer objects, and peers can be retrieved by their `peer.id`."""
def add(self, peer: PeerId) -> None:
"""Add a new peer to the storage. Raises a `ValueError` if the peer has already been added."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PeerStorage:
"""PeerStorage is used to store all known peers in memory. It is a dict of peer objects, and peers can be retrieved by their `peer.id`."""
def add(self, peer: PeerId) -> None:
"""Add a new peer to the storage. Raises a `ValueError` if the peer has already been added."""
asser... | the_stack_v2_python_sparse | hathor/p2p/peer_storage.py | HathorNetwork/hathor-core | train | 75 |
11381740ad4206fc7788789e9e752c6618b05d2d | [
"user_templates_list = readAll()\nglobal_templates_list = getAll()\nactinia_templates_list = user_templates_list + global_templates_list\nreturn make_response(jsonify(actinia_templates_list), 200)",
"template_id = request.get_json(force=True)['id']\nactinia_template = createTemplate(request.get_json(force=True))\... | <|body_start_0|>
user_templates_list = readAll()
global_templates_list = getAll()
actinia_templates_list = user_templates_list + global_templates_list
return make_response(jsonify(actinia_templates_list), 200)
<|end_body_0|>
<|body_start_1|>
template_id = request.get_json(force=... | List all actinia templates (process chain templates) | ActiniaTemplate | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActiniaTemplate:
"""List all actinia templates (process chain templates)"""
def get(self):
"""Get a list of all actinia templates (process chain templates)."""
<|body_0|>
def post(self):
"""Create an actinia template (process chain template)."""
<|body_1|... | stack_v2_sparse_classes_75kplus_train_067527 | 5,250 | permissive | [
{
"docstring": "Get a list of all actinia templates (process chain templates).",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Create an actinia template (process chain template).",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_026083 | Implement the Python class `ActiniaTemplate` described below.
Class description:
List all actinia templates (process chain templates)
Method signatures and docstrings:
- def get(self): Get a list of all actinia templates (process chain templates).
- def post(self): Create an actinia template (process chain template). | Implement the Python class `ActiniaTemplate` described below.
Class description:
List all actinia templates (process chain templates)
Method signatures and docstrings:
- def get(self): Get a list of all actinia templates (process chain templates).
- def post(self): Create an actinia template (process chain template).... | c01d98550ca9c49bf1a5f11a7209198e22122602 | <|skeleton|>
class ActiniaTemplate:
"""List all actinia templates (process chain templates)"""
def get(self):
"""Get a list of all actinia templates (process chain templates)."""
<|body_0|>
def post(self):
"""Create an actinia template (process chain template)."""
<|body_1|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ActiniaTemplate:
"""List all actinia templates (process chain templates)"""
def get(self):
"""Get a list of all actinia templates (process chain templates)."""
user_templates_list = readAll()
global_templates_list = getAll()
actinia_templates_list = user_templates_list + g... | the_stack_v2_python_sparse | actinia_module_plugin/api/actinia_templates.py | griembauer/actinia-module-plugin | train | 0 |
67d7e130cbc2456b0f9860e57580c04606bbfa5b | [
"self.tasks = [(self.cfg.get('poll_interval', 60), self.get_pages)]\nself.last_poll = dict()\nself.first_run = True",
"pages = self.cfg.get('pages', list())\nfor url in pages:\n self.last_poll[url] = datetime.datetime.now()\n body = get_page(url)\n self.producer.publish({'action': '%s.input' % self.name,... | <|body_start_0|>
self.tasks = [(self.cfg.get('poll_interval', 60), self.get_pages)]
self.last_poll = dict()
self.first_run = True
<|end_body_0|>
<|body_start_1|>
pages = self.cfg.get('pages', list())
for url in pages:
self.last_poll[url] = datetime.datetime.now()
... | HTTP Plugin | Plugin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Plugin:
"""HTTP Plugin"""
def on_init(self):
"""Main plugin initialisation"""
<|body_0|>
def get_pages(self):
"""HTTP page processor helper"""
<|body_1|>
def get_page(self, url):
"""HTTP page fetcher helper"""
<|body_2|>
<|end_skelet... | stack_v2_sparse_classes_75kplus_train_067528 | 1,144 | no_license | [
{
"docstring": "Main plugin initialisation",
"name": "on_init",
"signature": "def on_init(self)"
},
{
"docstring": "HTTP page processor helper",
"name": "get_pages",
"signature": "def get_pages(self)"
},
{
"docstring": "HTTP page fetcher helper",
"name": "get_page",
"sign... | 3 | stack_v2_sparse_classes_30k_train_024470 | Implement the Python class `Plugin` described below.
Class description:
HTTP Plugin
Method signatures and docstrings:
- def on_init(self): Main plugin initialisation
- def get_pages(self): HTTP page processor helper
- def get_page(self, url): HTTP page fetcher helper | Implement the Python class `Plugin` described below.
Class description:
HTTP Plugin
Method signatures and docstrings:
- def on_init(self): Main plugin initialisation
- def get_pages(self): HTTP page processor helper
- def get_page(self, url): HTTP page fetcher helper
<|skeleton|>
class Plugin:
"""HTTP Plugin"""
... | 61a16e6a17855c27f580a20e7c12b6743fea614e | <|skeleton|>
class Plugin:
"""HTTP Plugin"""
def on_init(self):
"""Main plugin initialisation"""
<|body_0|>
def get_pages(self):
"""HTTP page processor helper"""
<|body_1|>
def get_page(self, url):
"""HTTP page fetcher helper"""
<|body_2|>
<|end_skelet... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Plugin:
"""HTTP Plugin"""
def on_init(self):
"""Main plugin initialisation"""
self.tasks = [(self.cfg.get('poll_interval', 60), self.get_pages)]
self.last_poll = dict()
self.first_run = True
def get_pages(self):
"""HTTP page processor helper"""
pages =... | the_stack_v2_python_sparse | mhub/_old_plugins/_disabled/http.py | jinglemansweep/MHub | train | 0 |
227b870b7b2e2dcefece63ecc3a76e72fb55d11a | [
"self.session_key = session_key\nif categories is not None:\n self.categories = categories\nif default_category is not None:\n self.default_category = default_category\nif self.categories and self.default_category not in self.categories:\n raise ValueError('unrecognized default category %r' % (self.default... | <|body_start_0|>
self.session_key = session_key
if categories is not None:
self.categories = categories
if default_category is not None:
self.default_category = default_category
if self.categories and self.default_category not in self.categories:
raise... | Accumulate a list of messages to show at the next page request. | Flash | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Flash:
"""Accumulate a list of messages to show at the next page request."""
def __init__(self, session_key='flash', categories=None, default_category=None):
"""Instantiate a ``Flash`` object. ``session_key`` is the key to save the messages under in the user's session. ``categories``... | stack_v2_sparse_classes_75kplus_train_067529 | 4,469 | permissive | [
{
"docstring": "Instantiate a ``Flash`` object. ``session_key`` is the key to save the messages under in the user's session. ``categories`` is an optional list which overrides the default list of categories. ``default_category`` overrides the default category used for messages when none is specified.",
"nam... | 3 | null | Implement the Python class `Flash` described below.
Class description:
Accumulate a list of messages to show at the next page request.
Method signatures and docstrings:
- def __init__(self, session_key='flash', categories=None, default_category=None): Instantiate a ``Flash`` object. ``session_key`` is the key to save... | Implement the Python class `Flash` described below.
Class description:
Accumulate a list of messages to show at the next page request.
Method signatures and docstrings:
- def __init__(self, session_key='flash', categories=None, default_category=None): Instantiate a ``Flash`` object. ``session_key`` is the key to save... | 0b52380a9d4783f02c0a3c2611ded5f65edcf823 | <|skeleton|>
class Flash:
"""Accumulate a list of messages to show at the next page request."""
def __init__(self, session_key='flash', categories=None, default_category=None):
"""Instantiate a ``Flash`` object. ``session_key`` is the key to save the messages under in the user's session. ``categories``... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Flash:
"""Accumulate a list of messages to show at the next page request."""
def __init__(self, session_key='flash', categories=None, default_category=None):
"""Instantiate a ``Flash`` object. ``session_key`` is the key to save the messages under in the user's session. ``categories`` is an option... | the_stack_v2_python_sparse | spline/lib/flash.py | shadowlurker/spline | train | 0 |
7ba767373f8ea3a23a9f38c8b5fca09b18ffcde5 | [
"if root is None:\n return 0\nleft_depth = self.maxDepth(root.left)\nright_depth = self.maxDepth(root.right)\nreturn max(left_depth, right_depth) + 1",
"stack = []\nif root is not None:\n stack.append((1, root))\ndepth = 0\nwhile stack != []:\n cur_depth, root = stack.pop()\n if root is not None:\n ... | <|body_start_0|>
if root is None:
return 0
left_depth = self.maxDepth(root.left)
right_depth = self.maxDepth(root.right)
return max(left_depth, right_depth) + 1
<|end_body_0|>
<|body_start_1|>
stack = []
if root is not None:
stack.append((1, root)... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxDepth(self, root):
"""采用递归的方式 :type root: TreeNode :rtype: int"""
<|body_0|>
def maxDepth2(self, root):
"""DFS :param root: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if root is None:
return 0
left_... | stack_v2_sparse_classes_75kplus_train_067530 | 1,531 | no_license | [
{
"docstring": "采用递归的方式 :type root: TreeNode :rtype: int",
"name": "maxDepth",
"signature": "def maxDepth(self, root)"
},
{
"docstring": "DFS :param root: :return:",
"name": "maxDepth2",
"signature": "def maxDepth2(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth(self, root): 采用递归的方式 :type root: TreeNode :rtype: int
- def maxDepth2(self, root): DFS :param root: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth(self, root): 采用递归的方式 :type root: TreeNode :rtype: int
- def maxDepth2(self, root): DFS :param root: :return:
<|skeleton|>
class Solution:
def maxDepth(self, ro... | 1040b5dbbe509abe42df848bc34dd1626d7a05fb | <|skeleton|>
class Solution:
def maxDepth(self, root):
"""采用递归的方式 :type root: TreeNode :rtype: int"""
<|body_0|>
def maxDepth2(self, root):
"""DFS :param root: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxDepth(self, root):
"""采用递归的方式 :type root: TreeNode :rtype: int"""
if root is None:
return 0
left_depth = self.maxDepth(root.left)
right_depth = self.maxDepth(root.right)
return max(left_depth, right_depth) + 1
def maxDepth2(self, root):... | the_stack_v2_python_sparse | tree/maxDepth_104.py | NJ-zero/LeetCode_Answer | train | 1 | |
ccfbaee071c177ed75f739e748ea65bcc7d53700 | [
"if len(word) == k:\n return True\nif row < 0 or row >= row_max or col < 0 or (col >= col_max):\n return False\nif board[row][col] != word[k]:\n return False\nletter = board[row][col]\nboard[row][col] = None\nfor i, j in [[0, 1], [1, 0], [0, -1], [-1, 0]]:\n if self.recur(board, word, row_max, col_max, ... | <|body_start_0|>
if len(word) == k:
return True
if row < 0 or row >= row_max or col < 0 or (col >= col_max):
return False
if board[row][col] != word[k]:
return False
letter = board[row][col]
board[row][col] = None
for i, j in [[0, 1], [... | solution | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""solution"""
def recur(self, board: List[List[str]], word: str, row_max: int, col_max: int, row: int, col: int, k: int) -> bool:
"""recur Parameters ---------- board : List[List[str]] characters board word : str word row_max : int number of rows col_max : int number of co... | stack_v2_sparse_classes_75kplus_train_067531 | 2,889 | no_license | [
{
"docstring": "recur Parameters ---------- board : List[List[str]] characters board word : str word row_max : int number of rows col_max : int number of columns row : int current row col : int current column k : int index of letter in word Returns ------- bool result",
"name": "recur",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_004202 | Implement the Python class `Solution` described below.
Class description:
solution
Method signatures and docstrings:
- def recur(self, board: List[List[str]], word: str, row_max: int, col_max: int, row: int, col: int, k: int) -> bool: recur Parameters ---------- board : List[List[str]] characters board word : str wor... | Implement the Python class `Solution` described below.
Class description:
solution
Method signatures and docstrings:
- def recur(self, board: List[List[str]], word: str, row_max: int, col_max: int, row: int, col: int, k: int) -> bool: recur Parameters ---------- board : List[List[str]] characters board word : str wor... | 86766a73a617086784ad777906a2782e39fe262e | <|skeleton|>
class Solution:
"""solution"""
def recur(self, board: List[List[str]], word: str, row_max: int, col_max: int, row: int, col: int, k: int) -> bool:
"""recur Parameters ---------- board : List[List[str]] characters board word : str word row_max : int number of rows col_max : int number of co... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""solution"""
def recur(self, board: List[List[str]], word: str, row_max: int, col_max: int, row: int, col: int, k: int) -> bool:
"""recur Parameters ---------- board : List[List[str]] characters board word : str word row_max : int number of rows col_max : int number of columns row : i... | the_stack_v2_python_sparse | src/medium/word_search.py | albul-k/leetcode | train | 0 |
4c56a3913c5d6a4010d59706318cf9e5a73d5ba6 | [
"super().__init__()\nself.emb_dim = 512\nself.b_blocks = n_blocks\nself.pos_embedding = PositionalEncoding(emb_dim, pe_dropout, max_len)\n'\\n The encoder is made of N=6 identical blocks\\n '\nself.encoder_blocks = clones(EncoderBlock(emb_dim, dropout=dropout, **kwargs), n_blocks)",
"x = self.pos_em... | <|body_start_0|>
super().__init__()
self.emb_dim = 512
self.b_blocks = n_blocks
self.pos_embedding = PositionalEncoding(emb_dim, pe_dropout, max_len)
'\n The encoder is made of N=6 identical blocks\n '
self.encoder_blocks = clones(EncoderBlock(emb_dim, dropo... | TransformerEncoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerEncoder:
def __init__(self, emb_dim=512, n_blocks=6, max_len=5000, dropout=0.1, pe_dropout=0.0, **kwargs):
""":param emb_dim: the dimensionality of the input embeddings :param n_blocks: Number of identical stacked blocks :param max_len: Maximum length of a target sequence, req... | stack_v2_sparse_classes_75kplus_train_067532 | 3,349 | no_license | [
{
"docstring": ":param emb_dim: the dimensionality of the input embeddings :param n_blocks: Number of identical stacked blocks :param max_len: Maximum length of a target sequence, required for positional embeddings :param dropout: the amount of dropout to use in attention block",
"name": "__init__",
"si... | 2 | null | Implement the Python class `TransformerEncoder` described below.
Class description:
Implement the TransformerEncoder class.
Method signatures and docstrings:
- def __init__(self, emb_dim=512, n_blocks=6, max_len=5000, dropout=0.1, pe_dropout=0.0, **kwargs): :param emb_dim: the dimensionality of the input embeddings :... | Implement the Python class `TransformerEncoder` described below.
Class description:
Implement the TransformerEncoder class.
Method signatures and docstrings:
- def __init__(self, emb_dim=512, n_blocks=6, max_len=5000, dropout=0.1, pe_dropout=0.0, **kwargs): :param emb_dim: the dimensionality of the input embeddings :... | 6a27856f3f5d71373e6d42657233f7af0447a795 | <|skeleton|>
class TransformerEncoder:
def __init__(self, emb_dim=512, n_blocks=6, max_len=5000, dropout=0.1, pe_dropout=0.0, **kwargs):
""":param emb_dim: the dimensionality of the input embeddings :param n_blocks: Number of identical stacked blocks :param max_len: Maximum length of a target sequence, req... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TransformerEncoder:
def __init__(self, emb_dim=512, n_blocks=6, max_len=5000, dropout=0.1, pe_dropout=0.0, **kwargs):
""":param emb_dim: the dimensionality of the input embeddings :param n_blocks: Number of identical stacked blocks :param max_len: Maximum length of a target sequence, required for posi... | the_stack_v2_python_sparse | models/attention/encoder.py | cscribano/AYCE_2021 | train | 8 | |
1f0effa82660c9a34ae0ffe18d25d4af6e561731 | [
"self.config = config\nself.regs = config['model']['regs']\nself.decay = self.regs[0]\nself.batch_size = config['model']['batch_size']\nself.norm_adj = config['model']['norm_adj']\nself.model = NGCF(config['model'], self.norm_adj)\nsuper(NGCFEngine, self).__init__(config)\nself.model.to(self.device)",
"assert has... | <|body_start_0|>
self.config = config
self.regs = config['model']['regs']
self.decay = self.regs[0]
self.batch_size = config['model']['batch_size']
self.norm_adj = config['model']['norm_adj']
self.model = NGCF(config['model'], self.norm_adj)
super(NGCFEngine, self... | NGCFEngine Class. | NGCFEngine | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NGCFEngine:
"""NGCFEngine Class."""
def __init__(self, config):
"""Initialize NGCFEngine Class."""
<|body_0|>
def train_single_batch(self, batch_data):
"""Train the model in a single batch. Args: batch_data (list): batch users, positive items and negative items. ... | stack_v2_sparse_classes_75kplus_train_067533 | 7,227 | permissive | [
{
"docstring": "Initialize NGCFEngine Class.",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Train the model in a single batch. Args: batch_data (list): batch users, positive items and negative items. Return: loss (float): batch loss.",
"name": "train_singl... | 4 | stack_v2_sparse_classes_30k_train_013672 | Implement the Python class `NGCFEngine` described below.
Class description:
NGCFEngine Class.
Method signatures and docstrings:
- def __init__(self, config): Initialize NGCFEngine Class.
- def train_single_batch(self, batch_data): Train the model in a single batch. Args: batch_data (list): batch users, positive items... | Implement the Python class `NGCFEngine` described below.
Class description:
NGCFEngine Class.
Method signatures and docstrings:
- def __init__(self, config): Initialize NGCFEngine Class.
- def train_single_batch(self, batch_data): Train the model in a single batch. Args: batch_data (list): batch users, positive items... | 625189d5e1002a3edc27c3e3ce075fddf7ae1c92 | <|skeleton|>
class NGCFEngine:
"""NGCFEngine Class."""
def __init__(self, config):
"""Initialize NGCFEngine Class."""
<|body_0|>
def train_single_batch(self, batch_data):
"""Train the model in a single batch. Args: batch_data (list): batch users, positive items and negative items. ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NGCFEngine:
"""NGCFEngine Class."""
def __init__(self, config):
"""Initialize NGCFEngine Class."""
self.config = config
self.regs = config['model']['regs']
self.decay = self.regs[0]
self.batch_size = config['model']['batch_size']
self.norm_adj = config['mod... | the_stack_v2_python_sparse | beta_rec/models/ngcf.py | beta-team/beta-recsys | train | 156 |
af3cf9966fa75ce260e4139ba5e943ae7ddf3468 | [
"profit = 0\nfor i in range(len(prices)):\n for j in range(i + 1, len(prices)):\n if prices[j] > prices[i]:\n res = prices[j] - prices[i]\n if res > profit:\n profit = res\nreturn profit",
"max = None\nmin = None\nprofit = 0\nfor i in prices:\n if max is None:\n ... | <|body_start_0|>
profit = 0
for i in range(len(prices)):
for j in range(i + 1, len(prices)):
if prices[j] > prices[i]:
res = prices[j] - prices[i]
if res > profit:
profit = res
return profit
<|end_body_0|... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit2(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
profit = 0
for i in range(len(pr... | stack_v2_sparse_classes_75kplus_train_067534 | 1,163 | permissive | [
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit2",
"signature": "def maxProfit2(self, prices)"
},
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit",
"signature": "def maxProfit(self, prices)"
}
] | 2 | stack_v2_sparse_classes_30k_train_022468 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit2(self, prices): :type prices: List[int] :rtype: int
- def maxProfit(self, prices): :type prices: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit2(self, prices): :type prices: List[int] :rtype: int
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
<|skeleton|>
class Solution:
def maxPro... | 28c162c0f6923e4feaa0d6279c00dfe8237c726d | <|skeleton|>
class Solution:
def maxProfit2(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxProfit2(self, prices):
""":type prices: List[int] :rtype: int"""
profit = 0
for i in range(len(prices)):
for j in range(i + 1, len(prices)):
if prices[j] > prices[i]:
res = prices[j] - prices[i]
if res... | the_stack_v2_python_sparse | 121_best_time_to_buy_sell_stock_.py | sreedharg/leetcode | train | 0 | |
633d8f3244543bb65f6a10999e6bff4183f15520 | [
"t0_t1 = (0, 2.5)\ny0 = [0.99, 0.01, 0]\nobp = ode_hessian.ODEBackpropProblem(dim_y=3, tf_dy_dt=_tf_sir_dy_dt, tf_L_y0y1=_tf_sir_loss)\ndp_backprop = obp.dp_backprop(y0, t0_t1, odeint_kwargs=dict(rtol=1e-12, atol=1e-12), include_hessian_d2ydot_dy2_term=True)\ny1_via_dp, loss_via_dp, grad_via_dp, hessian_via_dp = dp... | <|body_start_0|>
t0_t1 = (0, 2.5)
y0 = [0.99, 0.01, 0]
obp = ode_hessian.ODEBackpropProblem(dim_y=3, tf_dy_dt=_tf_sir_dy_dt, tf_L_y0y1=_tf_sir_loss)
dp_backprop = obp.dp_backprop(y0, t0_t1, odeint_kwargs=dict(rtol=1e-12, atol=1e-12), include_hessian_d2ydot_dy2_term=True)
y1_via_d... | Basic tests for ODEBackpropProblem differential programming. | DifferentialProgrammingTest | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DifferentialProgrammingTest:
"""Basic tests for ODEBackpropProblem differential programming."""
def test_obp_dp(self):
"""Tests that ODEBackpropProblem.dp_backprop() agrees with .backprop()."""
<|body_0|>
def test_obp_dp_d2ydot_dy2(self):
"""Shows that ODEBackpro... | stack_v2_sparse_classes_75kplus_train_067535 | 9,913 | permissive | [
{
"docstring": "Tests that ODEBackpropProblem.dp_backprop() agrees with .backprop().",
"name": "test_obp_dp",
"signature": "def test_obp_dp(self)"
},
{
"docstring": "Shows that ODEBackpropProblem.dp_backprop() needs the s_i F_i,kl term.",
"name": "test_obp_dp_d2ydot_dy2",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_012221 | Implement the Python class `DifferentialProgrammingTest` described below.
Class description:
Basic tests for ODEBackpropProblem differential programming.
Method signatures and docstrings:
- def test_obp_dp(self): Tests that ODEBackpropProblem.dp_backprop() agrees with .backprop().
- def test_obp_dp_d2ydot_dy2(self): ... | Implement the Python class `DifferentialProgrammingTest` described below.
Class description:
Basic tests for ODEBackpropProblem differential programming.
Method signatures and docstrings:
- def test_obp_dp(self): Tests that ODEBackpropProblem.dp_backprop() agrees with .backprop().
- def test_obp_dp_d2ydot_dy2(self): ... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class DifferentialProgrammingTest:
"""Basic tests for ODEBackpropProblem differential programming."""
def test_obp_dp(self):
"""Tests that ODEBackpropProblem.dp_backprop() agrees with .backprop()."""
<|body_0|>
def test_obp_dp_d2ydot_dy2(self):
"""Shows that ODEBackpro... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DifferentialProgrammingTest:
"""Basic tests for ODEBackpropProblem differential programming."""
def test_obp_dp(self):
"""Tests that ODEBackpropProblem.dp_backprop() agrees with .backprop()."""
t0_t1 = (0, 2.5)
y0 = [0.99, 0.01, 0]
obp = ode_hessian.ODEBackpropProblem(dim_... | the_stack_v2_python_sparse | m_theory/m_theory_lib/ode/ode_hessian_test.py | Jimmy-INL/google-research | train | 1 |
1e55f46ba2cf43aa4c74a0c43072c0448095f921 | [
"testName = 'test_validatePolygon'\ntry:\n log.print_test_begin(testName)\n x_coords = np.asarray([550, 455, 491, 609, 645])\n y_coords = np.asarray([450, 519, 631, 631, 510])\n try:\n sc.Polygon(x_coords, y_coords)\n except ValueError as e:\n pass\n log.print_test_success(testName)\... | <|body_start_0|>
testName = 'test_validatePolygon'
try:
log.print_test_begin(testName)
x_coords = np.asarray([550, 455, 491, 609, 645])
y_coords = np.asarray([450, 519, 631, 631, 510])
try:
sc.Polygon(x_coords, y_coords)
except ... | TestCalculations_Polygon | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCalculations_Polygon:
def test_validatePolygon(self):
"""Does invalid polygon coordinates raise a ValueError exception?"""
<|body_0|>
def test_setPolyArea(self):
"""Is the Polygon Area calculated correctly?"""
<|body_1|>
def test_setPolyCentroid(self... | stack_v2_sparse_classes_75kplus_train_067536 | 4,814 | permissive | [
{
"docstring": "Does invalid polygon coordinates raise a ValueError exception?",
"name": "test_validatePolygon",
"signature": "def test_validatePolygon(self)"
},
{
"docstring": "Is the Polygon Area calculated correctly?",
"name": "test_setPolyArea",
"signature": "def test_setPolyArea(sel... | 4 | stack_v2_sparse_classes_30k_train_039930 | Implement the Python class `TestCalculations_Polygon` described below.
Class description:
Implement the TestCalculations_Polygon class.
Method signatures and docstrings:
- def test_validatePolygon(self): Does invalid polygon coordinates raise a ValueError exception?
- def test_setPolyArea(self): Is the Polygon Area c... | Implement the Python class `TestCalculations_Polygon` described below.
Class description:
Implement the TestCalculations_Polygon class.
Method signatures and docstrings:
- def test_validatePolygon(self): Does invalid polygon coordinates raise a ValueError exception?
- def test_setPolyArea(self): Is the Polygon Area c... | 6a5bfbb459f5a1309fdace4e38b44e8274c497db | <|skeleton|>
class TestCalculations_Polygon:
def test_validatePolygon(self):
"""Does invalid polygon coordinates raise a ValueError exception?"""
<|body_0|>
def test_setPolyArea(self):
"""Is the Polygon Area calculated correctly?"""
<|body_1|>
def test_setPolyCentroid(self... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestCalculations_Polygon:
def test_validatePolygon(self):
"""Does invalid polygon coordinates raise a ValueError exception?"""
testName = 'test_validatePolygon'
try:
log.print_test_begin(testName)
x_coords = np.asarray([550, 455, 491, 609, 645])
y_co... | the_stack_v2_python_sparse | testCalculations/polygon.py | sativa/SPEED | train | 0 | |
40cc20a08ab3bfd55741387def13cd7c2060a572 | [
"if not root:\n return None\nself.helper(root)\nreturn root",
"root.left, root.right = (root.right, root.left)\nif root.left:\n self.helper(root.left)\nif root.right:\n self.helper(root.right)",
"if not root:\n return None\nstack = [root]\nwhile stack:\n node = stack.pop()\n node.left, node.ri... | <|body_start_0|>
if not root:
return None
self.helper(root)
return root
<|end_body_0|>
<|body_start_1|>
root.left, root.right = (root.right, root.left)
if root.left:
self.helper(root.left)
if root.right:
self.helper(root.right)
<|end_b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def invertTree1(self, root):
"""方法一:递归的方式,反转左右子树 :type root: TreeNode :rtype: TreeNode"""
<|body_0|>
def helper(self, root):
"""反转root的左右子结点"""
<|body_1|>
def invertTree(self, root):
"""方法二:利用栈 :type root: TreeNode :rtype: TreeNode"""
... | stack_v2_sparse_classes_75kplus_train_067537 | 1,366 | no_license | [
{
"docstring": "方法一:递归的方式,反转左右子树 :type root: TreeNode :rtype: TreeNode",
"name": "invertTree1",
"signature": "def invertTree1(self, root)"
},
{
"docstring": "反转root的左右子结点",
"name": "helper",
"signature": "def helper(self, root)"
},
{
"docstring": "方法二:利用栈 :type root: TreeNode :rt... | 3 | stack_v2_sparse_classes_30k_test_001377 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def invertTree1(self, root): 方法一:递归的方式,反转左右子树 :type root: TreeNode :rtype: TreeNode
- def helper(self, root): 反转root的左右子结点
- def invertTree(self, root): 方法二:利用栈 :type root: TreeN... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def invertTree1(self, root): 方法一:递归的方式,反转左右子树 :type root: TreeNode :rtype: TreeNode
- def helper(self, root): 反转root的左右子结点
- def invertTree(self, root): 方法二:利用栈 :type root: TreeN... | 852fad258f5070c7b93c35252f7404e85e709ea6 | <|skeleton|>
class Solution:
def invertTree1(self, root):
"""方法一:递归的方式,反转左右子树 :type root: TreeNode :rtype: TreeNode"""
<|body_0|>
def helper(self, root):
"""反转root的左右子结点"""
<|body_1|>
def invertTree(self, root):
"""方法二:利用栈 :type root: TreeNode :rtype: TreeNode"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def invertTree1(self, root):
"""方法一:递归的方式,反转左右子树 :type root: TreeNode :rtype: TreeNode"""
if not root:
return None
self.helper(root)
return root
def helper(self, root):
"""反转root的左右子结点"""
root.left, root.right = (root.right, root.left)... | the_stack_v2_python_sparse | 201-300/226. Invert Binary Tree.py | SunnyMarkLiu/LeetCode | train | 1 | |
bf11714ca5e4926fac90528082d08d1a6fb3f2ba | [
"self.truncation = truncation\nself.nmin = nmin\nself.train = train\nif len(train.shape) == 1:\n train = np.atleast_2d(train).T\nself.num_points, self.num_dim = train.shape\nif weights is None:\n weights = np.ones(self.num_points)\nself.weights = weights\nself.mean = np.average(train, weights=weights, axis=0)... | <|body_start_0|>
self.truncation = truncation
self.nmin = nmin
self.train = train
if len(train.shape) == 1:
train = np.atleast_2d(train).T
self.num_points, self.num_dim = train.shape
if weights is None:
weights = np.ones(self.num_points)
se... | Matched Elliptical Gaussian Kernel Density Estimator Adapted from the algorithm specified in the BAMBIS's model specified Wolf 2017 to support weighted samples. | MegKDE | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MegKDE:
"""Matched Elliptical Gaussian Kernel Density Estimator Adapted from the algorithm specified in the BAMBIS's model specified Wolf 2017 to support weighted samples."""
def __init__(self, train, weights=None, truncation=3.0, nmin=4, factor=1.0):
"""Parameters ---------- train :... | stack_v2_sparse_classes_75kplus_train_067538 | 3,332 | permissive | [
{
"docstring": "Parameters ---------- train : np.ndarray The training data set. Should be a 1D array of samples or a 2D array of shape (n_samples, n_dim). weights : np.ndarray, optional An array of weights. If not specified, equal weights are assumed. truncation : float, optional The maximum deviation (in sigma... | 2 | stack_v2_sparse_classes_30k_train_043101 | Implement the Python class `MegKDE` described below.
Class description:
Matched Elliptical Gaussian Kernel Density Estimator Adapted from the algorithm specified in the BAMBIS's model specified Wolf 2017 to support weighted samples.
Method signatures and docstrings:
- def __init__(self, train, weights=None, truncatio... | Implement the Python class `MegKDE` described below.
Class description:
Matched Elliptical Gaussian Kernel Density Estimator Adapted from the algorithm specified in the BAMBIS's model specified Wolf 2017 to support weighted samples.
Method signatures and docstrings:
- def __init__(self, train, weights=None, truncatio... | 888921942789f7c7a817c7a3cee3e7e5da3a26bf | <|skeleton|>
class MegKDE:
"""Matched Elliptical Gaussian Kernel Density Estimator Adapted from the algorithm specified in the BAMBIS's model specified Wolf 2017 to support weighted samples."""
def __init__(self, train, weights=None, truncation=3.0, nmin=4, factor=1.0):
"""Parameters ---------- train :... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MegKDE:
"""Matched Elliptical Gaussian Kernel Density Estimator Adapted from the algorithm specified in the BAMBIS's model specified Wolf 2017 to support weighted samples."""
def __init__(self, train, weights=None, truncation=3.0, nmin=4, factor=1.0):
"""Parameters ---------- train : np.ndarray T... | the_stack_v2_python_sparse | chainconsumer/kde.py | Samreay/ChainConsumer | train | 74 |
51531e0f4022e8f1be1dd60777de8f5a591476b1 | [
"statement = 'a <- 3'\nself.assertEqual(ycc.parse_ps2py(statement).get('errors'), '')\nself.assertEqual(ycc.parse_ps2py(statement).get('result'), 'a = 3')\nstatement = 'a <- {1, 2, 3}'\nself.assertEqual(ycc.parse_ps2py(statement).get('errors'), '')\nself.assertEqual(ycc.parse_ps2py(statement).get('result'), 'a = {1... | <|body_start_0|>
statement = 'a <- 3'
self.assertEqual(ycc.parse_ps2py(statement).get('errors'), '')
self.assertEqual(ycc.parse_ps2py(statement).get('result'), 'a = 3')
statement = 'a <- {1, 2, 3}'
self.assertEqual(ycc.parse_ps2py(statement).get('errors'), '')
self.assert... | Class for testing assignments. | TestAssignment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAssignment:
"""Class for testing assignments."""
def test_assignment(self):
"""Tests 'normal' assignments without calculations. Keyword arguments: self -- the TestAssignment instance"""
<|body_0|>
def test_calcAssignment(self):
"""Tests assignments containing... | stack_v2_sparse_classes_75kplus_train_067539 | 9,275 | no_license | [
{
"docstring": "Tests 'normal' assignments without calculations. Keyword arguments: self -- the TestAssignment instance",
"name": "test_assignment",
"signature": "def test_assignment(self)"
},
{
"docstring": "Tests assignments containing a calculation. Keyword arguments: self -- the TestAssignme... | 2 | stack_v2_sparse_classes_30k_train_014239 | Implement the Python class `TestAssignment` described below.
Class description:
Class for testing assignments.
Method signatures and docstrings:
- def test_assignment(self): Tests 'normal' assignments without calculations. Keyword arguments: self -- the TestAssignment instance
- def test_calcAssignment(self): Tests a... | Implement the Python class `TestAssignment` described below.
Class description:
Class for testing assignments.
Method signatures and docstrings:
- def test_assignment(self): Tests 'normal' assignments without calculations. Keyword arguments: self -- the TestAssignment instance
- def test_calcAssignment(self): Tests a... | 2c0b907f5d9e74265e87ab3e36753f764a965f21 | <|skeleton|>
class TestAssignment:
"""Class for testing assignments."""
def test_assignment(self):
"""Tests 'normal' assignments without calculations. Keyword arguments: self -- the TestAssignment instance"""
<|body_0|>
def test_calcAssignment(self):
"""Tests assignments containing... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestAssignment:
"""Class for testing assignments."""
def test_assignment(self):
"""Tests 'normal' assignments without calculations. Keyword arguments: self -- the TestAssignment instance"""
statement = 'a <- 3'
self.assertEqual(ycc.parse_ps2py(statement).get('errors'), '')
... | the_stack_v2_python_sparse | AlgoBooster/ab_ui/ab_main/ab_unittests/parser_unittests.py | danielaboeing/algobooster | train | 0 |
0daa1bec3b45e39478cd417aa938c1c35b1c94ff | [
"if isinstance(xScale, PQU):\n xScale = float(xScale.inUnitsOf(xUnit).value)\nself.w = w\nparams = {'xScale': xScale, 'w': w}\nif domainMin is None:\n domainMin = -xScale / 10.0\nif domainMax is None:\n domainMax = xScale * 6.0\nUnivariatePDF.__init__(self, xUnit=xUnit, domainMin=domainMin, domainMax=domai... | <|body_start_0|>
if isinstance(xScale, PQU):
xScale = float(xScale.inUnitsOf(xUnit).value)
self.w = w
params = {'xScale': xScale, 'w': w}
if domainMin is None:
domainMin = -xScale / 10.0
if domainMax is None:
domainMax = xScale * 6.0
Un... | BrodyDistribution | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BrodyDistribution:
def __init__(self, xUnit='', xScale=1.0, w=0.5, domainMin=None, domainMax=None, xLabel='indep. variable', yLabel='PDF', **kwds):
"""Brody distribution vaguely interpolates between Poisson and Wigner distributions Outside of the interval (domainMin,domainMax), getValue(... | stack_v2_sparse_classes_75kplus_train_067540 | 43,010 | permissive | [
{
"docstring": "Brody distribution vaguely interpolates between Poisson and Wigner distributions Outside of the interval (domainMin,domainMax), getValue() evaluates to None since this pdf is undefined here :param xUnit: units to use for the x axis :param w: (float) exponent to use in the equation :param xScale:... | 2 | null | Implement the Python class `BrodyDistribution` described below.
Class description:
Implement the BrodyDistribution class.
Method signatures and docstrings:
- def __init__(self, xUnit='', xScale=1.0, w=0.5, domainMin=None, domainMax=None, xLabel='indep. variable', yLabel='PDF', **kwds): Brody distribution vaguely inte... | Implement the Python class `BrodyDistribution` described below.
Class description:
Implement the BrodyDistribution class.
Method signatures and docstrings:
- def __init__(self, xUnit='', xScale=1.0, w=0.5, domainMin=None, domainMax=None, xLabel='indep. variable', yLabel='PDF', **kwds): Brody distribution vaguely inte... | 6ba80855ae47cb32c37f635d065b228fadb03412 | <|skeleton|>
class BrodyDistribution:
def __init__(self, xUnit='', xScale=1.0, w=0.5, domainMin=None, domainMax=None, xLabel='indep. variable', yLabel='PDF', **kwds):
"""Brody distribution vaguely interpolates between Poisson and Wigner distributions Outside of the interval (domainMin,domainMax), getValue(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BrodyDistribution:
def __init__(self, xUnit='', xScale=1.0, w=0.5, domainMin=None, domainMax=None, xLabel='indep. variable', yLabel='PDF', **kwds):
"""Brody distribution vaguely interpolates between Poisson and Wigner distributions Outside of the interval (domainMin,domainMax), getValue() evaluates to... | the_stack_v2_python_sparse | fudge/core/math/pdf.py | LLNL/fudge | train | 21 | |
3c1d8af7ab082c2143946c618c25bd9a1fe9bc1a | [
"if not hasattr(self, '_zeval'):\n if self._args['evaluate_mc_at_zlens']:\n self._zeval = self.z\n else:\n self._zeval = self.z_infall\nreturn self._zeval",
"if not hasattr(self, '_params_physical'):\n [concentration, rt] = self.profile_args\n rhos, rs, r200 = self._lens_cosmo.NFW_params... | <|body_start_0|>
if not hasattr(self, '_zeval'):
if self._args['evaluate_mc_at_zlens']:
self._zeval = self.z
else:
self._zeval = self.z_infall
return self._zeval
<|end_body_0|>
<|body_start_1|>
if not hasattr(self, '_params_physical'):
... | Defines a truncated NFW halo that is a subhalo of the host dark matter halo | TNFWSubhalo | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TNFWSubhalo:
"""Defines a truncated NFW halo that is a subhalo of the host dark matter halo"""
def z_eval(self):
"""Returns the redshift at which to evalate the concentration-mass relation"""
<|body_0|>
def params_physical(self):
"""See documentation in base clas... | stack_v2_sparse_classes_75kplus_train_067541 | 5,061 | permissive | [
{
"docstring": "Returns the redshift at which to evalate the concentration-mass relation",
"name": "z_eval",
"signature": "def z_eval(self)"
},
{
"docstring": "See documentation in base class (Halos/halo_base.py)",
"name": "params_physical",
"signature": "def params_physical(self)"
},
... | 3 | stack_v2_sparse_classes_30k_train_024685 | Implement the Python class `TNFWSubhalo` described below.
Class description:
Defines a truncated NFW halo that is a subhalo of the host dark matter halo
Method signatures and docstrings:
- def z_eval(self): Returns the redshift at which to evalate the concentration-mass relation
- def params_physical(self): See docum... | Implement the Python class `TNFWSubhalo` described below.
Class description:
Defines a truncated NFW halo that is a subhalo of the host dark matter halo
Method signatures and docstrings:
- def z_eval(self): Returns the redshift at which to evalate the concentration-mass relation
- def params_physical(self): See docum... | aac61ed4dd6bb9df1f8295760c6ec5f6099f8983 | <|skeleton|>
class TNFWSubhalo:
"""Defines a truncated NFW halo that is a subhalo of the host dark matter halo"""
def z_eval(self):
"""Returns the redshift at which to evalate the concentration-mass relation"""
<|body_0|>
def params_physical(self):
"""See documentation in base clas... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TNFWSubhalo:
"""Defines a truncated NFW halo that is a subhalo of the host dark matter halo"""
def z_eval(self):
"""Returns the redshift at which to evalate the concentration-mass relation"""
if not hasattr(self, '_zeval'):
if self._args['evaluate_mc_at_zlens']:
... | the_stack_v2_python_sparse | pyHalo/Halos/HaloModels/TNFW.py | alexandres-lazar/pyHalo | train | 0 |
53542f34f49603e8034d63fbf3b5a643e0c7c16e | [
"menu = QtGui.QMenu(self)\ndelete_action = menu.addAction('Delete')\nany_selected = len(self.selectionModel().selectedRows()) > 0\nif not any_selected:\n delete_action.setEnabled(False)\naction = menu.exec_(self.mapToGlobal(event.pos()))\nif action == delete_action:\n self.delete_selected_models()\nreturn Non... | <|body_start_0|>
menu = QtGui.QMenu(self)
delete_action = menu.addAction('Delete')
any_selected = len(self.selectionModel().selectedRows()) > 0
if not any_selected:
delete_action.setEnabled(False)
action = menu.exec_(self.mapToGlobal(event.pos()))
if action ==... | TransitionsDialogTableView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransitionsDialogTableView:
def contextMenuEvent(self, event):
"""Provide a right-click menu for the line list table. :param event: The mouse event that triggered the menu."""
<|body_0|>
def delete_selected_models(self):
"""Remove models. This assumes the view's rows... | stack_v2_sparse_classes_75kplus_train_067542 | 39,011 | no_license | [
{
"docstring": "Provide a right-click menu for the line list table. :param event: The mouse event that triggered the menu.",
"name": "contextMenuEvent",
"signature": "def contextMenuEvent(self, event)"
},
{
"docstring": "Remove models. This assumes the view's rows are the same as the model's row... | 2 | stack_v2_sparse_classes_30k_train_050650 | Implement the Python class `TransitionsDialogTableView` described below.
Class description:
Implement the TransitionsDialogTableView class.
Method signatures and docstrings:
- def contextMenuEvent(self, event): Provide a right-click menu for the line list table. :param event: The mouse event that triggered the menu.
... | Implement the Python class `TransitionsDialogTableView` described below.
Class description:
Implement the TransitionsDialogTableView class.
Method signatures and docstrings:
- def contextMenuEvent(self, event): Provide a right-click menu for the line list table. :param event: The mouse event that triggered the menu.
... | 1977c7d1834186194945477c93af2b1d00865aad | <|skeleton|>
class TransitionsDialogTableView:
def contextMenuEvent(self, event):
"""Provide a right-click menu for the line list table. :param event: The mouse event that triggered the menu."""
<|body_0|>
def delete_selected_models(self):
"""Remove models. This assumes the view's rows... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TransitionsDialogTableView:
def contextMenuEvent(self, event):
"""Provide a right-click menu for the line list table. :param event: The mouse event that triggered the menu."""
menu = QtGui.QMenu(self)
delete_action = menu.addAction('Delete')
any_selected = len(self.selectionMod... | the_stack_v2_python_sparse | smh/gui/linelist_manager.py | jsobeck/smhr | train | 1 | |
c0a84d248aba6460574fb7b491e6624406a26b81 | [
"cmd = 'cp ' + test_tif_file + ' /var/tmp/'\nos.system(cmd)\npayload = {'uuid': test_export_cm_layer_uuid, 'type': 'raster'}\nexpected_status = 200\noutput = requests.post(url, json=payload)\nassert output.status_code == expected_status\ncmd = 'rm /var/tmp/' + test_export_cm_layer_uuid + '.tif'\nos.system(cmd)",
... | <|body_start_0|>
cmd = 'cp ' + test_tif_file + ' /var/tmp/'
os.system(cmd)
payload = {'uuid': test_export_cm_layer_uuid, 'type': 'raster'}
expected_status = 200
output = requests.post(url, json=payload)
assert output.status_code == expected_status
cmd = 'rm /var/t... | TestExportCMLayer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestExportCMLayer:
def test_post(self):
"""this test will pass the upload/export/cmLayer method"""
<|body_0|>
def test_port_wrong_parameters(self):
"""this test will fail because the wrong parameters are given"""
<|body_1|>
def test_post_wrong_layer(self... | stack_v2_sparse_classes_75kplus_train_067543 | 1,487 | permissive | [
{
"docstring": "this test will pass the upload/export/cmLayer method",
"name": "test_post",
"signature": "def test_post(self)"
},
{
"docstring": "this test will fail because the wrong parameters are given",
"name": "test_port_wrong_parameters",
"signature": "def test_port_wrong_parameter... | 3 | stack_v2_sparse_classes_30k_train_008350 | Implement the Python class `TestExportCMLayer` described below.
Class description:
Implement the TestExportCMLayer class.
Method signatures and docstrings:
- def test_post(self): this test will pass the upload/export/cmLayer method
- def test_port_wrong_parameters(self): this test will fail because the wrong paramete... | Implement the Python class `TestExportCMLayer` described below.
Class description:
Implement the TestExportCMLayer class.
Method signatures and docstrings:
- def test_post(self): this test will pass the upload/export/cmLayer method
- def test_port_wrong_parameters(self): this test will fail because the wrong paramete... | ba1e287dbc63e34bf9feb80b65b02c1db93ce91c | <|skeleton|>
class TestExportCMLayer:
def test_post(self):
"""this test will pass the upload/export/cmLayer method"""
<|body_0|>
def test_port_wrong_parameters(self):
"""this test will fail because the wrong parameters are given"""
<|body_1|>
def test_post_wrong_layer(self... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestExportCMLayer:
def test_post(self):
"""this test will pass the upload/export/cmLayer method"""
cmd = 'cp ' + test_tif_file + ' /var/tmp/'
os.system(cmd)
payload = {'uuid': test_export_cm_layer_uuid, 'type': 'raster'}
expected_status = 200
output = requests.p... | the_stack_v2_python_sparse | pytest_suit/routes/uploads/test_exportCMLayer.py | HotMaps/Hotmaps-toolbox-service | train | 4 | |
2d7f3a9104f8e2bdba36085acd6063711d2316fe | [
"super().__init__(name='vector_decoder')\nself.model_size = model_size\nassert isinstance(observation_space, gym.spaces.Box) and len(observation_space.shape) == 1\nself.mlp = MLP(model_size=model_size, output_layer_size=observation_space.shape[0])\ndl_type = tf.keras.mixed_precision.global_policy().compute_dtype or... | <|body_start_0|>
super().__init__(name='vector_decoder')
self.model_size = model_size
assert isinstance(observation_space, gym.spaces.Box) and len(observation_space.shape) == 1
self.mlp = MLP(model_size=model_size, output_layer_size=observation_space.shape[0])
dl_type = tf.keras.... | A simple vector decoder to reproduce non-image (1D vector) observations. Wraps an MLP for mean parameter computations and a Gaussian distribution, from which we then sample using these mean values and a fixed stddev of 1.0. | VectorDecoder | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VectorDecoder:
"""A simple vector decoder to reproduce non-image (1D vector) observations. Wraps an MLP for mean parameter computations and a Gaussian distribution, from which we then sample using these mean values and a fixed stddev of 1.0."""
def __init__(self, *, model_size: Optional[str]... | stack_v2_sparse_classes_75kplus_train_067544 | 3,227 | permissive | [
{
"docstring": "Initializes a VectorDecoder instance. Args: model_size: The \"Model Size\" used according to [1] Appendinx B. Determines the exact size of the underlying MLP. observation_space: The observation space to decode back into. This must be a Box of shape (d,), where d >= 1.",
"name": "__init__",
... | 2 | stack_v2_sparse_classes_30k_train_051201 | Implement the Python class `VectorDecoder` described below.
Class description:
A simple vector decoder to reproduce non-image (1D vector) observations. Wraps an MLP for mean parameter computations and a Gaussian distribution, from which we then sample using these mean values and a fixed stddev of 1.0.
Method signatur... | Implement the Python class `VectorDecoder` described below.
Class description:
A simple vector decoder to reproduce non-image (1D vector) observations. Wraps an MLP for mean parameter computations and a Gaussian distribution, from which we then sample using these mean values and a fixed stddev of 1.0.
Method signatur... | edba68c3e7cf255d1d6479329f305adb7fa4c3ed | <|skeleton|>
class VectorDecoder:
"""A simple vector decoder to reproduce non-image (1D vector) observations. Wraps an MLP for mean parameter computations and a Gaussian distribution, from which we then sample using these mean values and a fixed stddev of 1.0."""
def __init__(self, *, model_size: Optional[str]... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VectorDecoder:
"""A simple vector decoder to reproduce non-image (1D vector) observations. Wraps an MLP for mean parameter computations and a Gaussian distribution, from which we then sample using these mean values and a fixed stddev of 1.0."""
def __init__(self, *, model_size: Optional[str]='XS', observ... | the_stack_v2_python_sparse | rllib/algorithms/dreamerv3/tf/models/components/vector_decoder.py | ray-project/ray | train | 29,482 |
230f5f17b1dc1a7d637581d25d54f89adaa38d6f | [
"super(GRUCell, self).__init__()\nself.hidden = nn.CellList([nn.Dense(dim_hid, dim_hid, has_bias=bias) for _ in range(3)])\nself.input = nn.CellList([nn.Dense(dim_in, dim_hid, has_bias=bias) for _ in range(3)])\nself.sigmoid = nn.Sigmoid()\nself.tanh = nn.Tanh()",
"r = self.sigmoid(self.input[0](inputs) + self.hi... | <|body_start_0|>
super(GRUCell, self).__init__()
self.hidden = nn.CellList([nn.Dense(dim_hid, dim_hid, has_bias=bias) for _ in range(3)])
self.input = nn.CellList([nn.Dense(dim_in, dim_hid, has_bias=bias) for _ in range(3)])
self.sigmoid = nn.Sigmoid()
self.tanh = nn.Tanh()
<|end... | GRUCell | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GRUCell:
def __init__(self, dim_in: int, dim_hid: int, bias: bool=True):
"""Parameters ---------- dim_in : int input dimension. dim_hid : int dimension of hidden layers. bias : bool, optional adding a bias term or not. The default is True."""
<|body_0|>
def construct(self, i... | stack_v2_sparse_classes_75kplus_train_067545 | 9,199 | permissive | [
{
"docstring": "Parameters ---------- dim_in : int input dimension. dim_hid : int dimension of hidden layers. bias : bool, optional adding a bias term or not. The default is True.",
"name": "__init__",
"signature": "def __init__(self, dim_in: int, dim_hid: int, bias: bool=True)"
},
{
"docstring"... | 2 | stack_v2_sparse_classes_30k_train_026765 | Implement the Python class `GRUCell` described below.
Class description:
Implement the GRUCell class.
Method signatures and docstrings:
- def __init__(self, dim_in: int, dim_hid: int, bias: bool=True): Parameters ---------- dim_in : int input dimension. dim_hid : int dimension of hidden layers. bias : bool, optional ... | Implement the Python class `GRUCell` described below.
Class description:
Implement the GRUCell class.
Method signatures and docstrings:
- def __init__(self, dim_in: int, dim_hid: int, bias: bool=True): Parameters ---------- dim_in : int input dimension. dim_hid : int dimension of hidden layers. bias : bool, optional ... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class GRUCell:
def __init__(self, dim_in: int, dim_hid: int, bias: bool=True):
"""Parameters ---------- dim_in : int input dimension. dim_hid : int dimension of hidden layers. bias : bool, optional adding a bias term or not. The default is True."""
<|body_0|>
def construct(self, i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GRUCell:
def __init__(self, dim_in: int, dim_hid: int, bias: bool=True):
"""Parameters ---------- dim_in : int input dimension. dim_hid : int dimension of hidden layers. bias : bool, optional adding a bias term or not. The default is True."""
super(GRUCell, self).__init__()
self.hidden... | the_stack_v2_python_sparse | research/gnn/nri-mpm/models/base.py | mindspore-ai/models | train | 301 | |
7aa940c5e16635cab84e56ac0a2da1d5c34d1d90 | [
"pcp_obj = Features.select_features('pcp', self.file_struct, self.annot_beats, self.framesync)\nmfcc_obj = Features.select_features('mfcc', self.file_struct, self.annot_beats, self.framesync)\nframe_times = pcp_obj.frame_times\nassert np.array_equal(frame_times, mfcc_obj.frame_times)\nest_idxs, est_labels, F = main... | <|body_start_0|>
pcp_obj = Features.select_features('pcp', self.file_struct, self.annot_beats, self.framesync)
mfcc_obj = Features.select_features('mfcc', self.file_struct, self.annot_beats, self.framesync)
frame_times = pcp_obj.frame_times
assert np.array_equal(frame_times, mfcc_obj.fra... | This script identifies the boundaries of a given track using the Spectral Clustering method published here: Mcfee, B., & Ellis, D. P. W. (2014). Analyzing Song Structure with Spectral Clustering. In Proc. of the 15th International Society for Music Information Retrieval Conference (pp. 405–410). Taipei, Taiwan. Origina... | Segmenter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Segmenter:
"""This script identifies the boundaries of a given track using the Spectral Clustering method published here: Mcfee, B., & Ellis, D. P. W. (2014). Analyzing Song Structure with Spectral Clustering. In Proc. of the 15th International Society for Music Information Retrieval Conference (... | stack_v2_sparse_classes_75kplus_train_067546 | 3,235 | permissive | [
{
"docstring": "Main process. Returns ------- est_idxs : np.array(N) or list Estimated times for the segment boundaries in frame indeces. List if hierarchical segmentation. est_labels : np.array(N-1) or list Estimated labels for the segments. List if hierarchical segmentation.",
"name": "process",
"sign... | 3 | stack_v2_sparse_classes_30k_train_049980 | Implement the Python class `Segmenter` described below.
Class description:
This script identifies the boundaries of a given track using the Spectral Clustering method published here: Mcfee, B., & Ellis, D. P. W. (2014). Analyzing Song Structure with Spectral Clustering. In Proc. of the 15th International Society for M... | Implement the Python class `Segmenter` described below.
Class description:
This script identifies the boundaries of a given track using the Spectral Clustering method published here: Mcfee, B., & Ellis, D. P. W. (2014). Analyzing Song Structure with Spectral Clustering. In Proc. of the 15th International Society for M... | 5581db79499a7a2067038527c8e1f19e501395df | <|skeleton|>
class Segmenter:
"""This script identifies the boundaries of a given track using the Spectral Clustering method published here: Mcfee, B., & Ellis, D. P. W. (2014). Analyzing Song Structure with Spectral Clustering. In Proc. of the 15th International Society for Music Information Retrieval Conference (... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Segmenter:
"""This script identifies the boundaries of a given track using the Spectral Clustering method published here: Mcfee, B., & Ellis, D. P. W. (2014). Analyzing Song Structure with Spectral Clustering. In Proc. of the 15th International Society for Music Information Retrieval Conference (pp. 405–410).... | the_stack_v2_python_sparse | msaf/algorithms/scluster/segmenter.py | urinieto/msaf | train | 447 |
e586b9047a4a6f52abcb017f2875875f5a0aeaf9 | [
"self.path = path\nif not retrain and os.path.isfile(self.path):\n os.remove(self.path)\nreturn",
"if logs is None:\n logs = {}\nif not os.path.isfile(self.path):\n with open(self.path, 'w') as fw:\n json.dump({}, fw)\nwith open(self.path, 'r') as fr:\n data = json.load(fr)\nfor key in logs.key... | <|body_start_0|>
self.path = path
if not retrain and os.path.isfile(self.path):
os.remove(self.path)
return
<|end_body_0|>
<|body_start_1|>
if logs is None:
logs = {}
if not os.path.isfile(self.path):
with open(self.path, 'w') as fw:
... | This class represents extension of Keras' Callback class. It is used to log the performace of the model after each iteration. | EpochEvaluator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EpochEvaluator:
"""This class represents extension of Keras' Callback class. It is used to log the performace of the model after each iteration."""
def __init__(self, path, retrain=False):
"""Constructor of the logger. Parameters ---------- path: String The path where the outputs of ... | stack_v2_sparse_classes_75kplus_train_067547 | 2,136 | no_license | [
{
"docstring": "Constructor of the logger. Parameters ---------- path: String The path where the outputs of the logger should be written. retrain: boolean If True, it considers as if we are re-training the model, and thus does not overwrite previous logges performaces.",
"name": "__init__",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_051234 | Implement the Python class `EpochEvaluator` described below.
Class description:
This class represents extension of Keras' Callback class. It is used to log the performace of the model after each iteration.
Method signatures and docstrings:
- def __init__(self, path, retrain=False): Constructor of the logger. Paramete... | Implement the Python class `EpochEvaluator` described below.
Class description:
This class represents extension of Keras' Callback class. It is used to log the performace of the model after each iteration.
Method signatures and docstrings:
- def __init__(self, path, retrain=False): Constructor of the logger. Paramete... | 274022d141b2c7912cfaaa3ca2d5adfc9ac40413 | <|skeleton|>
class EpochEvaluator:
"""This class represents extension of Keras' Callback class. It is used to log the performace of the model after each iteration."""
def __init__(self, path, retrain=False):
"""Constructor of the logger. Parameters ---------- path: String The path where the outputs of ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EpochEvaluator:
"""This class represents extension of Keras' Callback class. It is used to log the performace of the model after each iteration."""
def __init__(self, path, retrain=False):
"""Constructor of the logger. Parameters ---------- path: String The path where the outputs of the logger sh... | the_stack_v2_python_sparse | src/models/callbacks/EpochEvaluator.py | ljupche98/EPFL-Tweets-Sentiment-Classification | train | 0 |
26eb0436bea29fe7457e1a0128a8074d582ee239 | [
"import multiprocessing as _mp\nself.cpu_count = _mp.cpu_count()\nself.mem_per_core = 110889500.0\nself.parallelisation_method = 'numba'",
"print(prefix + 'Parallelisation method:', self.parallelisation_method)\nif self.parallelisation_method.lower() in ['multiprocessing', 'mp', 'multi-processing']:\n print(pr... | <|body_start_0|>
import multiprocessing as _mp
self.cpu_count = _mp.cpu_count()
self.mem_per_core = 110889500.0
self.parallelisation_method = 'numba'
<|end_body_0|>
<|body_start_1|>
print(prefix + 'Parallelisation method:', self.parallelisation_method)
if self.parallelis... | IncidentFieldParallelProcessingParameters | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IncidentFieldParallelProcessingParameters:
def __init__(self):
"""Initialize the default parameters for incident field parallelisation."""
<|body_0|>
def print(self, prefix=''):
"""Print all parameters."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_067548 | 14,301 | permissive | [
{
"docstring": "Initialize the default parameters for incident field parallelisation.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Print all parameters.",
"name": "print",
"signature": "def print(self, prefix='')"
}
] | 2 | null | Implement the Python class `IncidentFieldParallelProcessingParameters` described below.
Class description:
Implement the IncidentFieldParallelProcessingParameters class.
Method signatures and docstrings:
- def __init__(self): Initialize the default parameters for incident field parallelisation.
- def print(self, pref... | Implement the Python class `IncidentFieldParallelProcessingParameters` described below.
Class description:
Implement the IncidentFieldParallelProcessingParameters class.
Method signatures and docstrings:
- def __init__(self): Initialize the default parameters for incident field parallelisation.
- def print(self, pref... | f4428c8f131c91b70e8304da0c87001cd459bf35 | <|skeleton|>
class IncidentFieldParallelProcessingParameters:
def __init__(self):
"""Initialize the default parameters for incident field parallelisation."""
<|body_0|>
def print(self, prefix=''):
"""Print all parameters."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IncidentFieldParallelProcessingParameters:
def __init__(self):
"""Initialize the default parameters for incident field parallelisation."""
import multiprocessing as _mp
self.cpu_count = _mp.cpu_count()
self.mem_per_core = 110889500.0
self.parallelisation_method = 'numba... | the_stack_v2_python_sparse | optimus/utils/parameters.py | optimuslib/optimus | train | 11 | |
f84875aabf7d564856ea31d7185f06a578fa85c0 | [
"if hasattr(node, 'lights'):\n if hasattr(node, 'ambient'):\n a = node.ambient\n glLightModelfv(GL_LIGHT_MODEL_AMBIENT, [a, a, a, 1.0])\n IDs = [GL_LIGHT0, GL_LIGHT1, GL_LIGHT2, GL_LIGHT3, GL_LIGHT4, GL_LIGHT5, GL_LIGHT6, GL_LIGHT7]\n from OpenGLContext.scenegraph import light\n for direct... | <|body_start_0|>
if hasattr(node, 'lights'):
if hasattr(node, 'ambient'):
a = node.ambient
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, [a, a, a, 1.0])
IDs = [GL_LIGHT0, GL_LIGHT1, GL_LIGHT2, GL_LIGHT3, GL_LIGHT4, GL_LIGHT5, GL_LIGHT6, GL_LIGHT7]
fro... | Rendering-pass mix-in which is visual-aware | PassMixIn | [
"LicenseRef-scancode-warranty-disclaimer",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-copyleft",
"LGPL-2.1-or-later",
"GPL-3.0-only",
"LGPL-2.0-or-later",
"GPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PassMixIn:
"""Rendering-pass mix-in which is visual-aware"""
def SceneGraphLights(self, node):
"""Render lights for a scenegraph The default implementation limits you to eight active lights, despite the fact that many OpenGL renderers support more than this. There have been problems ... | stack_v2_sparse_classes_75kplus_train_067549 | 2,740 | permissive | [
{
"docstring": "Render lights for a scenegraph The default implementation limits you to eight active lights, despite the fact that many OpenGL renderers support more than this. There have been problems with support for calculating light IDs beyond eight, so I have limited the set for now. This method relies on ... | 2 | stack_v2_sparse_classes_30k_train_020144 | Implement the Python class `PassMixIn` described below.
Class description:
Rendering-pass mix-in which is visual-aware
Method signatures and docstrings:
- def SceneGraphLights(self, node): Render lights for a scenegraph The default implementation limits you to eight active lights, despite the fact that many OpenGL re... | Implement the Python class `PassMixIn` described below.
Class description:
Rendering-pass mix-in which is visual-aware
Method signatures and docstrings:
- def SceneGraphLights(self, node): Render lights for a scenegraph The default implementation limits you to eight active lights, despite the fact that many OpenGL re... | 7f600ad153270feff12aa7aa86d7ed0a49ebc71c | <|skeleton|>
class PassMixIn:
"""Rendering-pass mix-in which is visual-aware"""
def SceneGraphLights(self, node):
"""Render lights for a scenegraph The default implementation limits you to eight active lights, despite the fact that many OpenGL renderers support more than this. There have been problems ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PassMixIn:
"""Rendering-pass mix-in which is visual-aware"""
def SceneGraphLights(self, node):
"""Render lights for a scenegraph The default implementation limits you to eight active lights, despite the fact that many OpenGL renderers support more than this. There have been problems with support ... | the_stack_v2_python_sparse | pythonAnimations/pyOpenGLChess/engineDirectory/oglc-env/lib/python2.7/site-packages/OpenGLContext/browser/passes.py | alexus37/AugmentedRealityChess | train | 1 |
244f8e592bfd5e276aa73954a79542cea9d65a04 | [
"self._assignments = None\nself._num_classes = None\nself._assigned_classes = None",
"if num_classes is None:\n num_classes = np.unique(y).max() + 1\nself._num_classes = num_classes\nnum_outputs = X.shape[1]\nmax_fr = np.zeros(num_outputs)\nassignments = np.zeros(num_outputs)\nfor i in range(num_classes):\n ... | <|body_start_0|>
self._assignments = None
self._num_classes = None
self._assigned_classes = None
<|end_body_0|>
<|body_start_1|>
if num_classes is None:
num_classes = np.unique(y).max() + 1
self._num_classes = num_classes
num_outputs = X.shape[1]
max_... | A readout classifier that uses the highest response hypothesis to predict class labels from output firing rates. The mechanism is described in: 'Unsupervised learning of digit recognition using spike-timing-dependent plasticity', Diehl Peter, Cook Matthew, 2015 (10.3389/fncom.2015.00099) Attributes: | HighestResponse | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HighestResponse:
"""A readout classifier that uses the highest response hypothesis to predict class labels from output firing rates. The mechanism is described in: 'Unsupervised learning of digit recognition using spike-timing-dependent plasticity', Diehl Peter, Cook Matthew, 2015 (10.3389/fncom.... | stack_v2_sparse_classes_75kplus_train_067550 | 4,756 | permissive | [
{
"docstring": "Init empty classifier. Args: Returns:",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Train the model. Args: X: A numpy array of size num_samples x num_features. I.e., the training input. y: A numpy array of size num_samples. I.e., the ground truth labe... | 3 | stack_v2_sparse_classes_30k_train_018236 | Implement the Python class `HighestResponse` described below.
Class description:
A readout classifier that uses the highest response hypothesis to predict class labels from output firing rates. The mechanism is described in: 'Unsupervised learning of digit recognition using spike-timing-dependent plasticity', Diehl Pe... | Implement the Python class `HighestResponse` described below.
Class description:
A readout classifier that uses the highest response hypothesis to predict class labels from output firing rates. The mechanism is described in: 'Unsupervised learning of digit recognition using spike-timing-dependent plasticity', Diehl Pe... | 3ee4037a4568c393378eaec74483696d5281f376 | <|skeleton|>
class HighestResponse:
"""A readout classifier that uses the highest response hypothesis to predict class labels from output firing rates. The mechanism is described in: 'Unsupervised learning of digit recognition using spike-timing-dependent plasticity', Diehl Peter, Cook Matthew, 2015 (10.3389/fncom.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HighestResponse:
"""A readout classifier that uses the highest response hypothesis to predict class labels from output firing rates. The mechanism is described in: 'Unsupervised learning of digit recognition using spike-timing-dependent plasticity', Diehl Peter, Cook Matthew, 2015 (10.3389/fncom.2015.00099) A... | the_stack_v2_python_sparse | src/readout/highest_response.py | xiuxiuzhang1995/snn_global_pattern_induction | train | 0 |
4d7be19923471af86b84cb5846e86b47593db6ef | [
"self.model = ViewCls()\nif weight_path:\n self.model.load_weights(weight_path)\nself.labels = ['PA', 'Lateral', 'Others']",
"imgo = np.squeeze(sitk.GetArrayFromImage(sitk.ReadImage(path)))\nimg = cv2.resize(imgo, (512, 512), interpolation=cv2.INTER_LINEAR)\nimg = img.astype(np.float32)\nimg -= np.min(img)\nim... | <|body_start_0|>
self.model = ViewCls()
if weight_path:
self.model.load_weights(weight_path)
self.labels = ['PA', 'Lateral', 'Others']
<|end_body_0|>
<|body_start_1|>
imgo = np.squeeze(sitk.GetArrayFromImage(sitk.ReadImage(path)))
img = cv2.resize(imgo, (512, 512), i... | ViewpointClassifier | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ViewpointClassifier:
def __init__(self, weight_path: Optional[str]=None):
"""Classifying PA / Lateral / Others Args: (string) weight_path : pretrained weight path (optional)"""
<|body_0|>
def _preprocessing(self, path: str) -> Tuple[np.array, np.array]:
"""Args: (str... | stack_v2_sparse_classes_75kplus_train_067551 | 13,351 | permissive | [
{
"docstring": "Classifying PA / Lateral / Others Args: (string) weight_path : pretrained weight path (optional)",
"name": "__init__",
"signature": "def __init__(self, weight_path: Optional[str]=None)"
},
{
"docstring": "Args: (string) path : dicom path Return: (numpy ndarray) imgo : original im... | 3 | stack_v2_sparse_classes_30k_train_004221 | Implement the Python class `ViewpointClassifier` described below.
Class description:
Implement the ViewpointClassifier class.
Method signatures and docstrings:
- def __init__(self, weight_path: Optional[str]=None): Classifying PA / Lateral / Others Args: (string) weight_path : pretrained weight path (optional)
- def ... | Implement the Python class `ViewpointClassifier` described below.
Class description:
Implement the ViewpointClassifier class.
Method signatures and docstrings:
- def __init__(self, weight_path: Optional[str]=None): Classifying PA / Lateral / Others Args: (string) weight_path : pretrained weight path (optional)
- def ... | 158a74985074f95fcd6a345c310903936dd2adbe | <|skeleton|>
class ViewpointClassifier:
def __init__(self, weight_path: Optional[str]=None):
"""Classifying PA / Lateral / Others Args: (string) weight_path : pretrained weight path (optional)"""
<|body_0|>
def _preprocessing(self, path: str) -> Tuple[np.array, np.array]:
"""Args: (str... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ViewpointClassifier:
def __init__(self, weight_path: Optional[str]=None):
"""Classifying PA / Lateral / Others Args: (string) weight_path : pretrained weight path (optional)"""
self.model = ViewCls()
if weight_path:
self.model.load_weights(weight_path)
self.labels =... | the_stack_v2_python_sparse | medimodule/Chest/module.py | mi2rl/MI2RLNet | train | 13 | |
180512de77ba3d71f5d3d0b9d050da4b262fc6c2 | [
"if cls.instance is None:\n obj = super(CCP, cls).__new__(cls)\n obj.rest = REST(serverIP, serverPort, softVersion)\n obj.rest.setAccount(accountSid, accountToken)\n obj.rest.setAppId(appId)\n cls.instance = obj\nreturn cls.instance",
"result = self.rest.sendTemplateSMS(to, datas, temp_id)\nstatus_... | <|body_start_0|>
if cls.instance is None:
obj = super(CCP, cls).__new__(cls)
obj.rest = REST(serverIP, serverPort, softVersion)
obj.rest.setAccount(accountSid, accountToken)
obj.rest.setAppId(appId)
cls.instance = obj
return cls.instance
<|end_... | ԼװͶŵĸ | CCP | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CCP:
"""ԼװͶŵĸ"""
def __new__(cls):
"""ԭRESTĴһΣֱ֮ӷ"""
<|body_0|>
def send_template_sms(self, to, datas, temp_id):
"""Ͷ"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if cls.instance is None:
obj = super(CCP, cls).__new__(cls)
... | stack_v2_sparse_classes_75kplus_train_067552 | 2,050 | no_license | [
{
"docstring": "ԭRESTĴһΣֱ֮ӷ",
"name": "__new__",
"signature": "def __new__(cls)"
},
{
"docstring": "Ͷ",
"name": "send_template_sms",
"signature": "def send_template_sms(self, to, datas, temp_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003046 | Implement the Python class `CCP` described below.
Class description:
ԼװͶŵĸ
Method signatures and docstrings:
- def __new__(cls): ԭRESTĴһΣֱ֮ӷ
- def send_template_sms(self, to, datas, temp_id): Ͷ | Implement the Python class `CCP` described below.
Class description:
ԼװͶŵĸ
Method signatures and docstrings:
- def __new__(cls): ԭRESTĴһΣֱ֮ӷ
- def send_template_sms(self, to, datas, temp_id): Ͷ
<|skeleton|>
class CCP:
"""ԼװͶŵĸ"""
def __new__(cls):
"""ԭRESTĴһΣֱ֮ӷ"""
<|body_0|>
def send_t... | 779c7a1a98e4dcb271d600f67297e8eb11f50c40 | <|skeleton|>
class CCP:
"""ԼװͶŵĸ"""
def __new__(cls):
"""ԭRESTĴһΣֱ֮ӷ"""
<|body_0|>
def send_template_sms(self, to, datas, temp_id):
"""Ͷ"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CCP:
"""ԼװͶŵĸ"""
def __new__(cls):
"""ԭRESTĴһΣֱ֮ӷ"""
if cls.instance is None:
obj = super(CCP, cls).__new__(cls)
obj.rest = REST(serverIP, serverPort, softVersion)
obj.rest.setAccount(accountSid, accountToken)
obj.rest.setAppId(appId)
... | the_stack_v2_python_sparse | ihome/libs/yuntongxun/sms.py | CHyuye/iHome | train | 0 |
2204969031f66f48eea7643de0824395bf19ef04 | [
"Drawable.__init__(self, RIDE_SPRITE)\nself.start, self.end = (start, end)\nself.start_time, self.end_time = (times[0], times[1])",
"if time == self.start_time:\n return (self.start.get_position(time)[0], self.start.get_position(time)[1])\nelif time == self.end_time:\n return (self.end.get_position(time)[0]... | <|body_start_0|>
Drawable.__init__(self, RIDE_SPRITE)
self.start, self.end = (start, end)
self.start_time, self.end_time = (times[0], times[1])
<|end_body_0|>
<|body_start_1|>
if time == self.start_time:
return (self.start.get_position(time)[0], self.start.get_position(time)... | A ride using a Bixi bike. === Attributes === start: the station where this ride starts end: the station where this ride ends start_time: the time this ride starts end_time: the time this ride ends === Representation Invariants === - start_time < end_time - start_time - end_time >= timedelta(minutes = 1) (that is the sh... | Ride | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ride:
"""A ride using a Bixi bike. === Attributes === start: the station where this ride starts end: the station where this ride ends start_time: the time this ride starts end_time: the time this ride ends === Representation Invariants === - start_time < end_time - start_time - end_time >= timede... | stack_v2_sparse_classes_75kplus_train_067553 | 6,235 | no_license | [
{
"docstring": "Initialize a ride object with the given start and end information.",
"name": "__init__",
"signature": "def __init__(self, start: Station, end: Station, times: Tuple[datetime, datetime]) -> None"
},
{
"docstring": "Return the (long, lat) position of this ride for the given time. A... | 2 | stack_v2_sparse_classes_30k_train_042739 | Implement the Python class `Ride` described below.
Class description:
A ride using a Bixi bike. === Attributes === start: the station where this ride starts end: the station where this ride ends start_time: the time this ride starts end_time: the time this ride ends === Representation Invariants === - start_time < end... | Implement the Python class `Ride` described below.
Class description:
A ride using a Bixi bike. === Attributes === start: the station where this ride starts end: the station where this ride ends start_time: the time this ride starts end_time: the time this ride ends === Representation Invariants === - start_time < end... | ce720ce6a151c8bdf355096d9e86e421121a4793 | <|skeleton|>
class Ride:
"""A ride using a Bixi bike. === Attributes === start: the station where this ride starts end: the station where this ride ends start_time: the time this ride starts end_time: the time this ride ends === Representation Invariants === - start_time < end_time - start_time - end_time >= timede... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Ride:
"""A ride using a Bixi bike. === Attributes === start: the station where this ride starts end: the station where this ride ends start_time: the time this ride starts end_time: the time this ride ends === Representation Invariants === - start_time < end_time - start_time - end_time >= timedelta(minutes =... | the_stack_v2_python_sparse | assignments/a1/bikeshare.py | ousmane-amadou/csc148-work | train | 2 |
993b3e3652dc7eebbb9ce2ace77f83b1b4caed27 | [
"try:\n if not data['project_id'] or not data['ids'] or (not data['apiGroupLevelFirst_id']):\n return JsonResponse(code='999996', msg='参数有误!')\n if not isinstance(data['project_id'], int) or not isinstance(data['ids'], list) or (not isinstance(data['apiGroupLevelFirst_id'], int)):\n return JsonR... | <|body_start_0|>
try:
if not data['project_id'] or not data['ids'] or (not data['apiGroupLevelFirst_id']):
return JsonResponse(code='999996', msg='参数有误!')
if not isinstance(data['project_id'], int) or not isinstance(data['ids'], list) or (not isinstance(data['apiGroupLeve... | UpdateGroup | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateGroup:
def parameter_check(self, data):
"""校验参数 :param data: :return:"""
<|body_0|>
def post(self, request):
"""修改接口所属分组 :param request: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
if not data['project_id'] or not... | stack_v2_sparse_classes_75kplus_train_067554 | 47,841 | permissive | [
{
"docstring": "校验参数 :param data: :return:",
"name": "parameter_check",
"signature": "def parameter_check(self, data)"
},
{
"docstring": "修改接口所属分组 :param request: :return:",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_039274 | Implement the Python class `UpdateGroup` described below.
Class description:
Implement the UpdateGroup class.
Method signatures and docstrings:
- def parameter_check(self, data): 校验参数 :param data: :return:
- def post(self, request): 修改接口所属分组 :param request: :return: | Implement the Python class `UpdateGroup` described below.
Class description:
Implement the UpdateGroup class.
Method signatures and docstrings:
- def parameter_check(self, data): 校验参数 :param data: :return:
- def post(self, request): 修改接口所属分组 :param request: :return:
<|skeleton|>
class UpdateGroup:
def parameter... | 6d08f58fa6985415ef7beae733e6f8147026806e | <|skeleton|>
class UpdateGroup:
def parameter_check(self, data):
"""校验参数 :param data: :return:"""
<|body_0|>
def post(self, request):
"""修改接口所属分组 :param request: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UpdateGroup:
def parameter_check(self, data):
"""校验参数 :param data: :return:"""
try:
if not data['project_id'] or not data['ids'] or (not data['apiGroupLevelFirst_id']):
return JsonResponse(code='999996', msg='参数有误!')
if not isinstance(data['project_id'],... | the_stack_v2_python_sparse | api_test/api/ApiDoc.py | yourant/tapi | train | 0 | |
ff8c898672da529c3c6791353f891404bc48dcfc | [
"if span_context.trace_id is None or span_context.span_id is None:\n log.debug('tried to inject invalid context %r', span_context)\n return\nif PROPAGATION_STYLE_DATADOG in config._propagation_style_inject:\n _DatadogMultiHeader._inject(span_context, headers)\nif PROPAGATION_STYLE_B3 in config._propagation... | <|body_start_0|>
if span_context.trace_id is None or span_context.span_id is None:
log.debug('tried to inject invalid context %r', span_context)
return
if PROPAGATION_STYLE_DATADOG in config._propagation_style_inject:
_DatadogMultiHeader._inject(span_context, headers)... | A HTTP Propagator using HTTP headers as carrier. | HTTPPropagator | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HTTPPropagator:
"""A HTTP Propagator using HTTP headers as carrier."""
def inject(span_context, headers):
"""Inject Context attributes that have to be propagated as HTTP headers. Here is an example using `requests`:: import requests from ddtrace.propagation.http import HTTPPropagator... | stack_v2_sparse_classes_75kplus_train_067555 | 35,485 | permissive | [
{
"docstring": "Inject Context attributes that have to be propagated as HTTP headers. Here is an example using `requests`:: import requests from ddtrace.propagation.http import HTTPPropagator def parent_call(): with tracer.trace('parent_span') as span: headers = {} HTTPPropagator.inject(span.context, headers) u... | 2 | stack_v2_sparse_classes_30k_train_052870 | Implement the Python class `HTTPPropagator` described below.
Class description:
A HTTP Propagator using HTTP headers as carrier.
Method signatures and docstrings:
- def inject(span_context, headers): Inject Context attributes that have to be propagated as HTTP headers. Here is an example using `requests`:: import req... | Implement the Python class `HTTPPropagator` described below.
Class description:
A HTTP Propagator using HTTP headers as carrier.
Method signatures and docstrings:
- def inject(span_context, headers): Inject Context attributes that have to be propagated as HTTP headers. Here is an example using `requests`:: import req... | 1e3bd6d4edef5cda5a0831a6a7ec8e4046659d17 | <|skeleton|>
class HTTPPropagator:
"""A HTTP Propagator using HTTP headers as carrier."""
def inject(span_context, headers):
"""Inject Context attributes that have to be propagated as HTTP headers. Here is an example using `requests`:: import requests from ddtrace.propagation.http import HTTPPropagator... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HTTPPropagator:
"""A HTTP Propagator using HTTP headers as carrier."""
def inject(span_context, headers):
"""Inject Context attributes that have to be propagated as HTTP headers. Here is an example using `requests`:: import requests from ddtrace.propagation.http import HTTPPropagator def parent_c... | the_stack_v2_python_sparse | ddtrace/propagation/http.py | DataDog/dd-trace-py | train | 461 |
e0588408c4de162b1a03284a0b325f5a42715aee | [
"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!')"
] | <|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... | Missing associated documentation comment in .proto file. | OauthCredentialsServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OauthCredentialsServicer:
"""Missing associated documentation comment in .proto file."""
def GetCredentials(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def SaveCredentials(self, request, context):
"""Missing ... | stack_v2_sparse_classes_75kplus_train_067556 | 4,254 | no_license | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "GetCredentials",
"signature": "def GetCredentials(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "SaveCredentials",
"signature": "def SaveCr... | 2 | stack_v2_sparse_classes_30k_val_001035 | Implement the Python class `OauthCredentialsServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def GetCredentials(self, request, context): Missing associated documentation comment in .proto file.
- def SaveCredentials(self, reques... | Implement the Python class `OauthCredentialsServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def GetCredentials(self, request, context): Missing associated documentation comment in .proto file.
- def SaveCredentials(self, reques... | a4e4283fc0040fc500ec6d71d078ddfff9b4be60 | <|skeleton|>
class OauthCredentialsServicer:
"""Missing associated documentation comment in .proto file."""
def GetCredentials(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def SaveCredentials(self, request, context):
"""Missing ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OauthCredentialsServicer:
"""Missing associated documentation comment in .proto file."""
def GetCredentials(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not imple... | the_stack_v2_python_sparse | gcp/viet-soccer/youtube-upload/credential_pb2_grpc.py | p-le/multi-cloud-app | train | 0 |
4c6fa7825d74acc2ea9ca5a0f38d6276453987ca | [
"self.params = {}\nself.reg = reg\nself.params['W1'] = weight_scale * np.random.randn(input_dim, hidden_dim)\nself.params['W2'] = weight_scale * np.random.randn(hidden_dim, num_classes)\nself.params['b1'] = np.zeros(hidden_dim)\nself.params['b2'] = np.zeros(num_classes)",
"scores = None\nW1 = self.params['W1']\nW... | <|body_start_0|>
self.params = {}
self.reg = reg
self.params['W1'] = weight_scale * np.random.randn(input_dim, hidden_dim)
self.params['W2'] = weight_scale * np.random.randn(hidden_dim, num_classes)
self.params['b1'] = np.zeros(hidden_dim)
self.params['b2'] = np.zeros(num... | A two-layer fully-connected neural network with ReLU nonlinearity and softmax loss that uses a modular layer design. We assume an input dimension of D, a hidden dimension of H, and perform classification over C classes. The architecure should be affine - relu - affine - softmax. Note that this class does not implement ... | TwoLayerNet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwoLayerNet:
"""A two-layer fully-connected neural network with ReLU nonlinearity and softmax loss that uses a modular layer design. We assume an input dimension of D, a hidden dimension of H, and perform classification over C classes. The architecure should be affine - relu - affine - softmax. N... | stack_v2_sparse_classes_75kplus_train_067557 | 27,147 | permissive | [
{
"docstring": "Initialize a new network. Inputs: - input_dim: An integer giving the size of the input - hidden_dim: An integer giving the size of the hidden layer - num_classes: An integer giving the number of classes to classify - weight_scale: Scalar giving the standard deviation for random initialization of... | 2 | stack_v2_sparse_classes_30k_val_000174 | Implement the Python class `TwoLayerNet` described below.
Class description:
A two-layer fully-connected neural network with ReLU nonlinearity and softmax loss that uses a modular layer design. We assume an input dimension of D, a hidden dimension of H, and perform classification over C classes. The architecure should... | Implement the Python class `TwoLayerNet` described below.
Class description:
A two-layer fully-connected neural network with ReLU nonlinearity and softmax loss that uses a modular layer design. We assume an input dimension of D, a hidden dimension of H, and perform classification over C classes. The architecure should... | 930ef4168ffbddbb5e81a782ba1328077a4f2525 | <|skeleton|>
class TwoLayerNet:
"""A two-layer fully-connected neural network with ReLU nonlinearity and softmax loss that uses a modular layer design. We assume an input dimension of D, a hidden dimension of H, and perform classification over C classes. The architecure should be affine - relu - affine - softmax. N... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TwoLayerNet:
"""A two-layer fully-connected neural network with ReLU nonlinearity and softmax loss that uses a modular layer design. We assume an input dimension of D, a hidden dimension of H, and perform classification over C classes. The architecure should be affine - relu - affine - softmax. Note that this... | the_stack_v2_python_sparse | practice5/fc_net.py | enliktjioe/nn2020 | train | 0 |
31d65fcd7da6bc1410e551274af92dd77be12504 | [
"if not v.exists():\n raise ValueError(f'Path object not found in filesystem : {v}')\nreturn v",
"configs = [c.config for c in values.get('configs')]\nfor test in values.get('tests'):\n if test.config not in configs:\n raise ValueError(f\"Test '{test.test}' gave the config '{test.config}', but this c... | <|body_start_0|>
if not v.exists():
raise ValueError(f'Path object not found in filesystem : {v}')
return v
<|end_body_0|>
<|body_start_1|>
configs = [c.config for c in values.get('configs')]
for test in values.get('tests'):
if test.config not in configs:
... | Represent the schema for the <directed-tests>.yaml file. The file on-disk should be of the form... - A flat list of both DConfig and DTest items - Each DTest must specify an existing DConfig item with the key 'config' Note that on-disk representation of this file is slightly-different to the validation schema defined h... | DirectedTestsYaml | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DirectedTestsYaml:
"""Represent the schema for the <directed-tests>.yaml file. The file on-disk should be of the form... - A flat list of both DConfig and DTest items - Each DTest must specify an existing DConfig item with the key 'config' Note that on-disk representation of this file is slightly... | stack_v2_sparse_classes_75kplus_train_067558 | 7,812 | permissive | [
{
"docstring": "Check that the yaml file exists on disk. This field needs its own validator, as other files are checked relative to the yaml file.",
"name": "yaml_file_must_exist",
"signature": "def yaml_file_must_exist(cls, v: pathlib.Path)"
},
{
"docstring": "Check that if a test specifies a c... | 3 | stack_v2_sparse_classes_30k_train_029555 | Implement the Python class `DirectedTestsYaml` described below.
Class description:
Represent the schema for the <directed-tests>.yaml file. The file on-disk should be of the form... - A flat list of both DConfig and DTest items - Each DTest must specify an existing DConfig item with the key 'config' Note that on-disk ... | Implement the Python class `DirectedTestsYaml` described below.
Class description:
Represent the schema for the <directed-tests>.yaml file. The file on-disk should be of the form... - A flat list of both DConfig and DTest items - Each DTest must specify an existing DConfig item with the key 'config' Note that on-disk ... | 51f6017b8425b14d5a4aa9abace8fe5a25ef08c8 | <|skeleton|>
class DirectedTestsYaml:
"""Represent the schema for the <directed-tests>.yaml file. The file on-disk should be of the form... - A flat list of both DConfig and DTest items - Each DTest must specify an existing DConfig item with the key 'config' Note that on-disk representation of this file is slightly... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DirectedTestsYaml:
"""Represent the schema for the <directed-tests>.yaml file. The file on-disk should be of the form... - A flat list of both DConfig and DTest items - Each DTest must specify an existing DConfig item with the key 'config' Note that on-disk representation of this file is slightly-different to... | the_stack_v2_python_sparse | hw/vendor/lowrisc_ibex/dv/uvm/core_ibex/scripts/directed_test_schema.py | lowRISC/opentitan | train | 2,077 |
fd6a25be8769a87cba91ef545ca2d0b044f5070c | [
"current_user = request.user\nform = self.form_class(instance=current_user)\nreturn render(request, self.template_name, {'form': form})",
"form = self.form_class(request.POST, instance=request.user)\nif form.is_valid():\n form.save()\n return redirect('profile')\nreturn render(request, self.template_name, {... | <|body_start_0|>
current_user = request.user
form = self.form_class(instance=current_user)
return render(request, self.template_name, {'form': form})
<|end_body_0|>
<|body_start_1|>
form = self.form_class(request.POST, instance=request.user)
if form.is_valid():
form.... | The class view for changing user data | EditUserView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EditUserView:
"""The class view for changing user data"""
def get(self, request):
"""Display user data edit form. :param request: request object :return: user data edit form view :rtype: HttpResponse"""
<|body_0|>
def post(self, request):
"""Save changes to user ... | stack_v2_sparse_classes_75kplus_train_067559 | 34,014 | no_license | [
{
"docstring": "Display user data edit form. :param request: request object :return: user data edit form view :rtype: HttpResponse",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Save changes to user data. :param request: request object :return: user profile page view (... | 2 | null | Implement the Python class `EditUserView` described below.
Class description:
The class view for changing user data
Method signatures and docstrings:
- def get(self, request): Display user data edit form. :param request: request object :return: user data edit form view :rtype: HttpResponse
- def post(self, request): ... | Implement the Python class `EditUserView` described below.
Class description:
The class view for changing user data
Method signatures and docstrings:
- def get(self, request): Display user data edit form. :param request: request object :return: user data edit form view :rtype: HttpResponse
- def post(self, request): ... | b6100d4082c197bc7b40bac27a9b8f07f8efcd84 | <|skeleton|>
class EditUserView:
"""The class view for changing user data"""
def get(self, request):
"""Display user data edit form. :param request: request object :return: user data edit form view :rtype: HttpResponse"""
<|body_0|>
def post(self, request):
"""Save changes to user ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EditUserView:
"""The class view for changing user data"""
def get(self, request):
"""Display user data edit form. :param request: request object :return: user data edit form view :rtype: HttpResponse"""
current_user = request.user
form = self.form_class(instance=current_user)
... | the_stack_v2_python_sparse | RunScheduleApp/views.py | Gribek/RunSchedules | train | 0 |
7b5b202f5fb9b5bb65200cce885a715e89577958 | [
"qs = self\nif start_year:\n qs = qs.filter(date__year__gte=start_year)\nif end_year:\n qs = qs.filter(date__year__lte=end_year)\nreturn qs",
"qs: 'SearchableModelQuerySet' = self\nsearchable_fields = qs.model.get_searchable_fields()\nif query and searchable_fields:\n search_query = SearchQuery(query)\n ... | <|body_start_0|>
qs = self
if start_year:
qs = qs.filter(date__year__gte=start_year)
if end_year:
qs = qs.filter(date__year__lte=end_year)
return qs
<|end_body_0|>
<|body_start_1|>
qs: 'SearchableModelQuerySet' = self
searchable_fields = qs.model.... | A queryset for a searchable model. | SearchableModelQuerySet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchableModelQuerySet:
"""A queryset for a searchable model."""
def filter_by_date(self, start_year: Optional[int]=None, end_year: Optional[int]=None) -> 'SearchableModelQuerySet':
"""Return a queryset filtered by start_year and/or end_year."""
<|body_0|>
def search(se... | stack_v2_sparse_classes_75kplus_train_067560 | 3,091 | no_license | [
{
"docstring": "Return a queryset filtered by start_year and/or end_year.",
"name": "filter_by_date",
"signature": "def filter_by_date(self, start_year: Optional[int]=None, end_year: Optional[int]=None) -> 'SearchableModelQuerySet'"
},
{
"docstring": "Return search results from apps.occurrences.... | 2 | stack_v2_sparse_classes_30k_train_046486 | Implement the Python class `SearchableModelQuerySet` described below.
Class description:
A queryset for a searchable model.
Method signatures and docstrings:
- def filter_by_date(self, start_year: Optional[int]=None, end_year: Optional[int]=None) -> 'SearchableModelQuerySet': Return a queryset filtered by start_year ... | Implement the Python class `SearchableModelQuerySet` described below.
Class description:
A queryset for a searchable model.
Method signatures and docstrings:
- def filter_by_date(self, start_year: Optional[int]=None, end_year: Optional[int]=None) -> 'SearchableModelQuerySet': Return a queryset filtered by start_year ... | edea4e5b0c382c604db2c3fbb58dc73e57de8431 | <|skeleton|>
class SearchableModelQuerySet:
"""A queryset for a searchable model."""
def filter_by_date(self, start_year: Optional[int]=None, end_year: Optional[int]=None) -> 'SearchableModelQuerySet':
"""Return a queryset filtered by start_year and/or end_year."""
<|body_0|>
def search(se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SearchableModelQuerySet:
"""A queryset for a searchable model."""
def filter_by_date(self, start_year: Optional[int]=None, end_year: Optional[int]=None) -> 'SearchableModelQuerySet':
"""Return a queryset filtered by start_year and/or end_year."""
qs = self
if start_year:
... | the_stack_v2_python_sparse | apps/search/models/manager.py | RealGuy69/modularhistory | train | 0 |
68c3bd1d989c1684e8690c999118cfaed097ec86 | [
"user_id = request.GET.get('user_id', -1)\nfriend = request.POST['newFriend']\nuser_obj = User.objects.get(id=user_id)\nfriend_obj = User.objects.get(username=friend)\nFriends.objects.create(user_one=user_obj, user_two=friend_obj, created_on=datetime.now())\nFriends.objects.create(user_one=friend_obj, user_two=user... | <|body_start_0|>
user_id = request.GET.get('user_id', -1)
friend = request.POST['newFriend']
user_obj = User.objects.get(id=user_id)
friend_obj = User.objects.get(username=friend)
Friends.objects.create(user_one=user_obj, user_two=friend_obj, created_on=datetime.now())
Fr... | Process_Friend | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Process_Friend:
def add_friend(self, request):
"""Creates friend relationship. Creates the 2 way friend relationship in the database. Removes the pending friend request from the database @param request: @param user_id: User id of displayed profile. :todo: None"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_067561 | 10,004 | no_license | [
{
"docstring": "Creates friend relationship. Creates the 2 way friend relationship in the database. Removes the pending friend request from the database @param request: @param user_id: User id of displayed profile. :todo: None",
"name": "add_friend",
"signature": "def add_friend(self, request)"
},
{... | 2 | null | Implement the Python class `Process_Friend` described below.
Class description:
Implement the Process_Friend class.
Method signatures and docstrings:
- def add_friend(self, request): Creates friend relationship. Creates the 2 way friend relationship in the database. Removes the pending friend request from the databas... | Implement the Python class `Process_Friend` described below.
Class description:
Implement the Process_Friend class.
Method signatures and docstrings:
- def add_friend(self, request): Creates friend relationship. Creates the 2 way friend relationship in the database. Removes the pending friend request from the databas... | 7c111ad800588cf200b9b6d8e5a815ebce4047b1 | <|skeleton|>
class Process_Friend:
def add_friend(self, request):
"""Creates friend relationship. Creates the 2 way friend relationship in the database. Removes the pending friend request from the database @param request: @param user_id: User id of displayed profile. :todo: None"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Process_Friend:
def add_friend(self, request):
"""Creates friend relationship. Creates the 2 way friend relationship in the database. Removes the pending friend request from the database @param request: @param user_id: User id of displayed profile. :todo: None"""
user_id = request.GET.get('use... | the_stack_v2_python_sparse | content/Nenniltoz/Users/Views/Friends.py | DustinWPernell/AppStateCapstone | train | 2 | |
e4780a92ff8e7c6ac3b0e4f606d4d0a7981155d2 | [
"s_len = len(s)\nfor window in windows:\n d_min = float('inf')\n d_norm_min = float('inf')\n minIndex = -1\n if s_len < window.endIndex * segmentLength:\n raise SeriesIsNotLongEnough()\n subseries = s[window.startIndex * segmentLength:window.endIndex * segmentLength]\n for i in range(0, len... | <|body_start_0|>
s_len = len(s)
for window in windows:
d_min = float('inf')
d_norm_min = float('inf')
minIndex = -1
if s_len < window.endIndex * segmentLength:
raise SeriesIsNotLongEnough()
subseries = s[window.startIndex * segm... | DynamicClustering | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DynamicClustering:
def dynamicClustering(s, windows, ts_id, segmentLength):
"""@description : when a series come, cut it to windows and assign each subseries to closest cluster. --------- @param : s -- coming series windows -- current windows with clustered timeseries ts_id -- the number... | stack_v2_sparse_classes_75kplus_train_067562 | 3,972 | no_license | [
{
"docstring": "@description : when a series come, cut it to windows and assign each subseries to closest cluster. --------- @param : s -- coming series windows -- current windows with clustered timeseries ts_id -- the number of coming timeseries segmentLength -- the length of segment set before ------- @Return... | 2 | stack_v2_sparse_classes_30k_train_001268 | Implement the Python class `DynamicClustering` described below.
Class description:
Implement the DynamicClustering class.
Method signatures and docstrings:
- def dynamicClustering(s, windows, ts_id, segmentLength): @description : when a series come, cut it to windows and assign each subseries to closest cluster. ----... | Implement the Python class `DynamicClustering` described below.
Class description:
Implement the DynamicClustering class.
Method signatures and docstrings:
- def dynamicClustering(s, windows, ts_id, segmentLength): @description : when a series come, cut it to windows and assign each subseries to closest cluster. ----... | 2693ce7a39e52973009312fcf508cabe6dcacd90 | <|skeleton|>
class DynamicClustering:
def dynamicClustering(s, windows, ts_id, segmentLength):
"""@description : when a series come, cut it to windows and assign each subseries to closest cluster. --------- @param : s -- coming series windows -- current windows with clustered timeseries ts_id -- the number... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DynamicClustering:
def dynamicClustering(s, windows, ts_id, segmentLength):
"""@description : when a series come, cut it to windows and assign each subseries to closest cluster. --------- @param : s -- coming series windows -- current windows with clustered timeseries ts_id -- the number of coming tim... | the_stack_v2_python_sparse | SLADE-MTS/_dynamic_clustering.py | ZJU-research/MTS-anomaly-detection | train | 5 | |
660e8c3008156b24758079d3954032cbafaf2d3c | [
"create_count = 0\nnext(csvreader)\nfor row in csvreader:\n ci, created = CoinifyInvoice.objects.get_or_create(coinify_id=row[0], coinify_id_alpha=row[1], coinify_created=timezone.make_aware(datetime.strptime(row[2], '%Y-%m-%d %H:%M:%S'), timezone=timezone.utc), payment_amount=Decimal(row[3]), payment_currency=r... | <|body_start_0|>
create_count = 0
next(csvreader)
for row in csvreader:
ci, created = CoinifyInvoice.objects.get_or_create(coinify_id=row[0], coinify_id_alpha=row[1], coinify_created=timezone.make_aware(datetime.strptime(row[2], '%Y-%m-%d %H:%M:%S'), timezone=timezone.utc), payment_a... | CoinifyCSVImporter | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CoinifyCSVImporter:
def import_coinify_invoice_csv(csvreader):
"""Import a CSV file with Coinify invoices exported from their webinterface. Assumes a CSV structure like this: id,id_alpha,created,payment_amount,payment_currency,payment_btc_amount,description,custom,credited_amount,credite... | stack_v2_sparse_classes_75kplus_train_067563 | 47,704 | permissive | [
{
"docstring": "Import a CSV file with Coinify invoices exported from their webinterface. Assumes a CSV structure like this: id,id_alpha,created,payment_amount,payment_currency,payment_btc_amount,description,custom,credited_amount,credited_currency,state,payment_type,original_payment_id 54276,sdJGd,\"2020-02-06... | 3 | stack_v2_sparse_classes_30k_train_040051 | Implement the Python class `CoinifyCSVImporter` described below.
Class description:
Implement the CoinifyCSVImporter class.
Method signatures and docstrings:
- def import_coinify_invoice_csv(csvreader): Import a CSV file with Coinify invoices exported from their webinterface. Assumes a CSV structure like this: id,id_... | Implement the Python class `CoinifyCSVImporter` described below.
Class description:
Implement the CoinifyCSVImporter class.
Method signatures and docstrings:
- def import_coinify_invoice_csv(csvreader): Import a CSV file with Coinify invoices exported from their webinterface. Assumes a CSV structure like this: id,id_... | 767deb7f58429e9162e0c2ef79be9f0f38f37ce1 | <|skeleton|>
class CoinifyCSVImporter:
def import_coinify_invoice_csv(csvreader):
"""Import a CSV file with Coinify invoices exported from their webinterface. Assumes a CSV structure like this: id,id_alpha,created,payment_amount,payment_currency,payment_btc_amount,description,custom,credited_amount,credite... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CoinifyCSVImporter:
def import_coinify_invoice_csv(csvreader):
"""Import a CSV file with Coinify invoices exported from their webinterface. Assumes a CSV structure like this: id,id_alpha,created,payment_amount,payment_currency,payment_btc_amount,description,custom,credited_amount,credited_currency,sta... | the_stack_v2_python_sparse | src/economy/utils.py | bornhack/bornhack-website | train | 9 | |
17af770d19b13bf3966e0867d49c3280d13c0059 | [
"try:\n code = pickle.dumps(activity_compile)\n obj = AES.new(AES_KEY, AES.MODE_ECB)\n code = code + '=' * (16 - len(code) % 16)\n code = obj.encrypt(code)\n code = base64.urlsafe_b64encode(code)\n return code\nexcept Exception as e:\n logging.error('encrypt_activity_compile_to_code error')\n ... | <|body_start_0|>
try:
code = pickle.dumps(activity_compile)
obj = AES.new(AES_KEY, AES.MODE_ECB)
code = code + '=' * (16 - len(code) % 16)
code = obj.encrypt(code)
code = base64.urlsafe_b64encode(code)
return code
except Exception a... | ActivityCompile | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActivityCompile:
def encrypt_activity_compile_to_code(activity_compile):
"""deprecated later"""
<|body_0|>
def decrypt_code_to_activity_compile(code):
"""deprecated later"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
code = pickle... | stack_v2_sparse_classes_75kplus_train_067564 | 1,840 | no_license | [
{
"docstring": "deprecated later",
"name": "encrypt_activity_compile_to_code",
"signature": "def encrypt_activity_compile_to_code(activity_compile)"
},
{
"docstring": "deprecated later",
"name": "decrypt_code_to_activity_compile",
"signature": "def decrypt_code_to_activity_compile(code)"... | 2 | stack_v2_sparse_classes_30k_train_016822 | Implement the Python class `ActivityCompile` described below.
Class description:
Implement the ActivityCompile class.
Method signatures and docstrings:
- def encrypt_activity_compile_to_code(activity_compile): deprecated later
- def decrypt_code_to_activity_compile(code): deprecated later | Implement the Python class `ActivityCompile` described below.
Class description:
Implement the ActivityCompile class.
Method signatures and docstrings:
- def encrypt_activity_compile_to_code(activity_compile): deprecated later
- def decrypt_code_to_activity_compile(code): deprecated later
<|skeleton|>
class Activity... | 0cd69ba5bf3c962c491fb7a814539929112def8f | <|skeleton|>
class ActivityCompile:
def encrypt_activity_compile_to_code(activity_compile):
"""deprecated later"""
<|body_0|>
def decrypt_code_to_activity_compile(code):
"""deprecated later"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ActivityCompile:
def encrypt_activity_compile_to_code(activity_compile):
"""deprecated later"""
try:
code = pickle.dumps(activity_compile)
obj = AES.new(AES_KEY, AES.MODE_ECB)
code = code + '=' * (16 - len(code) % 16)
code = obj.encrypt(code)
... | the_stack_v2_python_sparse | app/models/activity_compile.py | flyakite/tracker | train | 0 | |
47d1483522ca5036f858a1908a782bc91aa52bb9 | [
"lmethod = _method_or_default_lmethod(lmethod)\nsuper().__init__(species=species, method=lmethod, keywords=lmethod.keywords.grad, do_c_diff=False, shift=shift, n_cores=n_cores)\nif not set(idxs).issubset(set(range(species.n_atoms))):\n raise ValueError('Cannot calculate a partial numerical Hessian at least one a... | <|body_start_0|>
lmethod = _method_or_default_lmethod(lmethod)
super().__init__(species=species, method=lmethod, keywords=lmethod.keywords.grad, do_c_diff=False, shift=shift, n_cores=n_cores)
if not set(idxs).issubset(set(range(species.n_atoms))):
raise ValueError('Cannot calculate a... | Calculator for a numerical Hessian evaluated at two levels of theory. One fast low level method to generate an estimate of the full Hessian, then one slow method used to evaluate numerical derivatives for only a few atoms. For example, .. code-block:: Python >>> import autode as ade >>> >>> water = ade.Molecule(smiles=... | HybridHessianCalculator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HybridHessianCalculator:
"""Calculator for a numerical Hessian evaluated at two levels of theory. One fast low level method to generate an estimate of the full Hessian, then one slow method used to evaluate numerical derivatives for only a few atoms. For example, .. code-block:: Python >>> import... | stack_v2_sparse_classes_75kplus_train_067565 | 23,318 | permissive | [
{
"docstring": "Initialise a two-level numerical Hessian calculation using a low-level method (lmethod) and a high-level method (hmethod) for only some atoms, with indexes (idxs) ----------------------------------------------------------------------- Arguments: species: Species to evaluate the Hessian for idxs:... | 3 | stack_v2_sparse_classes_30k_train_018212 | Implement the Python class `HybridHessianCalculator` described below.
Class description:
Calculator for a numerical Hessian evaluated at two levels of theory. One fast low level method to generate an estimate of the full Hessian, then one slow method used to evaluate numerical derivatives for only a few atoms. For exa... | Implement the Python class `HybridHessianCalculator` described below.
Class description:
Calculator for a numerical Hessian evaluated at two levels of theory. One fast low level method to generate an estimate of the full Hessian, then one slow method used to evaluate numerical derivatives for only a few atoms. For exa... | 4d6667592f083dfcf38de6b75c4222c0a0e7b60b | <|skeleton|>
class HybridHessianCalculator:
"""Calculator for a numerical Hessian evaluated at two levels of theory. One fast low level method to generate an estimate of the full Hessian, then one slow method used to evaluate numerical derivatives for only a few atoms. For example, .. code-block:: Python >>> import... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HybridHessianCalculator:
"""Calculator for a numerical Hessian evaluated at two levels of theory. One fast low level method to generate an estimate of the full Hessian, then one slow method used to evaluate numerical derivatives for only a few atoms. For example, .. code-block:: Python >>> import autode as ad... | the_stack_v2_python_sparse | autode/hessians.py | duartegroup/autodE | train | 132 |
0661b411ccaecc369180ac74db245b0bd74ebc29 | [
"self.task = task\nself.connected = False\nself.error = ''\nself.immsock = None",
"log.debug('WhiskerImmSocket: connect')\nproto = socket.getprotobyname('tcp')\ntry:\n self.immsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, proto)\n self.immsock.connect((server, port))\n self.connected = True\ne... | <|body_start_0|>
self.task = task
self.connected = False
self.error = ''
self.immsock = None
<|end_body_0|>
<|body_start_1|>
log.debug('WhiskerImmSocket: connect')
proto = socket.getprotobyname('tcp')
try:
self.immsock = socket.socket(socket.AF_INET, ... | Whisker Twisted immediate socket handler. Uses raw sockets. | WhiskerImmSocket | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WhiskerImmSocket:
"""Whisker Twisted immediate socket handler. Uses raw sockets."""
def __init__(self, task: WhiskerTwistedTask) -> None:
"""Args: task: instance of :class:`WhiskerTwistedTask`"""
<|body_0|>
def connect(self, server: str, port: int) -> None:
"""Co... | stack_v2_sparse_classes_75kplus_train_067566 | 17,022 | permissive | [
{
"docstring": "Args: task: instance of :class:`WhiskerTwistedTask`",
"name": "__init__",
"signature": "def __init__(self, task: WhiskerTwistedTask) -> None"
},
{
"docstring": "Connects the Whisker immediate socket. Args: server: server hostname/IP address port: immediate port number",
"name... | 4 | stack_v2_sparse_classes_30k_train_049112 | Implement the Python class `WhiskerImmSocket` described below.
Class description:
Whisker Twisted immediate socket handler. Uses raw sockets.
Method signatures and docstrings:
- def __init__(self, task: WhiskerTwistedTask) -> None: Args: task: instance of :class:`WhiskerTwistedTask`
- def connect(self, server: str, p... | Implement the Python class `WhiskerImmSocket` described below.
Class description:
Whisker Twisted immediate socket handler. Uses raw sockets.
Method signatures and docstrings:
- def __init__(self, task: WhiskerTwistedTask) -> None: Args: task: instance of :class:`WhiskerTwistedTask`
- def connect(self, server: str, p... | 938e4dad4aa0789101421462d1a0b7ff1833d2bb | <|skeleton|>
class WhiskerImmSocket:
"""Whisker Twisted immediate socket handler. Uses raw sockets."""
def __init__(self, task: WhiskerTwistedTask) -> None:
"""Args: task: instance of :class:`WhiskerTwistedTask`"""
<|body_0|>
def connect(self, server: str, port: int) -> None:
"""Co... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WhiskerImmSocket:
"""Whisker Twisted immediate socket handler. Uses raw sockets."""
def __init__(self, task: WhiskerTwistedTask) -> None:
"""Args: task: instance of :class:`WhiskerTwistedTask`"""
self.task = task
self.connected = False
self.error = ''
self.immsock ... | the_stack_v2_python_sparse | whisker/twistedclient.py | RudolfCardinal/whisker-python-client | train | 0 |
6c85d28d6c94fe54275a55843c2312a73495c523 | [
"camera = RTSPCamera(self.mudpi, config)\nif camera:\n self.add_component(camera)\nreturn True",
"if not isinstance(config, list):\n config = [config]\nfor conf in config:\n if not conf.get('path'):\n raise ConfigError('Camera needs a `path` to save files to.')\n if not conf.get('source'):\n ... | <|body_start_0|>
camera = RTSPCamera(self.mudpi, config)
if camera:
self.add_component(camera)
return True
<|end_body_0|>
<|body_start_1|>
if not isinstance(config, list):
config = [config]
for conf in config:
if not conf.get('path'):
... | Interface | [
"BSD-4-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Interface:
def load(self, config):
"""Load rtsp camera component from configs"""
<|body_0|>
def validate(self, config):
"""Validate the camera config"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
camera = RTSPCamera(self.mudpi, config)
if ... | stack_v2_sparse_classes_75kplus_train_067567 | 5,858 | permissive | [
{
"docstring": "Load rtsp camera component from configs",
"name": "load",
"signature": "def load(self, config)"
},
{
"docstring": "Validate the camera config",
"name": "validate",
"signature": "def validate(self, config)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003945 | Implement the Python class `Interface` described below.
Class description:
Implement the Interface class.
Method signatures and docstrings:
- def load(self, config): Load rtsp camera component from configs
- def validate(self, config): Validate the camera config | Implement the Python class `Interface` described below.
Class description:
Implement the Interface class.
Method signatures and docstrings:
- def load(self, config): Load rtsp camera component from configs
- def validate(self, config): Validate the camera config
<|skeleton|>
class Interface:
def load(self, conf... | fb206b1136f529c7197f1e6b29629ed05630d377 | <|skeleton|>
class Interface:
def load(self, config):
"""Load rtsp camera component from configs"""
<|body_0|>
def validate(self, config):
"""Validate the camera config"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Interface:
def load(self, config):
"""Load rtsp camera component from configs"""
camera = RTSPCamera(self.mudpi, config)
if camera:
self.add_component(camera)
return True
def validate(self, config):
"""Validate the camera config"""
if not isinst... | the_stack_v2_python_sparse | mudpi/extensions/rtsp/camera.py | mistasp0ck/mudpi-core | train | 0 | |
f650d03c5a1e93b3354b1802c043fea55ad5aa9a | [
"ls = list(range(1, n + 1))\nres = ''\nk -= 1\nwhile ls:\n m = math.factorial(len(ls) - 1)\n i, k = (k // m, k % m)\n res += str(ls[i])\n ls.pop(i)\nreturn res",
"from itertools import permutations\nres = sorted(permutations(list(range(1, n + 1))))\nprint(res)\nreturn ''.join([str(x) for x in res[k - ... | <|body_start_0|>
ls = list(range(1, n + 1))
res = ''
k -= 1
while ls:
m = math.factorial(len(ls) - 1)
i, k = (k // m, k % m)
res += str(ls[i])
ls.pop(i)
return res
<|end_body_0|>
<|body_start_1|>
from itertools import permu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getPermutation(self, n: int, k: int) -> str:
"""先固定第一位 第一位的索引为 k//(n-1)! (k=k-1, n为列表长度) 然后数组中删掉被固定的那位,然后再拿剩下数组和k%(n-1)重复上一步 :param n: :param k: :return:"""
<|body_0|>
def getPermutation2(self, n: int, k: int) -> str:
"""超时 生成全排列 :param n: :param k: :re... | stack_v2_sparse_classes_75kplus_train_067568 | 2,286 | no_license | [
{
"docstring": "先固定第一位 第一位的索引为 k//(n-1)! (k=k-1, n为列表长度) 然后数组中删掉被固定的那位,然后再拿剩下数组和k%(n-1)重复上一步 :param n: :param k: :return:",
"name": "getPermutation",
"signature": "def getPermutation(self, n: int, k: int) -> str"
},
{
"docstring": "超时 生成全排列 :param n: :param k: :return:",
"name": "getPermutat... | 2 | stack_v2_sparse_classes_30k_test_001172 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getPermutation(self, n: int, k: int) -> str: 先固定第一位 第一位的索引为 k//(n-1)! (k=k-1, n为列表长度) 然后数组中删掉被固定的那位,然后再拿剩下数组和k%(n-1)重复上一步 :param n: :param k: :return:
- def getPermutation2(s... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getPermutation(self, n: int, k: int) -> str: 先固定第一位 第一位的索引为 k//(n-1)! (k=k-1, n为列表长度) 然后数组中删掉被固定的那位,然后再拿剩下数组和k%(n-1)重复上一步 :param n: :param k: :return:
- def getPermutation2(s... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def getPermutation(self, n: int, k: int) -> str:
"""先固定第一位 第一位的索引为 k//(n-1)! (k=k-1, n为列表长度) 然后数组中删掉被固定的那位,然后再拿剩下数组和k%(n-1)重复上一步 :param n: :param k: :return:"""
<|body_0|>
def getPermutation2(self, n: int, k: int) -> str:
"""超时 生成全排列 :param n: :param k: :re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def getPermutation(self, n: int, k: int) -> str:
"""先固定第一位 第一位的索引为 k//(n-1)! (k=k-1, n为列表长度) 然后数组中删掉被固定的那位,然后再拿剩下数组和k%(n-1)重复上一步 :param n: :param k: :return:"""
ls = list(range(1, n + 1))
res = ''
k -= 1
while ls:
m = math.factorial(len(ls) - 1)
... | the_stack_v2_python_sparse | 60_第k个排列.py | lovehhf/LeetCode | train | 0 | |
56b1da541bb8cca70306510fc8dafc9dd4a818b9 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn DelegatedAdminRelationshipRequest()",
"from .delegated_admin_relationship_request_action import DelegatedAdminRelationshipRequestAction\nfrom .delegated_admin_relationship_request_status import DelegatedAdminRelationshipRequestStatus\n... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return DelegatedAdminRelationshipRequest()
<|end_body_0|>
<|body_start_1|>
from .delegated_admin_relationship_request_action import DelegatedAdminRelationshipRequestAction
from .delegated_admin... | DelegatedAdminRelationshipRequest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DelegatedAdminRelationshipRequest:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DelegatedAdminRelationshipRequest:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discrimin... | stack_v2_sparse_classes_75kplus_train_067569 | 3,825 | 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: DelegatedAdminRelationshipRequest",
"name": "create_from_discriminator_value",
"signature": "def create_from... | 3 | stack_v2_sparse_classes_30k_val_002734 | Implement the Python class `DelegatedAdminRelationshipRequest` described below.
Class description:
Implement the DelegatedAdminRelationshipRequest class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DelegatedAdminRelationshipRequest: Creates a new in... | Implement the Python class `DelegatedAdminRelationshipRequest` described below.
Class description:
Implement the DelegatedAdminRelationshipRequest class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DelegatedAdminRelationshipRequest: Creates a new in... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class DelegatedAdminRelationshipRequest:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DelegatedAdminRelationshipRequest:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discrimin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DelegatedAdminRelationshipRequest:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DelegatedAdminRelationshipRequest:
"""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... | the_stack_v2_python_sparse | msgraph/generated/models/delegated_admin_relationship_request.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
d840f9abc46326c5cfe0e0550343870e214e4e72 | [
"self.patience = patience\nself.verbose = verbose\nself.counter = 0\nself.best_score = None\nself.early_stop = False\nself.val_loss_min = np.Inf\nself.delta = delta",
"score = -val_loss\nif self.best_score is None:\n self.best_score = score\n self.save_checkpoint(val_loss, model, path)\nelif score < self.be... | <|body_start_0|>
self.patience = patience
self.verbose = verbose
self.counter = 0
self.best_score = None
self.early_stop = False
self.val_loss_min = np.Inf
self.delta = delta
<|end_body_0|>
<|body_start_1|>
score = -val_loss
if self.best_score is ... | Class to montior the progress of the model and stop early if no improvement on validation set. | EarlyStopping | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EarlyStopping:
"""Class to montior the progress of the model and stop early if no improvement on validation set."""
def __init__(self, patience=7, verbose=False, delta=0):
"""Initializes parameters for EarlyStopping class. Args: patience: an integer verbose: a boolean delta: a float"... | stack_v2_sparse_classes_75kplus_train_067570 | 3,427 | permissive | [
{
"docstring": "Initializes parameters for EarlyStopping class. Args: patience: an integer verbose: a boolean delta: a float",
"name": "__init__",
"signature": "def __init__(self, patience=7, verbose=False, delta=0)"
},
{
"docstring": "Checks if the validation loss is better than the best valida... | 3 | stack_v2_sparse_classes_30k_train_027470 | Implement the Python class `EarlyStopping` described below.
Class description:
Class to montior the progress of the model and stop early if no improvement on validation set.
Method signatures and docstrings:
- def __init__(self, patience=7, verbose=False, delta=0): Initializes parameters for EarlyStopping class. Args... | Implement the Python class `EarlyStopping` described below.
Class description:
Class to montior the progress of the model and stop early if no improvement on validation set.
Method signatures and docstrings:
- def __init__(self, patience=7, verbose=False, delta=0): Initializes parameters for EarlyStopping class. Args... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class EarlyStopping:
"""Class to montior the progress of the model and stop early if no improvement on validation set."""
def __init__(self, patience=7, verbose=False, delta=0):
"""Initializes parameters for EarlyStopping class. Args: patience: an integer verbose: a boolean delta: a float"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EarlyStopping:
"""Class to montior the progress of the model and stop early if no improvement on validation set."""
def __init__(self, patience=7, verbose=False, delta=0):
"""Initializes parameters for EarlyStopping class. Args: patience: an integer verbose: a boolean delta: a float"""
se... | the_stack_v2_python_sparse | ime/utils/tools.py | Jimmy-INL/google-research | train | 1 |
48d05f3a7fe8ebb4b211001f64f0ee001b8da459 | [
"qs_rooms = request.user.rooms.all()\nroom_serializer = RoomSerializer(qs_rooms, context={'request': request}, many=True)\nparticipants = set()\nmessages = set()\nfor room_data in room_serializer.data:\n participants = participants.union(set(room_data['participants']))\n messages.add(room_data['last_message']... | <|body_start_0|>
qs_rooms = request.user.rooms.all()
room_serializer = RoomSerializer(qs_rooms, context={'request': request}, many=True)
participants = set()
messages = set()
for room_data in room_serializer.data:
participants = participants.union(set(room_data['parti... | Endpoints related to managing rooms | RoomViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoomViewSet:
"""Endpoints related to managing rooms"""
def list(self, request):
"""List rooms in which the current user is a participant"""
<|body_0|>
def create(self, request):
"""get (private kind) or create a new room with participants"""
<|body_1|>
<... | stack_v2_sparse_classes_75kplus_train_067571 | 7,668 | permissive | [
{
"docstring": "List rooms in which the current user is a participant",
"name": "list",
"signature": "def list(self, request)"
},
{
"docstring": "get (private kind) or create a new room with participants",
"name": "create",
"signature": "def create(self, request)"
}
] | 2 | null | Implement the Python class `RoomViewSet` described below.
Class description:
Endpoints related to managing rooms
Method signatures and docstrings:
- def list(self, request): List rooms in which the current user is a participant
- def create(self, request): get (private kind) or create a new room with participants | Implement the Python class `RoomViewSet` described below.
Class description:
Endpoints related to managing rooms
Method signatures and docstrings:
- def list(self, request): List rooms in which the current user is a participant
- def create(self, request): get (private kind) or create a new room with participants
<|... | 6ad3d8e2d9deede34ec57f7b47cadb6db9e8c8db | <|skeleton|>
class RoomViewSet:
"""Endpoints related to managing rooms"""
def list(self, request):
"""List rooms in which the current user is a participant"""
<|body_0|>
def create(self, request):
"""get (private kind) or create a new room with participants"""
<|body_1|>
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RoomViewSet:
"""Endpoints related to managing rooms"""
def list(self, request):
"""List rooms in which the current user is a participant"""
qs_rooms = request.user.rooms.all()
room_serializer = RoomSerializer(qs_rooms, context={'request': request}, many=True)
participants ... | the_stack_v2_python_sparse | djchat/chat/api/roomViews.py | DanRHamidullin/whatsapp-clone-django-vuejs | train | 0 |
75f9a3e72acb528e28996dbe8b245fcee93b5ddb | [
"if isinstance(evaluable, ParameterContainer):\n self.wrappingEvaluable = evaluable.copy()\n self._wasUnwrapped = True\nelif not (evaluable is None or isinstance(evaluable, list) or isinstance(evaluable, ndarray)):\n raise ValueError('Continuous optimization algorithms require a list, array or' + ' Paramet... | <|body_start_0|>
if isinstance(evaluable, ParameterContainer):
self.wrappingEvaluable = evaluable.copy()
self._wasUnwrapped = True
elif not (evaluable is None or isinstance(evaluable, list) or isinstance(evaluable, ndarray)):
raise ValueError('Continuous optimization ... | A more restricted class of black-box optimization algorithms that assume the parameters to be necessarily an array of continuous values (which can be wrapped in a ParameterContainer). | ContinuousOptimizer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContinuousOptimizer:
"""A more restricted class of black-box optimization algorithms that assume the parameters to be necessarily an array of continuous values (which can be wrapped in a ParameterContainer)."""
def _setInitEvaluable(self, evaluable):
"""If the parameters are wrapped,... | stack_v2_sparse_classes_75kplus_train_067572 | 15,225 | permissive | [
{
"docstring": "If the parameters are wrapped, we keep track of the wrapper explicitly.",
"name": "_setInitEvaluable",
"signature": "def _setInitEvaluable(self, evaluable)"
},
{
"docstring": "return the best found evaluable and its associated fitness.",
"name": "_bestFound",
"signature":... | 2 | stack_v2_sparse_classes_30k_val_001438 | Implement the Python class `ContinuousOptimizer` described below.
Class description:
A more restricted class of black-box optimization algorithms that assume the parameters to be necessarily an array of continuous values (which can be wrapped in a ParameterContainer).
Method signatures and docstrings:
- def _setInitE... | Implement the Python class `ContinuousOptimizer` described below.
Class description:
A more restricted class of black-box optimization algorithms that assume the parameters to be necessarily an array of continuous values (which can be wrapped in a ParameterContainer).
Method signatures and docstrings:
- def _setInitE... | 33ead60704d126e58c10d458ddd1e5e5fd17b65d | <|skeleton|>
class ContinuousOptimizer:
"""A more restricted class of black-box optimization algorithms that assume the parameters to be necessarily an array of continuous values (which can be wrapped in a ParameterContainer)."""
def _setInitEvaluable(self, evaluable):
"""If the parameters are wrapped,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ContinuousOptimizer:
"""A more restricted class of black-box optimization algorithms that assume the parameters to be necessarily an array of continuous values (which can be wrapped in a ParameterContainer)."""
def _setInitEvaluable(self, evaluable):
"""If the parameters are wrapped, we keep trac... | the_stack_v2_python_sparse | pybrain/optimization/optimizer.py | pybrain2/pybrain2 | train | 14 |
5b08bd32f6843c2a5eb398330af3ad1ff11a44e9 | [
"super(PreprocessorSupervised, self).__init__(root_dir=root_dir, patch_size=patch_size, pad_type=pad_type, look_for_labels=look_for_labels, crop=crop, spacing=spacing)\nself.transforms = [{'name': 'Mirroring', 'execution_probability': 0.5}, {'name': 'Rotate', 'execution_probability': 0.5}, {'name': 'ElasticDeformat... | <|body_start_0|>
super(PreprocessorSupervised, self).__init__(root_dir=root_dir, patch_size=patch_size, pad_type=pad_type, look_for_labels=look_for_labels, crop=crop, spacing=spacing)
self.transforms = [{'name': 'Mirroring', 'execution_probability': 0.5}, {'name': 'Rotate', 'execution_probability': 0.5}... | PreprocessorSupervised class. Extends the original class by additionaly processing labels and saving the processed data. | PreprocessorSupervised | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PreprocessorSupervised:
"""PreprocessorSupervised class. Extends the original class by additionaly processing labels and saving the processed data."""
def __init__(self, root_dir='../raw', patch_size=(64, 64, 32), crop=2, pad_type='zero_pad', look_for_labels=True, spacing=(0.8, 0.8, 0.8), **... | stack_v2_sparse_classes_75kplus_train_067573 | 19,145 | no_license | [
{
"docstring": "PreprocessorSupervised constructor, extending the Preprocessor constructor by defining augumentations and level of supervision. Args: root_dir (string): path to folder containing raw data. Defaults to '../raw'. patch_size (tuple of ints): patch size for padding and croping calculation. Defaults ... | 2 | stack_v2_sparse_classes_30k_train_024621 | Implement the Python class `PreprocessorSupervised` described below.
Class description:
PreprocessorSupervised class. Extends the original class by additionaly processing labels and saving the processed data.
Method signatures and docstrings:
- def __init__(self, root_dir='../raw', patch_size=(64, 64, 32), crop=2, pa... | Implement the Python class `PreprocessorSupervised` described below.
Class description:
PreprocessorSupervised class. Extends the original class by additionaly processing labels and saving the processed data.
Method signatures and docstrings:
- def __init__(self, root_dir='../raw', patch_size=(64, 64, 32), crop=2, pa... | d89f696a1404f5793b71ca46261055a7f4575497 | <|skeleton|>
class PreprocessorSupervised:
"""PreprocessorSupervised class. Extends the original class by additionaly processing labels and saving the processed data."""
def __init__(self, root_dir='../raw', patch_size=(64, 64, 32), crop=2, pad_type='zero_pad', look_for_labels=True, spacing=(0.8, 0.8, 0.8), **... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PreprocessorSupervised:
"""PreprocessorSupervised class. Extends the original class by additionaly processing labels and saving the processed data."""
def __init__(self, root_dir='../raw', patch_size=(64, 64, 32), crop=2, pad_type='zero_pad', look_for_labels=True, spacing=(0.8, 0.8, 0.8), **kwargs):
... | the_stack_v2_python_sparse | source/dataset/preprocessor.py | BereznyMatej/IBT | train | 0 |
d65eebc3f1048bf5a6a5ef456aed644d44efba4a | [
"self.value = value\nself.suit = suit\nself.set_name()",
"NAMES = {1: 'Ace', 11: 'Jack', 12: 'Queen', 13: 'King'}\nif self.value in NAMES:\n self.name = NAMES[self.value]",
"if self.name is not None:\n return '{} of {}'.format(self.name, self.suit)\nreturn '{} of {}'.format(self.value, self.suit)",
"if ... | <|body_start_0|>
self.value = value
self.suit = suit
self.set_name()
<|end_body_0|>
<|body_start_1|>
NAMES = {1: 'Ace', 11: 'Jack', 12: 'Queen', 13: 'King'}
if self.value in NAMES:
self.name = NAMES[self.value]
<|end_body_1|>
<|body_start_2|>
if self.name is... | Class -- PlayingCard Represents a playing card. Attributes: value -- the card's value, an integer. suit -- the card's suit, a string | PlayingCard | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlayingCard:
"""Class -- PlayingCard Represents a playing card. Attributes: value -- the card's value, an integer. suit -- the card's suit, a string"""
def __init__(self, value, suit):
"""Constructor -- creates a new instance of PlayingCard Parameters: self -- the current PlayingCard... | stack_v2_sparse_classes_75kplus_train_067574 | 2,418 | no_license | [
{
"docstring": "Constructor -- creates a new instance of PlayingCard Parameters: self -- the current PlayingCard object value -- the card's value, an integer suit -- the card's suit, a string",
"name": "__init__",
"signature": "def __init__(self, value, suit)"
},
{
"docstring": "Method -- set_na... | 4 | stack_v2_sparse_classes_30k_train_041035 | Implement the Python class `PlayingCard` described below.
Class description:
Class -- PlayingCard Represents a playing card. Attributes: value -- the card's value, an integer. suit -- the card's suit, a string
Method signatures and docstrings:
- def __init__(self, value, suit): Constructor -- creates a new instance o... | Implement the Python class `PlayingCard` described below.
Class description:
Class -- PlayingCard Represents a playing card. Attributes: value -- the card's value, an integer. suit -- the card's suit, a string
Method signatures and docstrings:
- def __init__(self, value, suit): Constructor -- creates a new instance o... | b9281f5f959e0268b75baa2c2b1262712da3780f | <|skeleton|>
class PlayingCard:
"""Class -- PlayingCard Represents a playing card. Attributes: value -- the card's value, an integer. suit -- the card's suit, a string"""
def __init__(self, value, suit):
"""Constructor -- creates a new instance of PlayingCard Parameters: self -- the current PlayingCard... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PlayingCard:
"""Class -- PlayingCard Represents a playing card. Attributes: value -- the card's value, an integer. suit -- the card's suit, a string"""
def __init__(self, value, suit):
"""Constructor -- creates a new instance of PlayingCard Parameters: self -- the current PlayingCard object value... | the_stack_v2_python_sparse | in_class_excercise/Lecture 10/cardgame/playingcard.py | arcPenguinj/CS5001-Intensive-Foundations-of-CS | train | 0 |
76f47b5efd4d570376b2b11e8b8e43e198e0bcbe | [
"msg = Message()\nmsg.msgType = msgTypes.COMMAND\nmsg.dest = self._commID\nmsg.content = {'user': self._userID, 'cmd': parameter}\nself._commManager.sendMessage(msg)",
"msg = Message()\nmsg.msgType = msgTypes.TAG\nmsg.dest = self._commID\nmsg.content = {'user': self._userID, 'type': types.RM_PARAMETER, 'tag': nam... | <|body_start_0|>
msg = Message()
msg.msgType = msgTypes.COMMAND
msg.dest = self._commID
msg.content = {'user': self._userID, 'cmd': parameter}
self._commManager.sendMessage(msg)
<|end_body_0|>
<|body_start_1|>
msg = Message()
msg.msgType = msgTypes.TAG
ms... | Remote control for ROS parameters. | RemoteParameterControl | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RemoteParameterControl:
"""Remote control for ROS parameters."""
def addParameter(self, parameter):
"""Add a parameter to the ROS environment. @param parameter: Parameter description which should be added. @type parameter: core.command._ParameterCommand"""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus_train_067575 | 10,878 | permissive | [
{
"docstring": "Add a parameter to the ROS environment. @param parameter: Parameter description which should be added. @type parameter: core.command._ParameterCommand",
"name": "addParameter",
"signature": "def addParameter(self, parameter)"
},
{
"docstring": "Remove a parameter from the ROS env... | 2 | stack_v2_sparse_classes_30k_train_011255 | Implement the Python class `RemoteParameterControl` described below.
Class description:
Remote control for ROS parameters.
Method signatures and docstrings:
- def addParameter(self, parameter): Add a parameter to the ROS environment. @param parameter: Parameter description which should be added. @type parameter: core... | Implement the Python class `RemoteParameterControl` described below.
Class description:
Remote control for ROS parameters.
Method signatures and docstrings:
- def addParameter(self, parameter): Add a parameter to the ROS environment. @param parameter: Parameter description which should be added. @type parameter: core... | c277efd809fce8f0f18b009fb3b9c7f785cc3739 | <|skeleton|>
class RemoteParameterControl:
"""Remote control for ROS parameters."""
def addParameter(self, parameter):
"""Add a parameter to the ROS environment. @param parameter: Parameter description which should be added. @type parameter: core.command._ParameterCommand"""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RemoteParameterControl:
"""Remote control for ROS parameters."""
def addParameter(self, parameter):
"""Add a parameter to the ROS environment. @param parameter: Parameter description which should be added. @type parameter: core.command._ParameterCommand"""
msg = Message()
msg.msgT... | the_stack_v2_python_sparse | framework/remote/control.py | LCROBOT/rce | train | 0 |
cae6234c1ec7b6077adee71649c4540e3e546011 | [
"cfrom = -1\ntry:\n if self.lnk.type == Lnk.CHARSPAN:\n cfrom = self.lnk.data[0]\nexcept AttributeError:\n pass\nreturn cfrom",
"cto = -1\ntry:\n if self.lnk.type == Lnk.CHARSPAN:\n cto = self.lnk.data[1]\nexcept AttributeError:\n pass\nreturn cto"
] | <|body_start_0|>
cfrom = -1
try:
if self.lnk.type == Lnk.CHARSPAN:
cfrom = self.lnk.data[0]
except AttributeError:
pass
return cfrom
<|end_body_0|>
<|body_start_1|>
cto = -1
try:
if self.lnk.type == Lnk.CHARSPAN:
... | A mixin class for predications ([EPs] or [Nodes]) or full [Xmrs] objects, which are the types that can be linked to surface strings. This class provides the `cfrom` and `cto` properties so they are always available (defaulting to a value of `-1` if there is no lnk or if the lnk is not a Lnk.CHARSPAN type). | _LnkMixin | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _LnkMixin:
"""A mixin class for predications ([EPs] or [Nodes]) or full [Xmrs] objects, which are the types that can be linked to surface strings. This class provides the `cfrom` and `cto` properties so they are always available (defaulting to a value of `-1` if there is no lnk or if the lnk is n... | stack_v2_sparse_classes_75kplus_train_067576 | 24,086 | permissive | [
{
"docstring": "The initial character position in the surface string. Defaults to -1 if there is no valid cfrom value.",
"name": "cfrom",
"signature": "def cfrom(self)"
},
{
"docstring": "The final character position in the surface string. Defaults to -1 if there is no valid cto value.",
"na... | 2 | stack_v2_sparse_classes_30k_train_044650 | Implement the Python class `_LnkMixin` described below.
Class description:
A mixin class for predications ([EPs] or [Nodes]) or full [Xmrs] objects, which are the types that can be linked to surface strings. This class provides the `cfrom` and `cto` properties so they are always available (defaulting to a value of `-1... | Implement the Python class `_LnkMixin` described below.
Class description:
A mixin class for predications ([EPs] or [Nodes]) or full [Xmrs] objects, which are the types that can be linked to surface strings. This class provides the `cfrom` and `cto` properties so they are always available (defaulting to a value of `-1... | de0a143e283a41e2ab15a7bb197bfdd0f7fb8655 | <|skeleton|>
class _LnkMixin:
"""A mixin class for predications ([EPs] or [Nodes]) or full [Xmrs] objects, which are the types that can be linked to surface strings. This class provides the `cfrom` and `cto` properties so they are always available (defaulting to a value of `-1` if there is no lnk or if the lnk is n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _LnkMixin:
"""A mixin class for predications ([EPs] or [Nodes]) or full [Xmrs] objects, which are the types that can be linked to surface strings. This class provides the `cfrom` and `cto` properties so they are always available (defaulting to a value of `-1` if there is no lnk or if the lnk is not a Lnk.CHAR... | the_stack_v2_python_sparse | delphin/mrs/components.py | draplater/hrg-parser | train | 10 |
6de53bf26181ed7068f9fb2b3d1e1581c2ea836e | [
"self.st = state\nself.suc = success\nself.d = depth\nself.cut = cutoff",
"if self.suc:\n prstr = 'Solution found at depth ' + str(self.d) + '\\nState:\\n'\nelif self.cut:\n prstr = 'Limit reached before solution was found\\n'\nelse:\n prstr = 'Failed to find a solution.\\n'\nprstr += format(self.st)\nre... | <|body_start_0|>
self.st = state
self.suc = success
self.d = depth
self.cut = cutoff
<|end_body_0|>
<|body_start_1|>
if self.suc:
prstr = 'Solution found at depth ' + str(self.d) + '\nState:\n'
elif self.cut:
prstr = 'Limit reached before solution... | MathSearchResult | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MathSearchResult:
def __init__(self, success, depth, state, cutoff=False):
"""Contains the results of a search. success -- True if solution found, false otherwise depth -- the distance from intial node to success node state -- the state at which success was met"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_067577 | 5,565 | no_license | [
{
"docstring": "Contains the results of a search. success -- True if solution found, false otherwise depth -- the distance from intial node to success node state -- the state at which success was met",
"name": "__init__",
"signature": "def __init__(self, success, depth, state, cutoff=False)"
},
{
... | 2 | stack_v2_sparse_classes_30k_test_002670 | Implement the Python class `MathSearchResult` described below.
Class description:
Implement the MathSearchResult class.
Method signatures and docstrings:
- def __init__(self, success, depth, state, cutoff=False): Contains the results of a search. success -- True if solution found, false otherwise depth -- the distanc... | Implement the Python class `MathSearchResult` described below.
Class description:
Implement the MathSearchResult class.
Method signatures and docstrings:
- def __init__(self, success, depth, state, cutoff=False): Contains the results of a search. success -- True if solution found, false otherwise depth -- the distanc... | aacf205c4a2eac4b518c9a38bf28eb65523a4cbb | <|skeleton|>
class MathSearchResult:
def __init__(self, success, depth, state, cutoff=False):
"""Contains the results of a search. success -- True if solution found, false otherwise depth -- the distance from intial node to success node state -- the state at which success was met"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MathSearchResult:
def __init__(self, success, depth, state, cutoff=False):
"""Contains the results of a search. success -- True if solution found, false otherwise depth -- the distance from intial node to success node state -- the state at which success was met"""
self.st = state
self.... | the_stack_v2_python_sparse | a1/a1q2.py | Azellic/317IntroToArtificialIntelligence | train | 0 | |
7b4ace370871dc81adb62d38021bd608023f57bc | [
"self.target_height = target_height\nself.margin = margin\nif self.target_height < 0:\n raise Exception('Bad Height Setting.')",
"new_action = current_action\nif current_height < 0:\n raise Exception('Sensor reading cannot be less than 0.')\nif current_action not in (-1, 0, 1):\n logging.debug('In Decide... | <|body_start_0|>
self.target_height = target_height
self.margin = margin
if self.target_height < 0:
raise Exception('Bad Height Setting.')
<|end_body_0|>
<|body_start_1|>
new_action = current_action
if current_height < 0:
raise Exception('Sensor reading c... | Encapsulates decision making in the water-regulation module | Decider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decider:
"""Encapsulates decision making in the water-regulation module"""
def __init__(self, target_height, margin):
"""Create a new decider instance for this tank. :param target_height: the target height for liquid in this tank :param margin: the margin of liquid above and below th... | stack_v2_sparse_classes_75kplus_train_067578 | 5,240 | no_license | [
{
"docstring": "Create a new decider instance for this tank. :param target_height: the target height for liquid in this tank :param margin: the margin of liquid above and below the target height for which the pump should not turn on. Ex: .05 represents a 5% margin above and below the target_height.",
"name"... | 2 | null | Implement the Python class `Decider` described below.
Class description:
Encapsulates decision making in the water-regulation module
Method signatures and docstrings:
- def __init__(self, target_height, margin): Create a new decider instance for this tank. :param target_height: the target height for liquid in this ta... | Implement the Python class `Decider` described below.
Class description:
Encapsulates decision making in the water-regulation module
Method signatures and docstrings:
- def __init__(self, target_height, margin): Create a new decider instance for this tank. :param target_height: the target height for liquid in this ta... | b1fea0309b3495b3e1dc167d7029bc9e4b6f00f1 | <|skeleton|>
class Decider:
"""Encapsulates decision making in the water-regulation module"""
def __init__(self, target_height, margin):
"""Create a new decider instance for this tank. :param target_height: the target height for liquid in this tank :param margin: the margin of liquid above and below th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Decider:
"""Encapsulates decision making in the water-regulation module"""
def __init__(self, target_height, margin):
"""Create a new decider instance for this tank. :param target_height: the target height for liquid in this tank :param margin: the margin of liquid above and below the target heig... | the_stack_v2_python_sparse | students/srepking/lesson06/water-regulation/waterregulation/decider.py | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | train | 4 |
1b2b2f17adf61069bb59c15f7115db41f6569f41 | [
"self.e = learning_rate\nself.w = (np.random.rand(dimension_kernel) - 0.5) * self.e\nself.k = kernel",
"z = self.k.transform(x)\nres = np.dot(z, self.w)\nreturn res",
"gradient = np.zeros(self.w.size)\nfor i in range(labeledSet.size()):\n elem = labeledSet.getX(i)\n z = self.predict(elem)\n elem = self... | <|body_start_0|>
self.e = learning_rate
self.w = (np.random.rand(dimension_kernel) - 0.5) * self.e
self.k = kernel
<|end_body_0|>
<|body_start_1|>
z = self.k.transform(x)
res = np.dot(z, self.w)
return res
<|end_body_1|>
<|body_start_2|>
gradient = np.zeros(self... | Descent du gradient en batch kernelisé | ClassifierGradientBatchKernel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassifierGradientBatchKernel:
"""Descent du gradient en batch kernelisé"""
def __init__(self, dimension_kernel, learning_rate, kernel):
"""Argument: - dimension_kernel (int) : dimension du kernel - learning_rate : e Hypothèse : dimension_kernel > 0"""
<|body_0|>
def pre... | stack_v2_sparse_classes_75kplus_train_067579 | 14,728 | no_license | [
{
"docstring": "Argument: - dimension_kernel (int) : dimension du kernel - learning_rate : e Hypothèse : dimension_kernel > 0",
"name": "__init__",
"signature": "def __init__(self, dimension_kernel, learning_rate, kernel)"
},
{
"docstring": "rend la prediction sur x",
"name": "predict",
... | 4 | stack_v2_sparse_classes_30k_train_030634 | Implement the Python class `ClassifierGradientBatchKernel` described below.
Class description:
Descent du gradient en batch kernelisé
Method signatures and docstrings:
- def __init__(self, dimension_kernel, learning_rate, kernel): Argument: - dimension_kernel (int) : dimension du kernel - learning_rate : e Hypothèse ... | Implement the Python class `ClassifierGradientBatchKernel` described below.
Class description:
Descent du gradient en batch kernelisé
Method signatures and docstrings:
- def __init__(self, dimension_kernel, learning_rate, kernel): Argument: - dimension_kernel (int) : dimension du kernel - learning_rate : e Hypothèse ... | a8313bd545f71ec276a9249478ac51eeaa3d4ee2 | <|skeleton|>
class ClassifierGradientBatchKernel:
"""Descent du gradient en batch kernelisé"""
def __init__(self, dimension_kernel, learning_rate, kernel):
"""Argument: - dimension_kernel (int) : dimension du kernel - learning_rate : e Hypothèse : dimension_kernel > 0"""
<|body_0|>
def pre... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ClassifierGradientBatchKernel:
"""Descent du gradient en batch kernelisé"""
def __init__(self, dimension_kernel, learning_rate, kernel):
"""Argument: - dimension_kernel (int) : dimension du kernel - learning_rate : e Hypothèse : dimension_kernel > 0"""
self.e = learning_rate
self.... | the_stack_v2_python_sparse | iads/Classifiers.py | arianacarnielli/3I026 | train | 2 |
275c281a90eff132e9616d73790084b960d1c6cc | [
"post_body = json.dumps({'service_provider': kwargs})\nresp, body = self.put('OS-FEDERATION/service_providers/%s' % service_provider_id, post_body)\nself.expected_success(201, resp.status)\nbody = json.loads(body)\nreturn rest_client.ResponseBody(resp, body)",
"url = 'OS-FEDERATION/service_providers'\nif kwargs:\... | <|body_start_0|>
post_body = json.dumps({'service_provider': kwargs})
resp, body = self.put('OS-FEDERATION/service_providers/%s' % service_provider_id, post_body)
self.expected_success(201, resp.status)
body = json.loads(body)
return rest_client.ResponseBody(resp, body)
<|end_bod... | ServiceProvidersClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServiceProvidersClient:
def register_service_provider(self, service_provider_id, **kwargs):
"""Register a service provider. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/identity/v3-ext/index.html#register-a-servic... | stack_v2_sparse_classes_75kplus_train_067580 | 3,705 | permissive | [
{
"docstring": "Register a service provider. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/identity/v3-ext/index.html#register-a-service-provider",
"name": "register_service_provider",
"signature": "def register_service_provider(s... | 5 | null | Implement the Python class `ServiceProvidersClient` described below.
Class description:
Implement the ServiceProvidersClient class.
Method signatures and docstrings:
- def register_service_provider(self, service_provider_id, **kwargs): Register a service provider. For a full list of available parameters, please refer... | Implement the Python class `ServiceProvidersClient` described below.
Class description:
Implement the ServiceProvidersClient class.
Method signatures and docstrings:
- def register_service_provider(self, service_provider_id, **kwargs): Register a service provider. For a full list of available parameters, please refer... | 3932a799e620a20d7abf7b89e21b520683a1809b | <|skeleton|>
class ServiceProvidersClient:
def register_service_provider(self, service_provider_id, **kwargs):
"""Register a service provider. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/identity/v3-ext/index.html#register-a-servic... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ServiceProvidersClient:
def register_service_provider(self, service_provider_id, **kwargs):
"""Register a service provider. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/identity/v3-ext/index.html#register-a-service-provider"""
... | the_stack_v2_python_sparse | tempest/lib/services/identity/v3/service_providers_client.py | openstack/tempest | train | 270 | |
3065704d215ce5c675465276f220e88cc6b53370 | [
"data = {'title': 'Reward Test', 'description': 'Descricao Reward Test', 'points': '2', 'badge_url': 'http://image'}\nresponse = post_rewards(self, '/api/rewards/', data)\nself.assertEqual(response.status_code, status.HTTP_201_CREATED)\nself.assertEqual(Reward.objects.count(), 1)\nself.assertEqual(Reward.objects.ge... | <|body_start_0|>
data = {'title': 'Reward Test', 'description': 'Descricao Reward Test', 'points': '2', 'badge_url': 'http://image'}
response = post_rewards(self, '/api/rewards/', data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(Reward.objects.count(... | RewardsTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RewardsTests:
def test_create_reward(self):
"""Ensure we can create a new reward."""
<|body_0|>
def test_get_rewards(self):
"""Ensure we can get all rewards."""
<|body_1|>
def test_create_reward_error(self):
"""Ensure error 400 when create reward... | stack_v2_sparse_classes_75kplus_train_067581 | 2,558 | permissive | [
{
"docstring": "Ensure we can create a new reward.",
"name": "test_create_reward",
"signature": "def test_create_reward(self)"
},
{
"docstring": "Ensure we can get all rewards.",
"name": "test_get_rewards",
"signature": "def test_get_rewards(self)"
},
{
"docstring": "Ensure error... | 4 | stack_v2_sparse_classes_30k_train_027508 | Implement the Python class `RewardsTests` described below.
Class description:
Implement the RewardsTests class.
Method signatures and docstrings:
- def test_create_reward(self): Ensure we can create a new reward.
- def test_get_rewards(self): Ensure we can get all rewards.
- def test_create_reward_error(self): Ensure... | Implement the Python class `RewardsTests` described below.
Class description:
Implement the RewardsTests class.
Method signatures and docstrings:
- def test_create_reward(self): Ensure we can create a new reward.
- def test_get_rewards(self): Ensure we can get all rewards.
- def test_create_reward_error(self): Ensure... | c9bc91fa6b3e16ceaf621543adf37b9449221803 | <|skeleton|>
class RewardsTests:
def test_create_reward(self):
"""Ensure we can create a new reward."""
<|body_0|>
def test_get_rewards(self):
"""Ensure we can get all rewards."""
<|body_1|>
def test_create_reward_error(self):
"""Ensure error 400 when create reward... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RewardsTests:
def test_create_reward(self):
"""Ensure we can create a new reward."""
data = {'title': 'Reward Test', 'description': 'Descricao Reward Test', 'points': '2', 'badge_url': 'http://image'}
response = post_rewards(self, '/api/rewards/', data)
self.assertEqual(respons... | the_stack_v2_python_sparse | service/mc3/rewards/tests.py | IanPSRocha/2019.1-PretEvent | train | 0 | |
790d03b54f8aeffadcf587f0f79de7a2b2e9b81e | [
"parser.display_info.AddFormat(vmware_constants.VMWARE_CLUSTERS_FORMAT)\nflags.AddClusterResourceArg(parser, 'to update', True)\nbase.ASYNC_FLAG.AddToParser(parser)\nflags.AddValidationOnly(parser)\nflags.AddAllowMissingUpdateCluster(parser)\nflags.AddDescription(parser)\nflags.AddVersion(parser)\nflags.AddVmwareCo... | <|body_start_0|>
parser.display_info.AddFormat(vmware_constants.VMWARE_CLUSTERS_FORMAT)
flags.AddClusterResourceArg(parser, 'to update', True)
base.ASYNC_FLAG.AddToParser(parser)
flags.AddValidationOnly(parser)
flags.AddAllowMissingUpdateCluster(parser)
flags.AddDescripti... | Update an Anthos cluster on VMware. | UpdateAlpha | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateAlpha:
"""Update an Anthos cluster on VMware."""
def Args(parser: parser_arguments.ArgumentInterceptor):
"""Gathers command line arguments for the update command. Args: parser: The argparse parser to add the flag to."""
<|body_0|>
def Run(self, args):
"""Ru... | stack_v2_sparse_classes_75kplus_train_067582 | 6,033 | permissive | [
{
"docstring": "Gathers command line arguments for the update command. Args: parser: The argparse parser to add the flag to.",
"name": "Args",
"signature": "def Args(parser: parser_arguments.ArgumentInterceptor)"
},
{
"docstring": "Runs the update command. Args: args: The arguments received from... | 2 | stack_v2_sparse_classes_30k_train_029743 | Implement the Python class `UpdateAlpha` described below.
Class description:
Update an Anthos cluster on VMware.
Method signatures and docstrings:
- def Args(parser: parser_arguments.ArgumentInterceptor): Gathers command line arguments for the update command. Args: parser: The argparse parser to add the flag to.
- de... | Implement the Python class `UpdateAlpha` described below.
Class description:
Update an Anthos cluster on VMware.
Method signatures and docstrings:
- def Args(parser: parser_arguments.ArgumentInterceptor): Gathers command line arguments for the update command. Args: parser: The argparse parser to add the flag to.
- de... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class UpdateAlpha:
"""Update an Anthos cluster on VMware."""
def Args(parser: parser_arguments.ArgumentInterceptor):
"""Gathers command line arguments for the update command. Args: parser: The argparse parser to add the flag to."""
<|body_0|>
def Run(self, args):
"""Ru... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UpdateAlpha:
"""Update an Anthos cluster on VMware."""
def Args(parser: parser_arguments.ArgumentInterceptor):
"""Gathers command line arguments for the update command. Args: parser: The argparse parser to add the flag to."""
parser.display_info.AddFormat(vmware_constants.VMWARE_CLUSTERS_... | the_stack_v2_python_sparse | lib/surface/container/vmware/clusters/update.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
5f8d630ae8bed336ba8b3708f5cd597b7bdce910 | [
"super().__post_init__()\ncheck_scalar(self.alpha_, 'alpha_', float)\nif self.alpha_ <= 0.0:\n raise ValueError(f'`alpha_`= {self.alpha_}, must be > 0.0.')\ncheck_scalar(self.lambda_, 'lambda_', float)\nif self.lambda_ <= 0.0:\n raise ValueError(f'`lambda_`= {self.lambda_}, must be > 0.0.')\nself.alpha_list =... | <|body_start_0|>
super().__post_init__()
check_scalar(self.alpha_, 'alpha_', float)
if self.alpha_ <= 0.0:
raise ValueError(f'`alpha_`= {self.alpha_}, must be > 0.0.')
check_scalar(self.lambda_, 'lambda_', float)
if self.lambda_ <= 0.0:
raise ValueError(f'... | Base class for contextual bandit policies using logistic regression. Parameters ---------- dim: int Number of dimensions of context vectors. n_actions: int Number of actions. len_list: int, default=1 Length of a list of actions recommended in each impression. When Open Bandit Dataset is used, 3 should be set. batch_siz... | BaseLogisticPolicy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseLogisticPolicy:
"""Base class for contextual bandit policies using logistic regression. Parameters ---------- dim: int Number of dimensions of context vectors. n_actions: int Number of actions. len_list: int, default=1 Length of a list of actions recommended in each impression. When Open Band... | stack_v2_sparse_classes_75kplus_train_067583 | 10,908 | permissive | [
{
"docstring": "Initialize class.",
"name": "__post_init__",
"signature": "def __post_init__(self) -> None"
},
{
"docstring": "Update policy parameters. Parameters ---------- action: int Selected action by the policy. reward: float Observed reward for the chosen action and position. context: arr... | 2 | stack_v2_sparse_classes_30k_train_029829 | Implement the Python class `BaseLogisticPolicy` described below.
Class description:
Base class for contextual bandit policies using logistic regression. Parameters ---------- dim: int Number of dimensions of context vectors. n_actions: int Number of actions. len_list: int, default=1 Length of a list of actions recomme... | Implement the Python class `BaseLogisticPolicy` described below.
Class description:
Base class for contextual bandit policies using logistic regression. Parameters ---------- dim: int Number of dimensions of context vectors. n_actions: int Number of actions. len_list: int, default=1 Length of a list of actions recomme... | 53598edab284b4364d127ec5662137de3f9c1206 | <|skeleton|>
class BaseLogisticPolicy:
"""Base class for contextual bandit policies using logistic regression. Parameters ---------- dim: int Number of dimensions of context vectors. n_actions: int Number of actions. len_list: int, default=1 Length of a list of actions recommended in each impression. When Open Band... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseLogisticPolicy:
"""Base class for contextual bandit policies using logistic regression. Parameters ---------- dim: int Number of dimensions of context vectors. n_actions: int Number of actions. len_list: int, default=1 Length of a list of actions recommended in each impression. When Open Bandit Dataset is... | the_stack_v2_python_sparse | obp/policy/logistic.py | han20192019/newRL | train | 0 |
0f4d0e0618fce94aaa3dfa1e8d61d4e041b77f95 | [
"DELETE = '#'\n\ndef backtrack(word):\n q = []\n for char in word:\n if char == DELETE:\n if q:\n q.pop()\n else:\n q.append(char)\n return ''.join(q)\nreturn backtrack(S) == backtrack(T)",
"DELETE = '#'\n\ndef backtrack(word):\n q = []\n skip = 0\... | <|body_start_0|>
DELETE = '#'
def backtrack(word):
q = []
for char in word:
if char == DELETE:
if q:
q.pop()
else:
q.append(char)
return ''.join(q)
return backtrac... | Strat: Build up the word using a stack. If the "#" is found, pop from the state. Stats: O(n + m) time, O(n + m) space where n = len(S) and m = len(T) | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Strat: Build up the word using a stack. If the "#" is found, pop from the state. Stats: O(n + m) time, O(n + m) space where n = len(S) and m = len(T)"""
def backspaceCompare(self, S, T):
""":type S: str :type T: str :rtype: bool"""
<|body_0|>
def backspaceCo... | stack_v2_sparse_classes_75kplus_train_067584 | 1,998 | no_license | [
{
"docstring": ":type S: str :type T: str :rtype: bool",
"name": "backspaceCompare",
"signature": "def backspaceCompare(self, S, T)"
},
{
"docstring": ":type S: str :type T: str :rtype: bool",
"name": "backspaceCompare",
"signature": "def backspaceCompare(self, S, T)"
}
] | 2 | stack_v2_sparse_classes_30k_train_052101 | Implement the Python class `Solution` described below.
Class description:
Strat: Build up the word using a stack. If the "#" is found, pop from the state. Stats: O(n + m) time, O(n + m) space where n = len(S) and m = len(T)
Method signatures and docstrings:
- def backspaceCompare(self, S, T): :type S: str :type T: st... | Implement the Python class `Solution` described below.
Class description:
Strat: Build up the word using a stack. If the "#" is found, pop from the state. Stats: O(n + m) time, O(n + m) space where n = len(S) and m = len(T)
Method signatures and docstrings:
- def backspaceCompare(self, S, T): :type S: str :type T: st... | 844f502da4d6fb9cd69cf0a1ef71da3385a4d2b4 | <|skeleton|>
class Solution:
"""Strat: Build up the word using a stack. If the "#" is found, pop from the state. Stats: O(n + m) time, O(n + m) space where n = len(S) and m = len(T)"""
def backspaceCompare(self, S, T):
""":type S: str :type T: str :rtype: bool"""
<|body_0|>
def backspaceCo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""Strat: Build up the word using a stack. If the "#" is found, pop from the state. Stats: O(n + m) time, O(n + m) space where n = len(S) and m = len(T)"""
def backspaceCompare(self, S, T):
""":type S: str :type T: str :rtype: bool"""
DELETE = '#'
def backtrack(word):
... | the_stack_v2_python_sparse | 822-backspace_string_compare.py | stevestar888/leetcode-problems | train | 2 |
1db7c70561305e5cfdb03827c0d88d10e90df498 | [
"super().__init__()\nself.N = N\nself.dm = dm\nself.embedding = tf.keras.layers.Embedding(input_vocab, dm)\nself.positional_encoding = positional_encoding(max_seq_len, self.dm)\nself.blocks = [EncoderBlock(dm, h, hidden, drop_rate) for _ in range(N)]\nself.dropout = tf.keras.layers.Dropout(drop_rate)",
"seq_len =... | <|body_start_0|>
super().__init__()
self.N = N
self.dm = dm
self.embedding = tf.keras.layers.Embedding(input_vocab, dm)
self.positional_encoding = positional_encoding(max_seq_len, self.dm)
self.blocks = [EncoderBlock(dm, h, hidden, drop_rate) for _ in range(N)]
se... | Encoder class | Encoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
"""Encoder class"""
def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1):
"""init"""
<|body_0|>
def call(self, x, training, mask):
"""call method"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__(... | stack_v2_sparse_classes_75kplus_train_067585 | 8,707 | no_license | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1)"
},
{
"docstring": "call method",
"name": "call",
"signature": "def call(self, x, training, mask)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019566 | Implement the Python class `Encoder` described below.
Class description:
Encoder class
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1): init
- def call(self, x, training, mask): call method | Implement the Python class `Encoder` described below.
Class description:
Encoder class
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1): init
- def call(self, x, training, mask): call method
<|skeleton|>
class Encoder:
"""Encoder class"""
def ... | e8a98d85b3bfd5665cb04bec9ee8c3eb23d6bd58 | <|skeleton|>
class Encoder:
"""Encoder class"""
def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1):
"""init"""
<|body_0|>
def call(self, x, training, mask):
"""call method"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Encoder:
"""Encoder class"""
def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1):
"""init"""
super().__init__()
self.N = N
self.dm = dm
self.embedding = tf.keras.layers.Embedding(input_vocab, dm)
self.positional_encoding = position... | the_stack_v2_python_sparse | supervised_learning/0x12-transformer_apps/5-transformer.py | AndrewMiranda/holbertonschool-machine_learning-1 | train | 0 |
c34ddffde4d67d830ccda0fecfdbfb34f82c6d7d | [
"c = Client()\nfor name, (jsearch, expected) in search_dict.items():\n try:\n response = c.post('/natica/search/', content_type='application/json', data=json.dumps(jsearch))\n except Exception as err:\n return dict(errorMessage='test_search_many: {}'.format(err))\n self.assertJSONEqual(json.d... | <|body_start_0|>
c = Client()
for name, (jsearch, expected) in search_dict.items():
try:
response = c.post('/natica/search/', content_type='application/json', data=json.dumps(jsearch))
except Exception as err:
return dict(errorMessage='test_search_... | SearchTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchTest:
def test_search_many(self):
"""Try one of each type of search clause supported by DAL."""
<|body_0|>
def test_search_0(self):
"""No filter. Verify: API version."""
<|body_1|>
def test_search_1(self):
"""MVP-1. Basics. No validation of... | stack_v2_sparse_classes_75kplus_train_067586 | 10,573 | no_license | [
{
"docstring": "Try one of each type of search clause supported by DAL.",
"name": "test_search_many",
"signature": "def test_search_many(self)"
},
{
"docstring": "No filter. Verify: API version.",
"name": "test_search_0",
"signature": "def test_search_0(self)"
},
{
"docstring": "... | 5 | null | Implement the Python class `SearchTest` described below.
Class description:
Implement the SearchTest class.
Method signatures and docstrings:
- def test_search_many(self): Try one of each type of search clause supported by DAL.
- def test_search_0(self): No filter. Verify: API version.
- def test_search_1(self): MVP-... | Implement the Python class `SearchTest` described below.
Class description:
Implement the SearchTest class.
Method signatures and docstrings:
- def test_search_many(self): Try one of each type of search clause supported by DAL.
- def test_search_0(self): No filter. Verify: API version.
- def test_search_1(self): MVP-... | efd0a6c00fdbdc04f58c3a075623e71eb8e5d723 | <|skeleton|>
class SearchTest:
def test_search_many(self):
"""Try one of each type of search clause supported by DAL."""
<|body_0|>
def test_search_0(self):
"""No filter. Verify: API version."""
<|body_1|>
def test_search_1(self):
"""MVP-1. Basics. No validation of... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SearchTest:
def test_search_many(self):
"""Try one of each type of search clause supported by DAL."""
c = Client()
for name, (jsearch, expected) in search_dict.items():
try:
response = c.post('/natica/search/', content_type='application/json', data=json.dump... | the_stack_v2_python_sparse | naticasite/natica/tests.py | NOAO/natica | train | 1 | |
47e8b638448f00aea63f25b65f3300a5801a9545 | [
"self.question = u''\nself.feedback = u''\nself.setupImage(idevice)",
"self.image = ImageField(x_(u'Image'), x_(u'Choose an optional image to be shown to the student on completion of this question'))\nself.image.idevice = idevice\nself.image.defaultImage = idevice.defaultImage"
] | <|body_start_0|>
self.question = u''
self.feedback = u''
self.setupImage(idevice)
<|end_body_0|>
<|body_start_1|>
self.image = ImageField(x_(u'Image'), x_(u'Choose an optional image to be shown to the student on completion of this question'))
self.image.idevice = idevice
... | A Case iDevice is built up of question and options. Each option can be rendered as an XHTML element | Question | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Question:
"""A Case iDevice is built up of question and options. Each option can be rendered as an XHTML element"""
def __init__(self, idevice):
"""Initialize"""
<|body_0|>
def setupImage(self, idevice):
"""Creates our image field"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus_train_067587 | 5,182 | no_license | [
{
"docstring": "Initialize",
"name": "__init__",
"signature": "def __init__(self, idevice)"
},
{
"docstring": "Creates our image field",
"name": "setupImage",
"signature": "def setupImage(self, idevice)"
}
] | 2 | null | Implement the Python class `Question` described below.
Class description:
A Case iDevice is built up of question and options. Each option can be rendered as an XHTML element
Method signatures and docstrings:
- def __init__(self, idevice): Initialize
- def setupImage(self, idevice): Creates our image field | Implement the Python class `Question` described below.
Class description:
A Case iDevice is built up of question and options. Each option can be rendered as an XHTML element
Method signatures and docstrings:
- def __init__(self, idevice): Initialize
- def setupImage(self, idevice): Creates our image field
<|skeleton... | 1a99c1788f0eb9f1e5d8c2ced3892d00cd9449ad | <|skeleton|>
class Question:
"""A Case iDevice is built up of question and options. Each option can be rendered as an XHTML element"""
def __init__(self, idevice):
"""Initialize"""
<|body_0|>
def setupImage(self, idevice):
"""Creates our image field"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Question:
"""A Case iDevice is built up of question and options. Each option can be rendered as an XHTML element"""
def __init__(self, idevice):
"""Initialize"""
self.question = u''
self.feedback = u''
self.setupImage(idevice)
def setupImage(self, idevice):
""... | the_stack_v2_python_sparse | eXe/rev2669-2722/left-trunk-2722/exe/engine/casestudyidevice.py | joliebig/featurehouse_fstmerge_examples | train | 3 |
da814904d40b66b3e6bd2b8a43af2e420a90ad77 | [
"super(DecoderLayer, self).__init__()\nself.masked_multi_head_attention = MultiHeadAttention(d_model, number_of_heads)\nself.multi_head_attention = MultiHeadAttention(d_model, number_of_heads)\nself.feed_forward_network = point_wise_feed_forward_network(d_model, dff)\nself.normalization_layer1 = tf.keras.layers.Lay... | <|body_start_0|>
super(DecoderLayer, self).__init__()
self.masked_multi_head_attention = MultiHeadAttention(d_model, number_of_heads)
self.multi_head_attention = MultiHeadAttention(d_model, number_of_heads)
self.feed_forward_network = point_wise_feed_forward_network(d_model, dff)
... | Decoder layer consists of masked multi-head attention followed by normalization layer, multi-head attention followed by normalization layer and point wise feed forward network followed by normalization layer | DecoderLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecoderLayer:
"""Decoder layer consists of masked multi-head attention followed by normalization layer, multi-head attention followed by normalization layer and point wise feed forward network followed by normalization layer"""
def __init__(self, d_model, number_of_heads, dff, rate=0.1):
... | stack_v2_sparse_classes_75kplus_train_067588 | 11,425 | no_license | [
{
"docstring": "Constructor for decoder layer :param d_model: dimension of the word embedding vector :param number_of_heads: number of heads to work in parallel :param dff: inner-layer dimensionality :param rate: dropout rate",
"name": "__init__",
"signature": "def __init__(self, d_model, number_of_head... | 2 | stack_v2_sparse_classes_30k_train_001558 | Implement the Python class `DecoderLayer` described below.
Class description:
Decoder layer consists of masked multi-head attention followed by normalization layer, multi-head attention followed by normalization layer and point wise feed forward network followed by normalization layer
Method signatures and docstrings... | Implement the Python class `DecoderLayer` described below.
Class description:
Decoder layer consists of masked multi-head attention followed by normalization layer, multi-head attention followed by normalization layer and point wise feed forward network followed by normalization layer
Method signatures and docstrings... | f164c21ed852dfd10a4701f4050d72dc87bd302a | <|skeleton|>
class DecoderLayer:
"""Decoder layer consists of masked multi-head attention followed by normalization layer, multi-head attention followed by normalization layer and point wise feed forward network followed by normalization layer"""
def __init__(self, d_model, number_of_heads, dff, rate=0.1):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DecoderLayer:
"""Decoder layer consists of masked multi-head attention followed by normalization layer, multi-head attention followed by normalization layer and point wise feed forward network followed by normalization layer"""
def __init__(self, d_model, number_of_heads, dff, rate=0.1):
"""Const... | the_stack_v2_python_sparse | backend/code/transformer_model.py | sovaso/NewsHeadlineGenerator | train | 3 |
1dbaa73d1cca7bcb0c64d9eb3fab062abce6113d | [
"for param in params:\n if param not in self.__info__['space']:\n print('Error: not supported parameters {}'.format(param))\nif self.dataset_type == PROBLEM.CLASSIFICATION:\n model = KNeighborsClassifier(n_neighbors=int(params['Num neighbors']), algorithm=params['Algorithm'], p=int(params['Minkowski po... | <|body_start_0|>
for param in params:
if param not in self.__info__['space']:
print('Error: not supported parameters {}'.format(param))
if self.dataset_type == PROBLEM.CLASSIFICATION:
model = KNeighborsClassifier(n_neighbors=int(params['Num neighbors']), algorithm... | Parameter accepted: - n_neighbors: integer number of nearest neighbors (K). - algorithm: algorithm used to compute the neighbors ('auto', 'ball_tree', 'kd_tree' and 'brute') - dist_power: power parameter for the minkowski metric (p=1 -> L1, P=2 -> L2) | KNeighbors | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KNeighbors:
"""Parameter accepted: - n_neighbors: integer number of nearest neighbors (K). - algorithm: algorithm used to compute the neighbors ('auto', 'ball_tree', 'kd_tree' and 'brute') - dist_power: power parameter for the minkowski metric (p=1 -> L1, P=2 -> L2)"""
def train(self, params... | stack_v2_sparse_classes_75kplus_train_067589 | 3,557 | no_license | [
{
"docstring": "Train the model with the given hyper-parameters. Args: :param params: dictionary of hyper-parameters. :return: trained model.",
"name": "train",
"signature": "def train(self, params)"
},
{
"docstring": "Classify the test set of the chosen dataset and produce the result correspond... | 2 | stack_v2_sparse_classes_30k_train_053183 | Implement the Python class `KNeighbors` described below.
Class description:
Parameter accepted: - n_neighbors: integer number of nearest neighbors (K). - algorithm: algorithm used to compute the neighbors ('auto', 'ball_tree', 'kd_tree' and 'brute') - dist_power: power parameter for the minkowski metric (p=1 -> L1, P=... | Implement the Python class `KNeighbors` described below.
Class description:
Parameter accepted: - n_neighbors: integer number of nearest neighbors (K). - algorithm: algorithm used to compute the neighbors ('auto', 'ball_tree', 'kd_tree' and 'brute') - dist_power: power parameter for the minkowski metric (p=1 -> L1, P=... | 27f861c09615aedfd96cffdebf7d9653f72b4d7b | <|skeleton|>
class KNeighbors:
"""Parameter accepted: - n_neighbors: integer number of nearest neighbors (K). - algorithm: algorithm used to compute the neighbors ('auto', 'ball_tree', 'kd_tree' and 'brute') - dist_power: power parameter for the minkowski metric (p=1 -> L1, P=2 -> L2)"""
def train(self, params... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KNeighbors:
"""Parameter accepted: - n_neighbors: integer number of nearest neighbors (K). - algorithm: algorithm used to compute the neighbors ('auto', 'ball_tree', 'kd_tree' and 'brute') - dist_power: power parameter for the minkowski metric (p=1 -> L1, P=2 -> L2)"""
def train(self, params):
""... | the_stack_v2_python_sparse | API/Metrics/KNeighbors.py | AndreaCorsini1/Ahmet | train | 1 |
22194b07d19eb1b7b8848e24d3f1436ed8d15636 | [
"chart_options = document.chart_options\nlayers = chart_options.layers\nreturn cls._add_hover_tool(chart_layers=layers, plot=base_object)",
"tooltips = []\nfor layer in chart_layers:\n axis = layer.axis\n cls._prepare_tooltip(tooltips=tooltips, axis=axis)\nif len(tooltips) > 0:\n hover_tool = HoverTool(t... | <|body_start_0|>
chart_options = document.chart_options
layers = chart_options.layers
return cls._add_hover_tool(chart_layers=layers, plot=base_object)
<|end_body_0|>
<|body_start_1|>
tooltips = []
for layer in chart_layers:
axis = layer.axis
cls._prepare... | Recipe for creating hover tool on the plot. | HoverToolRecipe | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HoverToolRecipe:
"""Recipe for creating hover tool on the plot."""
def create(cls, document: Chart, base_object: Figure) -> None:
"""Create a hover tool for a plot. :param document: (Chart) chart document object instance. :param base_object: (Figure) bokeh figure to create hover tool... | stack_v2_sparse_classes_75kplus_train_067590 | 9,655 | no_license | [
{
"docstring": "Create a hover tool for a plot. :param document: (Chart) chart document object instance. :param base_object: (Figure) bokeh figure to create hover tool for. :return: None",
"name": "create",
"signature": "def create(cls, document: Chart, base_object: Figure) -> None"
},
{
"docstr... | 3 | stack_v2_sparse_classes_30k_train_052928 | Implement the Python class `HoverToolRecipe` described below.
Class description:
Recipe for creating hover tool on the plot.
Method signatures and docstrings:
- def create(cls, document: Chart, base_object: Figure) -> None: Create a hover tool for a plot. :param document: (Chart) chart document object instance. :para... | Implement the Python class `HoverToolRecipe` described below.
Class description:
Recipe for creating hover tool on the plot.
Method signatures and docstrings:
- def create(cls, document: Chart, base_object: Figure) -> None: Create a hover tool for a plot. :param document: (Chart) chart document object instance. :para... | eae965a1eb6f53ec5bd5ab961ec0383737165ce4 | <|skeleton|>
class HoverToolRecipe:
"""Recipe for creating hover tool on the plot."""
def create(cls, document: Chart, base_object: Figure) -> None:
"""Create a hover tool for a plot. :param document: (Chart) chart document object instance. :param base_object: (Figure) bokeh figure to create hover tool... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HoverToolRecipe:
"""Recipe for creating hover tool on the plot."""
def create(cls, document: Chart, base_object: Figure) -> None:
"""Create a hover tool for a plot. :param document: (Chart) chart document object instance. :param base_object: (Figure) bokeh figure to create hover tool for. :return... | the_stack_v2_python_sparse | Visualiser/modules/charts/creators.py | RadoslawPotyka/DataVisualiser | train | 0 |
a35aa2414811648dbc9f44eb89346fcb4ca0781d | [
"self.action = action\nself.cluster_info = cluster_info\nself.details = details\nself.domain = domain\nself.entity_id = entity_id\nself.entity_name = entity_name\nself.entity_type = entity_type\nself.human_timestamp = human_timestamp\nself.impersonation = impersonation\nself.ip = ip\nself.new_record = new_record\ns... | <|body_start_0|>
self.action = action
self.cluster_info = cluster_info
self.details = details
self.domain = domain
self.entity_id = entity_id
self.entity_name = entity_name
self.entity_type = entity_type
self.human_timestamp = human_timestamp
self.... | Implementation of the 'ClusterAuditLog' model. Specifies information about a single Cluster audit log. When an action (such as pausing a Protection Job) occurs, an audit log is generated that provides details about the action. Attributes: action (string): Specifies the action that caused the log to be generated. cluste... | ClusterAuditLog | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClusterAuditLog:
"""Implementation of the 'ClusterAuditLog' model. Specifies information about a single Cluster audit log. When an action (such as pausing a Protection Job) occurs, an audit log is generated that provides details about the action. Attributes: action (string): Specifies the action ... | stack_v2_sparse_classes_75kplus_train_067591 | 6,311 | permissive | [
{
"docstring": "Constructor for the ClusterAuditLog class",
"name": "__init__",
"signature": "def __init__(self, action=None, cluster_info=None, details=None, domain=None, entity_id=None, entity_name=None, entity_type=None, human_timestamp=None, impersonation=None, ip=None, new_record=None, original_ten... | 2 | stack_v2_sparse_classes_30k_train_045433 | Implement the Python class `ClusterAuditLog` described below.
Class description:
Implementation of the 'ClusterAuditLog' model. Specifies information about a single Cluster audit log. When an action (such as pausing a Protection Job) occurs, an audit log is generated that provides details about the action. Attributes:... | Implement the Python class `ClusterAuditLog` described below.
Class description:
Implementation of the 'ClusterAuditLog' model. Specifies information about a single Cluster audit log. When an action (such as pausing a Protection Job) occurs, an audit log is generated that provides details about the action. Attributes:... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ClusterAuditLog:
"""Implementation of the 'ClusterAuditLog' model. Specifies information about a single Cluster audit log. When an action (such as pausing a Protection Job) occurs, an audit log is generated that provides details about the action. Attributes: action (string): Specifies the action ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ClusterAuditLog:
"""Implementation of the 'ClusterAuditLog' model. Specifies information about a single Cluster audit log. When an action (such as pausing a Protection Job) occurs, an audit log is generated that provides details about the action. Attributes: action (string): Specifies the action that caused t... | the_stack_v2_python_sparse | cohesity_management_sdk/models/cluster_audit_log.py | cohesity/management-sdk-python | train | 24 |
523180d9ca36ae28f02cb325e7ff8bdde9ad6886 | [
"m_file = mock.MagicMock()\nwith mock.patch('sys.version_info', new=(2, 7)), mock.patch('imp.find_module', return_value=(m_file, 'p', 'd')) as m_find_module, mock.patch('imp.load_module', return_value='mod') as m_load_module:\n self.assertEqual(tested._load_module_file('mymod', 'my/path'), 'mod')\n m_find_mod... | <|body_start_0|>
m_file = mock.MagicMock()
with mock.patch('sys.version_info', new=(2, 7)), mock.patch('imp.find_module', return_value=(m_file, 'p', 'd')) as m_find_module, mock.patch('imp.load_module', return_value='mod') as m_load_module:
self.assertEqual(tested._load_module_file('mymod', ... | Test__load_module_file | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test__load_module_file:
def test__load_module_file_py27(self):
"""Test SConsArguments.Importer._load_module_file() with python 2.7"""
<|body_0|>
def test__load_module_file_py33(self):
"""Test SConsArguments.Importer._load_module_file() with python 3.3"""
<|bo... | stack_v2_sparse_classes_75kplus_train_067592 | 42,804 | permissive | [
{
"docstring": "Test SConsArguments.Importer._load_module_file() with python 2.7",
"name": "test__load_module_file_py27",
"signature": "def test__load_module_file_py27(self)"
},
{
"docstring": "Test SConsArguments.Importer._load_module_file() with python 3.3",
"name": "test__load_module_file... | 3 | stack_v2_sparse_classes_30k_train_036942 | Implement the Python class `Test__load_module_file` described below.
Class description:
Implement the Test__load_module_file class.
Method signatures and docstrings:
- def test__load_module_file_py27(self): Test SConsArguments.Importer._load_module_file() with python 2.7
- def test__load_module_file_py33(self): Test ... | Implement the Python class `Test__load_module_file` described below.
Class description:
Implement the Test__load_module_file class.
Method signatures and docstrings:
- def test__load_module_file_py27(self): Test SConsArguments.Importer._load_module_file() with python 2.7
- def test__load_module_file_py33(self): Test ... | f4b783fc79fe3fc16e8d0f58308099a67752d299 | <|skeleton|>
class Test__load_module_file:
def test__load_module_file_py27(self):
"""Test SConsArguments.Importer._load_module_file() with python 2.7"""
<|body_0|>
def test__load_module_file_py33(self):
"""Test SConsArguments.Importer._load_module_file() with python 3.3"""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test__load_module_file:
def test__load_module_file_py27(self):
"""Test SConsArguments.Importer._load_module_file() with python 2.7"""
m_file = mock.MagicMock()
with mock.patch('sys.version_info', new=(2, 7)), mock.patch('imp.find_module', return_value=(m_file, 'p', 'd')) as m_find_modu... | the_stack_v2_python_sparse | unit_tests/SConsArgumentsT/ImporterTests.py | mcqueen256/scons-arguments | train | 0 | |
f3fd24ebb6726ed8618b8569695c29a602314230 | [
"StructProject.__init__(self, name_project, author, domain)\nif not os.path.exists(self.projectfolder):\n logger.error('[ ✗ ] Not exist name of project.')\n raise Exception('Not exist name of project.')\nself.templatesfolder = os.path.join(self.projectfolder, 'templates')",
"custom_name = self._clean_name(n... | <|body_start_0|>
StructProject.__init__(self, name_project, author, domain)
if not os.path.exists(self.projectfolder):
logger.error('[ ✗ ] Not exist name of project.')
raise Exception('Not exist name of project.')
self.templatesfolder = os.path.join(self.projectfolder, 't... | Represents Template. Template is an object that create templates modules. :class:`commands.Template` See :ref:`templates` for more information. | Template | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Template:
"""Represents Template. Template is an object that create templates modules. :class:`commands.Template` See :ref:`templates` for more information."""
def __init__(self, name_project, author, domain):
"""Init function."""
<|body_0|>
def ger_custom(self, name):
... | stack_v2_sparse_classes_75kplus_train_067593 | 16,173 | permissive | [
{
"docstring": "Init function.",
"name": "__init__",
"signature": "def __init__(self, name_project, author, domain)"
},
{
"docstring": "Generating custom template.",
"name": "ger_custom",
"signature": "def ger_custom(self, name)"
}
] | 2 | stack_v2_sparse_classes_30k_train_039252 | Implement the Python class `Template` described below.
Class description:
Represents Template. Template is an object that create templates modules. :class:`commands.Template` See :ref:`templates` for more information.
Method signatures and docstrings:
- def __init__(self, name_project, author, domain): Init function.... | Implement the Python class `Template` described below.
Class description:
Represents Template. Template is an object that create templates modules. :class:`commands.Template` See :ref:`templates` for more information.
Method signatures and docstrings:
- def __init__(self, name_project, author, domain): Init function.... | bcb1be6a67c10a444534db9913f03d7a3268ccb1 | <|skeleton|>
class Template:
"""Represents Template. Template is an object that create templates modules. :class:`commands.Template` See :ref:`templates` for more information."""
def __init__(self, name_project, author, domain):
"""Init function."""
<|body_0|>
def ger_custom(self, name):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Template:
"""Represents Template. Template is an object that create templates modules. :class:`commands.Template` See :ref:`templates` for more information."""
def __init__(self, name_project, author, domain):
"""Init function."""
StructProject.__init__(self, name_project, author, domain)... | the_stack_v2_python_sparse | zeusproject/commands.py | murilobsd/zeus | train | 6 |
aeb305f867b1b2a6c3b31bfc543aab01881bee7c | [
"self.bring_disks_online = bring_disks_online\nself.mount_volume_results = mount_volume_results\nself.other_error = other_error\nself.target_source_id = target_source_id\nself.username = username",
"if dictionary is None:\n return None\nbring_disks_online = dictionary.get('bringDisksOnline')\nmount_volume_resu... | <|body_start_0|>
self.bring_disks_online = bring_disks_online
self.mount_volume_results = mount_volume_results
self.other_error = other_error
self.target_source_id = target_source_id
self.username = username
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
... | Implementation of the 'MountVolumesState' model. Specifies the states of mounting all the volumes onto a mount target for a 'kRecoverVMs' Restore Task. Attributes: bring_disks_online (bool): Optional setting that determines if the volumes are brought online on the mount target after attaching the disks. This option is ... | MountVolumesState | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MountVolumesState:
"""Implementation of the 'MountVolumesState' model. Specifies the states of mounting all the volumes onto a mount target for a 'kRecoverVMs' Restore Task. Attributes: bring_disks_online (bool): Optional setting that determines if the volumes are brought online on the mount targ... | stack_v2_sparse_classes_75kplus_train_067594 | 3,734 | permissive | [
{
"docstring": "Constructor for the MountVolumesState class",
"name": "__init__",
"signature": "def __init__(self, bring_disks_online=None, mount_volume_results=None, other_error=None, target_source_id=None, username=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary A... | 2 | stack_v2_sparse_classes_30k_train_001118 | Implement the Python class `MountVolumesState` described below.
Class description:
Implementation of the 'MountVolumesState' model. Specifies the states of mounting all the volumes onto a mount target for a 'kRecoverVMs' Restore Task. Attributes: bring_disks_online (bool): Optional setting that determines if the volum... | Implement the Python class `MountVolumesState` described below.
Class description:
Implementation of the 'MountVolumesState' model. Specifies the states of mounting all the volumes onto a mount target for a 'kRecoverVMs' Restore Task. Attributes: bring_disks_online (bool): Optional setting that determines if the volum... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class MountVolumesState:
"""Implementation of the 'MountVolumesState' model. Specifies the states of mounting all the volumes onto a mount target for a 'kRecoverVMs' Restore Task. Attributes: bring_disks_online (bool): Optional setting that determines if the volumes are brought online on the mount targ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MountVolumesState:
"""Implementation of the 'MountVolumesState' model. Specifies the states of mounting all the volumes onto a mount target for a 'kRecoverVMs' Restore Task. Attributes: bring_disks_online (bool): Optional setting that determines if the volumes are brought online on the mount target after atta... | the_stack_v2_python_sparse | cohesity_management_sdk/models/mount_volumes_state.py | cohesity/management-sdk-python | train | 24 |
799e21a3097e1e3d725c443cdac5c82df799111d | [
"super().__init__()\nself.env = env\nself.env.seed(0)\nself.reward_state_is_done = (0.0, None, False)",
"state = self.env.reset()\nself.reward_state_is_done = (0.0, state, False)\nreturn state",
"current_state, reward, is_terminal, _ = self.env.step(action)\nself.reward_state_is_done = (reward, current_state, i... | <|body_start_0|>
super().__init__()
self.env = env
self.env.seed(0)
self.reward_state_is_done = (0.0, None, False)
<|end_body_0|>
<|body_start_1|>
state = self.env.reset()
self.reward_state_is_done = (0.0, state, False)
return state
<|end_body_1|>
<|body_start_2... | Environment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Environment:
def __init__(self, env):
"""Setup for the environment called when the environment first starts"""
<|body_0|>
def reset(self):
"""The first method called when the experiment starts, called before the agent starts. :return: The first state state from the e... | stack_v2_sparse_classes_75kplus_train_067595 | 1,163 | no_license | [
{
"docstring": "Setup for the environment called when the environment first starts",
"name": "__init__",
"signature": "def __init__(self, env)"
},
{
"docstring": "The first method called when the experiment starts, called before the agent starts. :return: The first state state from the environme... | 3 | stack_v2_sparse_classes_30k_train_034227 | Implement the Python class `Environment` described below.
Class description:
Implement the Environment class.
Method signatures and docstrings:
- def __init__(self, env): Setup for the environment called when the environment first starts
- def reset(self): The first method called when the experiment starts, called be... | Implement the Python class `Environment` described below.
Class description:
Implement the Environment class.
Method signatures and docstrings:
- def __init__(self, env): Setup for the environment called when the environment first starts
- def reset(self): The first method called when the experiment starts, called be... | 006e6c45b1b99daf1028d596c5be19f67a103a1a | <|skeleton|>
class Environment:
def __init__(self, env):
"""Setup for the environment called when the environment first starts"""
<|body_0|>
def reset(self):
"""The first method called when the experiment starts, called before the agent starts. :return: The first state state from the e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Environment:
def __init__(self, env):
"""Setup for the environment called when the environment first starts"""
super().__init__()
self.env = env
self.env.seed(0)
self.reward_state_is_done = (0.0, None, False)
def reset(self):
"""The first method called when... | the_stack_v2_python_sparse | Project_2/lunar_lander/environment.py | rushidesai1/ReinforcementLearningProjects | train | 0 | |
7a92f78752dcb3224a3f66c6bf886058c0f4625e | [
"lines_count = 0\nfor row in range(board.row_size):\n for col in range(board.column_size):\n if board.getAt(row, col) == player_value:\n lines_count += self.check_verticals_count(board, row, col, player_value, next_discs)\n lines_count += self.check_horizontals_count(board, row, col,... | <|body_start_0|>
lines_count = 0
for row in range(board.row_size):
for col in range(board.column_size):
if board.getAt(row, col) == player_value:
lines_count += self.check_verticals_count(board, row, col, player_value, next_discs)
lines... | Secuential_Count_Checker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Secuential_Count_Checker:
def check_lines(self, board, player_value, next_discs):
"""Overwrited function, deffers from its father in calling check_diagonals instead of check_diagonals_count"""
<|body_0|>
def check_horizontals_count(self, board, row, col, player_value, next_d... | stack_v2_sparse_classes_75kplus_train_067596 | 22,987 | no_license | [
{
"docstring": "Overwrited function, deffers from its father in calling check_diagonals instead of check_diagonals_count",
"name": "check_lines",
"signature": "def check_lines(self, board, player_value, next_discs)"
},
{
"docstring": "Overwrited function it differs from it father when asign disc... | 3 | null | Implement the Python class `Secuential_Count_Checker` described below.
Class description:
Implement the Secuential_Count_Checker class.
Method signatures and docstrings:
- def check_lines(self, board, player_value, next_discs): Overwrited function, deffers from its father in calling check_diagonals instead of check_d... | Implement the Python class `Secuential_Count_Checker` described below.
Class description:
Implement the Secuential_Count_Checker class.
Method signatures and docstrings:
- def check_lines(self, board, player_value, next_discs): Overwrited function, deffers from its father in calling check_diagonals instead of check_d... | 1fc3be2163adde10405bfd3a98579d2346ee49ec | <|skeleton|>
class Secuential_Count_Checker:
def check_lines(self, board, player_value, next_discs):
"""Overwrited function, deffers from its father in calling check_diagonals instead of check_diagonals_count"""
<|body_0|>
def check_horizontals_count(self, board, row, col, player_value, next_d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Secuential_Count_Checker:
def check_lines(self, board, player_value, next_discs):
"""Overwrited function, deffers from its father in calling check_diagonals instead of check_diagonals_count"""
lines_count = 0
for row in range(board.row_size):
for col in range(board.column_s... | the_stack_v2_python_sparse | WinAndBlock/WinAndBlock.py | anthonylle/IA-Proyecto2 | train | 0 | |
3b2d99644c451512a8d61ff253b45e91bce81bae | [
"if fl_model is None:\n fl_model = NaiveBayesFLModel('naive-bayes', None, GaussianNB())\nsuper().__init__(hyperparams, proto_handler, data_handler, fl_model, **kwargs)\nself.name = 'NaiveBayesFusion'\nself.model_update = fl_model.get_model_update() if fl_model else None",
"collected_theta = None\ncollected_var... | <|body_start_0|>
if fl_model is None:
fl_model = NaiveBayesFLModel('naive-bayes', None, GaussianNB())
super().__init__(hyperparams, proto_handler, data_handler, fl_model, **kwargs)
self.name = 'NaiveBayesFusion'
self.model_update = fl_model.get_model_update() if fl_model else... | Class for Gaussian Naive Bayes federated learning with differential privacy. Implements GaussianNB from diffprivlib, with party updates combined with the fusion handler. | NaiveBayesFusionHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NaiveBayesFusionHandler:
"""Class for Gaussian Naive Bayes federated learning with differential privacy. Implements GaussianNB from diffprivlib, with party updates combined with the fusion handler."""
def __init__(self, hyperparams, proto_handler, data_handler, fl_model=None, **kwargs):
... | stack_v2_sparse_classes_75kplus_train_067597 | 5,345 | permissive | [
{
"docstring": "Initializes a NaiveBayesFusionHandler object with provided fl_model, data_handler, proto_handler and hyperparams. :param hyperparams: Hyperparameters used for training. :type hyperparams: `dict` :param proto_handler: Proto_handler that will be used to send message :type proto_handler: `ProtoHand... | 4 | stack_v2_sparse_classes_30k_train_024987 | Implement the Python class `NaiveBayesFusionHandler` described below.
Class description:
Class for Gaussian Naive Bayes federated learning with differential privacy. Implements GaussianNB from diffprivlib, with party updates combined with the fusion handler.
Method signatures and docstrings:
- def __init__(self, hype... | Implement the Python class `NaiveBayesFusionHandler` described below.
Class description:
Class for Gaussian Naive Bayes federated learning with differential privacy. Implements GaussianNB from diffprivlib, with party updates combined with the fusion handler.
Method signatures and docstrings:
- def __init__(self, hype... | 64ffa2ee2e906b1bd6b3dd6aabcf6fc3de862608 | <|skeleton|>
class NaiveBayesFusionHandler:
"""Class for Gaussian Naive Bayes federated learning with differential privacy. Implements GaussianNB from diffprivlib, with party updates combined with the fusion handler."""
def __init__(self, hyperparams, proto_handler, data_handler, fl_model=None, **kwargs):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NaiveBayesFusionHandler:
"""Class for Gaussian Naive Bayes federated learning with differential privacy. Implements GaussianNB from diffprivlib, with party updates combined with the fusion handler."""
def __init__(self, hyperparams, proto_handler, data_handler, fl_model=None, **kwargs):
"""Initia... | the_stack_v2_python_sparse | debugging-constructs/ibmfl/aggregator/fusion/naive_bayes_fusion_handler.py | SEED-VT/FedDebug | train | 8 |
d9c2e0bef262bcb91ba24c8bdb6b2ca2f2c4f674 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn UnifiedRoleDefinition()",
"from .entity import Entity\nfrom .unified_role_permission import UnifiedRolePermission\nfrom .entity import Entity\nfrom .unified_role_permission import UnifiedRolePermission\nfields: Dict[str, Callable[[Any]... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return UnifiedRoleDefinition()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .unified_role_permission import UnifiedRolePermission
from .entity import Entity
f... | UnifiedRoleDefinition | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnifiedRoleDefinition:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedRoleDefinition:
"""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 th... | stack_v2_sparse_classes_75kplus_train_067598 | 5,302 | 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: UnifiedRoleDefinition",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminat... | 3 | stack_v2_sparse_classes_30k_train_035974 | Implement the Python class `UnifiedRoleDefinition` described below.
Class description:
Implement the UnifiedRoleDefinition class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedRoleDefinition: Creates a new instance of the appropriate class base... | Implement the Python class `UnifiedRoleDefinition` described below.
Class description:
Implement the UnifiedRoleDefinition class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedRoleDefinition: Creates a new instance of the appropriate class base... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class UnifiedRoleDefinition:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedRoleDefinition:
"""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 th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UnifiedRoleDefinition:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedRoleDefinition:
"""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 Retur... | the_stack_v2_python_sparse | msgraph/generated/models/unified_role_definition.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
3cbc59f3a8831e69fcadabc56560c909c2c1fcea | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ObjectMapping()",
"from .attribute_mapping import AttributeMapping\nfrom .filter import Filter\nfrom .object_flow_types import ObjectFlowTypes\nfrom .object_mapping_metadata_entry import ObjectMappingMetadataEntry\nfrom .attribute_mapp... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ObjectMapping()
<|end_body_0|>
<|body_start_1|>
from .attribute_mapping import AttributeMapping
from .filter import Filter
from .object_flow_types import ObjectFlowTypes
... | ObjectMapping | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectMapping:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ObjectMapping:
"""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... | stack_v2_sparse_classes_75kplus_train_067599 | 5,553 | 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: ObjectMapping",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value... | 3 | stack_v2_sparse_classes_30k_train_039677 | Implement the Python class `ObjectMapping` described below.
Class description:
Implement the ObjectMapping class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ObjectMapping: Creates a new instance of the appropriate class based on discriminator value... | Implement the Python class `ObjectMapping` described below.
Class description:
Implement the ObjectMapping class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ObjectMapping: Creates a new instance of the appropriate class based on discriminator value... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ObjectMapping:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ObjectMapping:
"""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... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ObjectMapping:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ObjectMapping:
"""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: ObjectMappin... | the_stack_v2_python_sparse | msgraph/generated/models/object_mapping.py | microsoftgraph/msgraph-sdk-python | train | 135 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.