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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1b507d9c7bbc9f1f6fd9ed7626d1efcb74ccc505 | [
"base.ASYNC_FLAG.AddToParser(parser)\nflags.AddRegion(parser)\nflags.AddCluster(parser)\nflags.AddPrimaryCluster(parser)\nflags.AddAllocatedIPRangeName(parser)\nkms_resource_args.AddKmsKeyResourceArg(parser, 'cluster', permission_info=\"The 'AlloyDB Service Agent' service account must hold permission 'Cloud KMS Cry... | <|body_start_0|>
base.ASYNC_FLAG.AddToParser(parser)
flags.AddRegion(parser)
flags.AddCluster(parser)
flags.AddPrimaryCluster(parser)
flags.AddAllocatedIPRangeName(parser)
kms_resource_args.AddKmsKeyResourceArg(parser, 'cluster', permission_info="The 'AlloyDB Service Agen... | Create a new AlloyDB SECONDARY cluster within a given project. | CreateSecondary | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateSecondary:
"""Create a new AlloyDB SECONDARY cluster within a given project."""
def Args(parser):
"""Specifies additional command flags. Args: parser: argparse.Parser: Parser object for command line inputs."""
<|body_0|>
def Run(self, args):
"""Constructs a... | stack_v2_sparse_classes_75kplus_train_073700 | 4,064 | permissive | [
{
"docstring": "Specifies additional command flags. Args: parser: argparse.Parser: Parser object for command line inputs.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "Constructs and sends request. Args: args: argparse.Namespace, An object that contains the values for the ... | 2 | stack_v2_sparse_classes_30k_train_034282 | Implement the Python class `CreateSecondary` described below.
Class description:
Create a new AlloyDB SECONDARY cluster within a given project.
Method signatures and docstrings:
- def Args(parser): Specifies additional command flags. Args: parser: argparse.Parser: Parser object for command line inputs.
- def Run(self... | Implement the Python class `CreateSecondary` described below.
Class description:
Create a new AlloyDB SECONDARY cluster within a given project.
Method signatures and docstrings:
- def Args(parser): Specifies additional command flags. Args: parser: argparse.Parser: Parser object for command line inputs.
- def Run(self... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class CreateSecondary:
"""Create a new AlloyDB SECONDARY cluster within a given project."""
def Args(parser):
"""Specifies additional command flags. Args: parser: argparse.Parser: Parser object for command line inputs."""
<|body_0|>
def Run(self, args):
"""Constructs a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CreateSecondary:
"""Create a new AlloyDB SECONDARY cluster within a given project."""
def Args(parser):
"""Specifies additional command flags. Args: parser: argparse.Parser: Parser object for command line inputs."""
base.ASYNC_FLAG.AddToParser(parser)
flags.AddRegion(parser)
... | the_stack_v2_python_sparse | lib/surface/alloydb/clusters/create_secondary.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
5e529dbd895398551c9be8f898244e599748cfb5 | [
"self.db_connect = kwargs.get('db_connect')\nif self.db_connect is None:\n raise ValueError('db_connect is required in the handler.')\nself.con = psycopg2.connect(self.db_connect)\nself.cur = self.con.cursor()\nif self.cur is None:\n raise ValueError('cursor has not been opened.')\nself.sql_create_table = kwa... | <|body_start_0|>
self.db_connect = kwargs.get('db_connect')
if self.db_connect is None:
raise ValueError('db_connect is required in the handler.')
self.con = psycopg2.connect(self.db_connect)
self.cur = self.con.cursor()
if self.cur is None:
raise ValueErr... | e.g. from db_postgres import db_connector class handler(connector_postgres): pass p = handler(logger=self.logger, debug_level=self.debug_level, db_connect="parameter_for_connect") p.submit(kv_data) e.g. of <parameter_for_connect> host=127.0.0.1 port=5432 dbname=postgres user=demo password=demo1 | db_connector | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class db_connector:
"""e.g. from db_postgres import db_connector class handler(connector_postgres): pass p = handler(logger=self.logger, debug_level=self.debug_level, db_connect="parameter_for_connect") p.submit(kv_data) e.g. of <parameter_for_connect> host=127.0.0.1 port=5432 dbname=postgres user=demo... | stack_v2_sparse_classes_75kplus_train_073701 | 1,935 | permissive | [
{
"docstring": "db_connect is mandate.",
"name": "db_init",
"signature": "def db_init(self, **kwargs)"
},
{
"docstring": "this method will call self.make_insert_string(). the value of make_insert_string method: None: ignore this data. (string): insert SQL",
"name": "db_submit",
"signatur... | 2 | stack_v2_sparse_classes_30k_train_001498 | Implement the Python class `db_connector` described below.
Class description:
e.g. from db_postgres import db_connector class handler(connector_postgres): pass p = handler(logger=self.logger, debug_level=self.debug_level, db_connect="parameter_for_connect") p.submit(kv_data) e.g. of <parameter_for_connect> host=127.0.... | Implement the Python class `db_connector` described below.
Class description:
e.g. from db_postgres import db_connector class handler(connector_postgres): pass p = handler(logger=self.logger, debug_level=self.debug_level, db_connect="parameter_for_connect") p.submit(kv_data) e.g. of <parameter_for_connect> host=127.0.... | f473be5bc88a2dab0b1dbe6734ec70b71fd8b48b | <|skeleton|>
class db_connector:
"""e.g. from db_postgres import db_connector class handler(connector_postgres): pass p = handler(logger=self.logger, debug_level=self.debug_level, db_connect="parameter_for_connect") p.submit(kv_data) e.g. of <parameter_for_connect> host=127.0.0.1 port=5432 dbname=postgres user=demo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class db_connector:
"""e.g. from db_postgres import db_connector class handler(connector_postgres): pass p = handler(logger=self.logger, debug_level=self.debug_level, db_connect="parameter_for_connect") p.submit(kv_data) e.g. of <parameter_for_connect> host=127.0.0.1 port=5432 dbname=postgres user=demo password=dem... | the_stack_v2_python_sparse | db_connectors/db_connector_postgres.py | just-kuna/lorawan-ssas | train | 0 |
519cb248c55b1e7cfcd9306e208c8df24942b6cd | [
"gph = [[[], []] for _ in range(n)]\nres = [[n * 2] * 2 for _ in range(n)]\nres[0] = [0, 0]\nlen_res = n << 1\nqueue = [(0, 0), (0, 1)]\nfor s, e in red_edges:\n gph[s][0].append(e)\nfor s, e in blue_edges:\n gph[s][1].append(e)\nfor si, c in queue:\n for ei in gph[si][c]:\n if res[ei][c] == len_res... | <|body_start_0|>
gph = [[[], []] for _ in range(n)]
res = [[n * 2] * 2 for _ in range(n)]
res[0] = [0, 0]
len_res = n << 1
queue = [(0, 0), (0, 1)]
for s, e in red_edges:
gph[s][0].append(e)
for s, e in blue_edges:
gph[s][1].append(e)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def shortestAlternatingPaths(self, n, red_edges, blue_edges):
""":type n: int :type red_edges: List[List[int]] :type blue_edges: List[List[int]] :rtype: List[int]"""
<|body_0|>
def shortestAlternatingPaths2(self, n, red_edges, blue_edges):
""":type n: int :... | stack_v2_sparse_classes_75kplus_train_073702 | 6,587 | no_license | [
{
"docstring": ":type n: int :type red_edges: List[List[int]] :type blue_edges: List[List[int]] :rtype: List[int]",
"name": "shortestAlternatingPaths",
"signature": "def shortestAlternatingPaths(self, n, red_edges, blue_edges)"
},
{
"docstring": ":type n: int :type red_edges: List[List[int]] :ty... | 2 | stack_v2_sparse_classes_30k_train_039576 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def shortestAlternatingPaths(self, n, red_edges, blue_edges): :type n: int :type red_edges: List[List[int]] :type blue_edges: List[List[int]] :rtype: List[int]
- def shortestAlte... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def shortestAlternatingPaths(self, n, red_edges, blue_edges): :type n: int :type red_edges: List[List[int]] :type blue_edges: List[List[int]] :rtype: List[int]
- def shortestAlte... | dbdb227e12f329e4ca064b338f1fbdca42f3a848 | <|skeleton|>
class Solution:
def shortestAlternatingPaths(self, n, red_edges, blue_edges):
""":type n: int :type red_edges: List[List[int]] :type blue_edges: List[List[int]] :rtype: List[int]"""
<|body_0|>
def shortestAlternatingPaths2(self, n, red_edges, blue_edges):
""":type n: int :... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def shortestAlternatingPaths(self, n, red_edges, blue_edges):
""":type n: int :type red_edges: List[List[int]] :type blue_edges: List[List[int]] :rtype: List[int]"""
gph = [[[], []] for _ in range(n)]
res = [[n * 2] * 2 for _ in range(n)]
res[0] = [0, 0]
len_r... | the_stack_v2_python_sparse | LC1129.py | Qiao-Liang/LeetCode | train | 0 | |
ca3e6c50ee6c12dfed3588318923f3633bf9dc9a | [
"try:\n verify_token(request.headers)\nexcept Exception as err:\n ns.abort(401, message=err)\noffset = request.args.get('offset', '0')\nlimit = request.args.get('limit', '10')\norder_by = request.args.get('order_by', 'id')\norder = request.args.get('order', 'ASC')\nper_page = request.args.get('per_page', '10'... | <|body_start_0|>
try:
verify_token(request.headers)
except Exception as err:
ns.abort(401, message=err)
offset = request.args.get('offset', '0')
limit = request.args.get('limit', '10')
order_by = request.args.get('order_by', 'id')
order = request.a... | ObservacionCyTGList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObservacionCyTGList:
def get(self):
"""To fetch several observations (CyTG (resultados)). On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages"""
<|body_0|>
def post(self):
"""To create an observation (CyTG (resultados))."""
<|body_1... | stack_v2_sparse_classes_75kplus_train_073703 | 18,120 | no_license | [
{
"docstring": "To fetch several observations (CyTG (resultados)). On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "To create an observation (CyTG (resultados)).",
"name": "post",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_043204 | Implement the Python class `ObservacionCyTGList` described below.
Class description:
Implement the ObservacionCyTGList class.
Method signatures and docstrings:
- def get(self): To fetch several observations (CyTG (resultados)). On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages
- def post(... | Implement the Python class `ObservacionCyTGList` described below.
Class description:
Implement the ObservacionCyTGList class.
Method signatures and docstrings:
- def get(self): To fetch several observations (CyTG (resultados)). On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages
- def post(... | e00610fac26ef3ca078fd037c0649b70fa0e9a09 | <|skeleton|>
class ObservacionCyTGList:
def get(self):
"""To fetch several observations (CyTG (resultados)). On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages"""
<|body_0|>
def post(self):
"""To create an observation (CyTG (resultados))."""
<|body_1... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ObservacionCyTGList:
def get(self):
"""To fetch several observations (CyTG (resultados)). On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages"""
try:
verify_token(request.headers)
except Exception as err:
ns.abort(401, message=err)
... | the_stack_v2_python_sparse | DOS/soa/service/genl/endpoints/observaciones_ires_cytg.py | Telematica/knight-rider | train | 1 | |
c7247df9f2c30e26fdfb0af7aab0043f0897364d | [
"skill = Skill.objects.create(**data)\nSkillIndex.store_index(skill)\nreturn skill",
"instance.name = data.get('name')\nSkillIndex.store_index(instance)\nreturn instance"
] | <|body_start_0|>
skill = Skill.objects.create(**data)
SkillIndex.store_index(skill)
return skill
<|end_body_0|>
<|body_start_1|>
instance.name = data.get('name')
SkillIndex.store_index(instance)
return instance
<|end_body_1|>
| Serializer for Skill objects. | SkillSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SkillSerializer:
"""Serializer for Skill objects."""
def create(self, data):
"""Create new instance of the skill."""
<|body_0|>
def update(self, instance, data):
"""Update new instance of the skill."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_073704 | 689 | no_license | [
{
"docstring": "Create new instance of the skill.",
"name": "create",
"signature": "def create(self, data)"
},
{
"docstring": "Update new instance of the skill.",
"name": "update",
"signature": "def update(self, instance, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_034995 | Implement the Python class `SkillSerializer` described below.
Class description:
Serializer for Skill objects.
Method signatures and docstrings:
- def create(self, data): Create new instance of the skill.
- def update(self, instance, data): Update new instance of the skill. | Implement the Python class `SkillSerializer` described below.
Class description:
Serializer for Skill objects.
Method signatures and docstrings:
- def create(self, data): Create new instance of the skill.
- def update(self, instance, data): Update new instance of the skill.
<|skeleton|>
class SkillSerializer:
""... | 252b0ebd77eefbcc945a0efc3068cc3421f46d5f | <|skeleton|>
class SkillSerializer:
"""Serializer for Skill objects."""
def create(self, data):
"""Create new instance of the skill."""
<|body_0|>
def update(self, instance, data):
"""Update new instance of the skill."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SkillSerializer:
"""Serializer for Skill objects."""
def create(self, data):
"""Create new instance of the skill."""
skill = Skill.objects.create(**data)
SkillIndex.store_index(skill)
return skill
def update(self, instance, data):
"""Update new instance of the... | the_stack_v2_python_sparse | app/skills/serializers.py | vsokoltsov/Interview360Server | train | 2 |
5941b852eabd3249c528b15a7ac173121b2c64dc | [
"self.input_path = input\nself.pack_name = get_pack_name(file_path=self.input_path)\nself.pack_path = os.path.join(PACKS_DIR, self.pack_name)\nself.input_file_name = os.path.basename(self.input_path).rstrip('.json')\nself.use_force = force\nself.marketplace = marketplace\nif output:\n if not os.path.isdir(output... | <|body_start_0|>
self.input_path = input
self.pack_name = get_pack_name(file_path=self.input_path)
self.pack_path = os.path.join(PACKS_DIR, self.pack_name)
self.input_file_name = os.path.basename(self.input_path).rstrip('.json')
self.use_force = force
self.marketplace = m... | Unifies a GenericModule object with it's Dashboards | GenericModuleUnifier | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenericModuleUnifier:
"""Unifies a GenericModule object with it's Dashboards"""
def __init__(self, input: str, output: str='', force: bool=False, marketplace: Optional[str]=None, **kwargs):
"""Init a GenericModuleUnifier Args: input: a path of the GenericModule file to unify. output:... | stack_v2_sparse_classes_75kplus_train_073705 | 4,492 | permissive | [
{
"docstring": "Init a GenericModuleUnifier Args: input: a path of the GenericModule file to unify. output: The output dir to write the unified GenericModule json to. force: if True - Forcefully overwrites the preexisting unified GenericModule file if one exists.",
"name": "__init__",
"signature": "def ... | 4 | stack_v2_sparse_classes_30k_test_000748 | Implement the Python class `GenericModuleUnifier` described below.
Class description:
Unifies a GenericModule object with it's Dashboards
Method signatures and docstrings:
- def __init__(self, input: str, output: str='', force: bool=False, marketplace: Optional[str]=None, **kwargs): Init a GenericModuleUnifier Args: ... | Implement the Python class `GenericModuleUnifier` described below.
Class description:
Unifies a GenericModule object with it's Dashboards
Method signatures and docstrings:
- def __init__(self, input: str, output: str='', force: bool=False, marketplace: Optional[str]=None, **kwargs): Init a GenericModuleUnifier Args: ... | 3169757a2f98c8457e46572bf656ec6b69cc3a2e | <|skeleton|>
class GenericModuleUnifier:
"""Unifies a GenericModule object with it's Dashboards"""
def __init__(self, input: str, output: str='', force: bool=False, marketplace: Optional[str]=None, **kwargs):
"""Init a GenericModuleUnifier Args: input: a path of the GenericModule file to unify. output:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GenericModuleUnifier:
"""Unifies a GenericModule object with it's Dashboards"""
def __init__(self, input: str, output: str='', force: bool=False, marketplace: Optional[str]=None, **kwargs):
"""Init a GenericModuleUnifier Args: input: a path of the GenericModule file to unify. output: The output d... | the_stack_v2_python_sparse | demisto_sdk/commands/prepare_content/generic_module_unifier.py | demisto/demisto-sdk | train | 63 |
7de46aae64796e99be5037595473ee1ff78b9851 | [
"filter_properties = kwargs.get('filter_properties', {})\nignore_hosts = filter_properties.get('ignore_hosts', [])\nhosts = [host for host in hosts if host not in ignore_hosts]\nreturn hosts",
"elevated = context.elevated()\nhosts = self.hosts_up(elevated, topic)\nif not hosts:\n msg = _('Is the appropriate se... | <|body_start_0|>
filter_properties = kwargs.get('filter_properties', {})
ignore_hosts = filter_properties.get('ignore_hosts', [])
hosts = [host for host in hosts if host not in ignore_hosts]
return hosts
<|end_body_0|>
<|body_start_1|>
elevated = context.elevated()
hosts... | Implements Scheduler as a random node selector. | ChanceScheduler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChanceScheduler:
"""Implements Scheduler as a random node selector."""
def _filter_hosts(self, request_spec, hosts, **kwargs):
"""Filter a list of hosts based on request_spec."""
<|body_0|>
def _schedule(self, context, topic, request_spec, **kwargs):
"""Picks a h... | stack_v2_sparse_classes_75kplus_train_073706 | 2,669 | permissive | [
{
"docstring": "Filter a list of hosts based on request_spec.",
"name": "_filter_hosts",
"signature": "def _filter_hosts(self, request_spec, hosts, **kwargs)"
},
{
"docstring": "Picks a host that is up at random.",
"name": "_schedule",
"signature": "def _schedule(self, context, topic, re... | 3 | stack_v2_sparse_classes_30k_train_030870 | Implement the Python class `ChanceScheduler` described below.
Class description:
Implements Scheduler as a random node selector.
Method signatures and docstrings:
- def _filter_hosts(self, request_spec, hosts, **kwargs): Filter a list of hosts based on request_spec.
- def _schedule(self, context, topic, request_spec,... | Implement the Python class `ChanceScheduler` described below.
Class description:
Implements Scheduler as a random node selector.
Method signatures and docstrings:
- def _filter_hosts(self, request_spec, hosts, **kwargs): Filter a list of hosts based on request_spec.
- def _schedule(self, context, topic, request_spec,... | a93a844398a11a8a85f204782fb9456f7caccdbe | <|skeleton|>
class ChanceScheduler:
"""Implements Scheduler as a random node selector."""
def _filter_hosts(self, request_spec, hosts, **kwargs):
"""Filter a list of hosts based on request_spec."""
<|body_0|>
def _schedule(self, context, topic, request_spec, **kwargs):
"""Picks a h... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChanceScheduler:
"""Implements Scheduler as a random node selector."""
def _filter_hosts(self, request_spec, hosts, **kwargs):
"""Filter a list of hosts based on request_spec."""
filter_properties = kwargs.get('filter_properties', {})
ignore_hosts = filter_properties.get('ignore_h... | the_stack_v2_python_sparse | manila/scheduler/drivers/chance.py | openstack/manila | train | 178 |
2a1518dbffb249c484e2010b84014a7c69125360 | [
"time = timezone.now() + datetime.timedelta(days=30)\nfuture_species = Species(pub_date=time)\nself.assertIs(future_species.was_created_recently(), False)",
"time = timezone.now() - datetime.timedelta(days=1, seconds=1)\nold_species = Species(pub_date=time)\nself.assertIs(old_species.was_created_recently(), False... | <|body_start_0|>
time = timezone.now() + datetime.timedelta(days=30)
future_species = Species(pub_date=time)
self.assertIs(future_species.was_created_recently(), False)
<|end_body_0|>
<|body_start_1|>
time = timezone.now() - datetime.timedelta(days=1, seconds=1)
old_species = Sp... | SpeciesModelTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpeciesModelTests:
def test_was_created_recently_with_future_species(self):
"""was_created_recently() returns False for species pub_date is in the future."""
<|body_0|>
def test_was_created_recently_with_old_question(self):
"""was_created_recently() returns False for... | stack_v2_sparse_classes_75kplus_train_073707 | 4,711 | no_license | [
{
"docstring": "was_created_recently() returns False for species pub_date is in the future.",
"name": "test_was_created_recently_with_future_species",
"signature": "def test_was_created_recently_with_future_species(self)"
},
{
"docstring": "was_created_recently() returns False for species whose ... | 3 | stack_v2_sparse_classes_30k_train_050275 | Implement the Python class `SpeciesModelTests` described below.
Class description:
Implement the SpeciesModelTests class.
Method signatures and docstrings:
- def test_was_created_recently_with_future_species(self): was_created_recently() returns False for species pub_date is in the future.
- def test_was_created_rece... | Implement the Python class `SpeciesModelTests` described below.
Class description:
Implement the SpeciesModelTests class.
Method signatures and docstrings:
- def test_was_created_recently_with_future_species(self): was_created_recently() returns False for species pub_date is in the future.
- def test_was_created_rece... | 633bd1d536a4f8ce413e14382637b5d8d317a87c | <|skeleton|>
class SpeciesModelTests:
def test_was_created_recently_with_future_species(self):
"""was_created_recently() returns False for species pub_date is in the future."""
<|body_0|>
def test_was_created_recently_with_old_question(self):
"""was_created_recently() returns False for... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpeciesModelTests:
def test_was_created_recently_with_future_species(self):
"""was_created_recently() returns False for species pub_date is in the future."""
time = timezone.now() + datetime.timedelta(days=30)
future_species = Species(pub_date=time)
self.assertIs(future_species... | the_stack_v2_python_sparse | hortadb/tests.py | mariacardoso/hortaDB | train | 0 | |
80bb998c8202fde111c8654035f600e86b966492 | [
"iso8601_string = self._GetJSONValue(json_dict, name)\nif not iso8601_string:\n return None\nif name == 'FinishedAt' and iso8601_string == '0001-01-01T00:00:00Z':\n return None\ntry:\n date_time = dfdatetime_time_elements.TimeElementsInMicroseconds()\n date_time.CopyFromStringISO8601(iso8601_string)\nex... | <|body_start_0|>
iso8601_string = self._GetJSONValue(json_dict, name)
if not iso8601_string:
return None
if name == 'FinishedAt' and iso8601_string == '0001-01-01T00:00:00Z':
return None
try:
date_time = dfdatetime_time_elements.TimeElementsInMicroseco... | JSON-L parser plugin for Docker container configuration files. This parser handles per Docker container configuration files stored in: DOCKER_DIR/containers/<container_identifier>/config.json | DockerContainerConfigurationJSONLPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DockerContainerConfigurationJSONLPlugin:
"""JSON-L parser plugin for Docker container configuration files. This parser handles per Docker container configuration files stored in: DOCKER_DIR/containers/<container_identifier>/config.json"""
def _ParseISO8601DateTimeString(self, parser_mediator... | stack_v2_sparse_classes_75kplus_train_073708 | 4,653 | permissive | [
{
"docstring": "Parses an ISO8601 date and time string. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfVFS. json_dict (dict): JSON dictionary. name (str): name of the value to retrieve. Returns: dfdatetime.TimeElementsInMicroseconds: dat... | 3 | stack_v2_sparse_classes_30k_train_034181 | Implement the Python class `DockerContainerConfigurationJSONLPlugin` described below.
Class description:
JSON-L parser plugin for Docker container configuration files. This parser handles per Docker container configuration files stored in: DOCKER_DIR/containers/<container_identifier>/config.json
Method signatures and... | Implement the Python class `DockerContainerConfigurationJSONLPlugin` described below.
Class description:
JSON-L parser plugin for Docker container configuration files. This parser handles per Docker container configuration files stored in: DOCKER_DIR/containers/<container_identifier>/config.json
Method signatures and... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class DockerContainerConfigurationJSONLPlugin:
"""JSON-L parser plugin for Docker container configuration files. This parser handles per Docker container configuration files stored in: DOCKER_DIR/containers/<container_identifier>/config.json"""
def _ParseISO8601DateTimeString(self, parser_mediator... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DockerContainerConfigurationJSONLPlugin:
"""JSON-L parser plugin for Docker container configuration files. This parser handles per Docker container configuration files stored in: DOCKER_DIR/containers/<container_identifier>/config.json"""
def _ParseISO8601DateTimeString(self, parser_mediator, json_dict, ... | the_stack_v2_python_sparse | plaso/parsers/jsonl_plugins/docker_container_config.py | log2timeline/plaso | train | 1,506 |
cdda8a14090380a17b41430e97cd910c05171aed | [
"self.kv = {keys[i]: values[i] for i in range(len(keys))}\nself.vk = defaultdict(list)\nfor i in range(len(keys)):\n vk[values[i]].append(keys[i])\nself.d = Trie()\nfor word in dictionary:\n self.d.insert(word)",
"res = []\nfor ch in word1:\n res.append(self.kv[ch])\nreturn ''.join(res)",
"res = []\nfo... | <|body_start_0|>
self.kv = {keys[i]: values[i] for i in range(len(keys))}
self.vk = defaultdict(list)
for i in range(len(keys)):
vk[values[i]].append(keys[i])
self.d = Trie()
for word in dictionary:
self.d.insert(word)
<|end_body_0|>
<|body_start_1|>
... | Encrypter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encrypter:
def __init__(self, keys, values, dictionary):
""":type keys: List[str] :type values: List[str] :type dictionary: List[str]"""
<|body_0|>
def encrypt(self, word1):
""":type word1: str :rtype: str"""
<|body_1|>
def decrypt(self, word2):
... | stack_v2_sparse_classes_75kplus_train_073709 | 2,665 | no_license | [
{
"docstring": ":type keys: List[str] :type values: List[str] :type dictionary: List[str]",
"name": "__init__",
"signature": "def __init__(self, keys, values, dictionary)"
},
{
"docstring": ":type word1: str :rtype: str",
"name": "encrypt",
"signature": "def encrypt(self, word1)"
},
... | 3 | stack_v2_sparse_classes_30k_train_000895 | Implement the Python class `Encrypter` described below.
Class description:
Implement the Encrypter class.
Method signatures and docstrings:
- def __init__(self, keys, values, dictionary): :type keys: List[str] :type values: List[str] :type dictionary: List[str]
- def encrypt(self, word1): :type word1: str :rtype: str... | Implement the Python class `Encrypter` described below.
Class description:
Implement the Encrypter class.
Method signatures and docstrings:
- def __init__(self, keys, values, dictionary): :type keys: List[str] :type values: List[str] :type dictionary: List[str]
- def encrypt(self, word1): :type word1: str :rtype: str... | ee59b82125f100970c842d5e1245287c484d6649 | <|skeleton|>
class Encrypter:
def __init__(self, keys, values, dictionary):
""":type keys: List[str] :type values: List[str] :type dictionary: List[str]"""
<|body_0|>
def encrypt(self, word1):
""":type word1: str :rtype: str"""
<|body_1|>
def decrypt(self, word2):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Encrypter:
def __init__(self, keys, values, dictionary):
""":type keys: List[str] :type values: List[str] :type dictionary: List[str]"""
self.kv = {keys[i]: values[i] for i in range(len(keys))}
self.vk = defaultdict(list)
for i in range(len(keys)):
vk[values[i]].app... | the_stack_v2_python_sparse | _CodeTopics/LeetCode_contest/weekly/weekly2022/287/unfinished--287_4.py | BIAOXYZ/variousCodes | train | 0 | |
8f8b0d900948e6ce06eaffd6c2fd819d84876a02 | [
"if not decompose:\n rwmd, _, _, _, _ = self._rwmd()\n return rwmd\nelif decompose:\n if i2w == None:\n print('i2w argument is missing.')\n else:\n rwmd, flow_source, flow_sink, dist_source, dist_sink = self._rwmd()\n w_source = [i2w[idx] for idx in self.source.idxs]\n w_sink... | <|body_start_0|>
if not decompose:
rwmd, _, _, _, _ = self._rwmd()
return rwmd
elif decompose:
if i2w == None:
print('i2w argument is missing.')
else:
rwmd, flow_source, flow_sink, dist_source, dist_sink = self._rwmd()
... | Relaxed Word Mover's Distance (RWMD) with matrix operations in numpy. Inherits the WMD class. Attributes: see WMD class | RWMD | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RWMD:
"""Relaxed Word Mover's Distance (RWMD) with matrix operations in numpy. Inherits the WMD class. Attributes: see WMD class"""
def get_distance(self, i2w: Dict[int, str]=None, decompose: bool=False) -> Tuple[float, List[float], List[float], List[float], List[float], List[str], List[str]... | stack_v2_sparse_classes_75kplus_train_073710 | 21,755 | permissive | [
{
"docstring": "Get the RWMD between a pair of documents, with or without decomposed word-level distances. Args: i2w: A dictionary mapping the index of word vectors to the words themselves. decompose: A boolean to determine whether word-level distances should be decomposed. Returns: rwmd: A float value of the R... | 3 | stack_v2_sparse_classes_30k_train_032512 | Implement the Python class `RWMD` described below.
Class description:
Relaxed Word Mover's Distance (RWMD) with matrix operations in numpy. Inherits the WMD class. Attributes: see WMD class
Method signatures and docstrings:
- def get_distance(self, i2w: Dict[int, str]=None, decompose: bool=False) -> Tuple[float, List... | Implement the Python class `RWMD` described below.
Class description:
Relaxed Word Mover's Distance (RWMD) with matrix operations in numpy. Inherits the WMD class. Attributes: see WMD class
Method signatures and docstrings:
- def get_distance(self, i2w: Dict[int, str]=None, decompose: bool=False) -> Tuple[float, List... | 25d81616aeb6a27cd0511d1e12316bc63673e599 | <|skeleton|>
class RWMD:
"""Relaxed Word Mover's Distance (RWMD) with matrix operations in numpy. Inherits the WMD class. Attributes: see WMD class"""
def get_distance(self, i2w: Dict[int, str]=None, decompose: bool=False) -> Tuple[float, List[float], List[float], List[float], List[float], List[str], List[str]... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RWMD:
"""Relaxed Word Mover's Distance (RWMD) with matrix operations in numpy. Inherits the WMD class. Attributes: see WMD class"""
def get_distance(self, i2w: Dict[int, str]=None, decompose: bool=False) -> Tuple[float, List[float], List[float], List[float], List[float], List[str], List[str]]:
""... | the_stack_v2_python_sparse | src/wmdecompose/models.py | maybemkl/wmdecompose | train | 5 |
6cac0f31537727d617227d04df999bd63cf5b7a7 | [
"root_key = camel_to_snake_case(cls.__name__)\n\ndef find_errors(metadata=metadata, path_key=root_key):\n \"\"\"Generator for vmware attributes errors\n\n for each attribute in 'metadata' gets relevant values from vmware\n 'value' and checks them with restrictions and regexs\n \"... | <|body_start_0|>
root_key = camel_to_snake_case(cls.__name__)
def find_errors(metadata=metadata, path_key=root_key):
"""Generator for vmware attributes errors
for each attribute in 'metadata' gets relevant values from vmware
'value' and checks them w... | VmwareAttributesRestriction | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VmwareAttributesRestriction:
def check_data(cls, models, metadata, data):
"""Check cluster vmware attributes data :param models: objects which represent models in restrictions :type models: dict :param metadata: vmware attributes metadata object :type metadata: list|dict :param data: vmw... | stack_v2_sparse_classes_75kplus_train_073711 | 13,635 | permissive | [
{
"docstring": "Check cluster vmware attributes data :param models: objects which represent models in restrictions :type models: dict :param metadata: vmware attributes metadata object :type metadata: list|dict :param data: vmware attributes data(value) object :type data: list|dict :retruns: func -- generator w... | 2 | stack_v2_sparse_classes_30k_train_042415 | Implement the Python class `VmwareAttributesRestriction` described below.
Class description:
Implement the VmwareAttributesRestriction class.
Method signatures and docstrings:
- def check_data(cls, models, metadata, data): Check cluster vmware attributes data :param models: objects which represent models in restricti... | Implement the Python class `VmwareAttributesRestriction` described below.
Class description:
Implement the VmwareAttributesRestriction class.
Method signatures and docstrings:
- def check_data(cls, models, metadata, data): Check cluster vmware attributes data :param models: objects which represent models in restricti... | 0e09dce510927f2cc490b898e5fe3f813bd791be | <|skeleton|>
class VmwareAttributesRestriction:
def check_data(cls, models, metadata, data):
"""Check cluster vmware attributes data :param models: objects which represent models in restrictions :type models: dict :param metadata: vmware attributes metadata object :type metadata: list|dict :param data: vmw... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VmwareAttributesRestriction:
def check_data(cls, models, metadata, data):
"""Check cluster vmware attributes data :param models: objects which represent models in restrictions :type models: dict :param metadata: vmware attributes metadata object :type metadata: list|dict :param data: vmware attributes... | the_stack_v2_python_sparse | nailgun/nailgun/utils/restrictions.py | mba811/fuel-web | train | 1 | |
ef71312f1bc859973f5bdc83c0365c4ca68ed15a | [
"response = self.client.get(reverse('events:index'))\nself.assertEqual(response.status_code, 200)\nself.assertContains(response, 'No upcoming events.')\nself.assertContains(response, 'No past events.')",
"create_event(name='Past event', days=-30, description='A past event', location='place', admission='0 SEK', pu... | <|body_start_0|>
response = self.client.get(reverse('events:index'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'No upcoming events.')
self.assertContains(response, 'No past events.')
<|end_body_0|>
<|body_start_1|>
create_event(name='Past event', ... | EventViewTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventViewTests:
def test_index_view_with_no_events(self):
"""If no events exist, appropriate messages should be displayed."""
<|body_0|>
def test_index_view_with_past_but_no_upcoming_events(self):
"""If no upcoming events exist, an appropriate message should be displ... | stack_v2_sparse_classes_75kplus_train_073712 | 4,458 | no_license | [
{
"docstring": "If no events exist, appropriate messages should be displayed.",
"name": "test_index_view_with_no_events",
"signature": "def test_index_view_with_no_events(self)"
},
{
"docstring": "If no upcoming events exist, an appropriate message should be displayed.",
"name": "test_index_... | 6 | null | Implement the Python class `EventViewTests` described below.
Class description:
Implement the EventViewTests class.
Method signatures and docstrings:
- def test_index_view_with_no_events(self): If no events exist, appropriate messages should be displayed.
- def test_index_view_with_past_but_no_upcoming_events(self): ... | Implement the Python class `EventViewTests` described below.
Class description:
Implement the EventViewTests class.
Method signatures and docstrings:
- def test_index_view_with_no_events(self): If no events exist, appropriate messages should be displayed.
- def test_index_view_with_past_but_no_upcoming_events(self): ... | 2a26b1d9b466c919c2596899c1c95fa681c2bcda | <|skeleton|>
class EventViewTests:
def test_index_view_with_no_events(self):
"""If no events exist, appropriate messages should be displayed."""
<|body_0|>
def test_index_view_with_past_but_no_upcoming_events(self):
"""If no upcoming events exist, an appropriate message should be displ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EventViewTests:
def test_index_view_with_no_events(self):
"""If no events exist, appropriate messages should be displayed."""
response = self.client.get(reverse('events:index'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'No upcoming events.')
... | the_stack_v2_python_sparse | events/tests.py | mhelmer/earthvibration_web | train | 0 | |
c035e4b7ff10552b8bf4c55378f3a31e9000158b | [
"self.verbose = verbose\nself.logger = init_logger(self.__class__.__name__)\nself.use_gpu = use_gpu\nself.rel_vocab_size = rel_vocab_size\nself.n_features = dim_in\nif type(poly_degree) is int:\n for i in range(1, poly_degree):\n combs = combinations_with_replacement(range(dim_in), i + 1)\n self.n_... | <|body_start_0|>
self.verbose = verbose
self.logger = init_logger(self.__class__.__name__)
self.use_gpu = use_gpu
self.rel_vocab_size = rel_vocab_size
self.n_features = dim_in
if type(poly_degree) is int:
for i in range(1, poly_degree):
combs =... | MLP ensembler. | MLPEnsembler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MLPEnsembler:
"""MLP ensembler."""
def __init__(self, dim_in, rel_vocab_size, dim_hid=16, activation='sigmoid', use_gpu=False, poly_degree=None, flag_unifw=False, verbose=False):
"""Initialize a model."""
<|body_0|>
def __call__(self, rels, vecs):
"""Return a sco... | stack_v2_sparse_classes_75kplus_train_073713 | 4,169 | no_license | [
{
"docstring": "Initialize a model.",
"name": "__init__",
"signature": "def __init__(self, dim_in, rel_vocab_size, dim_hid=16, activation='sigmoid', use_gpu=False, poly_degree=None, flag_unifw=False, verbose=False)"
},
{
"docstring": "Return a score of fact; closer to zero is better.",
"name... | 2 | stack_v2_sparse_classes_30k_train_018430 | Implement the Python class `MLPEnsembler` described below.
Class description:
MLP ensembler.
Method signatures and docstrings:
- def __init__(self, dim_in, rel_vocab_size, dim_hid=16, activation='sigmoid', use_gpu=False, poly_degree=None, flag_unifw=False, verbose=False): Initialize a model.
- def __call__(self, rels... | Implement the Python class `MLPEnsembler` described below.
Class description:
MLP ensembler.
Method signatures and docstrings:
- def __init__(self, dim_in, rel_vocab_size, dim_hid=16, activation='sigmoid', use_gpu=False, poly_degree=None, flag_unifw=False, verbose=False): Initialize a model.
- def __call__(self, rels... | bf1608c4f12e8f294d3733041697a9bdeb5b086b | <|skeleton|>
class MLPEnsembler:
"""MLP ensembler."""
def __init__(self, dim_in, rel_vocab_size, dim_hid=16, activation='sigmoid', use_gpu=False, poly_degree=None, flag_unifw=False, verbose=False):
"""Initialize a model."""
<|body_0|>
def __call__(self, rels, vecs):
"""Return a sco... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MLPEnsembler:
"""MLP ensembler."""
def __init__(self, dim_in, rel_vocab_size, dim_hid=16, activation='sigmoid', use_gpu=False, poly_degree=None, flag_unifw=False, verbose=False):
"""Initialize a model."""
self.verbose = verbose
self.logger = init_logger(self.__class__.__name__)
... | the_stack_v2_python_sparse | src/twa/ensemble/models.py | notani/CLKP-MTKBC | train | 6 |
1519d9153d90ba4c14bc16d7d896605384114721 | [
"res = {}\nres['retcode'] = e.code\nres['retmsg'] = e.message\nres.update(e.ext)\nreturn res",
"res = {}\nres['retcode'] = BaseError.SUCCESS\nres['retmsg'] = BaseError.get_message(res['retcode'])\nres['retdata'] = data if data is not None else {}\nreturn res"
] | <|body_start_0|>
res = {}
res['retcode'] = e.code
res['retmsg'] = e.message
res.update(e.ext)
return res
<|end_body_0|>
<|body_start_1|>
res = {}
res['retcode'] = BaseError.SUCCESS
res['retmsg'] = BaseError.get_message(res['retcode'])
res['retdata... | 响应 | ResponseBuilder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResponseBuilder:
"""响应"""
def build_error(handler, e):
"""返回错误 Args: handler: torndb.web.RequestHandler object e: An instance of UFOException Returns: A json string"""
<|body_0|>
def build_success(handler, data=None):
"""返回成功 Args: handler: torndb.web.RequestHand... | stack_v2_sparse_classes_75kplus_train_073714 | 1,250 | no_license | [
{
"docstring": "返回错误 Args: handler: torndb.web.RequestHandler object e: An instance of UFOException Returns: A json string",
"name": "build_error",
"signature": "def build_error(handler, e)"
},
{
"docstring": "返回成功 Args: handler: torndb.web.RequestHandler object data: data returned by processor ... | 2 | stack_v2_sparse_classes_30k_train_024219 | Implement the Python class `ResponseBuilder` described below.
Class description:
响应
Method signatures and docstrings:
- def build_error(handler, e): 返回错误 Args: handler: torndb.web.RequestHandler object e: An instance of UFOException Returns: A json string
- def build_success(handler, data=None): 返回成功 Args: handler: t... | Implement the Python class `ResponseBuilder` described below.
Class description:
响应
Method signatures and docstrings:
- def build_error(handler, e): 返回错误 Args: handler: torndb.web.RequestHandler object e: An instance of UFOException Returns: A json string
- def build_success(handler, data=None): 返回成功 Args: handler: t... | d520316d773ee14e7db25d2da56e4a19e52f8821 | <|skeleton|>
class ResponseBuilder:
"""响应"""
def build_error(handler, e):
"""返回错误 Args: handler: torndb.web.RequestHandler object e: An instance of UFOException Returns: A json string"""
<|body_0|>
def build_success(handler, data=None):
"""返回成功 Args: handler: torndb.web.RequestHand... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResponseBuilder:
"""响应"""
def build_error(handler, e):
"""返回错误 Args: handler: torndb.web.RequestHandler object e: An instance of UFOException Returns: A json string"""
res = {}
res['retcode'] = e.code
res['retmsg'] = e.message
res.update(e.ext)
return res
... | the_stack_v2_python_sparse | utils/protocol_utils.py | zikkinbun/s2s | train | 0 |
6bd25a442fcef5067eef82114f0434a89532ca67 | [
"self._mutation = actual_mutation\nself._accept_less_percent = accept_less\nself._accept_less_rand = random.Random()",
"new_org = self._mutation.mutate(org)\nnew_org.recalculate_fitness()\nif org.fitness > new_org.fitness:\n accept_less_chance = self._accept_less_rand.random()\n if accept_less_chance <= sel... | <|body_start_0|>
self._mutation = actual_mutation
self._accept_less_percent = accept_less
self._accept_less_rand = random.Random()
<|end_body_0|>
<|body_start_1|>
new_org = self._mutation.mutate(org)
new_org.recalculate_fitness()
if org.fitness > new_org.fitness:
... | Perform mutations, but do not allow decreases in organism fitness. This doesn't actually do any mutation work, but just checks that newly create organisms do not have lower fitnesses. | SafeFitnessMutation | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SafeFitnessMutation:
"""Perform mutations, but do not allow decreases in organism fitness. This doesn't actually do any mutation work, but just checks that newly create organisms do not have lower fitnesses."""
def __init__(self, actual_mutation, accept_less=0.0):
"""Initialize to do... | stack_v2_sparse_classes_75kplus_train_073715 | 1,414 | permissive | [
{
"docstring": "Initialize to do safe mutations Arguments: o actual_mutation - A Mutation class which actually implements mutation. functionality. o accept_less - A probability to accept mutations which generate lower fitness. This allows you to accept some crossovers which reduce fitness, but not all of them."... | 2 | stack_v2_sparse_classes_30k_train_012502 | Implement the Python class `SafeFitnessMutation` described below.
Class description:
Perform mutations, but do not allow decreases in organism fitness. This doesn't actually do any mutation work, but just checks that newly create organisms do not have lower fitnesses.
Method signatures and docstrings:
- def __init__(... | Implement the Python class `SafeFitnessMutation` described below.
Class description:
Perform mutations, but do not allow decreases in organism fitness. This doesn't actually do any mutation work, but just checks that newly create organisms do not have lower fitnesses.
Method signatures and docstrings:
- def __init__(... | 1d9a8e84a8572809ee3260ede44290e14de3bdd1 | <|skeleton|>
class SafeFitnessMutation:
"""Perform mutations, but do not allow decreases in organism fitness. This doesn't actually do any mutation work, but just checks that newly create organisms do not have lower fitnesses."""
def __init__(self, actual_mutation, accept_less=0.0):
"""Initialize to do... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SafeFitnessMutation:
"""Perform mutations, but do not allow decreases in organism fitness. This doesn't actually do any mutation work, but just checks that newly create organisms do not have lower fitnesses."""
def __init__(self, actual_mutation, accept_less=0.0):
"""Initialize to do safe mutatio... | the_stack_v2_python_sparse | bin/last_wrapper/Bio/GA/Mutation/General.py | LyonsLab/coge | train | 41 |
ce499f7077fa83bdde37f63dbc0f5498f687f559 | [
"if not email:\n raise ValueError('The given email must be set')\nuser = self.model(email=email, **extra_fields)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"extra_fields.setdefault('is_staff', False)\nextra_fields.setdefault('is_superuser', False)\nreturn self._create_user(email, pa... | <|body_start_0|>
if not email:
raise ValueError('The given email must be set')
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
<|end_body_0|>
<|body_start_1|>
extra_fields.setdefault('is_staff',... | ユーザーマネージャー. | MyUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyUserManager:
"""ユーザーマネージャー."""
def _create_user(self, email, password, **extra_fields):
"""メールアドレスでの登録を必須にする"""
<|body_0|>
def create_user(self, email, password=None, **extra_fields):
"""is_staff(管理サイトにログインできるか)と、is_superuer(全ての権限)をFalseに"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_073716 | 5,326 | no_license | [
{
"docstring": "メールアドレスでの登録を必須にする",
"name": "_create_user",
"signature": "def _create_user(self, email, password, **extra_fields)"
},
{
"docstring": "is_staff(管理サイトにログインできるか)と、is_superuer(全ての権限)をFalseに",
"name": "create_user",
"signature": "def create_user(self, email, password=None, **e... | 3 | stack_v2_sparse_classes_30k_train_052538 | Implement the Python class `MyUserManager` described below.
Class description:
ユーザーマネージャー.
Method signatures and docstrings:
- def _create_user(self, email, password, **extra_fields): メールアドレスでの登録を必須にする
- def create_user(self, email, password=None, **extra_fields): is_staff(管理サイトにログインできるか)と、is_superuer(全ての権限)をFalseに
-... | Implement the Python class `MyUserManager` described below.
Class description:
ユーザーマネージャー.
Method signatures and docstrings:
- def _create_user(self, email, password, **extra_fields): メールアドレスでの登録を必須にする
- def create_user(self, email, password=None, **extra_fields): is_staff(管理サイトにログインできるか)と、is_superuer(全ての権限)をFalseに
-... | d146570d0cf3df1a0358f8f35a0a9ed9fdf268e4 | <|skeleton|>
class MyUserManager:
"""ユーザーマネージャー."""
def _create_user(self, email, password, **extra_fields):
"""メールアドレスでの登録を必須にする"""
<|body_0|>
def create_user(self, email, password=None, **extra_fields):
"""is_staff(管理サイトにログインできるか)と、is_superuer(全ての権限)をFalseに"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyUserManager:
"""ユーザーマネージャー."""
def _create_user(self, email, password, **extra_fields):
"""メールアドレスでの登録を必須にする"""
if not email:
raise ValueError('The given email must be set')
user = self.model(email=email, **extra_fields)
user.set_password(password)
us... | the_stack_v2_python_sparse | myauth/models.py | shusaku-ishikawa/chatbackend | train | 0 |
a582ce1f752753cc211948cfab3beeed2cf5f61b | [
"error_messages = []\nform = SignupForm()\ncontext = {'errors': error_messages, 'signup_form': form}\nreturn render(request, 'users/registro.html', context)",
"success_message = ''\nform = SignupForm(request.POST)\nif form.is_valid():\n new_user = User.objects.create_user(form.cleaned_data.get('username'), for... | <|body_start_0|>
error_messages = []
form = SignupForm()
context = {'errors': error_messages, 'signup_form': form}
return render(request, 'users/registro.html', context)
<|end_body_0|>
<|body_start_1|>
success_message = ''
form = SignupForm(request.POST)
if form.... | Vista basada en clase para el registro de nuevo usuario. Definimos qué hacer en los métodos GET y POST del request | SignupView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignupView:
"""Vista basada en clase para el registro de nuevo usuario. Definimos qué hacer en los métodos GET y POST del request"""
def get(self, request):
"""Método para cuando el signup viene del método HTTP get :param request: HttpRequest :return: render que contruye un HttpRespo... | stack_v2_sparse_classes_75kplus_train_073717 | 5,961 | no_license | [
{
"docstring": "Método para cuando el signup viene del método HTTP get :param request: HttpRequest :return: render que contruye un HttpResponse con el template indicado",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Método para cuando el signup viene del método HTTP ge... | 2 | stack_v2_sparse_classes_30k_train_011368 | Implement the Python class `SignupView` described below.
Class description:
Vista basada en clase para el registro de nuevo usuario. Definimos qué hacer en los métodos GET y POST del request
Method signatures and docstrings:
- def get(self, request): Método para cuando el signup viene del método HTTP get :param reque... | Implement the Python class `SignupView` described below.
Class description:
Vista basada en clase para el registro de nuevo usuario. Definimos qué hacer en los métodos GET y POST del request
Method signatures and docstrings:
- def get(self, request): Método para cuando el signup viene del método HTTP get :param reque... | 0c11971a152a3c9aa5679c61f475d072cd7cb71e | <|skeleton|>
class SignupView:
"""Vista basada en clase para el registro de nuevo usuario. Definimos qué hacer en los métodos GET y POST del request"""
def get(self, request):
"""Método para cuando el signup viene del método HTTP get :param request: HttpRequest :return: render que contruye un HttpRespo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SignupView:
"""Vista basada en clase para el registro de nuevo usuario. Definimos qué hacer en los métodos GET y POST del request"""
def get(self, request):
"""Método para cuando el signup viene del método HTTP get :param request: HttpRequest :return: render que contruye un HttpResponse con el te... | the_stack_v2_python_sparse | users/views.py | daviddetena/AGBO_Python-Django_Wordplease | train | 0 |
6abbc6e16446f50209cb39efd9c47588a3791151 | [
"i = 0\nj = x / 2 + 1\nwhile i <= j:\n mid = (i + j) / 2\n if mid * mid == x:\n return mid\n if mid * mid > x:\n j = mid - 1\n else:\n i = mid + 1\nreturn j",
"x_i = n\nwhile x_i * x_i > n:\n x_i = (x_i + n / x_i) / 2\nreturn x_i"
] | <|body_start_0|>
i = 0
j = x / 2 + 1
while i <= j:
mid = (i + j) / 2
if mid * mid == x:
return mid
if mid * mid > x:
j = mid - 1
else:
i = mid + 1
return j
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mySqrt2(self, x):
"""二分搜索 :type x: int :rtype: int"""
<|body_0|>
def mySqrt(self, n):
"""牛顿法求解 ref: http://www.cnblogs.com/AnnieKim/archive/2013/04/18/3028607.html x_i+1 = (x_i + n/x_i) / 2 x_i+1 无线逼近 x_i :type x: int :rtype: int"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_073718 | 1,044 | no_license | [
{
"docstring": "二分搜索 :type x: int :rtype: int",
"name": "mySqrt2",
"signature": "def mySqrt2(self, x)"
},
{
"docstring": "牛顿法求解 ref: http://www.cnblogs.com/AnnieKim/archive/2013/04/18/3028607.html x_i+1 = (x_i + n/x_i) / 2 x_i+1 无线逼近 x_i :type x: int :rtype: int",
"name": "mySqrt",
"sign... | 2 | stack_v2_sparse_classes_30k_train_042982 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mySqrt2(self, x): 二分搜索 :type x: int :rtype: int
- def mySqrt(self, n): 牛顿法求解 ref: http://www.cnblogs.com/AnnieKim/archive/2013/04/18/3028607.html x_i+1 = (x_i + n/x_i) / 2 x_... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mySqrt2(self, x): 二分搜索 :type x: int :rtype: int
- def mySqrt(self, n): 牛顿法求解 ref: http://www.cnblogs.com/AnnieKim/archive/2013/04/18/3028607.html x_i+1 = (x_i + n/x_i) / 2 x_... | 852fad258f5070c7b93c35252f7404e85e709ea6 | <|skeleton|>
class Solution:
def mySqrt2(self, x):
"""二分搜索 :type x: int :rtype: int"""
<|body_0|>
def mySqrt(self, n):
"""牛顿法求解 ref: http://www.cnblogs.com/AnnieKim/archive/2013/04/18/3028607.html x_i+1 = (x_i + n/x_i) / 2 x_i+1 无线逼近 x_i :type x: int :rtype: int"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def mySqrt2(self, x):
"""二分搜索 :type x: int :rtype: int"""
i = 0
j = x / 2 + 1
while i <= j:
mid = (i + j) / 2
if mid * mid == x:
return mid
if mid * mid > x:
j = mid - 1
else:
... | the_stack_v2_python_sparse | 1-100/69. Sqrt(x).py | SunnyMarkLiu/LeetCode | train | 1 | |
6f0ace7f84b0f01f0e6548c9a9cfcda4f6faac2f | [
"low = 0\nup = len(s) - 1\nwhile low < up:\n if s[low] == s[up]:\n low += 1\n up -= 1\n else:\n return 0\nreturn 1",
"for i in range(k, len(s) + 1):\n select = s[i - k:i]\n if self.isPal(select) == 1:\n return select\nreturn ''",
"if len(s) == 0:\n return ''\nelif len(... | <|body_start_0|>
low = 0
up = len(s) - 1
while low < up:
if s[low] == s[up]:
low += 1
up -= 1
else:
return 0
return 1
<|end_body_0|>
<|body_start_1|>
for i in range(k, len(s) + 1):
select = s[i -... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPal(self, s):
"""Return 1 if s is a palindrome and 0 otherwise"""
<|body_0|>
def check(self, s, k):
"""Returns "" if there is no palindrome of size k, and the first palindrome of size k if there is one"""
<|body_1|>
def longestPalindrome(... | stack_v2_sparse_classes_75kplus_train_073719 | 4,427 | no_license | [
{
"docstring": "Return 1 if s is a palindrome and 0 otherwise",
"name": "isPal",
"signature": "def isPal(self, s)"
},
{
"docstring": "Returns \"\" if there is no palindrome of size k, and the first palindrome of size k if there is one",
"name": "check",
"signature": "def check(self, s, k... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPal(self, s): Return 1 if s is a palindrome and 0 otherwise
- def check(self, s, k): Returns "" if there is no palindrome of size k, and the first palindrome of size k if t... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPal(self, s): Return 1 if s is a palindrome and 0 otherwise
- def check(self, s, k): Returns "" if there is no palindrome of size k, and the first palindrome of size k if t... | f4ac2609f8809ee543074a11dafc08726046f6a2 | <|skeleton|>
class Solution:
def isPal(self, s):
"""Return 1 if s is a palindrome and 0 otherwise"""
<|body_0|>
def check(self, s, k):
"""Returns "" if there is no palindrome of size k, and the first palindrome of size k if there is one"""
<|body_1|>
def longestPalindrome(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isPal(self, s):
"""Return 1 if s is a palindrome and 0 otherwise"""
low = 0
up = len(s) - 1
while low < up:
if s[low] == s[up]:
low += 1
up -= 1
else:
return 0
return 1
def check(... | the_stack_v2_python_sparse | LeetCode/5_longest-palindromic-substring.py | curiousTauseef/Algorithms_and_solutions | train | 0 | |
45be52f5cdad0ea77ac8ff8b2d837b37796370ec | [
"super(PacketModel, self).__init__()\nself.rowsPerPacket = rowsPerPacket\nself.dataShape = data.shape\nself.packetSeq = self.dataToPacket(data)",
"self.numZeros = 0\nif self.dataShape[1] % self.rowsPerPacket == 0:\n data = np.reshape(data, (self.dataShape[0], -1, self.rowsPerPacket, self.dataShape[2], self.dat... | <|body_start_0|>
super(PacketModel, self).__init__()
self.rowsPerPacket = rowsPerPacket
self.dataShape = data.shape
self.packetSeq = self.dataToPacket(data)
<|end_body_0|>
<|body_start_1|>
self.numZeros = 0
if self.dataShape[1] % self.rowsPerPacket == 0:
data... | Convert data to packets | PacketModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PacketModel:
"""Convert data to packets"""
def __init__(self, data, rowsPerPacket):
"""# Arguments data: 4-D tensor to be packetized rowsPerPacket: number of rows of the feature map to be considered as one packet"""
<|body_0|>
def dataToPacket(self, data):
"""Con... | stack_v2_sparse_classes_75kplus_train_073720 | 1,848 | permissive | [
{
"docstring": "# Arguments data: 4-D tensor to be packetized rowsPerPacket: number of rows of the feature map to be considered as one packet",
"name": "__init__",
"signature": "def __init__(self, data, rowsPerPacket)"
},
{
"docstring": "Converts 4D tensor to 5D tensor of packets # Arguments dat... | 3 | stack_v2_sparse_classes_30k_val_001295 | Implement the Python class `PacketModel` described below.
Class description:
Convert data to packets
Method signatures and docstrings:
- def __init__(self, data, rowsPerPacket): # Arguments data: 4-D tensor to be packetized rowsPerPacket: number of rows of the feature map to be considered as one packet
- def dataToPa... | Implement the Python class `PacketModel` described below.
Class description:
Convert data to packets
Method signatures and docstrings:
- def __init__(self, data, rowsPerPacket): # Arguments data: 4-D tensor to be packetized rowsPerPacket: number of rows of the feature map to be considered as one packet
- def dataToPa... | 976e6087ff629c45f7bbc79a3de25718ed143db5 | <|skeleton|>
class PacketModel:
"""Convert data to packets"""
def __init__(self, data, rowsPerPacket):
"""# Arguments data: 4-D tensor to be packetized rowsPerPacket: number of rows of the feature map to be considered as one packet"""
<|body_0|>
def dataToPacket(self, data):
"""Con... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PacketModel:
"""Convert data to packets"""
def __init__(self, data, rowsPerPacket):
"""# Arguments data: 4-D tensor to be packetized rowsPerPacket: number of rows of the feature map to be considered as one packet"""
super(PacketModel, self).__init__()
self.rowsPerPacket = rowsPerP... | the_stack_v2_python_sparse | models/packetModel.py | AshivDhondea/DFTS_compat_v1 | train | 1 |
b3e4f533f7e242307a4e20201dbe92f187815d84 | [
"self.xyz_offset = xyz_offset\nself.resolution = resolution\nself.cutout = cutout\nself.voxels = voxels\nRAMONBase.__init__(self, id=id, confidence=confidence, kvpairs=kvpairs, status=status, author=author)",
"if self.cutout:\n return self.cutout\nelse:\n raise NotImplementedError('Cannot convert from voxel... | <|body_start_0|>
self.xyz_offset = xyz_offset
self.resolution = resolution
self.cutout = cutout
self.voxels = voxels
RAMONBase.__init__(self, id=id, confidence=confidence, kvpairs=kvpairs, status=status, author=author)
<|end_body_0|>
<|body_start_1|>
if self.cutout:
... | RAMONVolume Object for storing neuroscience data with a voxel volume | RAMONVolume | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RAMONVolume:
"""RAMONVolume Object for storing neuroscience data with a voxel volume"""
def __init__(self, xyz_offset=(0, 0, 0), resolution=0, cutout=None, voxels=None, id=DEFAULT_ID, confidence=DEFAULT_CONFIDENCE, kvpairs=DEFAULT_DYNAMIC_METADATA, status=DEFAULT_STATUS, author=DEFAULT_AUTHO... | stack_v2_sparse_classes_75kplus_train_073721 | 1,931 | permissive | [
{
"docstring": "Initialize a new RAMONVolume object. Inherits attributes from RAMONBase as well as: Arguments: xyz_offset (int[3] : (0, 0, 0)): x,y,z coordinates of the minimum corner of the cube (if data is a cutout), otherwise empty resolution (int : 0): level in the database resolution hierarchy cutout (nump... | 2 | stack_v2_sparse_classes_30k_train_053148 | Implement the Python class `RAMONVolume` described below.
Class description:
RAMONVolume Object for storing neuroscience data with a voxel volume
Method signatures and docstrings:
- def __init__(self, xyz_offset=(0, 0, 0), resolution=0, cutout=None, voxels=None, id=DEFAULT_ID, confidence=DEFAULT_CONFIDENCE, kvpairs=D... | Implement the Python class `RAMONVolume` described below.
Class description:
RAMONVolume Object for storing neuroscience data with a voxel volume
Method signatures and docstrings:
- def __init__(self, xyz_offset=(0, 0, 0), resolution=0, cutout=None, voxels=None, id=DEFAULT_ID, confidence=DEFAULT_CONFIDENCE, kvpairs=D... | 8323b2c6b5e0ef985e4528c242236c38e8d64045 | <|skeleton|>
class RAMONVolume:
"""RAMONVolume Object for storing neuroscience data with a voxel volume"""
def __init__(self, xyz_offset=(0, 0, 0), resolution=0, cutout=None, voxels=None, id=DEFAULT_ID, confidence=DEFAULT_CONFIDENCE, kvpairs=DEFAULT_DYNAMIC_METADATA, status=DEFAULT_STATUS, author=DEFAULT_AUTHO... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RAMONVolume:
"""RAMONVolume Object for storing neuroscience data with a voxel volume"""
def __init__(self, xyz_offset=(0, 0, 0), resolution=0, cutout=None, voxels=None, id=DEFAULT_ID, confidence=DEFAULT_CONFIDENCE, kvpairs=DEFAULT_DYNAMIC_METADATA, status=DEFAULT_STATUS, author=DEFAULT_AUTHOR):
"... | the_stack_v2_python_sparse | ndio/ramon/RAMONVolume.py | neurodata/ndio | train | 16 |
3967a747b861bd5b20f6b1fe663df94b8425f842 | [
"self.train_data, self.train_label = self.process_dirs(train_dir)\nself.test_data, self.test_label = self.process_dirs(test_dir)\nprint(len(self.train_data), len(self.train_label))",
"if os.path.exists(base + '.npz') == True:\n files = np.load(base + '.npz')\n inputs = files['inputs']\n labels = files['l... | <|body_start_0|>
self.train_data, self.train_label = self.process_dirs(train_dir)
self.test_data, self.test_label = self.process_dirs(test_dir)
print(len(self.train_data), len(self.train_label))
<|end_body_0|>
<|body_start_1|>
if os.path.exists(base + '.npz') == True:
files ... | Data | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Data:
def __init__(self, train_dir='Train', test_dir='Test'):
"""初始化 输入参数:训练、测试数据文件"""
<|body_0|>
def process_dirs(self, base):
"""读取数据 输入参数:数据文件夹"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.train_data, self.train_label = self.process_dirs(... | stack_v2_sparse_classes_75kplus_train_073722 | 3,205 | no_license | [
{
"docstring": "初始化 输入参数:训练、测试数据文件",
"name": "__init__",
"signature": "def __init__(self, train_dir='Train', test_dir='Test')"
},
{
"docstring": "读取数据 输入参数:数据文件夹",
"name": "process_dirs",
"signature": "def process_dirs(self, base)"
}
] | 2 | stack_v2_sparse_classes_30k_train_023002 | Implement the Python class `Data` described below.
Class description:
Implement the Data class.
Method signatures and docstrings:
- def __init__(self, train_dir='Train', test_dir='Test'): 初始化 输入参数:训练、测试数据文件
- def process_dirs(self, base): 读取数据 输入参数:数据文件夹 | Implement the Python class `Data` described below.
Class description:
Implement the Data class.
Method signatures and docstrings:
- def __init__(self, train_dir='Train', test_dir='Test'): 初始化 输入参数:训练、测试数据文件
- def process_dirs(self, base): 读取数据 输入参数:数据文件夹
<|skeleton|>
class Data:
def __init__(self, train_dir='Tr... | 462ee12c72b7f84c5ae45aaf0f65b812d7c1ada1 | <|skeleton|>
class Data:
def __init__(self, train_dir='Train', test_dir='Test'):
"""初始化 输入参数:训练、测试数据文件"""
<|body_0|>
def process_dirs(self, base):
"""读取数据 输入参数:数据文件夹"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Data:
def __init__(self, train_dir='Train', test_dir='Test'):
"""初始化 输入参数:训练、测试数据文件"""
self.train_data, self.train_label = self.process_dirs(train_dir)
self.test_data, self.test_label = self.process_dirs(test_dir)
print(len(self.train_data), len(self.train_label))
def proc... | the_stack_v2_python_sparse | AIE23/20191208_flipped_classroom/数据读取代码与参考分类代码.py | shcqupc/Alg_study | train | 2 | |
060c12c46995c4b07fe0a59ebf3793b65c696ea8 | [
"self.ai_settings = ai_settings\nself.reset_stats()\nself.rewrite = False\nself.game_active = False\nself.check_hs = False\nhs_file = open('high_scores.txt', 'r')\nfor line in hs_file:\n self.hs_list = line.split()\nhs_file.close()\nself.hs_list.sort(key=int, reverse=True)\nself.high_score = int(self.hs_list[0])... | <|body_start_0|>
self.ai_settings = ai_settings
self.reset_stats()
self.rewrite = False
self.game_active = False
self.check_hs = False
hs_file = open('high_scores.txt', 'r')
for line in hs_file:
self.hs_list = line.split()
hs_file.close()
... | Track statistics for Space Potaters | GameStats | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GameStats:
"""Track statistics for Space Potaters"""
def __init__(self, ai_settings):
"""initialziae statistics"""
<|body_0|>
def reset_stats(self):
"""Initialize statistics that can change during the game"""
<|body_1|>
def save_high_score(self, curr... | stack_v2_sparse_classes_75kplus_train_073723 | 1,505 | no_license | [
{
"docstring": "initialziae statistics",
"name": "__init__",
"signature": "def __init__(self, ai_settings)"
},
{
"docstring": "Initialize statistics that can change during the game",
"name": "reset_stats",
"signature": "def reset_stats(self)"
},
{
"docstring": "Writes high over h... | 3 | stack_v2_sparse_classes_30k_train_025318 | Implement the Python class `GameStats` described below.
Class description:
Track statistics for Space Potaters
Method signatures and docstrings:
- def __init__(self, ai_settings): initialziae statistics
- def reset_stats(self): Initialize statistics that can change during the game
- def save_high_score(self, current_... | Implement the Python class `GameStats` described below.
Class description:
Track statistics for Space Potaters
Method signatures and docstrings:
- def __init__(self, ai_settings): initialziae statistics
- def reset_stats(self): Initialize statistics that can change during the game
- def save_high_score(self, current_... | a6beadf8bb55b5b2185c8606c9f7527588a6355a | <|skeleton|>
class GameStats:
"""Track statistics for Space Potaters"""
def __init__(self, ai_settings):
"""initialziae statistics"""
<|body_0|>
def reset_stats(self):
"""Initialize statistics that can change during the game"""
<|body_1|>
def save_high_score(self, curr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GameStats:
"""Track statistics for Space Potaters"""
def __init__(self, ai_settings):
"""initialziae statistics"""
self.ai_settings = ai_settings
self.reset_stats()
self.rewrite = False
self.game_active = False
self.check_hs = False
hs_file = open('... | the_stack_v2_python_sparse | game_stats.py | ganzabeans/Space-Potaters | train | 0 |
4ae0e4fc4ca383a82ef39e61639100ec27e27c9d | [
"self.entity_id = entity_id\nself.remediation_state = remediation_state\nself.root_inode_id = root_inode_id\nself.view_id = view_id",
"if dictionary is None:\n return None\nentity_id = dictionary.get('entityId')\nremediation_state = dictionary.get('remediationState')\nroot_inode_id = dictionary.get('rootInodeI... | <|body_start_0|>
self.entity_id = entity_id
self.remediation_state = remediation_state
self.root_inode_id = root_inode_id
self.view_id = view_id
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
entity_id = dictionary.get('entityId')
... | Implementation of the 'InfectedFileParam' model. TODO: type description here. Attributes: entity_id (long|int): Specifies the entity id of the infected file. remediation_state (RemediationStateEnum): Specifies the remediation state of the file. Remediation State. 'kQuarantine' indicates 'Quarantine' state of the file. ... | InfectedFileParam | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InfectedFileParam:
"""Implementation of the 'InfectedFileParam' model. TODO: type description here. Attributes: entity_id (long|int): Specifies the entity id of the infected file. remediation_state (RemediationStateEnum): Specifies the remediation state of the file. Remediation State. 'kQuarantin... | stack_v2_sparse_classes_75kplus_train_073724 | 2,750 | permissive | [
{
"docstring": "Constructor for the InfectedFileParam class",
"name": "__init__",
"signature": "def __init__(self, entity_id=None, remediation_state=None, root_inode_id=None, view_id=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A di... | 2 | stack_v2_sparse_classes_30k_train_038669 | Implement the Python class `InfectedFileParam` described below.
Class description:
Implementation of the 'InfectedFileParam' model. TODO: type description here. Attributes: entity_id (long|int): Specifies the entity id of the infected file. remediation_state (RemediationStateEnum): Specifies the remediation state of t... | Implement the Python class `InfectedFileParam` described below.
Class description:
Implementation of the 'InfectedFileParam' model. TODO: type description here. Attributes: entity_id (long|int): Specifies the entity id of the infected file. remediation_state (RemediationStateEnum): Specifies the remediation state of t... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class InfectedFileParam:
"""Implementation of the 'InfectedFileParam' model. TODO: type description here. Attributes: entity_id (long|int): Specifies the entity id of the infected file. remediation_state (RemediationStateEnum): Specifies the remediation state of the file. Remediation State. 'kQuarantin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InfectedFileParam:
"""Implementation of the 'InfectedFileParam' model. TODO: type description here. Attributes: entity_id (long|int): Specifies the entity id of the infected file. remediation_state (RemediationStateEnum): Specifies the remediation state of the file. Remediation State. 'kQuarantine' indicates ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/infected_file_param.py | cohesity/management-sdk-python | train | 24 |
4c504b796203c2f971bcd1d622019a58f68fc062 | [
"self.x = x\nself.y = y\nself.c = c\nself.d = P_D\nself.vv = random.randint(P_VEL_MIN, P_VEL_MAX)\nself.hv = random.randint(P_VEL_MIN, P_VEL_MAX)\nself.vg = GRAVITY\nself.faded = False\nself.fading_steps = P_STEPS",
"if not self.faded:\n if self.vv != 0:\n self.y -= self.vv\n if self.hv != 0:\n ... | <|body_start_0|>
self.x = x
self.y = y
self.c = c
self.d = P_D
self.vv = random.randint(P_VEL_MIN, P_VEL_MAX)
self.hv = random.randint(P_VEL_MIN, P_VEL_MAX)
self.vg = GRAVITY
self.faded = False
self.fading_steps = P_STEPS
<|end_body_0|>
<|body_sta... | Particle class. | Particle | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Particle:
"""Particle class."""
def __init__(self, x, y, c):
"""Constructor."""
<|body_0|>
def move(self):
"""Moves particle."""
<|body_1|>
def draw(self):
"""Draws particle."""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
s... | stack_v2_sparse_classes_75kplus_train_073725 | 3,152 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, x, y, c)"
},
{
"docstring": "Moves particle.",
"name": "move",
"signature": "def move(self)"
},
{
"docstring": "Draws particle.",
"name": "draw",
"signature": "def draw(self)"
}
] | 3 | stack_v2_sparse_classes_30k_train_044185 | Implement the Python class `Particle` described below.
Class description:
Particle class.
Method signatures and docstrings:
- def __init__(self, x, y, c): Constructor.
- def move(self): Moves particle.
- def draw(self): Draws particle. | Implement the Python class `Particle` described below.
Class description:
Particle class.
Method signatures and docstrings:
- def __init__(self, x, y, c): Constructor.
- def move(self): Moves particle.
- def draw(self): Draws particle.
<|skeleton|>
class Particle:
"""Particle class."""
def __init__(self, x,... | 59531ab05cc540f1b76dd62099ad2476daef636f | <|skeleton|>
class Particle:
"""Particle class."""
def __init__(self, x, y, c):
"""Constructor."""
<|body_0|>
def move(self):
"""Moves particle."""
<|body_1|>
def draw(self):
"""Draws particle."""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Particle:
"""Particle class."""
def __init__(self, x, y, c):
"""Constructor."""
self.x = x
self.y = y
self.c = c
self.d = P_D
self.vv = random.randint(P_VEL_MIN, P_VEL_MAX)
self.hv = random.randint(P_VEL_MIN, P_VEL_MAX)
self.vg = GRAVITY
... | the_stack_v2_python_sparse | processing/fireworks.py | jsmolka/sandbox-python | train | 0 |
de99b9d246dbcb67f9fd433fe045eb21fe5cd0bd | [
"self._config = CONFIG\nself._device_dict = {}\nself._devicename = devicename\nlog_message = 'Starting port idle times for device {}.'.format(devicename)\nlog.log2debug(1034, log_message)\nfilepath = self._config.temp_topology_device_file(devicename)\nif os.path.isfile(filepath) is True:\n self._device_dict = ge... | <|body_start_0|>
self._config = CONFIG
self._device_dict = {}
self._devicename = devicename
log_message = 'Starting port idle times for device {}.'.format(devicename)
log.log2debug(1034, log_message)
filepath = self._config.temp_topology_device_file(devicename)
if... | Process device port idle times. | IdleTimes | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IdleTimes:
"""Process device port idle times."""
def __init__(self, devicename):
"""Initialize class. Args: devicename: Name of device to calculate idle times Returns: None"""
<|body_0|>
def save(self):
"""Save the idle times to file. Args: None Returns: None"""
... | stack_v2_sparse_classes_75kplus_train_073726 | 20,081 | permissive | [
{
"docstring": "Initialize class. Args: devicename: Name of device to calculate idle times Returns: None",
"name": "__init__",
"signature": "def __init__(self, devicename)"
},
{
"docstring": "Save the idle times to file. Args: None Returns: None",
"name": "save",
"signature": "def save(s... | 2 | stack_v2_sparse_classes_30k_train_001846 | Implement the Python class `IdleTimes` described below.
Class description:
Process device port idle times.
Method signatures and docstrings:
- def __init__(self, devicename): Initialize class. Args: devicename: Name of device to calculate idle times Returns: None
- def save(self): Save the idle times to file. Args: N... | Implement the Python class `IdleTimes` described below.
Class description:
Process device port idle times.
Method signatures and docstrings:
- def __init__(self, devicename): Initialize class. Args: devicename: Name of device to calculate idle times Returns: None
- def save(self): Save the idle times to file. Args: N... | ae82589fbbab77fef6d6be09c1fcca5846f595a8 | <|skeleton|>
class IdleTimes:
"""Process device port idle times."""
def __init__(self, devicename):
"""Initialize class. Args: devicename: Name of device to calculate idle times Returns: None"""
<|body_0|>
def save(self):
"""Save the idle times to file. Args: None Returns: None"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IdleTimes:
"""Process device port idle times."""
def __init__(self, devicename):
"""Initialize class. Args: devicename: Name of device to calculate idle times Returns: None"""
self._config = CONFIG
self._device_dict = {}
self._devicename = devicename
log_message = ... | the_stack_v2_python_sparse | switchmap/process/device.py | PalisadoesFoundation/switchmap-ng | train | 8 |
737e6736fba9eca295117d03131560384f7c1f89 | [
"self.logDateName = datetime.datetime.now().strftime('%Y%m%d%H%M%S')\nself.processName = datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')\nself.plugin_dir = directory\nself.log = None\nself.database = None\nself.noa = None\nself.thread = None\nself.thread_clock = None\nself.javaProcessObject = None\nself.pixmap_w... | <|body_start_0|>
self.logDateName = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
self.processName = datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')
self.plugin_dir = directory
self.log = None
self.database = None
self.noa = None
self.thread = None
s... | Resources used by the process & interface Objects | Resources | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Resources:
"""Resources used by the process & interface Objects"""
def __init__(self, directory):
"""Constructor"""
<|body_0|>
def loadAppResources(self):
"""load interface graphical resources"""
<|body_1|>
def releaseResources(self, planHeatDMM):
... | stack_v2_sparse_classes_75kplus_train_073727 | 5,429 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, directory)"
},
{
"docstring": "load interface graphical resources",
"name": "loadAppResources",
"signature": "def loadAppResources(self)"
},
{
"docstring": "Release application resources",
"nam... | 3 | stack_v2_sparse_classes_30k_train_024405 | Implement the Python class `Resources` described below.
Class description:
Resources used by the process & interface Objects
Method signatures and docstrings:
- def __init__(self, directory): Constructor
- def loadAppResources(self): load interface graphical resources
- def releaseResources(self, planHeatDMM): Releas... | Implement the Python class `Resources` described below.
Class description:
Resources used by the process & interface Objects
Method signatures and docstrings:
- def __init__(self, directory): Constructor
- def loadAppResources(self): load interface graphical resources
- def releaseResources(self, planHeatDMM): Releas... | 9764fcb86d3898b232c4cc333dab75ebe41cd421 | <|skeleton|>
class Resources:
"""Resources used by the process & interface Objects"""
def __init__(self, directory):
"""Constructor"""
<|body_0|>
def loadAppResources(self):
"""load interface graphical resources"""
<|body_1|>
def releaseResources(self, planHeatDMM):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Resources:
"""Resources used by the process & interface Objects"""
def __init__(self, directory):
"""Constructor"""
self.logDateName = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
self.processName = datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')
self.plugin_dir = d... | the_stack_v2_python_sparse | PlanheatMappingModule/PlanHeatDMM/src/resources.py | Planheat/Planheat-Tool | train | 2 |
b7429a64befe2c04c0844c1f4cbdc429a345aa5f | [
"if treeNode is None:\n return\nprint(treeNode.data.data)\nself.middleOrderTraversalRecursion(treeNode.leftChild)\nself.middleOrderTraversalRecursion(treeNode.rightChild)",
"stack = []\nresult = []\nwhile treeNode or stack:\n if treeNode:\n result.append(treeNode.data.data)\n stack.append(tree... | <|body_start_0|>
if treeNode is None:
return
print(treeNode.data.data)
self.middleOrderTraversalRecursion(treeNode.leftChild)
self.middleOrderTraversalRecursion(treeNode.rightChild)
<|end_body_0|>
<|body_start_1|>
stack = []
result = []
while treeNode... | MiddleOrderTraversal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MiddleOrderTraversal:
def middleOrderTraversalRecursion(self, treeNode):
"""先序遍历的递归实现 :param treeNode: :return:"""
<|body_0|>
def middleOrderTraversalNotRecursion(self, treeNode):
"""先序遍历的非递归实现 :param treeNode: :return:"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_75kplus_train_073728 | 2,289 | no_license | [
{
"docstring": "先序遍历的递归实现 :param treeNode: :return:",
"name": "middleOrderTraversalRecursion",
"signature": "def middleOrderTraversalRecursion(self, treeNode)"
},
{
"docstring": "先序遍历的非递归实现 :param treeNode: :return:",
"name": "middleOrderTraversalNotRecursion",
"signature": "def middleOr... | 2 | stack_v2_sparse_classes_30k_train_033720 | Implement the Python class `MiddleOrderTraversal` described below.
Class description:
Implement the MiddleOrderTraversal class.
Method signatures and docstrings:
- def middleOrderTraversalRecursion(self, treeNode): 先序遍历的递归实现 :param treeNode: :return:
- def middleOrderTraversalNotRecursion(self, treeNode): 先序遍历的非递归实现 ... | Implement the Python class `MiddleOrderTraversal` described below.
Class description:
Implement the MiddleOrderTraversal class.
Method signatures and docstrings:
- def middleOrderTraversalRecursion(self, treeNode): 先序遍历的递归实现 :param treeNode: :return:
- def middleOrderTraversalNotRecursion(self, treeNode): 先序遍历的非递归实现 ... | cded97a52c422f98b55f2b3527a054d23541d5a4 | <|skeleton|>
class MiddleOrderTraversal:
def middleOrderTraversalRecursion(self, treeNode):
"""先序遍历的递归实现 :param treeNode: :return:"""
<|body_0|>
def middleOrderTraversalNotRecursion(self, treeNode):
"""先序遍历的非递归实现 :param treeNode: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MiddleOrderTraversal:
def middleOrderTraversalRecursion(self, treeNode):
"""先序遍历的递归实现 :param treeNode: :return:"""
if treeNode is None:
return
print(treeNode.data.data)
self.middleOrderTraversalRecursion(treeNode.leftChild)
self.middleOrderTraversalRecursion... | the_stack_v2_python_sparse | chapter5/先序遍历.py | AnJian2020/Leetcode | train | 1 | |
54dcc8891439a5350d8ec44525b64eda8554423c | [
"n = len(s)\nm = len(t)\ndp = [[0] * (m + 1) for _ in range(n + 1)]\ni = 0\nwhile i <= n:\n j = 0\n while j <= m:\n if i == j == 0:\n dp[i][j] = 0\n elif s[i - 1] == t[j - 1]:\n dp[i][j] = dp[i - 1][j - 1]\n else:\n dp[i][j] = min([dp[i - 1][j - 1] + 1, dp... | <|body_start_0|>
n = len(s)
m = len(t)
dp = [[0] * (m + 1) for _ in range(n + 1)]
i = 0
while i <= n:
j = 0
while j <= m:
if i == j == 0:
dp[i][j] = 0
elif s[i - 1] == t[j - 1]:
dp[i][... | @param s: a string @param t: a string @return: true if they are both one edit distance apart or false | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""@param s: a string @param t: a string @return: true if they are both one edit distance apart or false"""
def isOneEditDistance(self, s, t):
"""Dynamic Programming solution (not recommended): O(n2) runtime, O(n2) space https://leetcode-cn.com/problems/edit-distance/soluti... | stack_v2_sparse_classes_75kplus_train_073729 | 1,840 | no_license | [
{
"docstring": "Dynamic Programming solution (not recommended): O(n2) runtime, O(n2) space https://leetcode-cn.com/problems/edit-distance/solution/edit-distance-by-ikaruga/",
"name": "isOneEditDistance",
"signature": "def isOneEditDistance(self, s, t)"
},
{
"docstring": "O(n) runtime, O(1) space... | 2 | stack_v2_sparse_classes_30k_test_002344 | Implement the Python class `Solution` described below.
Class description:
@param s: a string @param t: a string @return: true if they are both one edit distance apart or false
Method signatures and docstrings:
- def isOneEditDistance(self, s, t): Dynamic Programming solution (not recommended): O(n2) runtime, O(n2) sp... | Implement the Python class `Solution` described below.
Class description:
@param s: a string @param t: a string @return: true if they are both one edit distance apart or false
Method signatures and docstrings:
- def isOneEditDistance(self, s, t): Dynamic Programming solution (not recommended): O(n2) runtime, O(n2) sp... | 3ea03cd8b1fa507553ebee4fd765c4cc4b5814b6 | <|skeleton|>
class Solution:
"""@param s: a string @param t: a string @return: true if they are both one edit distance apart or false"""
def isOneEditDistance(self, s, t):
"""Dynamic Programming solution (not recommended): O(n2) runtime, O(n2) space https://leetcode-cn.com/problems/edit-distance/soluti... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""@param s: a string @param t: a string @return: true if they are both one edit distance apart or false"""
def isOneEditDistance(self, s, t):
"""Dynamic Programming solution (not recommended): O(n2) runtime, O(n2) space https://leetcode-cn.com/problems/edit-distance/solution/edit-dista... | the_stack_v2_python_sparse | One_Edit_Distance_14.py | jay6413682/Leetcode | train | 0 |
f39b6483965651b08ae6daa9797c6b53d66b3d8a | [
"if logger.isEnabledFor(logging.DEBUG):\n logger.debug('Entry with args=(ctx=%s, kwargs=%s, parameters=%s) called by=%s', ctx, kwargs, parameters, '::L'.join((str(i) for i in inspect.getouterframes(inspect.currentframe(), 2)[1][1:3])))\nctx.tapes = kwargs['tapes']\nctx.device = kwargs['device']\nctx.execute_fn =... | <|body_start_0|>
if logger.isEnabledFor(logging.DEBUG):
logger.debug('Entry with args=(ctx=%s, kwargs=%s, parameters=%s) called by=%s', ctx, kwargs, parameters, '::L'.join((str(i) for i in inspect.getouterframes(inspect.currentframe(), 2)[1][1:3])))
ctx.tapes = kwargs['tapes']
ctx.de... | The signature of this ``torch.autograd.Function`` is designed to work around Torch restrictions. In particular, ``torch.autograd.Function``: - Cannot accept keyword arguments. As a result, we pass a dictionary as the first argument ``kwargs``. This dictionary **must** contain: * ``"tapes"``: the quantum tapes to batch ... | ExecuteTapes | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExecuteTapes:
"""The signature of this ``torch.autograd.Function`` is designed to work around Torch restrictions. In particular, ``torch.autograd.Function``: - Cannot accept keyword arguments. As a result, we pass a dictionary as the first argument ``kwargs``. This dictionary **must** contain: * ... | stack_v2_sparse_classes_75kplus_train_073730 | 15,349 | permissive | [
{
"docstring": "Implements the forward pass batch tape evaluation.",
"name": "forward",
"signature": "def forward(ctx, kwargs, *parameters)"
},
{
"docstring": "Returns the vector-Jacobian product with given parameter values p and output gradient dy",
"name": "backward",
"signature": "def... | 2 | stack_v2_sparse_classes_30k_train_021298 | Implement the Python class `ExecuteTapes` described below.
Class description:
The signature of this ``torch.autograd.Function`` is designed to work around Torch restrictions. In particular, ``torch.autograd.Function``: - Cannot accept keyword arguments. As a result, we pass a dictionary as the first argument ``kwargs`... | Implement the Python class `ExecuteTapes` described below.
Class description:
The signature of this ``torch.autograd.Function`` is designed to work around Torch restrictions. In particular, ``torch.autograd.Function``: - Cannot accept keyword arguments. As a result, we pass a dictionary as the first argument ``kwargs`... | 0843183ff15a013c2622af5e61fea431d18076d3 | <|skeleton|>
class ExecuteTapes:
"""The signature of this ``torch.autograd.Function`` is designed to work around Torch restrictions. In particular, ``torch.autograd.Function``: - Cannot accept keyword arguments. As a result, we pass a dictionary as the first argument ``kwargs``. This dictionary **must** contain: * ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExecuteTapes:
"""The signature of this ``torch.autograd.Function`` is designed to work around Torch restrictions. In particular, ``torch.autograd.Function``: - Cannot accept keyword arguments. As a result, we pass a dictionary as the first argument ``kwargs``. This dictionary **must** contain: * ``"tapes"``: ... | the_stack_v2_python_sparse | pennylane/interfaces/torch.py | PennyLaneAI/pennylane | train | 1,431 |
4a15858a72e39b01e2baed9315aa4b314f0b1395 | [
"form.instance.user = self.request.user\nform.save()\nreturn super(ProfileView, self).form_valid(form)",
"if not form_class:\n form_class = self.get_form_class()\nreturn form_class(instance=self.request.user, **self.get_form_kwargs())"
] | <|body_start_0|>
form.instance.user = self.request.user
form.save()
return super(ProfileView, self).form_valid(form)
<|end_body_0|>
<|body_start_1|>
if not form_class:
form_class = self.get_form_class()
return form_class(instance=self.request.user, **self.get_form_kw... | Profile view class | ProfileView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileView:
"""Profile view class"""
def form_valid(self, form):
"""Saves the form along with user instance"""
<|body_0|>
def get_form(self, form_class=None):
"""Provides form with initial data"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
fo... | stack_v2_sparse_classes_75kplus_train_073731 | 813 | no_license | [
{
"docstring": "Saves the form along with user instance",
"name": "form_valid",
"signature": "def form_valid(self, form)"
},
{
"docstring": "Provides form with initial data",
"name": "get_form",
"signature": "def get_form(self, form_class=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_043343 | Implement the Python class `ProfileView` described below.
Class description:
Profile view class
Method signatures and docstrings:
- def form_valid(self, form): Saves the form along with user instance
- def get_form(self, form_class=None): Provides form with initial data | Implement the Python class `ProfileView` described below.
Class description:
Profile view class
Method signatures and docstrings:
- def form_valid(self, form): Saves the form along with user instance
- def get_form(self, form_class=None): Provides form with initial data
<|skeleton|>
class ProfileView:
"""Profile... | 277f9aad2456b77981ee701a1b359eb05e25cc28 | <|skeleton|>
class ProfileView:
"""Profile view class"""
def form_valid(self, form):
"""Saves the form along with user instance"""
<|body_0|>
def get_form(self, form_class=None):
"""Provides form with initial data"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProfileView:
"""Profile view class"""
def form_valid(self, form):
"""Saves the form along with user instance"""
form.instance.user = self.request.user
form.save()
return super(ProfileView, self).form_valid(form)
def get_form(self, form_class=None):
"""Provides... | the_stack_v2_python_sparse | cryptosignals/views/profile.py | GianlucaCode/cryptosignals | train | 0 |
6ecf34203786a82cdb3426efc7f51ca34580021e | [
"with transaction.atomic():\n event = CampusEvent.objects.select_for_update().get(id=enrollment_data['campus_event'].id)\n if now() > event.deadline:\n raise BadRequest('报名时间已过')\n if event.num_enrolled >= event.num_participants:\n raise BadRequest('报名人数已满')\n enrollment = Enrollment.objec... | <|body_start_0|>
with transaction.atomic():
event = CampusEvent.objects.select_for_update().get(id=enrollment_data['campus_event'].id)
if now() > event.deadline:
raise BadRequest('报名时间已过')
if event.num_enrolled >= event.num_participants:
raise ... | Provide services for Enrollment. | EnrollmentService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnrollmentService:
"""Provide services for Enrollment."""
def create_enrollment(enrollment_data):
"""Create a enrollment for specific campus event. This action is atomic, will fail if there are no more heads counts for the campus event or duplicated enrollments are created. Parametse... | stack_v2_sparse_classes_75kplus_train_073732 | 8,615 | no_license | [
{
"docstring": "Create a enrollment for specific campus event. This action is atomic, will fail if there are no more heads counts for the campus event or duplicated enrollments are created. Parametsers ---------- enrollment_data: dict This dict should have full information needed to create an Enrollment. Return... | 5 | stack_v2_sparse_classes_30k_train_014764 | Implement the Python class `EnrollmentService` described below.
Class description:
Provide services for Enrollment.
Method signatures and docstrings:
- def create_enrollment(enrollment_data): Create a enrollment for specific campus event. This action is atomic, will fail if there are no more heads counts for the camp... | Implement the Python class `EnrollmentService` described below.
Class description:
Provide services for Enrollment.
Method signatures and docstrings:
- def create_enrollment(enrollment_data): Create a enrollment for specific campus event. This action is atomic, will fail if there are no more heads counts for the camp... | 48cccddbe8347167cb6120a1cd7d61f9fc57cc7c | <|skeleton|>
class EnrollmentService:
"""Provide services for Enrollment."""
def create_enrollment(enrollment_data):
"""Create a enrollment for specific campus event. This action is atomic, will fail if there are no more heads counts for the campus event or duplicated enrollments are created. Parametse... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EnrollmentService:
"""Provide services for Enrollment."""
def create_enrollment(enrollment_data):
"""Create a enrollment for specific campus event. This action is atomic, will fail if there are no more heads counts for the campus event or duplicated enrollments are created. Parametsers ----------... | the_stack_v2_python_sparse | training_event/services.py | DLUT-SIE/TMSFTT-BE | train | 1 |
828dbb37ef0e139c616567fbff25f6d9e0e420af | [
"try:\n send_health_message(KAFKA_SERVER, HEALTHTOPIC, SERVICENAME)\nexcept Exception as error:\n LogMessage(str(error), LogMessage.LogTyp.ERROR, SERVICENAME).log()",
"try:\n report = json.loads(report.value.decode('UTF-8'))\n misp_connection = PyMISP(MISP_SERVER, MISP_TOKEN, MISP_CERT_VERIFY)\n ha... | <|body_start_0|>
try:
send_health_message(KAFKA_SERVER, HEALTHTOPIC, SERVICENAME)
except Exception as error:
LogMessage(str(error), LogMessage.LogTyp.ERROR, SERVICENAME).log()
<|end_body_0|>
<|body_start_1|>
try:
report = json.loads(report.value.decode('UTF-8... | Reporter will be a class representing the reporter-service. | Reporter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Reporter:
"""Reporter will be a class representing the reporter-service."""
def healthpush():
"""healthpush will send a health message to KAFKA."""
<|body_0|>
def push_misp_report(report):
"""push_misp_report will send the misp report to the misp-platfrom."""
... | stack_v2_sparse_classes_75kplus_train_073733 | 3,082 | permissive | [
{
"docstring": "healthpush will send a health message to KAFKA.",
"name": "healthpush",
"signature": "def healthpush()"
},
{
"docstring": "push_misp_report will send the misp report to the misp-platfrom.",
"name": "push_misp_report",
"signature": "def push_misp_report(report)"
},
{
... | 4 | stack_v2_sparse_classes_30k_train_025272 | Implement the Python class `Reporter` described below.
Class description:
Reporter will be a class representing the reporter-service.
Method signatures and docstrings:
- def healthpush(): healthpush will send a health message to KAFKA.
- def push_misp_report(report): push_misp_report will send the misp report to the ... | Implement the Python class `Reporter` described below.
Class description:
Reporter will be a class representing the reporter-service.
Method signatures and docstrings:
- def healthpush(): healthpush will send a health message to KAFKA.
- def push_misp_report(report): push_misp_report will send the misp report to the ... | cdad9966ab2aef495d0dca51a06cf567dd38a315 | <|skeleton|>
class Reporter:
"""Reporter will be a class representing the reporter-service."""
def healthpush():
"""healthpush will send a health message to KAFKA."""
<|body_0|>
def push_misp_report(report):
"""push_misp_report will send the misp report to the misp-platfrom."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Reporter:
"""Reporter will be a class representing the reporter-service."""
def healthpush():
"""healthpush will send a health message to KAFKA."""
try:
send_health_message(KAFKA_SERVER, HEALTHTOPIC, SERVICENAME)
except Exception as error:
LogMessage(str(er... | the_stack_v2_python_sparse | iocreporter/core/server.py | hm-seclab/YAFRA | train | 32 |
e3d08c81142929b34f52d3bab71457e6b8894706 | [
"idx1, idx2 = (-1, -1)\nrst = len(words)\nfor idx, word in enumerate(words):\n if word == word1:\n idx1 = idx\n if idx2 != -1:\n rst = min(rst, abs(idx1 - idx2))\n elif word == word2:\n idx2 = idx\n if idx1 != -1:\n rst = min(rst, abs(idx1 - idx2))\nreturn rst... | <|body_start_0|>
idx1, idx2 = (-1, -1)
rst = len(words)
for idx, word in enumerate(words):
if word == word1:
idx1 = idx
if idx2 != -1:
rst = min(rst, abs(idx1 - idx2))
elif word == word2:
idx2 = idx
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def shortestDistance(self, words, word1, word2):
""":type words: List[str] :type word1: str :type word2: str :rtype: int"""
<|body_0|>
def shortestDistance2(self, words, word1, word2):
""":type words: List[str] :type word1: str :type word2: str :rtype: int"... | stack_v2_sparse_classes_75kplus_train_073734 | 1,628 | no_license | [
{
"docstring": ":type words: List[str] :type word1: str :type word2: str :rtype: int",
"name": "shortestDistance",
"signature": "def shortestDistance(self, words, word1, word2)"
},
{
"docstring": ":type words: List[str] :type word1: str :type word2: str :rtype: int",
"name": "shortestDistanc... | 2 | stack_v2_sparse_classes_30k_train_035761 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def shortestDistance(self, words, word1, word2): :type words: List[str] :type word1: str :type word2: str :rtype: int
- def shortestDistance2(self, words, word1, word2): :type wo... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def shortestDistance(self, words, word1, word2): :type words: List[str] :type word1: str :type word2: str :rtype: int
- def shortestDistance2(self, words, word1, word2): :type wo... | 41365b549f1e6b04aac9f1632a66e71c1e05b322 | <|skeleton|>
class Solution:
def shortestDistance(self, words, word1, word2):
""":type words: List[str] :type word1: str :type word2: str :rtype: int"""
<|body_0|>
def shortestDistance2(self, words, word1, word2):
""":type words: List[str] :type word1: str :type word2: str :rtype: int"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def shortestDistance(self, words, word1, word2):
""":type words: List[str] :type word1: str :type word2: str :rtype: int"""
idx1, idx2 = (-1, -1)
rst = len(words)
for idx, word in enumerate(words):
if word == word1:
idx1 = idx
... | the_stack_v2_python_sparse | python practice/Array/243_shortest_word_distance.py | SuzyWu2014/coding-practice | train | 1 | |
eb5cb76d822a0f3a690f4d1c957496fca20225c5 | [
"self.gateway = gateway\nself.id = id\nself.ip_vec = ip_vec\nself.subnet_ip = subnet_ip",
"if dictionary is None:\n return None\ngateway = dictionary.get('gateway')\nid = dictionary.get('id')\nip_vec = dictionary.get('ipVec')\nsubnet_ip = dictionary.get('subnetIp')\nreturn cls(gateway, id, ip_vec, subnet_ip)"
... | <|body_start_0|>
self.gateway = gateway
self.id = id
self.ip_vec = ip_vec
self.subnet_ip = subnet_ip
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
gateway = dictionary.get('gateway')
id = dictionary.get('id')
ip_vec = dict... | Implementation of the 'OracleVlanInfo' model. TODO: type description here. Attributes: gateway (string): Gateway for this VLAN. id (int): ID of this VLAN. ip_vec (list of string): List of IPs in this VLAN. subnet_ip (string): Subnet IP for this VLAN. | OracleVlanInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OracleVlanInfo:
"""Implementation of the 'OracleVlanInfo' model. TODO: type description here. Attributes: gateway (string): Gateway for this VLAN. id (int): ID of this VLAN. ip_vec (list of string): List of IPs in this VLAN. subnet_ip (string): Subnet IP for this VLAN."""
def __init__(self, ... | stack_v2_sparse_classes_75kplus_train_073735 | 1,857 | permissive | [
{
"docstring": "Constructor for the OracleVlanInfo class",
"name": "__init__",
"signature": "def __init__(self, gateway=None, id=None, ip_vec=None, subnet_ip=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation o... | 2 | null | Implement the Python class `OracleVlanInfo` described below.
Class description:
Implementation of the 'OracleVlanInfo' model. TODO: type description here. Attributes: gateway (string): Gateway for this VLAN. id (int): ID of this VLAN. ip_vec (list of string): List of IPs in this VLAN. subnet_ip (string): Subnet IP for... | Implement the Python class `OracleVlanInfo` described below.
Class description:
Implementation of the 'OracleVlanInfo' model. TODO: type description here. Attributes: gateway (string): Gateway for this VLAN. id (int): ID of this VLAN. ip_vec (list of string): List of IPs in this VLAN. subnet_ip (string): Subnet IP for... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class OracleVlanInfo:
"""Implementation of the 'OracleVlanInfo' model. TODO: type description here. Attributes: gateway (string): Gateway for this VLAN. id (int): ID of this VLAN. ip_vec (list of string): List of IPs in this VLAN. subnet_ip (string): Subnet IP for this VLAN."""
def __init__(self, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OracleVlanInfo:
"""Implementation of the 'OracleVlanInfo' model. TODO: type description here. Attributes: gateway (string): Gateway for this VLAN. id (int): ID of this VLAN. ip_vec (list of string): List of IPs in this VLAN. subnet_ip (string): Subnet IP for this VLAN."""
def __init__(self, gateway=None,... | the_stack_v2_python_sparse | cohesity_management_sdk/models/oracle_vlan_info.py | cohesity/management-sdk-python | train | 24 |
936c409c1faff447bddd6daa2b66059df6d76a0c | [
"self.media_folder = mkdtemp()\nif not os.path.exists(app.settings.MEDIA_ROOT):\n os.makedirs(app.settings.MEDIA_ROOT)\nif not os.path.exists(app.settings.THUMBS_ROOT):\n os.makedirs(app.settings.THUMBS_ROOT)",
"dir_path = app.settings.MEDIA_ROOT\nfor f in os.listdir(dir_path):\n file_path = '{}/{}'.form... | <|body_start_0|>
self.media_folder = mkdtemp()
if not os.path.exists(app.settings.MEDIA_ROOT):
os.makedirs(app.settings.MEDIA_ROOT)
if not os.path.exists(app.settings.THUMBS_ROOT):
os.makedirs(app.settings.THUMBS_ROOT)
<|end_body_0|>
<|body_start_1|>
dir_path = a... | Tests class for AttachmentViewSet. | AttachmentViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttachmentViewSet:
"""Tests class for AttachmentViewSet."""
def setUp(self):
"""Set up testing dependencies."""
<|body_0|>
def tearDown(self):
"""Remove all dependencies after test."""
<|body_1|>
def test_success_photo_upload(self):
"""Test s... | stack_v2_sparse_classes_75kplus_train_073736 | 2,222 | no_license | [
{
"docstring": "Set up testing dependencies.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Remove all dependencies after test.",
"name": "tearDown",
"signature": "def tearDown(self)"
},
{
"docstring": "Test successfull photo upload.",
"name": "test_succ... | 4 | null | Implement the Python class `AttachmentViewSet` described below.
Class description:
Tests class for AttachmentViewSet.
Method signatures and docstrings:
- def setUp(self): Set up testing dependencies.
- def tearDown(self): Remove all dependencies after test.
- def test_success_photo_upload(self): Test successfull phot... | Implement the Python class `AttachmentViewSet` described below.
Class description:
Tests class for AttachmentViewSet.
Method signatures and docstrings:
- def setUp(self): Set up testing dependencies.
- def tearDown(self): Remove all dependencies after test.
- def test_success_photo_upload(self): Test successfull phot... | 252b0ebd77eefbcc945a0efc3068cc3421f46d5f | <|skeleton|>
class AttachmentViewSet:
"""Tests class for AttachmentViewSet."""
def setUp(self):
"""Set up testing dependencies."""
<|body_0|>
def tearDown(self):
"""Remove all dependencies after test."""
<|body_1|>
def test_success_photo_upload(self):
"""Test s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AttachmentViewSet:
"""Tests class for AttachmentViewSet."""
def setUp(self):
"""Set up testing dependencies."""
self.media_folder = mkdtemp()
if not os.path.exists(app.settings.MEDIA_ROOT):
os.makedirs(app.settings.MEDIA_ROOT)
if not os.path.exists(app.settings... | the_stack_v2_python_sparse | app/attachments/tests.py | vsokoltsov/Interview360Server | train | 2 |
1ccbd4d294ee012380c5dacc4ee772f7bf2a5467 | [
"if l1.val <= l2.val:\n return (l1, l2)\nelse:\n return (l2, l1)",
"here, there = self.ll_sort(l1, l2)\nstart = here\nwhile here.next is not None:\n here.next, there = self.ll_sort(here.next, there)\n here = here.next\nreturn start"
] | <|body_start_0|>
if l1.val <= l2.val:
return (l1, l2)
else:
return (l2, l1)
<|end_body_0|>
<|body_start_1|>
here, there = self.ll_sort(l1, l2)
start = here
while here.next is not None:
here.next, there = self.ll_sort(here.next, there)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def ll_sort(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
i... | stack_v2_sparse_classes_75kplus_train_073737 | 1,456 | no_license | [
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "ll_sort",
"signature": "def ll_sort(self, l1, l2)"
},
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "mergeTwoLists",
"signature": "def mergeTwoLists(self, l1, l2)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017589 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def ll_sort(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def ll_sort(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
<|ske... | a0fe408a74fd88cb5061f827dd3cb606f988f367 | <|skeleton|>
class Solution:
def ll_sort(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def ll_sort(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
if l1.val <= l2.val:
return (l1, l2)
else:
return (l2, l1)
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode""... | the_stack_v2_python_sparse | solutions/lc_21_merge_two_sorted_lists.py | mtmbutler/leetcode | train | 0 | |
94afaef8ebdec1a87cd9c7f1243759a7bc4dda0a | [
"context = context or {}\ntotal = 0.0\nres = {}\nfor inv in self.browse(cr, uid, ids, context=context):\n for line in inv.invoice_line:\n total += line.subtotal_wo_discount\n res[inv.id] = total\nreturn res",
"context = context or {}\ntotal = 0.0\nres = {}\nfor inv in self.browse(cr, uid, ids, contex... | <|body_start_0|>
context = context or {}
total = 0.0
res = {}
for inv in self.browse(cr, uid, ids, context=context):
for line in inv.invoice_line:
total += line.subtotal_wo_discount
res[inv.id] = total
return res
<|end_body_0|>
<|body_star... | Inherit from account.invoice to get the amount total without discount and the amount total of this, of all invoice lines. | AccountInvoice | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountInvoice:
"""Inherit from account.invoice to get the amount total without discount and the amount total of this, of all invoice lines."""
def _get_subtotal_without_discount(self, cr, uid, ids, args, field_name, context=None):
"""Method to get the subtotal of the amount without ... | stack_v2_sparse_classes_75kplus_train_073738 | 6,805 | no_license | [
{
"docstring": "Method to get the subtotal of the amount without discount of the sum of invoice lines. @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param ids: list of ids for which name should be read @param field_name: field that call the method ... | 2 | null | Implement the Python class `AccountInvoice` described below.
Class description:
Inherit from account.invoice to get the amount total without discount and the amount total of this, of all invoice lines.
Method signatures and docstrings:
- def _get_subtotal_without_discount(self, cr, uid, ids, args, field_name, context... | Implement the Python class `AccountInvoice` described below.
Class description:
Inherit from account.invoice to get the amount total without discount and the amount total of this, of all invoice lines.
Method signatures and docstrings:
- def _get_subtotal_without_discount(self, cr, uid, ids, args, field_name, context... | 511dc410b4eba1f8ea939c6af02a5adea5122c92 | <|skeleton|>
class AccountInvoice:
"""Inherit from account.invoice to get the amount total without discount and the amount total of this, of all invoice lines."""
def _get_subtotal_without_discount(self, cr, uid, ids, args, field_name, context=None):
"""Method to get the subtotal of the amount without ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AccountInvoice:
"""Inherit from account.invoice to get the amount total without discount and the amount total of this, of all invoice lines."""
def _get_subtotal_without_discount(self, cr, uid, ids, args, field_name, context=None):
"""Method to get the subtotal of the amount without discount of t... | the_stack_v2_python_sparse | invoice_discount/model/invoice.py | yelizariev/addons-vauxoo | train | 3 |
0faca9c3c9d51d799b5d86a4bf6b1108d05d3a6a | [
"if uri.startswith(const.SFTP_URI):\n return FetcherFactory.UriType.SFTP\nif uri.startswith(const.HTTPS_URI):\n return FetcherFactory.UriType.HTTPS\nif uri.startswith(const.TRESTLE_HREF_HEADING):\n return FetcherFactory.UriType.TRESTLE\nuri_clean = uri.strip()\nuri_len = len(uri_clean)\nif uri_len > 4 and ... | <|body_start_0|>
if uri.startswith(const.SFTP_URI):
return FetcherFactory.UriType.SFTP
if uri.startswith(const.HTTPS_URI):
return FetcherFactory.UriType.HTTPS
if uri.startswith(const.TRESTLE_HREF_HEADING):
return FetcherFactory.UriType.TRESTLE
uri_clea... | Factory method for creating a fetcher. | FetcherFactory | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FetcherFactory:
"""Factory method for creating a fetcher."""
def _get_uri_type(uri: str) -> UriType:
"""Determine the type of uri."""
<|body_0|>
def in_trestle_directory(trestle_root: pathlib.Path, uri: str) -> bool:
"""Check if in trestle directory when uri may ... | stack_v2_sparse_classes_75kplus_train_073739 | 21,049 | permissive | [
{
"docstring": "Determine the type of uri.",
"name": "_get_uri_type",
"signature": "def _get_uri_type(uri: str) -> UriType"
},
{
"docstring": "Check if in trestle directory when uri may not be a file path.",
"name": "in_trestle_directory",
"signature": "def in_trestle_directory(trestle_r... | 3 | null | Implement the Python class `FetcherFactory` described below.
Class description:
Factory method for creating a fetcher.
Method signatures and docstrings:
- def _get_uri_type(uri: str) -> UriType: Determine the type of uri.
- def in_trestle_directory(trestle_root: pathlib.Path, uri: str) -> bool: Check if in trestle di... | Implement the Python class `FetcherFactory` described below.
Class description:
Factory method for creating a fetcher.
Method signatures and docstrings:
- def _get_uri_type(uri: str) -> UriType: Determine the type of uri.
- def in_trestle_directory(trestle_root: pathlib.Path, uri: str) -> bool: Check if in trestle di... | 969c10eceb73202d2b7856bac598f9b11afc696e | <|skeleton|>
class FetcherFactory:
"""Factory method for creating a fetcher."""
def _get_uri_type(uri: str) -> UriType:
"""Determine the type of uri."""
<|body_0|>
def in_trestle_directory(trestle_root: pathlib.Path, uri: str) -> bool:
"""Check if in trestle directory when uri may ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FetcherFactory:
"""Factory method for creating a fetcher."""
def _get_uri_type(uri: str) -> UriType:
"""Determine the type of uri."""
if uri.startswith(const.SFTP_URI):
return FetcherFactory.UriType.SFTP
if uri.startswith(const.HTTPS_URI):
return FetcherFac... | the_stack_v2_python_sparse | trestle/core/remote/cache.py | xee5ch/compliance-trestle | train | 0 |
5113842aee9a621eb8adfd6393c5df6921fcd912 | [
"if not pathlib.Path(self.path).is_block_device():\n raise GenericError('Path \"{}\" is not a block device.'.format(self.path))\nif self.parent:\n print_warning('\"{}\" is a child device.'.format(self.path))\n if ask('Use parent device \"{}\" instead?'.format(self.parent)):\n self.path = os.path.rea... | <|body_start_0|>
if not pathlib.Path(self.path).is_block_device():
raise GenericError('Path "{}" is not a block device.'.format(self.path))
if self.parent:
print_warning('"{}" is a child device.'.format(self.path))
if ask('Use parent device "{}" instead?'.format(self.... | Block device object. | DevObj | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DevObj:
"""Block device object."""
def self_check(self):
"""Verify that self.path points to a block device."""
<|body_0|>
def set_details(self):
"""Set details via lsblk."""
<|body_1|>
def update_filename_prefix(self):
"""Set filename prefix ... | stack_v2_sparse_classes_75kplus_train_073740 | 46,295 | permissive | [
{
"docstring": "Verify that self.path points to a block device.",
"name": "self_check",
"signature": "def self_check(self)"
},
{
"docstring": "Set details via lsblk.",
"name": "set_details",
"signature": "def set_details(self)"
},
{
"docstring": "Set filename prefix based on deta... | 3 | null | Implement the Python class `DevObj` described below.
Class description:
Block device object.
Method signatures and docstrings:
- def self_check(self): Verify that self.path points to a block device.
- def set_details(self): Set details via lsblk.
- def update_filename_prefix(self): Set filename prefix based on detail... | Implement the Python class `DevObj` described below.
Class description:
Block device object.
Method signatures and docstrings:
- def self_check(self): Verify that self.path points to a block device.
- def set_details(self): Set details via lsblk.
- def update_filename_prefix(self): Set filename prefix based on detail... | 569a77edf28169dbeab9ecf708e8b5638ef2774c | <|skeleton|>
class DevObj:
"""Block device object."""
def self_check(self):
"""Verify that self.path points to a block device."""
<|body_0|>
def set_details(self):
"""Set details via lsblk."""
<|body_1|>
def update_filename_prefix(self):
"""Set filename prefix ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DevObj:
"""Block device object."""
def self_check(self):
"""Verify that self.path points to a block device."""
if not pathlib.Path(self.path).is_block_device():
raise GenericError('Path "{}" is not a block device.'.format(self.path))
if self.parent:
print_w... | the_stack_v2_python_sparse | .bin/Scripts/functions/ddrescue.py | 2Shirt/WizardKit | train | 0 |
727a153cad997ed407be1efe566de51c257ae05f | [
"self.model_name = model\nself.degree = degree\nself.model = None\nself.model_fit = None\nself.model_constructor()",
"if self.model_name == 'chebyshev':\n self.model = models.Chebyshev1D(degree=self.degree)\n self.model_fit = fitting.LevMarLSQFitter()\nelif self.model_name == 'linear':\n self.model = mod... | <|body_start_0|>
self.model_name = model
self.degree = degree
self.model = None
self.model_fit = None
self.model_constructor()
<|end_body_0|>
<|body_start_1|>
if self.model_name == 'chebyshev':
self.model = models.Chebyshev1D(degree=self.degree)
s... | Contains methods to do pixel to angstrom fit | WavelengthFitter | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WavelengthFitter:
"""Contains methods to do pixel to angstrom fit"""
def __init__(self, model='chebyshev', degree=3):
"""Initializes the WavelengthFitter class Args: model (str): Name of the model to fit, Chebyshev (default) or Linear degree (int): Degree of the model. Only needed by... | stack_v2_sparse_classes_75kplus_train_073741 | 13,107 | permissive | [
{
"docstring": "Initializes the WavelengthFitter class Args: model (str): Name of the model to fit, Chebyshev (default) or Linear degree (int): Degree of the model. Only needed by Chebyshev model.",
"name": "__init__",
"signature": "def __init__(self, model='chebyshev', degree=3)"
},
{
"docstrin... | 3 | stack_v2_sparse_classes_30k_test_001746 | Implement the Python class `WavelengthFitter` described below.
Class description:
Contains methods to do pixel to angstrom fit
Method signatures and docstrings:
- def __init__(self, model='chebyshev', degree=3): Initializes the WavelengthFitter class Args: model (str): Name of the model to fit, Chebyshev (default) or... | Implement the Python class `WavelengthFitter` described below.
Class description:
Contains methods to do pixel to angstrom fit
Method signatures and docstrings:
- def __init__(self, model='chebyshev', degree=3): Initializes the WavelengthFitter class Args: model (str): Name of the model to fit, Chebyshev (default) or... | 167dcbd1bd66d938103964d725b92f2e3cc3a281 | <|skeleton|>
class WavelengthFitter:
"""Contains methods to do pixel to angstrom fit"""
def __init__(self, model='chebyshev', degree=3):
"""Initializes the WavelengthFitter class Args: model (str): Name of the model to fit, Chebyshev (default) or Linear degree (int): Degree of the model. Only needed by... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WavelengthFitter:
"""Contains methods to do pixel to angstrom fit"""
def __init__(self, model='chebyshev', degree=3):
"""Initializes the WavelengthFitter class Args: model (str): Name of the model to fit, Chebyshev (default) or Linear degree (int): Degree of the model. Only needed by Chebyshev mo... | the_stack_v2_python_sparse | goodman_spec/wsbuilder.py | wschoenell/goodman | train | 0 |
6fbb6afc88cbec39482d2f41284ea54ec6be13a2 | [
"Hist1D.__init__(self, d=None, startDate=startDate, endDate=endDate, filterDict=filterDict, flag=flag)\nself.histKeyX = histKeyX\nself.histKeyY = histKeyY\nif bins is None:\n if 'lm' in histKeyX.lower():\n self.bins = np.array([np.arange(2, 10), np.arange(0, 24)])\n elif 'lm' in histKeyY.lower():\n ... | <|body_start_0|>
Hist1D.__init__(self, d=None, startDate=startDate, endDate=endDate, filterDict=filterDict, flag=flag)
self.histKeyX = histKeyX
self.histKeyY = histKeyY
if bins is None:
if 'lm' in histKeyX.lower():
self.bins = np.array([np.arange(2, 10), np.ar... | Hist2D | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Hist2D:
def __init__(self, histKeyX, histKeyY, bins=None, startDate=datetime(2014, 1, 1), endDate=datetime.now(), filterDict={}, flag=True):
"""This class calculates the 2D histograms as a function of distance for the various filter parameters."""
<|body_0|>
def hist_data(se... | stack_v2_sparse_classes_75kplus_train_073742 | 14,020 | no_license | [
{
"docstring": "This class calculates the 2D histograms as a function of distance for the various filter parameters.",
"name": "__init__",
"signature": "def __init__(self, histKeyX, histKeyY, bins=None, startDate=datetime(2014, 1, 1), endDate=datetime.now(), filterDict={}, flag=True)"
},
{
"docs... | 3 | stack_v2_sparse_classes_30k_train_037298 | Implement the Python class `Hist2D` described below.
Class description:
Implement the Hist2D class.
Method signatures and docstrings:
- def __init__(self, histKeyX, histKeyY, bins=None, startDate=datetime(2014, 1, 1), endDate=datetime.now(), filterDict={}, flag=True): This class calculates the 2D histograms as a func... | Implement the Python class `Hist2D` described below.
Class description:
Implement the Hist2D class.
Method signatures and docstrings:
- def __init__(self, histKeyX, histKeyY, bins=None, startDate=datetime(2014, 1, 1), endDate=datetime.now(), filterDict={}, flag=True): This class calculates the 2D histograms as a func... | 81761d96947d4794e71efff9d9965c4e320f7b1a | <|skeleton|>
class Hist2D:
def __init__(self, histKeyX, histKeyY, bins=None, startDate=datetime(2014, 1, 1), endDate=datetime.now(), filterDict={}, flag=True):
"""This class calculates the 2D histograms as a function of distance for the various filter parameters."""
<|body_0|>
def hist_data(se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Hist2D:
def __init__(self, histKeyX, histKeyY, bins=None, startDate=datetime(2014, 1, 1), endDate=datetime.now(), filterDict={}, flag=True):
"""This class calculates the 2D histograms as a function of distance for the various filter parameters."""
Hist1D.__init__(self, d=None, startDate=startD... | the_stack_v2_python_sparse | stats/norm.py | mshumko/ac6_microburst_scale_sizes | train | 0 | |
337dc67ed4620a488f66b001d77dd9753dde6486 | [
"try:\n exception = request.json\n (services.log_service().upsert_exception(exception), 201)\nexcept Exception as e:\n nsp.abort(500, 'An internal error has occurred: {}'.format(e))",
"try:\n exception = request.json\n (services.log_service().upsert_exception(exception), 204)\nexcept Exception as e... | <|body_start_0|>
try:
exception = request.json
(services.log_service().upsert_exception(exception), 201)
except Exception as e:
nsp.abort(500, 'An internal error has occurred: {}'.format(e))
<|end_body_0|>
<|body_start_1|>
try:
exception = request... | Exception | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Exception:
def post(self):
"""Insert a new exception log"""
<|body_0|>
def put(self):
"""Update an exception object by it's id."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
exception = request.json
(services.log_servi... | stack_v2_sparse_classes_75kplus_train_073743 | 4,427 | no_license | [
{
"docstring": "Insert a new exception log",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Update an exception object by it's id.",
"name": "put",
"signature": "def put(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_043914 | Implement the Python class `Exception` described below.
Class description:
Implement the Exception class.
Method signatures and docstrings:
- def post(self): Insert a new exception log
- def put(self): Update an exception object by it's id. | Implement the Python class `Exception` described below.
Class description:
Implement the Exception class.
Method signatures and docstrings:
- def post(self): Insert a new exception log
- def put(self): Update an exception object by it's id.
<|skeleton|>
class Exception:
def post(self):
"""Insert a new e... | df826cf7098aee59e0a1ced6f465c2e8bb3df9a5 | <|skeleton|>
class Exception:
def post(self):
"""Insert a new exception log"""
<|body_0|>
def put(self):
"""Update an exception object by it's id."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Exception:
def post(self):
"""Insert a new exception log"""
try:
exception = request.json
(services.log_service().upsert_exception(exception), 201)
except Exception as e:
nsp.abort(500, 'An internal error has occurred: {}'.format(e))
def put(sel... | the_stack_v2_python_sparse | patient_portal/patient_portal/api/logs.py | bkh148/patient-cloud | train | 0 | |
536f92fbd41caf1fe602b81c53763013c7bb1888 | [
"try:\n natController = NatController()\n json_data = json.dumps(natController.get_floating_ip_private_address(id))\n resp = Response(json_data, status=200, mimetype='application/json')\n return resp\nexcept ValueError as ve:\n return Response(json.dumps(str(ve)), status=404, mimetype='application/js... | <|body_start_0|>
try:
natController = NatController()
json_data = json.dumps(natController.get_floating_ip_private_address(id))
resp = Response(json_data, status=200, mimetype='application/json')
return resp
except ValueError as ve:
return Resp... | Nat_FloatingIP_PrivateAddress | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Nat_FloatingIP_PrivateAddress:
def get(self, id=None):
"""Gets the Floating IP private address parameter"""
<|body_0|>
def put(self, id):
"""Update the Floating IP private address parameter"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
... | stack_v2_sparse_classes_75kplus_train_073744 | 7,153 | no_license | [
{
"docstring": "Gets the Floating IP private address parameter",
"name": "get",
"signature": "def get(self, id=None)"
},
{
"docstring": "Update the Floating IP private address parameter",
"name": "put",
"signature": "def put(self, id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014064 | Implement the Python class `Nat_FloatingIP_PrivateAddress` described below.
Class description:
Implement the Nat_FloatingIP_PrivateAddress class.
Method signatures and docstrings:
- def get(self, id=None): Gets the Floating IP private address parameter
- def put(self, id): Update the Floating IP private address param... | Implement the Python class `Nat_FloatingIP_PrivateAddress` described below.
Class description:
Implement the Nat_FloatingIP_PrivateAddress class.
Method signatures and docstrings:
- def get(self, id=None): Gets the Floating IP private address parameter
- def put(self, id): Update the Floating IP private address param... | 6070e3cb6bf957e04f5d8267db11f3296410e18e | <|skeleton|>
class Nat_FloatingIP_PrivateAddress:
def get(self, id=None):
"""Gets the Floating IP private address parameter"""
<|body_0|>
def put(self, id):
"""Update the Floating IP private address parameter"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Nat_FloatingIP_PrivateAddress:
def get(self, id=None):
"""Gets the Floating IP private address parameter"""
try:
natController = NatController()
json_data = json.dumps(natController.get_floating_ip_private_address(id))
resp = Response(json_data, status=200, ... | the_stack_v2_python_sparse | configuration-agent/nat/rest_api/resources/floating_ip.py | ReliableLion/frog4-configurable-vnf | train | 0 | |
324edeb5e8512941d8c893e2c191365e14d4b432 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn Workflow()",
"from .run import Run\nfrom .task_report import TaskReport\nfrom .user_processing_result import UserProcessingResult\nfrom .workflow_base import WorkflowBase\nfrom .workflow_version import WorkflowVersion\nfrom .run import... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return Workflow()
<|end_body_0|>
<|body_start_1|>
from .run import Run
from .task_report import TaskReport
from .user_processing_result import UserProcessingResult
from .workflo... | Workflow | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Workflow:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Workflow:
"""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: Workflow... | stack_v2_sparse_classes_75kplus_train_073745 | 5,371 | 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: Workflow",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(pars... | 3 | stack_v2_sparse_classes_30k_train_039110 | Implement the Python class `Workflow` described below.
Class description:
Implement the Workflow class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Workflow: Creates a new instance of the appropriate class based on discriminator value Args: parse_no... | Implement the Python class `Workflow` described below.
Class description:
Implement the Workflow class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Workflow: Creates a new instance of the appropriate class based on discriminator value Args: parse_no... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class Workflow:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Workflow:
"""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: Workflow... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Workflow:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Workflow:
"""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: Workflow"""
if... | the_stack_v2_python_sparse | msgraph/generated/models/identity_governance/workflow.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
d7281478d43429629f29acec081d2ae9e4269405 | [
"distributions = [p]\np_data = EmpiricalDistribution(p.var)\nloss = AdversarialJensenShannon(p_data, p, discriminator, optimizer=d_optimizer, optimizer_params=d_optimizer_params)\nsuper().__init__(loss, test_loss=loss, distributions=distributions, optimizer=optimizer, optimizer_params=optimizer_params, clip_grad_no... | <|body_start_0|>
distributions = [p]
p_data = EmpiricalDistribution(p.var)
loss = AdversarialJensenShannon(p_data, p, discriminator, optimizer=d_optimizer, optimizer_params=d_optimizer_params)
super().__init__(loss, test_loss=loss, distributions=distributions, optimizer=optimizer, optimi... | Generative Adversarial Network (Adversarial) Jensen-Shannon divergence between given distributions (p_data, p) is set as the loss class of this model. Examples -------- >>> import torch >>> from torch import nn, optim >>> from pixyz.distributions import Deterministic >>> from pixyz.distributions import Normal >>> from ... | GAN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GAN:
"""Generative Adversarial Network (Adversarial) Jensen-Shannon divergence between given distributions (p_data, p) is set as the loss class of this model. Examples -------- >>> import torch >>> from torch import nn, optim >>> from pixyz.distributions import Deterministic >>> from pixyz.distri... | stack_v2_sparse_classes_75kplus_train_073746 | 5,491 | permissive | [
{
"docstring": "Parameters ---------- p : torch.distributions.Distribution Generative model (generator). discriminator : torch.distributions.Distribution Critic (discriminator). optimizer : torch.optim Optimization algorithm. optimizer_params : dict Parameters of optimizer clip_grad_norm : float or int Maximum ... | 3 | stack_v2_sparse_classes_30k_train_001214 | Implement the Python class `GAN` described below.
Class description:
Generative Adversarial Network (Adversarial) Jensen-Shannon divergence between given distributions (p_data, p) is set as the loss class of this model. Examples -------- >>> import torch >>> from torch import nn, optim >>> from pixyz.distributions imp... | Implement the Python class `GAN` described below.
Class description:
Generative Adversarial Network (Adversarial) Jensen-Shannon divergence between given distributions (p_data, p) is set as the loss class of this model. Examples -------- >>> import torch >>> from torch import nn, optim >>> from pixyz.distributions imp... | a9baf067730035d03351476f5c2e1e43016808ce | <|skeleton|>
class GAN:
"""Generative Adversarial Network (Adversarial) Jensen-Shannon divergence between given distributions (p_data, p) is set as the loss class of this model. Examples -------- >>> import torch >>> from torch import nn, optim >>> from pixyz.distributions import Deterministic >>> from pixyz.distri... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GAN:
"""Generative Adversarial Network (Adversarial) Jensen-Shannon divergence between given distributions (p_data, p) is set as the loss class of this model. Examples -------- >>> import torch >>> from torch import nn, optim >>> from pixyz.distributions import Deterministic >>> from pixyz.distributions impor... | the_stack_v2_python_sparse | pixyz/models/gan.py | masa-su/pixyz | train | 483 |
0c4c0da9c7bd22492357149030214fce661c7e25 | [
"listr = Category.objects.all().order_by('id')\nresults = self.paginate_queryset(listr, request)\nserializer = self.serializer(results, many=True)\nreturn self.get_paginated_response(serializer.data)",
"response = self.serializer(data=request.data)\nif response.is_valid():\n response.save()\n return Respons... | <|body_start_0|>
listr = Category.objects.all().order_by('id')
results = self.paginate_queryset(listr, request)
serializer = self.serializer(results, many=True)
return self.get_paginated_response(serializer.data)
<|end_body_0|>
<|body_start_1|>
response = self.serializer(data=re... | ... | VCategoryList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VCategoryList:
"""..."""
def get(self, request, format=None):
"""..."""
<|body_0|>
def post(self, request, format=None):
"""..."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
listr = Category.objects.all().order_by('id')
results = self.... | stack_v2_sparse_classes_75kplus_train_073747 | 2,534 | permissive | [
{
"docstring": "...",
"name": "get",
"signature": "def get(self, request, format=None)"
},
{
"docstring": "...",
"name": "post",
"signature": "def post(self, request, format=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004910 | Implement the Python class `VCategoryList` described below.
Class description:
...
Method signatures and docstrings:
- def get(self, request, format=None): ...
- def post(self, request, format=None): ... | Implement the Python class `VCategoryList` described below.
Class description:
...
Method signatures and docstrings:
- def get(self, request, format=None): ...
- def post(self, request, format=None): ...
<|skeleton|>
class VCategoryList:
"""..."""
def get(self, request, format=None):
"""..."""
... | 660664ba2321499e92c3c5c23719756db2569e90 | <|skeleton|>
class VCategoryList:
"""..."""
def get(self, request, format=None):
"""..."""
<|body_0|>
def post(self, request, format=None):
"""..."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VCategoryList:
"""..."""
def get(self, request, format=None):
"""..."""
listr = Category.objects.all().order_by('id')
results = self.paginate_queryset(listr, request)
serializer = self.serializer(results, many=True)
return self.get_paginated_response(serializer.dat... | the_stack_v2_python_sparse | apps/category/views/vcategory.py | magocod/djrepo | train | 1 |
1269bdcff47b9ff61d0d648c27707adce93a5d49 | [
"webapp_user = args['webapp_user']\nship_infos = webapp_user.ship_infos\ndata = {'ship_infos': ship_infos}\nreturn data",
"webapp_user = args['webapp_user']\nresult = webapp_user.select_default_ship(args['ship_id'])\nif result:\n return {'result': result}\nelse:\n return 500"
] | <|body_start_0|>
webapp_user = args['webapp_user']
ship_infos = webapp_user.ship_infos
data = {'ship_infos': ship_infos}
return data
<|end_body_0|>
<|body_start_1|>
webapp_user = args['webapp_user']
result = webapp_user.select_default_ship(args['ship_id'])
if res... | 商品 | AShipInfos | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AShipInfos:
"""商品"""
def get(args):
"""获取收货地址列表 @param 无 @return 'ship_infos': ship_infos(列表)"""
<|body_0|>
def post(args):
"""选择默认收货地址 @param ship_id @return {'result': True}"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
webapp_user = args['w... | stack_v2_sparse_classes_75kplus_train_073748 | 777 | no_license | [
{
"docstring": "获取收货地址列表 @param 无 @return 'ship_infos': ship_infos(列表)",
"name": "get",
"signature": "def get(args)"
},
{
"docstring": "选择默认收货地址 @param ship_id @return {'result': True}",
"name": "post",
"signature": "def post(args)"
}
] | 2 | stack_v2_sparse_classes_30k_train_037941 | Implement the Python class `AShipInfos` described below.
Class description:
商品
Method signatures and docstrings:
- def get(args): 获取收货地址列表 @param 无 @return 'ship_infos': ship_infos(列表)
- def post(args): 选择默认收货地址 @param ship_id @return {'result': True} | Implement the Python class `AShipInfos` described below.
Class description:
商品
Method signatures and docstrings:
- def get(args): 获取收货地址列表 @param 无 @return 'ship_infos': ship_infos(列表)
- def post(args): 选择默认收货地址 @param ship_id @return {'result': True}
<|skeleton|>
class AShipInfos:
"""商品"""
def get(args):
... | 15621db1a64ffe199619924b75a5b5c5e6416bed | <|skeleton|>
class AShipInfos:
"""商品"""
def get(args):
"""获取收货地址列表 @param 无 @return 'ship_infos': ship_infos(列表)"""
<|body_0|>
def post(args):
"""选择默认收货地址 @param ship_id @return {'result': True}"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AShipInfos:
"""商品"""
def get(args):
"""获取收货地址列表 @param 无 @return 'ship_infos': ship_infos(列表)"""
webapp_user = args['webapp_user']
ship_infos = webapp_user.ship_infos
data = {'ship_infos': ship_infos}
return data
def post(args):
"""选择默认收货地址 @param ship... | the_stack_v2_python_sparse | api/mall/a_ship_infos.py | nuaays/apiserver | train | 0 |
792bd23050e71d4410798a68d9b2456a1c024600 | [
"events = [ESCAPE_CHAR, driver.press_return_re, driver.standby_re, driver.username_re, driver.password_re, driver.more_re, self.device.prompt_re, driver.rommon_re, driver.unable_to_connect_re, driver.timeout_re, pexpect.TIMEOUT, PASSWORD_OK]\ntransitions = [(ESCAPE_CHAR, [0], 1, partial(a_send, '\\r\\n'), _C['esc_c... | <|body_start_0|>
events = [ESCAPE_CHAR, driver.press_return_re, driver.standby_re, driver.username_re, driver.password_re, driver.more_re, self.device.prompt_re, driver.rommon_re, driver.unable_to_connect_re, driver.timeout_re, pexpect.TIMEOUT, PASSWORD_OK]
transitions = [(ESCAPE_CHAR, [0], 1, partial(a... | Telnet to the console protocol implementation. | TelnetConsole | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TelnetConsole:
"""Telnet to the console protocol implementation."""
def connect(self, driver):
"""Connect using console specific FSM."""
<|body_0|>
def disconnect(self, driver):
"""Disconnect from the console."""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_75kplus_train_073749 | 8,039 | permissive | [
{
"docstring": "Connect using console specific FSM.",
"name": "connect",
"signature": "def connect(self, driver)"
},
{
"docstring": "Disconnect from the console.",
"name": "disconnect",
"signature": "def disconnect(self, driver)"
}
] | 2 | stack_v2_sparse_classes_30k_train_024420 | Implement the Python class `TelnetConsole` described below.
Class description:
Telnet to the console protocol implementation.
Method signatures and docstrings:
- def connect(self, driver): Connect using console specific FSM.
- def disconnect(self, driver): Disconnect from the console. | Implement the Python class `TelnetConsole` described below.
Class description:
Telnet to the console protocol implementation.
Method signatures and docstrings:
- def connect(self, driver): Connect using console specific FSM.
- def disconnect(self, driver): Disconnect from the console.
<|skeleton|>
class TelnetConsol... | fb8ec4c72b0dfda0f0e312ff7f84217fc836522b | <|skeleton|>
class TelnetConsole:
"""Telnet to the console protocol implementation."""
def connect(self, driver):
"""Connect using console specific FSM."""
<|body_0|>
def disconnect(self, driver):
"""Disconnect from the console."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TelnetConsole:
"""Telnet to the console protocol implementation."""
def connect(self, driver):
"""Connect using console specific FSM."""
events = [ESCAPE_CHAR, driver.press_return_re, driver.standby_re, driver.username_re, driver.password_re, driver.more_re, self.device.prompt_re, driver.... | the_stack_v2_python_sparse | condoor/protocols/telnet.py | decolnz/condoor | train | 1 |
bdc55bf7e83eef5f676c07d41f4fdf9ae57d0991 | [
"try:\n client = boto3.client('s3', config=default_config(region=region))\n client.head_bucket(Bucket=bucket)\nexcept ClientError:\n LOGGER.error('An error occurred during S3 HeadBucket')\n raise",
"try:\n client = boto3.client('s3', config=default_config(region=region))\n client.create_bucket(B... | <|body_start_0|>
try:
client = boto3.client('s3', config=default_config(region=region))
client.head_bucket(Bucket=bucket)
except ClientError:
LOGGER.error('An error occurred during S3 HeadBucket')
raise
<|end_body_0|>
<|body_start_1|>
try:
... | AwsS3 | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AwsS3:
def head_bucket(bucket, region):
"""Determines if given bucket exists with correct permissions. See: https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketHEAD.html Args: bucket (str): AWS S3 bucket name region (str): AWS Region Returns: bool: True on success Raises: ClientErr... | stack_v2_sparse_classes_75kplus_train_073750 | 7,811 | permissive | [
{
"docstring": "Determines if given bucket exists with correct permissions. See: https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketHEAD.html Args: bucket (str): AWS S3 bucket name region (str): AWS Region Returns: bool: True on success Raises: ClientError; Raises when the bucket does not exist or is den... | 4 | null | Implement the Python class `AwsS3` described below.
Class description:
Implement the AwsS3 class.
Method signatures and docstrings:
- def head_bucket(bucket, region): Determines if given bucket exists with correct permissions. See: https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketHEAD.html Args: bucket (str)... | Implement the Python class `AwsS3` described below.
Class description:
Implement the AwsS3 class.
Method signatures and docstrings:
- def head_bucket(bucket, region): Determines if given bucket exists with correct permissions. See: https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketHEAD.html Args: bucket (str)... | 75ba140d2e1aa6e903313d88326920adcb8bff45 | <|skeleton|>
class AwsS3:
def head_bucket(bucket, region):
"""Determines if given bucket exists with correct permissions. See: https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketHEAD.html Args: bucket (str): AWS S3 bucket name region (str): AWS Region Returns: bool: True on success Raises: ClientErr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AwsS3:
def head_bucket(bucket, region):
"""Determines if given bucket exists with correct permissions. See: https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketHEAD.html Args: bucket (str): AWS S3 bucket name region (str): AWS Region Returns: bool: True on success Raises: ClientError; Raises whe... | the_stack_v2_python_sparse | streamalert/shared/helpers/aws_api_client.py | avmi/streamalert | train | 0 | |
9e7c78048d9344e098bdaaa0f56144cd9fc43f01 | [
"Frame.__init__(self, parent)\nself._title = title\nself._fontSize = fontSize\nself.create()",
"self.master.title(self._title)\nself._cpaStatus = StatusGroup(self, 'CPA', numStations=6, fontSize=self._fontSize)\nself._cpaStatus.pack(expand=True, fill='both')\nself._ctsStatus = StatusGroup(self, 'CTS', numStations... | <|body_start_0|>
Frame.__init__(self, parent)
self._title = title
self._fontSize = fontSize
self.create()
<|end_body_0|>
<|body_start_1|>
self.master.title(self._title)
self._cpaStatus = StatusGroup(self, 'CPA', numStations=6, fontSize=self._fontSize)
self._cpaSt... | The app main window, containing several StatusGroups. | StatusWindow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StatusWindow:
"""The app main window, containing several StatusGroups."""
def __init__(self, parent, title='StatusApp', fontSize=18):
"""Constructor."""
<|body_0|>
def create(self):
"""Create the status groups."""
<|body_1|>
def setStatus(self, statu... | stack_v2_sparse_classes_75kplus_train_073751 | 7,129 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, parent, title='StatusApp', fontSize=18)"
},
{
"docstring": "Create the status groups.",
"name": "create",
"signature": "def create(self)"
},
{
"docstring": "Set the button statuses from an ordered... | 3 | stack_v2_sparse_classes_30k_train_052034 | Implement the Python class `StatusWindow` described below.
Class description:
The app main window, containing several StatusGroups.
Method signatures and docstrings:
- def __init__(self, parent, title='StatusApp', fontSize=18): Constructor.
- def create(self): Create the status groups.
- def setStatus(self, status): ... | Implement the Python class `StatusWindow` described below.
Class description:
The app main window, containing several StatusGroups.
Method signatures and docstrings:
- def __init__(self, parent, title='StatusApp', fontSize=18): Constructor.
- def create(self): Create the status groups.
- def setStatus(self, status): ... | 510bc7e6465af080f0ad11503afcd0be1ac06f58 | <|skeleton|>
class StatusWindow:
"""The app main window, containing several StatusGroups."""
def __init__(self, parent, title='StatusApp', fontSize=18):
"""Constructor."""
<|body_0|>
def create(self):
"""Create the status groups."""
<|body_1|>
def setStatus(self, statu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StatusWindow:
"""The app main window, containing several StatusGroups."""
def __init__(self, parent, title='StatusApp', fontSize=18):
"""Constructor."""
Frame.__init__(self, parent)
self._title = title
self._fontSize = fontSize
self.create()
def create(self):
... | the_stack_v2_python_sparse | bin/NetStatusMonitor.py | brata-hsdc/brata.station | train | 0 |
36dec1c4d15136eedf9ec50fc66dc6c78c4bf3e5 | [
"n, res = (len(nums), 0)\nproduct = 1\ni = 0\nfor j in range(n):\n product *= nums[j]\n while i <= j and product >= k:\n product //= nums[i]\n i += 1\n res += j - i + 1\nreturn res",
"nums.sort()\nn = len(nums)\nproduct = [nums[0]]\nfor i in range(1, n):\n product.append(product[-1] * nu... | <|body_start_0|>
n, res = (len(nums), 0)
product = 1
i = 0
for j in range(n):
product *= nums[j]
while i <= j and product >= k:
product //= nums[i]
i += 1
res += j - i + 1
return res
<|end_body_0|>
<|body_start_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numSubarrayProductLessThanK(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def numSubarrayProductLessThanK_WRONG(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_75kplus_train_073752 | 2,457 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "numSubarrayProductLessThanK",
"signature": "def numSubarrayProductLessThanK(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "numSubarrayProductLessThanK_WRONG",
"signatur... | 2 | stack_v2_sparse_classes_30k_train_004763 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSubarrayProductLessThanK(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def numSubarrayProductLessThanK_WRONG(self, nums, k): :type nums: List[int] :type... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSubarrayProductLessThanK(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def numSubarrayProductLessThanK_WRONG(self, nums, k): :type nums: List[int] :type... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class Solution:
def numSubarrayProductLessThanK(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def numSubarrayProductLessThanK_WRONG(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def numSubarrayProductLessThanK(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
n, res = (len(nums), 0)
product = 1
i = 0
for j in range(n):
product *= nums[j]
while i <= j and product >= k:
product ... | the_stack_v2_python_sparse | code713SubarrayProductLessThanK.py | cybelewang/leetcode-python | train | 0 | |
e49fa94a3b9a59cf82ec296590b2156bf9e74624 | [
"self.username = ''\nself.password = ''\nself.baseUrl = 'http://{0}:{1}/'.format(hostname, port)",
"api = self.baseUrl + 'init'\ntry:\n return self._http_request(api, 'GET', timeout=30)\nexcept ServerUnavailableException:\n print('Dashboard is not available... bypassing.')\n return (False, None)",
"api... | <|body_start_0|>
self.username = ''
self.password = ''
self.baseUrl = 'http://{0}:{1}/'.format(hostname, port)
<|end_body_0|>
<|body_start_1|>
api = self.baseUrl + 'init'
try:
return self._http_request(api, 'GET', timeout=30)
except ServerUnavailableException... | Performance dashboard (cbkarma) REST API | CbKarmaClient | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CbKarmaClient:
"""Performance dashboard (cbkarma) REST API"""
def __init__(self, hostname, port='80'):
"""Create REST API client. Keyword arguments: hostname -- dashboard hostname/ip address port -- dashboard port"""
<|body_0|>
def init(self):
"""Get initial test... | stack_v2_sparse_classes_75kplus_train_073753 | 2,862 | permissive | [
{
"docstring": "Create REST API client. Keyword arguments: hostname -- dashboard hostname/ip address port -- dashboard port",
"name": "__init__",
"signature": "def __init__(self, hostname, port='80')"
},
{
"docstring": "Get initial test id (optional)",
"name": "init",
"signature": "def i... | 5 | stack_v2_sparse_classes_30k_train_023040 | Implement the Python class `CbKarmaClient` described below.
Class description:
Performance dashboard (cbkarma) REST API
Method signatures and docstrings:
- def __init__(self, hostname, port='80'): Create REST API client. Keyword arguments: hostname -- dashboard hostname/ip address port -- dashboard port
- def init(se... | Implement the Python class `CbKarmaClient` described below.
Class description:
Performance dashboard (cbkarma) REST API
Method signatures and docstrings:
- def __init__(self, hostname, port='80'): Create REST API client. Keyword arguments: hostname -- dashboard hostname/ip address port -- dashboard port
- def init(se... | 9d8220a0925327bddf0e10887e22b57c5d6adb37 | <|skeleton|>
class CbKarmaClient:
"""Performance dashboard (cbkarma) REST API"""
def __init__(self, hostname, port='80'):
"""Create REST API client. Keyword arguments: hostname -- dashboard hostname/ip address port -- dashboard port"""
<|body_0|>
def init(self):
"""Get initial test... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CbKarmaClient:
"""Performance dashboard (cbkarma) REST API"""
def __init__(self, hostname, port='80'):
"""Create REST API client. Keyword arguments: hostname -- dashboard hostname/ip address port -- dashboard port"""
self.username = ''
self.password = ''
self.baseUrl = 'ht... | the_stack_v2_python_sparse | lib/cbkarma/rest_client.py | couchbase/testrunner | train | 18 |
deae950e30b5024fdfd36a2dfe67b3aabc4481d1 | [
"self.bare = bare\nif not self.bare and (not gitdir.endswith('/.git')):\n self.gitdir = os.path.join(gitdir, '.git')\nelse:\n self.gitdir = gitdir",
"if os.path.exists(self.gitdir):\n raise FileExists()\noptions = ''\nif mirror:\n options += '--mirror'\ncommand = 'git clone {options} {url} {path}'.for... | <|body_start_0|>
self.bare = bare
if not self.bare and (not gitdir.endswith('/.git')):
self.gitdir = os.path.join(gitdir, '.git')
else:
self.gitdir = gitdir
<|end_body_0|>
<|body_start_1|>
if os.path.exists(self.gitdir):
raise FileExists()
opt... | Class for managing a git repo. We could make this functional, but OO is helpful in case we ever want to e.g. use remote git repos. In those cases, we may want to e.g. maintain open ssh connections and whatnot. It can also help with caching. | GitRepo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GitRepo:
"""Class for managing a git repo. We could make this functional, but OO is helpful in case we ever want to e.g. use remote git repos. In those cases, we may want to e.g. maintain open ssh connections and whatnot. It can also help with caching."""
def __init__(self, gitdir, bare=Fals... | stack_v2_sparse_classes_75kplus_train_073754 | 4,906 | no_license | [
{
"docstring": "We store where the repo is, and return an object we can use to browse it.",
"name": "__init__",
"signature": "def __init__(self, gitdir, bare=False)"
},
{
"docstring": "Clone the repo. Hopefully raise an exception if it already exists.",
"name": "clone",
"signature": "def... | 5 | stack_v2_sparse_classes_30k_val_000009 | Implement the Python class `GitRepo` described below.
Class description:
Class for managing a git repo. We could make this functional, but OO is helpful in case we ever want to e.g. use remote git repos. In those cases, we may want to e.g. maintain open ssh connections and whatnot. It can also help with caching.
Meth... | Implement the Python class `GitRepo` described below.
Class description:
Class for managing a git repo. We could make this functional, but OO is helpful in case we ever want to e.g. use remote git repos. In those cases, we may want to e.g. maintain open ssh connections and whatnot. It can also help with caching.
Meth... | cdcd48a66091e23d562424a6770ddf70ef557759 | <|skeleton|>
class GitRepo:
"""Class for managing a git repo. We could make this functional, but OO is helpful in case we ever want to e.g. use remote git repos. In those cases, we may want to e.g. maintain open ssh connections and whatnot. It can also help with caching."""
def __init__(self, gitdir, bare=Fals... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GitRepo:
"""Class for managing a git repo. We could make this functional, but OO is helpful in case we ever want to e.g. use remote git repos. In those cases, we may want to e.g. maintain open ssh connections and whatnot. It can also help with caching."""
def __init__(self, gitdir, bare=False):
"... | the_stack_v2_python_sparse | gitserve/gitserve/gitaccess.py | Stalkcomrade/writing_observer | train | 0 |
d41f035f306b555bc00521db2a2e468e7fc4d313 | [
"tipo_transacao = TipoTransacoes.get_tipo_transacao(id)\nif not tipo_transacao:\n api.abort(409, 'Tipo Transacao not found')\nreturn (tipo_transacao, 200)",
"tipo_transacao = TipoTransacoes.get_tipo_transacao(id)\nif not tipo_transacao:\n api.abort(404, 'Tipo Transacao not found')\nTipoTransacoes.delete_tip... | <|body_start_0|>
tipo_transacao = TipoTransacoes.get_tipo_transacao(id)
if not tipo_transacao:
api.abort(409, 'Tipo Transacao not found')
return (tipo_transacao, 200)
<|end_body_0|>
<|body_start_1|>
tipo_transacao = TipoTransacoes.get_tipo_transacao(id)
if not tipo_t... | TipoContaId | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TipoContaId:
def get(self, id):
"""Get tipo transacao by ID"""
<|body_0|>
def delete(self, id):
"""Delete tipo transacao by ID"""
<|body_1|>
def put(self, id):
"""Updates the tipo transacao"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_75kplus_train_073755 | 4,210 | no_license | [
{
"docstring": "Get tipo transacao by ID",
"name": "get",
"signature": "def get(self, id)"
},
{
"docstring": "Delete tipo transacao by ID",
"name": "delete",
"signature": "def delete(self, id)"
},
{
"docstring": "Updates the tipo transacao",
"name": "put",
"signature": "d... | 3 | null | Implement the Python class `TipoContaId` described below.
Class description:
Implement the TipoContaId class.
Method signatures and docstrings:
- def get(self, id): Get tipo transacao by ID
- def delete(self, id): Delete tipo transacao by ID
- def put(self, id): Updates the tipo transacao | Implement the Python class `TipoContaId` described below.
Class description:
Implement the TipoContaId class.
Method signatures and docstrings:
- def get(self, id): Get tipo transacao by ID
- def delete(self, id): Delete tipo transacao by ID
- def put(self, id): Updates the tipo transacao
<|skeleton|>
class TipoCont... | 84cf0d27762dfab893fbf8cba73e92b64b6ccb7c | <|skeleton|>
class TipoContaId:
def get(self, id):
"""Get tipo transacao by ID"""
<|body_0|>
def delete(self, id):
"""Delete tipo transacao by ID"""
<|body_1|>
def put(self, id):
"""Updates the tipo transacao"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TipoContaId:
def get(self, id):
"""Get tipo transacao by ID"""
tipo_transacao = TipoTransacoes.get_tipo_transacao(id)
if not tipo_transacao:
api.abort(409, 'Tipo Transacao not found')
return (tipo_transacao, 200)
def delete(self, id):
"""Delete tipo tra... | the_stack_v2_python_sparse | api/v1/resources/tipo_transacoes/tipo_transacao.py | RicardoTurco/AMCOM_backend | train | 0 | |
26c0e2bfc5816e8dc0bd21e658a6b0adca637d41 | [
"if not isinstance(batch_size, int) or batch_size < 1:\n raise ValueError(f'Batch size must be a positive integer, but got {batch_size}')\nelif batch_size == 1:\n raise ValueError('This is a batch acquisition function. If batch-size is 1, use the single-point acquisition instead')\nself.model = model\nself.ac... | <|body_start_0|>
if not isinstance(batch_size, int) or batch_size < 1:
raise ValueError(f'Batch size must be a positive integer, but got {batch_size}')
elif batch_size == 1:
raise ValueError('This is a batch acquisition function. If batch-size is 1, use the single-point acquisiti... | Batch point calculator. This point calculator calculates the first point in the batch using a single-point acquisition function, and then selects the rest of the points uniformly at random | GreedyRandomBatchPointCalculator | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GreedyRandomBatchPointCalculator:
"""Batch point calculator. This point calculator calculates the first point in the batch using a single-point acquisition function, and then selects the rest of the points uniformly at random"""
def __init__(self, model: IModel, acquisition: Acquisition, acq... | stack_v2_sparse_classes_75kplus_train_073756 | 9,291 | permissive | [
{
"docstring": ":param model: Model that is used by the acquisition function :param acquisition: Acquisition to be optimized to find each point in batch :param acquisition_optimizer: Acquisition optimizer that optimizes acquisition function to find each point in batch :param batch_size: Number of points to calc... | 2 | stack_v2_sparse_classes_30k_train_004888 | Implement the Python class `GreedyRandomBatchPointCalculator` described below.
Class description:
Batch point calculator. This point calculator calculates the first point in the batch using a single-point acquisition function, and then selects the rest of the points uniformly at random
Method signatures and docstring... | Implement the Python class `GreedyRandomBatchPointCalculator` described below.
Class description:
Batch point calculator. This point calculator calculates the first point in the batch using a single-point acquisition function, and then selects the rest of the points uniformly at random
Method signatures and docstring... | 40bab526af6562653c42dbb32b174524c44ce2ba | <|skeleton|>
class GreedyRandomBatchPointCalculator:
"""Batch point calculator. This point calculator calculates the first point in the batch using a single-point acquisition function, and then selects the rest of the points uniformly at random"""
def __init__(self, model: IModel, acquisition: Acquisition, acq... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GreedyRandomBatchPointCalculator:
"""Batch point calculator. This point calculator calculates the first point in the batch using a single-point acquisition function, and then selects the rest of the points uniformly at random"""
def __init__(self, model: IModel, acquisition: Acquisition, acquisition_opti... | the_stack_v2_python_sparse | PyStationB/libraries/GlobalPenalisation/gp/calculators.py | mebristo/station-b-libraries | train | 0 |
100ebc59f62ce75926519a996fe763cd9b1cc50c | [
"res = []\nself.dfs(root, res)\nreturn res",
"if node != None:\n res.append(node.val)\n self.dfs(node.left, res)\n self.dfs(node.right, res)"
] | <|body_start_0|>
res = []
self.dfs(root, res)
return res
<|end_body_0|>
<|body_start_1|>
if node != None:
res.append(node.val)
self.dfs(node.left, res)
self.dfs(node.right, res)
<|end_body_1|>
| Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def preorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def dfs(self, node, res):
""":type node: TreeNode :type res: List[int] :rtype: void"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = []
... | stack_v2_sparse_classes_75kplus_train_073757 | 769 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "preorderTraversal",
"signature": "def preorderTraversal(self, root)"
},
{
"docstring": ":type node: TreeNode :type res: List[int] :rtype: void",
"name": "dfs",
"signature": "def dfs(self, node, res)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def preorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def dfs(self, node, res): :type node: TreeNode :type res: List[int] :rtype: void | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def preorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def dfs(self, node, res): :type node: TreeNode :type res: List[int] :rtype: void
<|skeleton|>
class S... | 4c3d5b37d5c3a8624783a8fc261cdd794379037f | <|skeleton|>
class Solution:
def preorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def dfs(self, node, res):
""":type node: TreeNode :type res: List[int] :rtype: void"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def preorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
res = []
self.dfs(root, res)
return res
def dfs(self, node, res):
""":type node: TreeNode :type res: List[int] :rtype: void"""
if node != None:
res.append(... | the_stack_v2_python_sparse | LeetCode/Binary Tree/Problems/preorderTraversal.py | ADWright18/Learning | train | 0 | |
1c6c69e12eccccc3287fa81fdd1566bbcab1641a | [
"if columns_drop is not None:\n if isinstance(columns_drop, list) or isinstance(columns_drop, tuple):\n self.columns_drop = columns_drop\n else:\n raise NameError('Invalid type {}'.format(type(columns_drop)))\nelse:\n self.columns_drop = columns_drop\nself.random_state = random_state",
"if ... | <|body_start_0|>
if columns_drop is not None:
if isinstance(columns_drop, list) or isinstance(columns_drop, tuple):
self.columns_drop = columns_drop
else:
raise NameError('Invalid type {}'.format(type(columns_drop)))
else:
self.columns_... | This transformer drop features. Attributes ---------- columns: list of columns to transformer [n_columns] Examples -------- For usage examples, please see https://jaisenbe58r.github.io/MLearner/user_guide/preprocessing/DropFeatures/ | DropFeatures | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DropFeatures:
"""This transformer drop features. Attributes ---------- columns: list of columns to transformer [n_columns] Examples -------- For usage examples, please see https://jaisenbe58r.github.io/MLearner/user_guide/preprocessing/DropFeatures/"""
def __init__(self, columns_drop=None, r... | stack_v2_sparse_classes_75kplus_train_073758 | 6,690 | permissive | [
{
"docstring": "Init replace missing values.",
"name": "__init__",
"signature": "def __init__(self, columns_drop=None, random_state=99)"
},
{
"docstring": "Gets the columns to make a replace missing values. Parameters ---------- X : {Dataframe}, shape = [n_samples, n_features] Dataframe, where n... | 3 | stack_v2_sparse_classes_30k_train_030437 | Implement the Python class `DropFeatures` described below.
Class description:
This transformer drop features. Attributes ---------- columns: list of columns to transformer [n_columns] Examples -------- For usage examples, please see https://jaisenbe58r.github.io/MLearner/user_guide/preprocessing/DropFeatures/
Method ... | Implement the Python class `DropFeatures` described below.
Class description:
This transformer drop features. Attributes ---------- columns: list of columns to transformer [n_columns] Examples -------- For usage examples, please see https://jaisenbe58r.github.io/MLearner/user_guide/preprocessing/DropFeatures/
Method ... | e768a4cad150b35fb5bf543ab28aa23764af51d9 | <|skeleton|>
class DropFeatures:
"""This transformer drop features. Attributes ---------- columns: list of columns to transformer [n_columns] Examples -------- For usage examples, please see https://jaisenbe58r.github.io/MLearner/user_guide/preprocessing/DropFeatures/"""
def __init__(self, columns_drop=None, r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DropFeatures:
"""This transformer drop features. Attributes ---------- columns: list of columns to transformer [n_columns] Examples -------- For usage examples, please see https://jaisenbe58r.github.io/MLearner/user_guide/preprocessing/DropFeatures/"""
def __init__(self, columns_drop=None, random_state=9... | the_stack_v2_python_sparse | mlearner/preprocessing/feature_selector.py | jaisenbe58r/MLearner | train | 9 |
946c256589a86e201562bbebf9861374e7153835 | [
"self.sound_matcher = sound_matcher\nself.host = host\nself.receive_port = receive\nself.send_port = send",
"server = socketserver.UDPServer((self.host, self.receive_port), UDPSocketHandler)\nserver.send_port = self.send_port\nserver.sound_matcher = self.sound_matcher\nprint('Starting OSC server. Receiving on %s:... | <|body_start_0|>
self.sound_matcher = sound_matcher
self.host = host
self.receive_port = receive
self.send_port = send
<|end_body_0|>
<|body_start_1|>
server = socketserver.UDPServer((self.host, self.receive_port), UDPSocketHandler)
server.send_port = self.send_port
... | Args: sound_matcher (:class:`~spiegelib.core.SoundMatch`): SoundMatch object to use host (str, optional): address to run server at. Defaults to 127.0.0.1 receive (int, optonal): port to receive OSC messages on. Defaults to 9001. send (int, optional): port to send OSC messages on. Defaults to 9002. | SoundMatchOSCServer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SoundMatchOSCServer:
"""Args: sound_matcher (:class:`~spiegelib.core.SoundMatch`): SoundMatch object to use host (str, optional): address to run server at. Defaults to 127.0.0.1 receive (int, optonal): port to receive OSC messages on. Defaults to 9001. send (int, optional): port to send OSC messa... | stack_v2_sparse_classes_75kplus_train_073759 | 4,227 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, sound_matcher, host='127.0.0.1', receive=9001, send=9002)"
},
{
"docstring": "Start OSC server",
"name": "start",
"signature": "def start(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011725 | Implement the Python class `SoundMatchOSCServer` described below.
Class description:
Args: sound_matcher (:class:`~spiegelib.core.SoundMatch`): SoundMatch object to use host (str, optional): address to run server at. Defaults to 127.0.0.1 receive (int, optonal): port to receive OSC messages on. Defaults to 9001. send ... | Implement the Python class `SoundMatchOSCServer` described below.
Class description:
Args: sound_matcher (:class:`~spiegelib.core.SoundMatch`): SoundMatch object to use host (str, optional): address to run server at. Defaults to 127.0.0.1 receive (int, optonal): port to receive OSC messages on. Defaults to 9001. send ... | ace1a9fa5496f7176592eb706a458855352b801a | <|skeleton|>
class SoundMatchOSCServer:
"""Args: sound_matcher (:class:`~spiegelib.core.SoundMatch`): SoundMatch object to use host (str, optional): address to run server at. Defaults to 127.0.0.1 receive (int, optonal): port to receive OSC messages on. Defaults to 9001. send (int, optional): port to send OSC messa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SoundMatchOSCServer:
"""Args: sound_matcher (:class:`~spiegelib.core.SoundMatch`): SoundMatch object to use host (str, optional): address to run server at. Defaults to 127.0.0.1 receive (int, optonal): port to receive OSC messages on. Defaults to 9001. send (int, optional): port to send OSC messages on. Defau... | the_stack_v2_python_sparse | src/spiegelib/network/sound_match_osc_server.py | turian/spiegelib | train | 2 |
439753d1c7d9d9600de54802684a4fb53f91065d | [
"self._trf0 = trf0\nself._trf1 = trf1\nSO3Interpolation.__init__(self, self._trf0.orient, self._trf1.orient, shortest)\nR3Interpolation.__init__(self, self._trf0.pos, self._trf1.pos)",
"if checkrange:\n time = utils.flt(time)\n if time < 0.0 or time > 1.0:\n raise self.Error('\"time\" must be number ... | <|body_start_0|>
self._trf0 = trf0
self._trf1 = trf1
SO3Interpolation.__init__(self, self._trf0.orient, self._trf1.orient, shortest)
R3Interpolation.__init__(self, self._trf0.pos, self._trf1.pos)
<|end_body_0|>
<|body_start_1|>
if checkrange:
time = utils.flt(time)
... | A class for object representing a linear interpolation in task space, SE(3), between two points. Interpolation is done from one configuration, trf0, to another, trf1. trf0 and trf1 can be given as Transform objects. | SE3Interpolation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SE3Interpolation:
"""A class for object representing a linear interpolation in task space, SE(3), between two points. Interpolation is done from one configuration, trf0, to another, trf1. trf0 and trf1 can be given as Transform objects."""
def __init__(self, trf0, trf1, shortest=True):
... | stack_v2_sparse_classes_75kplus_train_073760 | 2,593 | no_license | [
{
"docstring": "Initialise an SE(3) interpolation from transform 'trf0' to transform 'trf1'. If 'shortest' is True, the shortest rotation path is chosen, if False, the long rotation is used, and if None it is indeterminate, given by the Versor objects being constructed from the transforms.",
"name": "__init... | 2 | stack_v2_sparse_classes_30k_train_007754 | Implement the Python class `SE3Interpolation` described below.
Class description:
A class for object representing a linear interpolation in task space, SE(3), between two points. Interpolation is done from one configuration, trf0, to another, trf1. trf0 and trf1 can be given as Transform objects.
Method signatures an... | Implement the Python class `SE3Interpolation` described below.
Class description:
A class for object representing a linear interpolation in task space, SE(3), between two points. Interpolation is done from one configuration, trf0, to another, trf1. trf0 and trf1 can be given as Transform objects.
Method signatures an... | cfd67fc1ce8003670db3666e2598cc4f0f3c7210 | <|skeleton|>
class SE3Interpolation:
"""A class for object representing a linear interpolation in task space, SE(3), between two points. Interpolation is done from one configuration, trf0, to another, trf1. trf0 and trf1 can be given as Transform objects."""
def __init__(self, trf0, trf1, shortest=True):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SE3Interpolation:
"""A class for object representing a linear interpolation in task space, SE(3), between two points. Interpolation is done from one configuration, trf0, to another, trf1. trf0 and trf1 can be given as Transform objects."""
def __init__(self, trf0, trf1, shortest=True):
"""Initial... | the_stack_v2_python_sparse | first/venv/Lib/site-packages/math3d/interpolation/se3interpolation.py | anndrozd4321/diplomchik | train | 0 |
52702024972f5e1d516e6180a7277d411697c342 | [
"try:\n account_id = lookup_account_id(request.headers['username'])\nexcept Exception:\n return make_response(jsonify({'Error': 'Invalid username or account'}), client.BAD_REQUEST)\nreturn paginate(request, DEFAULT_SUBSCRIPTIONS_TABLE, 'subscriptions', filters={'account_id': account_id})",
"registration_id ... | <|body_start_0|>
try:
account_id = lookup_account_id(request.headers['username'])
except Exception:
return make_response(jsonify({'Error': 'Invalid username or account'}), client.BAD_REQUEST)
return paginate(request, DEFAULT_SUBSCRIPTIONS_TABLE, 'subscriptions', filters={... | Handles the (webhook) subscriptions table interactions | Subscription | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Subscription:
"""Handles the (webhook) subscriptions table interactions"""
def get(self):
"""Get the user's webhook subscriptions"""
<|body_0|>
def post(self, subscription_id):
"""Creates new subscription"""
<|body_1|>
def delete(self, subscription_i... | stack_v2_sparse_classes_75kplus_train_073761 | 2,486 | permissive | [
{
"docstring": "Get the user's webhook subscriptions",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Creates new subscription",
"name": "post",
"signature": "def post(self, subscription_id)"
},
{
"docstring": "Deletes subscription record",
"name": "delete",
... | 3 | stack_v2_sparse_classes_30k_train_037409 | Implement the Python class `Subscription` described below.
Class description:
Handles the (webhook) subscriptions table interactions
Method signatures and docstrings:
- def get(self): Get the user's webhook subscriptions
- def post(self, subscription_id): Creates new subscription
- def delete(self, subscription_id): ... | Implement the Python class `Subscription` described below.
Class description:
Handles the (webhook) subscriptions table interactions
Method signatures and docstrings:
- def get(self): Get the user's webhook subscriptions
- def post(self, subscription_id): Creates new subscription
- def delete(self, subscription_id): ... | 1f4dc112b3293f80a7a03b339ce9b5e87386a04c | <|skeleton|>
class Subscription:
"""Handles the (webhook) subscriptions table interactions"""
def get(self):
"""Get the user's webhook subscriptions"""
<|body_0|>
def post(self, subscription_id):
"""Creates new subscription"""
<|body_1|>
def delete(self, subscription_i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Subscription:
"""Handles the (webhook) subscriptions table interactions"""
def get(self):
"""Get the user's webhook subscriptions"""
try:
account_id = lookup_account_id(request.headers['username'])
except Exception:
return make_response(jsonify({'Error': 'I... | the_stack_v2_python_sparse | pywebhooks/api/resources/v1/webhook/subscription.py | amitsaha/pywebhooks | train | 1 |
8e523ebbce76e764f3279b5dd982c00e36288c6b | [
"stop = sqrt(n)\nsquares_list = self.allSquares(stop)\n\ndef min_subset(k, s):\n best = s\n for i, j in enumerate(squares_list[:k]):\n if j <= s:\n sz = min_subset(i, s - j) + 1\n if sz < best:\n best = sz\n return best\nreturn min_subset(len(squares_list), n)",
... | <|body_start_0|>
stop = sqrt(n)
squares_list = self.allSquares(stop)
def min_subset(k, s):
best = s
for i, j in enumerate(squares_list[:k]):
if j <= s:
sz = min_subset(i, s - j) + 1
if sz < best:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numSquares(self, n):
"""Return minimum number of perfect squares that sum to n :type n: int :rtype: int"""
<|body_0|>
def allSquares(self, stop_val):
"""Returns list of all perfect squares up to the stop_val :type stop_val: int :rtype: List[int]"""
... | stack_v2_sparse_classes_75kplus_train_073762 | 1,020 | no_license | [
{
"docstring": "Return minimum number of perfect squares that sum to n :type n: int :rtype: int",
"name": "numSquares",
"signature": "def numSquares(self, n)"
},
{
"docstring": "Returns list of all perfect squares up to the stop_val :type stop_val: int :rtype: List[int]",
"name": "allSquares... | 2 | stack_v2_sparse_classes_30k_train_042096 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSquares(self, n): Return minimum number of perfect squares that sum to n :type n: int :rtype: int
- def allSquares(self, stop_val): Returns list of all perfect squares up ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSquares(self, n): Return minimum number of perfect squares that sum to n :type n: int :rtype: int
- def allSquares(self, stop_val): Returns list of all perfect squares up ... | 308889e57e71c369aa8516fba8a2064f6a26abee | <|skeleton|>
class Solution:
def numSquares(self, n):
"""Return minimum number of perfect squares that sum to n :type n: int :rtype: int"""
<|body_0|>
def allSquares(self, stop_val):
"""Returns list of all perfect squares up to the stop_val :type stop_val: int :rtype: List[int]"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def numSquares(self, n):
"""Return minimum number of perfect squares that sum to n :type n: int :rtype: int"""
stop = sqrt(n)
squares_list = self.allSquares(stop)
def min_subset(k, s):
best = s
for i, j in enumerate(squares_list[:k]):
... | the_stack_v2_python_sparse | leet_279.py | mike-jolliffe/Learning | train | 0 | |
47e89bcda9a06bed35db4c8da3c9bd1bae827188 | [
"if not head:\n return None\nleft = None\nright = head\nwhile right:\n tmp = right.next\n right.next = left\n left = right\n right = tmp\nreturn left",
"if not head:\n return None\nnodes = [None]\nwhile head:\n nodes.append(head)\n head = head.next\nnew_head = None\nresult = nodes[-1]\nwhi... | <|body_start_0|>
if not head:
return None
left = None
right = head
while right:
tmp = right.next
right.next = left
left = right
right = tmp
return left
<|end_body_0|>
<|body_start_1|>
if not head:
re... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
"""双指针 :param head: :return:"""
<|body_0|>
def reverseList1(self, head: ListNode) -> ListNode:
"""双指针 :param head: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not head:
... | stack_v2_sparse_classes_75kplus_train_073763 | 1,487 | no_license | [
{
"docstring": "双指针 :param head: :return:",
"name": "reverseList",
"signature": "def reverseList(self, head: ListNode) -> ListNode"
},
{
"docstring": "双指针 :param head: :return:",
"name": "reverseList1",
"signature": "def reverseList1(self, head: ListNode) -> ListNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_037649 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head: ListNode) -> ListNode: 双指针 :param head: :return:
- def reverseList1(self, head: ListNode) -> ListNode: 双指针 :param head: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head: ListNode) -> ListNode: 双指针 :param head: :return:
- def reverseList1(self, head: ListNode) -> ListNode: 双指针 :param head: :return:
<|skeleton|>
class S... | 5f67368e72c376c1299b849e7a92e6d0cbd9ae55 | <|skeleton|>
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
"""双指针 :param head: :return:"""
<|body_0|>
def reverseList1(self, head: ListNode) -> ListNode:
"""双指针 :param head: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverseList(self, head: ListNode) -> ListNode:
"""双指针 :param head: :return:"""
if not head:
return None
left = None
right = head
while right:
tmp = right.next
right.next = left
left = right
right ... | the_stack_v2_python_sparse | 206-反转列表/solution.py | BillyChao/leetcode | train | 5 | |
590a2eea6d6b202acbbbbe4340d35ff48a92973a | [
"try:\n return User.objects.get(pk=pk_user)\nexcept User.DoesNotExist:\n raise Http404",
"user = self.get_object(pk)\nresponse = UserHeavySerializer(user)\nreturn Response(response.data, status=status.HTTP_200_OK)",
"user = self.get_object(pk)\nresponse = self.serializer(user, data=request.data)\nif respo... | <|body_start_0|>
try:
return User.objects.get(pk=pk_user)
except User.DoesNotExist:
raise Http404
<|end_body_0|>
<|body_start_1|>
user = self.get_object(pk)
response = UserHeavySerializer(user)
return Response(response.data, status=status.HTTP_200_OK)
<|e... | ... | VUserDetail | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VUserDetail:
"""..."""
def get_object(self, pk_user: Union[int, str]):
"""..."""
<|body_0|>
def get(self, request, pk: Union[int, str], format=None):
"""..."""
<|body_1|>
def put(self, request, pk: Union[int, str], format=None):
"""..."""
... | stack_v2_sparse_classes_75kplus_train_073764 | 3,288 | permissive | [
{
"docstring": "...",
"name": "get_object",
"signature": "def get_object(self, pk_user: Union[int, str])"
},
{
"docstring": "...",
"name": "get",
"signature": "def get(self, request, pk: Union[int, str], format=None)"
},
{
"docstring": "...",
"name": "put",
"signature": "... | 4 | stack_v2_sparse_classes_30k_train_026143 | Implement the Python class `VUserDetail` described below.
Class description:
...
Method signatures and docstrings:
- def get_object(self, pk_user: Union[int, str]): ...
- def get(self, request, pk: Union[int, str], format=None): ...
- def put(self, request, pk: Union[int, str], format=None): ...
- def delete(self, re... | Implement the Python class `VUserDetail` described below.
Class description:
...
Method signatures and docstrings:
- def get_object(self, pk_user: Union[int, str]): ...
- def get(self, request, pk: Union[int, str], format=None): ...
- def put(self, request, pk: Union[int, str], format=None): ...
- def delete(self, re... | 660664ba2321499e92c3c5c23719756db2569e90 | <|skeleton|>
class VUserDetail:
"""..."""
def get_object(self, pk_user: Union[int, str]):
"""..."""
<|body_0|>
def get(self, request, pk: Union[int, str], format=None):
"""..."""
<|body_1|>
def put(self, request, pk: Union[int, str], format=None):
"""..."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VUserDetail:
"""..."""
def get_object(self, pk_user: Union[int, str]):
"""..."""
try:
return User.objects.get(pk=pk_user)
except User.DoesNotExist:
raise Http404
def get(self, request, pk: Union[int, str], format=None):
"""..."""
user =... | the_stack_v2_python_sparse | apps/user/views/vuser.py | magocod/djrepo | train | 1 |
a0b074843eb919ca31ea389f9f15c00d6c47e3f8 | [
"result = str(TemporalInterpolation(interval_in_minutes=60))\nmsg = '<TemporalInterpolation: interval_in_minutes: 60, times: None, method: linear>'\nself.assertEqual(result, msg)",
"result = str(TemporalInterpolation(interval_in_minutes=60, interpolation_method='solar'))\nmsg = '<TemporalInterpolation: interval_i... | <|body_start_0|>
result = str(TemporalInterpolation(interval_in_minutes=60))
msg = '<TemporalInterpolation: interval_in_minutes: 60, times: None, method: linear>'
self.assertEqual(result, msg)
<|end_body_0|>
<|body_start_1|>
result = str(TemporalInterpolation(interval_in_minutes=60, int... | Test the repr method. | Test__repr__ | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test__repr__:
"""Test the repr method."""
def test_basic(self):
"""Test that the __repr__ returns the expected string."""
<|body_0|>
def test_solar(self):
"""Test that the __repr__ returns the expected string for solar."""
<|body_1|>
def test_daynigh... | stack_v2_sparse_classes_75kplus_train_073765 | 33,531 | permissive | [
{
"docstring": "Test that the __repr__ returns the expected string.",
"name": "test_basic",
"signature": "def test_basic(self)"
},
{
"docstring": "Test that the __repr__ returns the expected string for solar.",
"name": "test_solar",
"signature": "def test_solar(self)"
},
{
"docst... | 3 | null | Implement the Python class `Test__repr__` described below.
Class description:
Test the repr method.
Method signatures and docstrings:
- def test_basic(self): Test that the __repr__ returns the expected string.
- def test_solar(self): Test that the __repr__ returns the expected string for solar.
- def test_daynight(se... | Implement the Python class `Test__repr__` described below.
Class description:
Test the repr method.
Method signatures and docstrings:
- def test_basic(self): Test that the __repr__ returns the expected string.
- def test_solar(self): Test that the __repr__ returns the expected string for solar.
- def test_daynight(se... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test__repr__:
"""Test the repr method."""
def test_basic(self):
"""Test that the __repr__ returns the expected string."""
<|body_0|>
def test_solar(self):
"""Test that the __repr__ returns the expected string for solar."""
<|body_1|>
def test_daynigh... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test__repr__:
"""Test the repr method."""
def test_basic(self):
"""Test that the __repr__ returns the expected string."""
result = str(TemporalInterpolation(interval_in_minutes=60))
msg = '<TemporalInterpolation: interval_in_minutes: 60, times: None, method: linear>'
self.... | the_stack_v2_python_sparse | improver_tests/utilities/test_TemporalInterpolation.py | metoppv/improver | train | 101 |
bcc949b30a585cc361c00f711fd49b317c7f8340 | [
"self._parameters = parameters\nself._mapper = OCPAllProviderMap(provider=self.provider, report_type=parameters.report_type)\nsuper().__init__(parameters)",
"filter_map = deepcopy(TagQueryHandler.FILTER_MAP)\nif self._parameters.get_filter('value'):\n filter_map.update({'account': [{'field': 'account_aliases',... | <|body_start_0|>
self._parameters = parameters
self._mapper = OCPAllProviderMap(provider=self.provider, report_type=parameters.report_type)
super().__init__(parameters)
<|end_body_0|>
<|body_start_1|>
filter_map = deepcopy(TagQueryHandler.FILTER_MAP)
if self._parameters.get_filt... | Handles tag queries and responses for OCP-on-All. | OCPAllTagQueryHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OCPAllTagQueryHandler:
"""Handles tag queries and responses for OCP-on-All."""
def __init__(self, parameters):
"""Establish OCP on All infrastructure tag query handler. Args: parameters (QueryParameters): parameter object for query"""
<|body_0|>
def filter_map(self):
... | stack_v2_sparse_classes_75kplus_train_073766 | 4,248 | permissive | [
{
"docstring": "Establish OCP on All infrastructure tag query handler. Args: parameters (QueryParameters): parameter object for query",
"name": "__init__",
"signature": "def __init__(self, parameters)"
},
{
"docstring": "Establish which filter map to use based on tag API.",
"name": "filter_m... | 2 | null | Implement the Python class `OCPAllTagQueryHandler` described below.
Class description:
Handles tag queries and responses for OCP-on-All.
Method signatures and docstrings:
- def __init__(self, parameters): Establish OCP on All infrastructure tag query handler. Args: parameters (QueryParameters): parameter object for q... | Implement the Python class `OCPAllTagQueryHandler` described below.
Class description:
Handles tag queries and responses for OCP-on-All.
Method signatures and docstrings:
- def __init__(self, parameters): Establish OCP on All infrastructure tag query handler. Args: parameters (QueryParameters): parameter object for q... | 0416e5216eb1ec4b41c8dd4999adde218b1ab2e1 | <|skeleton|>
class OCPAllTagQueryHandler:
"""Handles tag queries and responses for OCP-on-All."""
def __init__(self, parameters):
"""Establish OCP on All infrastructure tag query handler. Args: parameters (QueryParameters): parameter object for query"""
<|body_0|>
def filter_map(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OCPAllTagQueryHandler:
"""Handles tag queries and responses for OCP-on-All."""
def __init__(self, parameters):
"""Establish OCP on All infrastructure tag query handler. Args: parameters (QueryParameters): parameter object for query"""
self._parameters = parameters
self._mapper = O... | the_stack_v2_python_sparse | koku/api/tags/all/openshift/queries.py | project-koku/koku | train | 225 |
e0487270a3bd5c3a5a2aa74ff0726e1758f4ae4b | [
"features = []\ncount = len(request.feature) - 1\nwhile count >= 0:\n features.append(str(request.feature[count]))\n count -= 1\nprepped_features = Pairwise.prepare_features(request.cohort_id, features)\noutputs = Pairwise.run_pairwise(prepped_features)\nresults = PairwiseResults(result_vectors=[], filter_mes... | <|body_start_0|>
features = []
count = len(request.feature) - 1
while count >= 0:
features.append(str(request.feature[count]))
count -= 1
prepped_features = Pairwise.prepare_features(request.cohort_id, features)
outputs = Pairwise.run_pairwise(prepped_feat... | Pairwise API v1 | PairwiseApi | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PairwiseApi:
"""Pairwise API v1"""
def run_job(self, request):
"""Used by the web application."""
<|body_0|>
def precomputed_results(self, request):
"""Used by the web application."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
features = []
... | stack_v2_sparse_classes_75kplus_train_073767 | 7,340 | permissive | [
{
"docstring": "Used by the web application.",
"name": "run_job",
"signature": "def run_job(self, request)"
},
{
"docstring": "Used by the web application.",
"name": "precomputed_results",
"signature": "def precomputed_results(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_053334 | Implement the Python class `PairwiseApi` described below.
Class description:
Pairwise API v1
Method signatures and docstrings:
- def run_job(self, request): Used by the web application.
- def precomputed_results(self, request): Used by the web application. | Implement the Python class `PairwiseApi` described below.
Class description:
Pairwise API v1
Method signatures and docstrings:
- def run_job(self, request): Used by the web application.
- def precomputed_results(self, request): Used by the web application.
<|skeleton|>
class PairwiseApi:
"""Pairwise API v1"""
... | 1c1809eb5b3ab7ec8a7d028df878ce8b0de9854f | <|skeleton|>
class PairwiseApi:
"""Pairwise API v1"""
def run_job(self, request):
"""Used by the web application."""
<|body_0|>
def precomputed_results(self, request):
"""Used by the web application."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PairwiseApi:
"""Pairwise API v1"""
def run_job(self, request):
"""Used by the web application."""
features = []
count = len(request.feature) - 1
while count >= 0:
features.append(str(request.feature[count]))
count -= 1
prepped_features = Pai... | the_stack_v2_python_sparse | api/pairwise_api.py | Angiotension/ISB-CGC-Webapp | train | 0 |
24668dddbca482d0f40d5125213e88718addea73 | [
"global passcase\nhr = requests.post(url, data=data, headers=headers)\njson_data = json.loads(hr.text)\nif hope == json_data['resCode']:\n passcase += 1\n log.info('测试用例ID:%s' % testcassid)\n log.info('测试用例名称:%s' % testcassname)\n log.debug('测试通过')\n log.debug('测试返回数据:%s' % json_data)\n log.info('... | <|body_start_0|>
global passcase
hr = requests.post(url, data=data, headers=headers)
json_data = json.loads(hr.text)
if hope == json_data['resCode']:
passcase += 1
log.info('测试用例ID:%s' % testcassid)
log.info('测试用例名称:%s' % testcassname)
log.... | TestRequest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestRequest:
def testpostreuqest(self, url, data, headers, testcassid, testcassname, hope):
"""获取post方法返回的数据 url: 接口地址 data: 请求参数 headers: 请求头 testcassid: 用例ID testcassname: 用例名称 hope: 预期code"""
<|body_0|>
def testgetrequest(self, url, data, headers, testcassid, testcassname... | stack_v2_sparse_classes_75kplus_train_073768 | 2,795 | no_license | [
{
"docstring": "获取post方法返回的数据 url: 接口地址 data: 请求参数 headers: 请求头 testcassid: 用例ID testcassname: 用例名称 hope: 预期code",
"name": "testpostreuqest",
"signature": "def testpostreuqest(self, url, data, headers, testcassid, testcassname, hope)"
},
{
"docstring": "获取get方法返回的数据 url: 接口地址 data: 请求参数 headers:... | 2 | stack_v2_sparse_classes_30k_train_020701 | Implement the Python class `TestRequest` described below.
Class description:
Implement the TestRequest class.
Method signatures and docstrings:
- def testpostreuqest(self, url, data, headers, testcassid, testcassname, hope): 获取post方法返回的数据 url: 接口地址 data: 请求参数 headers: 请求头 testcassid: 用例ID testcassname: 用例名称 hope: 预期c... | Implement the Python class `TestRequest` described below.
Class description:
Implement the TestRequest class.
Method signatures and docstrings:
- def testpostreuqest(self, url, data, headers, testcassid, testcassname, hope): 获取post方法返回的数据 url: 接口地址 data: 请求参数 headers: 请求头 testcassid: 用例ID testcassname: 用例名称 hope: 预期c... | 621e6807e609f227cf76bf8d33e242d2e3cd3253 | <|skeleton|>
class TestRequest:
def testpostreuqest(self, url, data, headers, testcassid, testcassname, hope):
"""获取post方法返回的数据 url: 接口地址 data: 请求参数 headers: 请求头 testcassid: 用例ID testcassname: 用例名称 hope: 预期code"""
<|body_0|>
def testgetrequest(self, url, data, headers, testcassid, testcassname... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestRequest:
def testpostreuqest(self, url, data, headers, testcassid, testcassname, hope):
"""获取post方法返回的数据 url: 接口地址 data: 请求参数 headers: 请求头 testcassid: 用例ID testcassname: 用例名称 hope: 预期code"""
global passcase
hr = requests.post(url, data=data, headers=headers)
json_data = jso... | the_stack_v2_python_sparse | business/TestRequest.py | Issmqi/B2CAPITest | train | 0 | |
e514c7b3cf803f1bd17bfdea179525276a360e81 | [
"IrConfig = self.env['ir.config_parameter'].sudo()\nforce_email = IrConfig.get_param('email.force_from')\nvals['email_from'] = force_email\nreturn super(MailMail, self).create(vals)",
"IrConfig = self.env['ir.config_parameter'].sudo()\nforce_email = IrConfig.get_param('email.force_from')\nvals['email_from'] = for... | <|body_start_0|>
IrConfig = self.env['ir.config_parameter'].sudo()
force_email = IrConfig.get_param('email.force_from')
vals['email_from'] = force_email
return super(MailMail, self).create(vals)
<|end_body_0|>
<|body_start_1|>
IrConfig = self.env['ir.config_parameter'].sudo()
... | mail.mail model | MailMail | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MailMail:
"""mail.mail model"""
def create(self, vals):
"""Force FORCE_EMAIL in email_from"""
<|body_0|>
def write(self, vals):
"""Force FORCE_EMAIL in email_from"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
IrConfig = self.env['ir.config_par... | stack_v2_sparse_classes_75kplus_train_073769 | 794 | no_license | [
{
"docstring": "Force FORCE_EMAIL in email_from",
"name": "create",
"signature": "def create(self, vals)"
},
{
"docstring": "Force FORCE_EMAIL in email_from",
"name": "write",
"signature": "def write(self, vals)"
}
] | 2 | null | Implement the Python class `MailMail` described below.
Class description:
mail.mail model
Method signatures and docstrings:
- def create(self, vals): Force FORCE_EMAIL in email_from
- def write(self, vals): Force FORCE_EMAIL in email_from | Implement the Python class `MailMail` described below.
Class description:
mail.mail model
Method signatures and docstrings:
- def create(self, vals): Force FORCE_EMAIL in email_from
- def write(self, vals): Force FORCE_EMAIL in email_from
<|skeleton|>
class MailMail:
"""mail.mail model"""
def create(self, v... | 00e3a5ee1771d2e09a48460ca23c2e9c2ef507d6 | <|skeleton|>
class MailMail:
"""mail.mail model"""
def create(self, vals):
"""Force FORCE_EMAIL in email_from"""
<|body_0|>
def write(self, vals):
"""Force FORCE_EMAIL in email_from"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MailMail:
"""mail.mail model"""
def create(self, vals):
"""Force FORCE_EMAIL in email_from"""
IrConfig = self.env['ir.config_parameter'].sudo()
force_email = IrConfig.get_param('email.force_from')
vals['email_from'] = force_email
return super(MailMail, self).create... | the_stack_v2_python_sparse | Free/mail_force_from/models/mail_mail.py | mulaudzicalvin/perpul | train | 0 |
f7a9329d5ad32224207121fe82e976e8a2743832 | [
"super(FunctionGamma, self).__init__()\nself.num = num\nself.EPSILON = 1e-07",
"num = self.num\nif num < 0.5:\n return self.PI / (math.sin(self.PI * num) * FunctionGamma(1 - num).calculateEquation())\nelse:\n num -= 1\n x = lanczos_coef[0]\n for i in range(1, len(lanczos_coef)):\n x += lanczos_... | <|body_start_0|>
super(FunctionGamma, self).__init__()
self.num = num
self.EPSILON = 1e-07
<|end_body_0|>
<|body_start_1|>
num = self.num
if num < 0.5:
return self.PI / (math.sin(self.PI * num) * FunctionGamma(1 - num).calculateEquation())
else:
n... | Class used to calculate the Gamma function. | FunctionGamma | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FunctionGamma:
"""Class used to calculate the Gamma function."""
def __init__(self, num: float) -> None:
"""Constructor."""
<|body_0|>
def calculateEquation(self) -> float:
"""Function used to calculate the gamma function. Returns Gamma(self.num)"""
<|bod... | stack_v2_sparse_classes_75kplus_train_073770 | 1,589 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, num: float) -> None"
},
{
"docstring": "Function used to calculate the gamma function. Returns Gamma(self.num)",
"name": "calculateEquation",
"signature": "def calculateEquation(self) -> float"
}
] | 2 | stack_v2_sparse_classes_30k_train_000679 | Implement the Python class `FunctionGamma` described below.
Class description:
Class used to calculate the Gamma function.
Method signatures and docstrings:
- def __init__(self, num: float) -> None: Constructor.
- def calculateEquation(self) -> float: Function used to calculate the gamma function. Returns Gamma(self.... | Implement the Python class `FunctionGamma` described below.
Class description:
Class used to calculate the Gamma function.
Method signatures and docstrings:
- def __init__(self, num: float) -> None: Constructor.
- def calculateEquation(self) -> float: Function used to calculate the gamma function. Returns Gamma(self.... | c1f864dabc5ba4a83da635f37002a2e5d07b7d25 | <|skeleton|>
class FunctionGamma:
"""Class used to calculate the Gamma function."""
def __init__(self, num: float) -> None:
"""Constructor."""
<|body_0|>
def calculateEquation(self) -> float:
"""Function used to calculate the gamma function. Returns Gamma(self.num)"""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FunctionGamma:
"""Class used to calculate the Gamma function."""
def __init__(self, num: float) -> None:
"""Constructor."""
super(FunctionGamma, self).__init__()
self.num = num
self.EPSILON = 1e-07
def calculateEquation(self) -> float:
"""Function used to calc... | the_stack_v2_python_sparse | src/FunctionGamma.py | shvnks/comp354_calculator | train | 0 |
661ab982264c5d663cf93c9b0fef4b443715dad6 | [
"template = API.getVNFTemplate()\nif template is None:\n return HttpResponse(status=404)\nreturn Response(data=template)",
"if request.META['CONTENT_TYPE'] != 'application/json':\n return HttpResponse(status=415)\nif 'image-upload-status' not in request.data.keys():\n try:\n if 'functional-capabil... | <|body_start_0|>
template = API.getVNFTemplate()
if template is None:
return HttpResponse(status=404)
return Response(data=template)
<|end_body_0|>
<|body_start_1|>
if request.META['CONTENT_TYPE'] != 'application/json':
return HttpResponse(status=415)
if ... | VNFTemplateAll | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VNFTemplateAll:
def get(self, request):
"""Get the all VNF with the respectively template"""
<|body_0|>
def put(self, request):
"""Create a new VNF template. The 'vnf_id' assigned by the datastore is contained in the response."""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_75kplus_train_073771 | 13,103 | no_license | [
{
"docstring": "Get the all VNF with the respectively template",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Create a new VNF template. The 'vnf_id' assigned by the datastore is contained in the response.",
"name": "put",
"signature": "def put(self, request)"
... | 2 | stack_v2_sparse_classes_30k_train_018018 | Implement the Python class `VNFTemplateAll` described below.
Class description:
Implement the VNFTemplateAll class.
Method signatures and docstrings:
- def get(self, request): Get the all VNF with the respectively template
- def put(self, request): Create a new VNF template. The 'vnf_id' assigned by the datastore is ... | Implement the Python class `VNFTemplateAll` described below.
Class description:
Implement the VNFTemplateAll class.
Method signatures and docstrings:
- def get(self, request): Get the all VNF with the respectively template
- def put(self, request): Create a new VNF template. The 'vnf_id' assigned by the datastore is ... | bf4c0468531681991e80aedaef78b2a43607511c | <|skeleton|>
class VNFTemplateAll:
def get(self, request):
"""Get the all VNF with the respectively template"""
<|body_0|>
def put(self, request):
"""Create a new VNF template. The 'vnf_id' assigned by the datastore is contained in the response."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VNFTemplateAll:
def get(self, request):
"""Get the all VNF with the respectively template"""
template = API.getVNFTemplate()
if template is None:
return HttpResponse(status=404)
return Response(data=template)
def put(self, request):
"""Create a new VNF ... | the_stack_v2_python_sparse | datastore/views.py | netgroup-polito/frog4-datastore | train | 4 | |
36b7d7396db6d1295406598de4598b75d73465db | [
"self.arduino = Serial(config)\nself.arduino.add_listener(self.parse_data)\nObservableComponent.__init__(self, self.arduino)",
"if len(reading) == 5:\n try:\n packet = TrollPacket.from_binary_packet(reading)\n self.update_listeners(packet)\n except KeyError as e:\n err_msg = 'Arduino me... | <|body_start_0|>
self.arduino = Serial(config)
self.arduino.add_listener(self.parse_data)
ObservableComponent.__init__(self, self.arduino)
<|end_body_0|>
<|body_start_1|>
if len(reading) == 5:
try:
packet = TrollPacket.from_binary_packet(reading)
... | Arduino layer for handling data inconsistensies. | Arduino | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Arduino:
"""Arduino layer for handling data inconsistensies."""
def __init__(self, config):
""":param config: Dictionary containing connection headers :type config: dict"""
<|body_0|>
def parse_data(self, reading):
"""Arduino sends data incosistently sometimes. T... | stack_v2_sparse_classes_75kplus_train_073772 | 10,572 | permissive | [
{
"docstring": ":param config: Dictionary containing connection headers :type config: dict",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Arduino sends data incosistently sometimes. This implementation assumes a format when receiving from arduino: - First byte... | 2 | stack_v2_sparse_classes_30k_train_013178 | Implement the Python class `Arduino` described below.
Class description:
Arduino layer for handling data inconsistensies.
Method signatures and docstrings:
- def __init__(self, config): :param config: Dictionary containing connection headers :type config: dict
- def parse_data(self, reading): Arduino sends data incos... | Implement the Python class `Arduino` described below.
Class description:
Arduino layer for handling data inconsistensies.
Method signatures and docstrings:
- def __init__(self, config): :param config: Dictionary containing connection headers :type config: dict
- def parse_data(self, reading): Arduino sends data incos... | d554403dc73e8de43e723c08994b3dae08ac0c1c | <|skeleton|>
class Arduino:
"""Arduino layer for handling data inconsistensies."""
def __init__(self, config):
""":param config: Dictionary containing connection headers :type config: dict"""
<|body_0|>
def parse_data(self, reading):
"""Arduino sends data incosistently sometimes. T... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Arduino:
"""Arduino layer for handling data inconsistensies."""
def __init__(self, config):
""":param config: Dictionary containing connection headers :type config: dict"""
self.arduino = Serial(config)
self.arduino.add_listener(self.parse_data)
ObservableComponent.__init_... | the_stack_v2_python_sparse | backend/endpoints.py | trolllabs/trollsim | train | 0 |
dd0c8188b54166702913121601d0e6be9fc1e3d1 | [
"self.pts = []\npre = 0\nfor rect in rects:\n pre += (rect[2] - rect[0] + 1) * (rect[3] - rect[1] + 1)\n self.pts.append(pre)\nself.rects = rects",
"rand = random.randint(1, self.pts[-1])\nind = bisect.bisect_left(self.pts, rand)\nx1, y1, x2, y2 = self.rects[ind]\nreturn [random.randint(x1, x2), random.rand... | <|body_start_0|>
self.pts = []
pre = 0
for rect in rects:
pre += (rect[2] - rect[0] + 1) * (rect[3] - rect[1] + 1)
self.pts.append(pre)
self.rects = rects
<|end_body_0|>
<|body_start_1|>
rand = random.randint(1, self.pts[-1])
ind = bisect.bisect_l... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
<|body_0|>
def pick(self):
""":rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.pts = []
pre = 0
for rect in rects:
pre += (rect... | stack_v2_sparse_classes_75kplus_train_073773 | 702 | no_license | [
{
"docstring": ":type rects: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, rects)"
},
{
"docstring": ":rtype: List[int]",
"name": "pick",
"signature": "def pick(self)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, rects): :type rects: List[List[int]]
- def pick(self): :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, rects): :type rects: List[List[int]]
- def pick(self): :rtype: List[int]
<|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: ... | b0ce69985c51a9a794397cd98a996fca0e91d7d1 | <|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
<|body_0|>
def pick(self):
""":rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
self.pts = []
pre = 0
for rect in rects:
pre += (rect[2] - rect[0] + 1) * (rect[3] - rect[1] + 1)
self.pts.append(pre)
self.rects = rects
def pick(self):
""":rty... | the_stack_v2_python_sparse | Solutions/497-Random-Point-in-Non-overlapping-Rectangles/python.py | JerryHu1994/LeetCode-Practice | train | 0 | |
1f84672c0be4910490ad78a489a71c283b76ca31 | [
"self.pool_size = pool_size\nif self.pool_size > 0:\n self.num_imgs = 0\n self.images = []",
"if isinstance(images, Tensor):\n images = images.asnumpy()\nif self.pool_size == 0:\n return Tensor(images)\nreturn_images = []\nfor image in images:\n if self.num_imgs < self.pool_size:\n self.num_... | <|body_start_0|>
self.pool_size = pool_size
if self.pool_size > 0:
self.num_imgs = 0
self.images = []
<|end_body_0|>
<|body_start_1|>
if isinstance(images, Tensor):
images = images.asnumpy()
if self.pool_size == 0:
return Tensor(images)
... | This class implements an image buffer that stores previously generated images. This buffer enables us to update discriminators using a history of generated images rather than the ones produced by the latest generators. Args: pool_size (int): The size of image buffer, if pool_size=0, no buffer will be created. | GanImagePool | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GanImagePool:
"""This class implements an image buffer that stores previously generated images. This buffer enables us to update discriminators using a history of generated images rather than the ones produced by the latest generators. Args: pool_size (int): The size of image buffer, if pool_size... | stack_v2_sparse_classes_75kplus_train_073774 | 11,638 | permissive | [
{
"docstring": "Initialize the ImagePool class.",
"name": "__init__",
"signature": "def __init__(self, pool_size)"
},
{
"docstring": "Query an image from the pool. By 50/100, the buffer will return input images. By 50/100, the buffer will return images previously stored in the buffer, and insert... | 2 | stack_v2_sparse_classes_30k_train_043292 | Implement the Python class `GanImagePool` described below.
Class description:
This class implements an image buffer that stores previously generated images. This buffer enables us to update discriminators using a history of generated images rather than the ones produced by the latest generators. Args: pool_size (int):... | Implement the Python class `GanImagePool` described below.
Class description:
This class implements an image buffer that stores previously generated images. This buffer enables us to update discriminators using a history of generated images rather than the ones produced by the latest generators. Args: pool_size (int):... | 0bdbac45328b898908f395c48fbbc25af6ba0dde | <|skeleton|>
class GanImagePool:
"""This class implements an image buffer that stores previously generated images. This buffer enables us to update discriminators using a history of generated images rather than the ones produced by the latest generators. Args: pool_size (int): The size of image buffer, if pool_size... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GanImagePool:
"""This class implements an image buffer that stores previously generated images. This buffer enables us to update discriminators using a history of generated images rather than the ones produced by the latest generators. Args: pool_size (int): The size of image buffer, if pool_size=0, no buffer... | the_stack_v2_python_sparse | tinyms/utils/common_utils.py | bravotty/tinyms | train | 0 |
6b420d4be7b83e895314143c02ee7d296ac36e89 | [
"self.model = model\nself.episodes = episodes\nself.batch_size = batch_size\nself.past_timesteps = past_timesteps\nself.width = width\nself.height = height\nself.radius = radius\nself.scenes = [ThreeCircles(width=self.width, height=self.height, radius=self.radius) for _ in range(self.batch_size)]",
"num_circles =... | <|body_start_0|>
self.model = model
self.episodes = episodes
self.batch_size = batch_size
self.past_timesteps = past_timesteps
self.width = width
self.height = height
self.radius = radius
self.scenes = [ThreeCircles(width=self.width, height=self.height, ra... | Environment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Environment:
def __init__(self, model, episodes=100, batch_size=128, width=256, height=256, radius=30, past_timesteps=2):
"""Initializes the environment."""
<|body_0|>
def get_reward(self, configurations):
"""Returns the reward given configuration vectors. The config... | stack_v2_sparse_classes_75kplus_train_073775 | 5,917 | no_license | [
{
"docstring": "Initializes the environment.",
"name": "__init__",
"signature": "def __init__(self, model, episodes=100, batch_size=128, width=256, height=256, radius=30, past_timesteps=2)"
},
{
"docstring": "Returns the reward given configuration vectors. The configuration vector specifies the ... | 2 | stack_v2_sparse_classes_30k_train_054172 | Implement the Python class `Environment` described below.
Class description:
Implement the Environment class.
Method signatures and docstrings:
- def __init__(self, model, episodes=100, batch_size=128, width=256, height=256, radius=30, past_timesteps=2): Initializes the environment.
- def get_reward(self, configurati... | Implement the Python class `Environment` described below.
Class description:
Implement the Environment class.
Method signatures and docstrings:
- def __init__(self, model, episodes=100, batch_size=128, width=256, height=256, radius=30, past_timesteps=2): Initializes the environment.
- def get_reward(self, configurati... | 4c7b6dcd3406a3b01f52bbdc48796c98f7002a30 | <|skeleton|>
class Environment:
def __init__(self, model, episodes=100, batch_size=128, width=256, height=256, radius=30, past_timesteps=2):
"""Initializes the environment."""
<|body_0|>
def get_reward(self, configurations):
"""Returns the reward given configuration vectors. The config... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Environment:
def __init__(self, model, episodes=100, batch_size=128, width=256, height=256, radius=30, past_timesteps=2):
"""Initializes the environment."""
self.model = model
self.episodes = episodes
self.batch_size = batch_size
self.past_timesteps = past_timesteps
... | the_stack_v2_python_sparse | experiments/playconf/environment.py | revalo/neural-physics | train | 1 | |
3fa3af006c75daf33c9f4edbaa0adf7a2ffe5ae4 | [
"arguments = SaleResource.parser.parse_args()\nname = arguments.get('name')\nprice = arguments.get('price')\nfor product in getattr(db, 'products'):\n if not name == product['name']:\n return ({'message': 'Product does not exist.'}, 400)\nif not re.match('^[a-zA-Z 0-9]+$', name):\n return ({'message': ... | <|body_start_0|>
arguments = SaleResource.parser.parse_args()
name = arguments.get('name')
price = arguments.get('price')
for product in getattr(db, 'products'):
if not name == product['name']:
return ({'message': 'Product does not exist.'}, 400)
if no... | Class for handling products. | SaleResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SaleResource:
"""Class for handling products."""
def post(cls):
"""Post Product"""
<|body_0|>
def get(cls, sale_id=None):
"""Get Products"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
arguments = SaleResource.parser.parse_args()
name =... | stack_v2_sparse_classes_75kplus_train_073776 | 1,611 | permissive | [
{
"docstring": "Post Product",
"name": "post",
"signature": "def post(cls)"
},
{
"docstring": "Get Products",
"name": "get",
"signature": "def get(cls, sale_id=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013133 | Implement the Python class `SaleResource` described below.
Class description:
Class for handling products.
Method signatures and docstrings:
- def post(cls): Post Product
- def get(cls, sale_id=None): Get Products | Implement the Python class `SaleResource` described below.
Class description:
Class for handling products.
Method signatures and docstrings:
- def post(cls): Post Product
- def get(cls, sale_id=None): Get Products
<|skeleton|>
class SaleResource:
"""Class for handling products."""
def post(cls):
"""... | e6240eac541632760f4a74e3e27a83ae0d2d3be5 | <|skeleton|>
class SaleResource:
"""Class for handling products."""
def post(cls):
"""Post Product"""
<|body_0|>
def get(cls, sale_id=None):
"""Get Products"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SaleResource:
"""Class for handling products."""
def post(cls):
"""Post Product"""
arguments = SaleResource.parser.parse_args()
name = arguments.get('name')
price = arguments.get('price')
for product in getattr(db, 'products'):
if not name == product['n... | the_stack_v2_python_sparse | app/v1/views/sales.py | Nyakaru/Store-Manager-Backend | train | 0 |
f4b8afd0437e6be91dc002bde22a9c0dc98fdf69 | [
"mask1 = 1 << 7\nmask2 = 1 << 6\nn_byte = 0\nfor num in data:\n mask = 1 << 7\n if n_byte == 0:\n while mask & num:\n n_byte += 1\n mask >>= 1\n if n_byte == 0:\n continue\n if n_byte > 4 or n_byte == 1:\n return False\n n_byte -= 1\n ... | <|body_start_0|>
mask1 = 1 << 7
mask2 = 1 << 6
n_byte = 0
for num in data:
mask = 1 << 7
if n_byte == 0:
while mask & num:
n_byte += 1
mask >>= 1
if n_byte == 0:
continue
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def validUtf8(self, data):
""":type data: List[int] :rtype: bool"""
<|body_0|>
def validUtf8_1(self, data):
""":type data: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
mask1 = 1 << 7
mask2 = 1 << 6
... | stack_v2_sparse_classes_75kplus_train_073777 | 1,579 | no_license | [
{
"docstring": ":type data: List[int] :rtype: bool",
"name": "validUtf8",
"signature": "def validUtf8(self, data)"
},
{
"docstring": ":type data: List[int] :rtype: bool",
"name": "validUtf8_1",
"signature": "def validUtf8_1(self, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006880 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validUtf8(self, data): :type data: List[int] :rtype: bool
- def validUtf8_1(self, data): :type data: List[int] :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validUtf8(self, data): :type data: List[int] :rtype: bool
- def validUtf8_1(self, data): :type data: List[int] :rtype: bool
<|skeleton|>
class Solution:
def validUtf8(s... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class Solution:
def validUtf8(self, data):
""":type data: List[int] :rtype: bool"""
<|body_0|>
def validUtf8_1(self, data):
""":type data: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def validUtf8(self, data):
""":type data: List[int] :rtype: bool"""
mask1 = 1 << 7
mask2 = 1 << 6
n_byte = 0
for num in data:
mask = 1 << 7
if n_byte == 0:
while mask & num:
n_byte += 1
... | the_stack_v2_python_sparse | python/leetcode/393_UTF-8_Validation.py | bobcaoge/my-code | train | 0 | |
681bc28a89e31007d5f6cd57d503862a2b211bec | [
"self.max_number_of_buckets = max_number_of_buckets\nself.size = 0\nself.next = None\nself.prev = None\nself.sum = []\nself.variance = []\nfor i in range(self.max_number_of_buckets + 1):\n self.sum.append(0.0)\n self.variance.append(0.0)",
"self.sum[self.size] = value\nself.variance[self.size] = variance\ns... | <|body_start_0|>
self.max_number_of_buckets = max_number_of_buckets
self.size = 0
self.next = None
self.prev = None
self.sum = []
self.variance = []
for i in range(self.max_number_of_buckets + 1):
self.sum.append(0.0)
self.variance.append(0... | Implementation of a node of adwin list | AdwinListNode | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdwinListNode:
"""Implementation of a node of adwin list"""
def __init__(self, max_number_of_buckets):
"""Init a node with a given parameter number_of_buckets Parameters ---------- max_number_of_buckets : In each row, the max number of buckets"""
<|body_0|>
def insert_bu... | stack_v2_sparse_classes_75kplus_train_073778 | 1,515 | no_license | [
{
"docstring": "Init a node with a given parameter number_of_buckets Parameters ---------- max_number_of_buckets : In each row, the max number of buckets",
"name": "__init__",
"signature": "def __init__(self, max_number_of_buckets)"
},
{
"docstring": "Insert a bucket at the end Parameters ------... | 3 | stack_v2_sparse_classes_30k_train_030518 | Implement the Python class `AdwinListNode` described below.
Class description:
Implementation of a node of adwin list
Method signatures and docstrings:
- def __init__(self, max_number_of_buckets): Init a node with a given parameter number_of_buckets Parameters ---------- max_number_of_buckets : In each row, the max n... | Implement the Python class `AdwinListNode` described below.
Class description:
Implementation of a node of adwin list
Method signatures and docstrings:
- def __init__(self, max_number_of_buckets): Init a node with a given parameter number_of_buckets Parameters ---------- max_number_of_buckets : In each row, the max n... | 9d5870aedafe094fea6c3ffdc0dd1dadfc0e82f5 | <|skeleton|>
class AdwinListNode:
"""Implementation of a node of adwin list"""
def __init__(self, max_number_of_buckets):
"""Init a node with a given parameter number_of_buckets Parameters ---------- max_number_of_buckets : In each row, the max number of buckets"""
<|body_0|>
def insert_bu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AdwinListNode:
"""Implementation of a node of adwin list"""
def __init__(self, max_number_of_buckets):
"""Init a node with a given parameter number_of_buckets Parameters ---------- max_number_of_buckets : In each row, the max number of buckets"""
self.max_number_of_buckets = max_number_of... | the_stack_v2_python_sparse | Code/drift_detector/adwin_list_node.py | TyngJiunKuo/Data-Mining-Labor | train | 0 |
dfb6dffb0f177d15b329a7ec41cdbdf6521be772 | [
"try:\n serializer = RadiologistPmtSerializers(RadiologistPmt.objects.all(), many=True)\n return JsonResponse({'message': 'listed all', 'data': serializer.data}, status=200)\nexcept Exception as e:\n info_message = 'Internal Server Error'\n logger.error(info_message, e)\n return JsonResponse({'error'... | <|body_start_0|>
try:
serializer = RadiologistPmtSerializers(RadiologistPmt.objects.all(), many=True)
return JsonResponse({'message': 'listed all', 'data': serializer.data}, status=200)
except Exception as e:
info_message = 'Internal Server Error'
logger.e... | RadiologistPmtView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RadiologistPmtView:
def get(self, request):
"""Get all Radiologist_Payment"""
<|body_0|>
def post(self, request):
"""Save Radiologist data"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
serializer = RadiologistPmtSerializers(Radiol... | stack_v2_sparse_classes_75kplus_train_073779 | 31,833 | no_license | [
{
"docstring": "Get all Radiologist_Payment",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Save Radiologist data",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_029579 | Implement the Python class `RadiologistPmtView` described below.
Class description:
Implement the RadiologistPmtView class.
Method signatures and docstrings:
- def get(self, request): Get all Radiologist_Payment
- def post(self, request): Save Radiologist data | Implement the Python class `RadiologistPmtView` described below.
Class description:
Implement the RadiologistPmtView class.
Method signatures and docstrings:
- def get(self, request): Get all Radiologist_Payment
- def post(self, request): Save Radiologist data
<|skeleton|>
class RadiologistPmtView:
def get(self... | b63849983a592fd6a1f654191020fd86aa0787ae | <|skeleton|>
class RadiologistPmtView:
def get(self, request):
"""Get all Radiologist_Payment"""
<|body_0|>
def post(self, request):
"""Save Radiologist data"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RadiologistPmtView:
def get(self, request):
"""Get all Radiologist_Payment"""
try:
serializer = RadiologistPmtSerializers(RadiologistPmt.objects.all(), many=True)
return JsonResponse({'message': 'listed all', 'data': serializer.data}, status=200)
except Exceptio... | the_stack_v2_python_sparse | radiologist/views.py | RupeshKurlekar/biocare | train | 1 | |
2182570754f97c1779e565a342d9676e5bc19a05 | [
"if type(y_true) or type(y_pred) is not np.ndarray:\n y_true = np.array(y_true)\n y_pred = np.array(y_pred)\nerror = abs(y_true - y_pred)\nmae = np.mean(error)\nreturn mae",
"if type(y_true) or type(y_pred) is not np.ndarray:\n y_true = np.array(y_true)\n y_pred = np.array(y_pred)\nerror = (y_true - y... | <|body_start_0|>
if type(y_true) or type(y_pred) is not np.ndarray:
y_true = np.array(y_true)
y_pred = np.array(y_pred)
error = abs(y_true - y_pred)
mae = np.mean(error)
return mae
<|end_body_0|>
<|body_start_1|>
if type(y_true) or type(y_pred) is not np.... | Regression | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Regression:
def meanAbsoluteError(self, y_true, y_pred):
""":param y_true: nilai y asli, type: ndarray :param y_pred: nilai y prediksi, type: ndarray :return: nilai MAE"""
<|body_0|>
def meanSquaredError(self, y_true, y_pred):
""":param y_true: nilai y asli, type: nd... | stack_v2_sparse_classes_75kplus_train_073780 | 12,629 | no_license | [
{
"docstring": ":param y_true: nilai y asli, type: ndarray :param y_pred: nilai y prediksi, type: ndarray :return: nilai MAE",
"name": "meanAbsoluteError",
"signature": "def meanAbsoluteError(self, y_true, y_pred)"
},
{
"docstring": ":param y_true: nilai y asli, type: ndarray :param y_pred: nila... | 6 | null | Implement the Python class `Regression` described below.
Class description:
Implement the Regression class.
Method signatures and docstrings:
- def meanAbsoluteError(self, y_true, y_pred): :param y_true: nilai y asli, type: ndarray :param y_pred: nilai y prediksi, type: ndarray :return: nilai MAE
- def meanSquaredErr... | Implement the Python class `Regression` described below.
Class description:
Implement the Regression class.
Method signatures and docstrings:
- def meanAbsoluteError(self, y_true, y_pred): :param y_true: nilai y asli, type: ndarray :param y_pred: nilai y prediksi, type: ndarray :return: nilai MAE
- def meanSquaredErr... | 25188166962b02487c19c2aff5d17e06a9a8909a | <|skeleton|>
class Regression:
def meanAbsoluteError(self, y_true, y_pred):
""":param y_true: nilai y asli, type: ndarray :param y_pred: nilai y prediksi, type: ndarray :return: nilai MAE"""
<|body_0|>
def meanSquaredError(self, y_true, y_pred):
""":param y_true: nilai y asli, type: nd... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Regression:
def meanAbsoluteError(self, y_true, y_pred):
""":param y_true: nilai y asli, type: ndarray :param y_pred: nilai y prediksi, type: ndarray :return: nilai MAE"""
if type(y_true) or type(y_pred) is not np.ndarray:
y_true = np.array(y_true)
y_pred = np.array(y_p... | the_stack_v2_python_sparse | Machine Learning/WildanML.py | abuwildanm/Python-Machine-Learning | train | 0 | |
360af7f3b40277af1fecc7bd7b60bc0b0818bc36 | [
"i = 32\nres = 0\nwhile i:\n res += n & 1\n res <<= 1\n n >>= 1\n i -= 1\nreturn res >> 1",
"ret, power = (0, 31)\nwhile n:\n ret += (n & 1) << power\n n = n >> 1\n power -= 1\nreturn ret"
] | <|body_start_0|>
i = 32
res = 0
while i:
res += n & 1
res <<= 1
n >>= 1
i -= 1
return res >> 1
<|end_body_0|>
<|body_start_1|>
ret, power = (0, 31)
while n:
ret += (n & 1) << power
n = n >> 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseBits1(self, n: int) -> int:
"""思路:每次获取最后一位左移 @param n: @return:"""
<|body_0|>
def reverseBits2(self, n):
"""思路:将二进制低位的数左移到对应的位置,如第一位移动到32位,第二位移动到31位 @param n: @return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
i = 32
... | stack_v2_sparse_classes_75kplus_train_073781 | 2,250 | no_license | [
{
"docstring": "思路:每次获取最后一位左移 @param n: @return:",
"name": "reverseBits1",
"signature": "def reverseBits1(self, n: int) -> int"
},
{
"docstring": "思路:将二进制低位的数左移到对应的位置,如第一位移动到32位,第二位移动到31位 @param n: @return:",
"name": "reverseBits2",
"signature": "def reverseBits2(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006653 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseBits1(self, n: int) -> int: 思路:每次获取最后一位左移 @param n: @return:
- def reverseBits2(self, n): 思路:将二进制低位的数左移到对应的位置,如第一位移动到32位,第二位移动到31位 @param n: @return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseBits1(self, n: int) -> int: 思路:每次获取最后一位左移 @param n: @return:
- def reverseBits2(self, n): 思路:将二进制低位的数左移到对应的位置,如第一位移动到32位,第二位移动到31位 @param n: @return:
<|skeleton|>
cla... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def reverseBits1(self, n: int) -> int:
"""思路:每次获取最后一位左移 @param n: @return:"""
<|body_0|>
def reverseBits2(self, n):
"""思路:将二进制低位的数左移到对应的位置,如第一位移动到32位,第二位移动到31位 @param n: @return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverseBits1(self, n: int) -> int:
"""思路:每次获取最后一位左移 @param n: @return:"""
i = 32
res = 0
while i:
res += n & 1
res <<= 1
n >>= 1
i -= 1
return res >> 1
def reverseBits2(self, n):
"""思路:将二进制低位的数左移... | the_stack_v2_python_sparse | LeetCode/位运算/190. 颠倒二进制位.py | yiming1012/MyLeetCode | train | 2 | |
2653ba984ab0fe8e798f79ef46535b9e62c31559 | [
"self.preprocessors = preprocessors\nself.generators = generators\nself.output_preprocessors = output_preprocessors",
"data = self.runProcessors(self.preprocessors, data)\ndata = self.runProcessors(self.generators, data)\ndata = self.runProcessors(self.output_preprocessors, data)\nreturn data",
"if processors:\... | <|body_start_0|>
self.preprocessors = preprocessors
self.generators = generators
self.output_preprocessors = output_preprocessors
<|end_body_0|>
<|body_start_1|>
data = self.runProcessors(self.preprocessors, data)
data = self.runProcessors(self.generators, data)
data = s... | The DatasetAugmentationBuilder builds a pipeline for augmentation from the given preprocessors, generators and output_preprocessors :Attributes: preprocessors: (List of (tf) functions) preprocessors will be applied first and create no "new data" they only change the input data by preprocessing. generators: (List of (tf... | DatasetAugmentationBuilder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatasetAugmentationBuilder:
"""The DatasetAugmentationBuilder builds a pipeline for augmentation from the given preprocessors, generators and output_preprocessors :Attributes: preprocessors: (List of (tf) functions) preprocessors will be applied first and create no "new data" they only change the... | stack_v2_sparse_classes_75kplus_train_073782 | 2,900 | permissive | [
{
"docstring": "Constructor, initialize member variables. :param preprocessors: (List of (tf) functions) preprocessors will be applied first and create no \"new data\" they only change the input data by preprocessing. None by default. :param generators: (List of (tf) functions) generators will be applied second... | 3 | stack_v2_sparse_classes_30k_train_031779 | Implement the Python class `DatasetAugmentationBuilder` described below.
Class description:
The DatasetAugmentationBuilder builds a pipeline for augmentation from the given preprocessors, generators and output_preprocessors :Attributes: preprocessors: (List of (tf) functions) preprocessors will be applied first and cr... | Implement the Python class `DatasetAugmentationBuilder` described below.
Class description:
The DatasetAugmentationBuilder builds a pipeline for augmentation from the given preprocessors, generators and output_preprocessors :Attributes: preprocessors: (List of (tf) functions) preprocessors will be applied first and cr... | 6907ae5781765f56a8492bfba594bfb3b9987f29 | <|skeleton|>
class DatasetAugmentationBuilder:
"""The DatasetAugmentationBuilder builds a pipeline for augmentation from the given preprocessors, generators and output_preprocessors :Attributes: preprocessors: (List of (tf) functions) preprocessors will be applied first and create no "new data" they only change the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DatasetAugmentationBuilder:
"""The DatasetAugmentationBuilder builds a pipeline for augmentation from the given preprocessors, generators and output_preprocessors :Attributes: preprocessors: (List of (tf) functions) preprocessors will be applied first and create no "new data" they only change the input data b... | the_stack_v2_python_sparse | Input_Component/DatasetAugmentationBuilder.py | BonifazStuhr/OFM | train | 0 |
2acdc3142cdfea3def580b1ce0bf3a77e348fdc0 | [
"if request.method in self.safe_methods:\n return True\nif request.user.is_authenticated and hasattr(request.user, 'profile'):\n return True\nreturn False",
"if obj.user == request.user.profile:\n return True\nreturn False"
] | <|body_start_0|>
if request.method in self.safe_methods:
return True
if request.user.is_authenticated and hasattr(request.user, 'profile'):
return True
return False
<|end_body_0|>
<|body_start_1|>
if obj.user == request.user.profile:
return True
... | The Permission class used by DriverReviewView. | DriverReviewPermissions | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DriverReviewPermissions:
"""The Permission class used by DriverReviewView."""
def has_permission(self, request, view):
"""Checks if the request is in safe methods if not checks if the user is authenticated and has a valid regular user profile, because that account may be other type l... | stack_v2_sparse_classes_75kplus_train_073783 | 1,905 | permissive | [
{
"docstring": "Checks if the request is in safe methods if not checks if the user is authenticated and has a valid regular user profile, because that account may be other type like a driver, shop or an admin.",
"name": "has_permission",
"signature": "def has_permission(self, request, view)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_031363 | Implement the Python class `DriverReviewPermissions` described below.
Class description:
The Permission class used by DriverReviewView.
Method signatures and docstrings:
- def has_permission(self, request, view): Checks if the request is in safe methods if not checks if the user is authenticated and has a valid regul... | Implement the Python class `DriverReviewPermissions` described below.
Class description:
The Permission class used by DriverReviewView.
Method signatures and docstrings:
- def has_permission(self, request, view): Checks if the request is in safe methods if not checks if the user is authenticated and has a valid regul... | 7c361a31c5225c6ad649fcf92e323bdb10cc4c16 | <|skeleton|>
class DriverReviewPermissions:
"""The Permission class used by DriverReviewView."""
def has_permission(self, request, view):
"""Checks if the request is in safe methods if not checks if the user is authenticated and has a valid regular user profile, because that account may be other type l... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DriverReviewPermissions:
"""The Permission class used by DriverReviewView."""
def has_permission(self, request, view):
"""Checks if the request is in safe methods if not checks if the user is authenticated and has a valid regular user profile, because that account may be other type like a driver,... | the_stack_v2_python_sparse | drivers/permissions.py | ahmed-alllam/Koshkie-Server | train | 0 |
d44f55e449332180c0a5ec051cb0813a453deca6 | [
"batch_size = self.tensors.batch_size\nmask = self._get_mask()\nspatial_temporal_log_loss = self._get_spatial_temporal_loss(n_location_categories, layer_2_output_socres) * mask\ncategorical_log_loss = self._get_categorical_loss(layer_1_output_socres) * mask\nreturn [tf.reduce_sum(categorical_log_loss) / batch_size,... | <|body_start_0|>
batch_size = self.tensors.batch_size
mask = self._get_mask()
spatial_temporal_log_loss = self._get_spatial_temporal_loss(n_location_categories, layer_2_output_socres) * mask
categorical_log_loss = self._get_categorical_loss(layer_1_output_socres) * mask
return [t... | TwoLayerCategoricalLocationLossFunction | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwoLayerCategoricalLocationLossFunction:
def get_loss(self, n_location_categories, layer_1_output_socres, layer_2_output_socres):
"""Get total loss from layer 1 and layer 2 output."""
<|body_0|>
def _get_spatial_temporal_loss(self, n_location_categories, output_socres):
... | stack_v2_sparse_classes_75kplus_train_073784 | 3,718 | permissive | [
{
"docstring": "Get total loss from layer 1 and layer 2 output.",
"name": "get_loss",
"signature": "def get_loss(self, n_location_categories, layer_1_output_socres, layer_2_output_socres)"
},
{
"docstring": "Compute the spatial-temporal log loss",
"name": "_get_spatial_temporal_loss",
"s... | 2 | stack_v2_sparse_classes_30k_train_014316 | Implement the Python class `TwoLayerCategoricalLocationLossFunction` described below.
Class description:
Implement the TwoLayerCategoricalLocationLossFunction class.
Method signatures and docstrings:
- def get_loss(self, n_location_categories, layer_1_output_socres, layer_2_output_socres): Get total loss from layer 1... | Implement the Python class `TwoLayerCategoricalLocationLossFunction` described below.
Class description:
Implement the TwoLayerCategoricalLocationLossFunction class.
Method signatures and docstrings:
- def get_loss(self, n_location_categories, layer_1_output_socres, layer_2_output_socres): Get total loss from layer 1... | 36f21b46a5c9382f90ece561a3efb1885be3c74f | <|skeleton|>
class TwoLayerCategoricalLocationLossFunction:
def get_loss(self, n_location_categories, layer_1_output_socres, layer_2_output_socres):
"""Get total loss from layer 1 and layer 2 output."""
<|body_0|>
def _get_spatial_temporal_loss(self, n_location_categories, output_socres):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TwoLayerCategoricalLocationLossFunction:
def get_loss(self, n_location_categories, layer_1_output_socres, layer_2_output_socres):
"""Get total loss from layer 1 and layer 2 output."""
batch_size = self.tensors.batch_size
mask = self._get_mask()
spatial_temporal_log_loss = self.... | the_stack_v2_python_sparse | lstm_mobility_model/two_layer_categorical_location/loss_function.py | zihenglin/LSTM-Mobility-Model | train | 20 | |
9f84f303c33c7bfbf8c46d810268710006c834f4 | [
"if '_all_models_' not in cls.__dict__:\n cls._all_models_ = []\n if cls.typeclass_key:\n if not cls.model_name:\n raise ValueError(\"%s's model name is empty.\" % cls.typeclass_key)\n for c in cls.__bases__:\n if hasattr(c, 'get_models'):\n cls._all_models_.... | <|body_start_0|>
if '_all_models_' not in cls.__dict__:
cls._all_models_ = []
if cls.typeclass_key:
if not cls.model_name:
raise ValueError("%s's model name is empty." % cls.typeclass_key)
for c in cls.__bases__:
if ... | This base typeclass. | BaseTypeclass | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseTypeclass:
"""This base typeclass."""
def get_models(cls):
"""Get this typeclass's models."""
<|body_0|>
def get_properties_info(cls):
"""Get this typeclass's models."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if '_all_models_' not in c... | stack_v2_sparse_classes_75kplus_train_073785 | 1,975 | permissive | [
{
"docstring": "Get this typeclass's models.",
"name": "get_models",
"signature": "def get_models(cls)"
},
{
"docstring": "Get this typeclass's models.",
"name": "get_properties_info",
"signature": "def get_properties_info(cls)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017992 | Implement the Python class `BaseTypeclass` described below.
Class description:
This base typeclass.
Method signatures and docstrings:
- def get_models(cls): Get this typeclass's models.
- def get_properties_info(cls): Get this typeclass's models. | Implement the Python class `BaseTypeclass` described below.
Class description:
This base typeclass.
Method signatures and docstrings:
- def get_models(cls): Get this typeclass's models.
- def get_properties_info(cls): Get this typeclass's models.
<|skeleton|>
class BaseTypeclass:
"""This base typeclass."""
... | 4b4c6c0dc5cc237a5df012a05ed260fad1a793a7 | <|skeleton|>
class BaseTypeclass:
"""This base typeclass."""
def get_models(cls):
"""Get this typeclass's models."""
<|body_0|>
def get_properties_info(cls):
"""Get this typeclass's models."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseTypeclass:
"""This base typeclass."""
def get_models(cls):
"""Get this typeclass's models."""
if '_all_models_' not in cls.__dict__:
cls._all_models_ = []
if cls.typeclass_key:
if not cls.model_name:
raise ValueError("%s's mo... | the_stack_v2_python_sparse | muddery/server/typeclasses/base_typeclass.py | nobodxbodon/muddery | train | 0 |
3ba8924bc5fa0e3a1ba10f25fedf647ea08db318 | [
"super(BERTForICSL, self).__init__(prefix=prefix, params=params)\nself.bert = bert\nwith self.name_scope():\n self.intent_classifier = nn.HybridSequential()\n with self.intent_classifier.name_scope():\n self.intent_classifier.add(nn.Dropout(rate=dropout_prob))\n self.intent_classifier.add(nn.Den... | <|body_start_0|>
super(BERTForICSL, self).__init__(prefix=prefix, params=params)
self.bert = bert
with self.name_scope():
self.intent_classifier = nn.HybridSequential()
with self.intent_classifier.name_scope():
self.intent_classifier.add(nn.Dropout(rate=dr... | Model | BERTForICSL | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BERTForICSL:
"""Model"""
def __init__(self, bert, num_intent_classes, num_slot_classes, dropout_prob, prefix=None, params=None):
"""Parameters ---------- bert : Block num_intent_classes : int num_slot_classes : int dropout_prob : float prefix : None or str params : None or ParamDict"... | stack_v2_sparse_classes_75kplus_train_073786 | 20,404 | permissive | [
{
"docstring": "Parameters ---------- bert : Block num_intent_classes : int num_slot_classes : int dropout_prob : float prefix : None or str params : None or ParamDict",
"name": "__init__",
"signature": "def __init__(self, bert, num_intent_classes, num_slot_classes, dropout_prob, prefix=None, params=Non... | 2 | stack_v2_sparse_classes_30k_train_035601 | Implement the Python class `BERTForICSL` described below.
Class description:
Model
Method signatures and docstrings:
- def __init__(self, bert, num_intent_classes, num_slot_classes, dropout_prob, prefix=None, params=None): Parameters ---------- bert : Block num_intent_classes : int num_slot_classes : int dropout_prob... | Implement the Python class `BERTForICSL` described below.
Class description:
Model
Method signatures and docstrings:
- def __init__(self, bert, num_intent_classes, num_slot_classes, dropout_prob, prefix=None, params=None): Parameters ---------- bert : Block num_intent_classes : int num_slot_classes : int dropout_prob... | ffff7237d2bb73a8a66addc04dee94824976aae0 | <|skeleton|>
class BERTForICSL:
"""Model"""
def __init__(self, bert, num_intent_classes, num_slot_classes, dropout_prob, prefix=None, params=None):
"""Parameters ---------- bert : Block num_intent_classes : int num_slot_classes : int dropout_prob : float prefix : None or str params : None or ParamDict"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BERTForICSL:
"""Model"""
def __init__(self, bert, num_intent_classes, num_slot_classes, dropout_prob, prefix=None, params=None):
"""Parameters ---------- bert : Block num_intent_classes : int num_slot_classes : int dropout_prob : float prefix : None or str params : None or ParamDict"""
su... | the_stack_v2_python_sparse | intent_classification_and_slot_labelling/finetune_icsl.py | eric-haibin-lin/nlp-notebooks | train | 22 |
69e9d3b1df32a7b0114dfdc664460ebf37f437d7 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Service that manages user's ratings of videos | RatingsServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RatingsServiceServicer:
"""Service that manages user's ratings of videos"""
def RateVideo(self, request, context):
"""Rate a video"""
<|body_0|>
def GetRating(self, request, context):
"""Gets the current rating stats for a video"""
<|body_1|>
def Get... | stack_v2_sparse_classes_75kplus_train_073787 | 3,319 | permissive | [
{
"docstring": "Rate a video",
"name": "RateVideo",
"signature": "def RateVideo(self, request, context)"
},
{
"docstring": "Gets the current rating stats for a video",
"name": "GetRating",
"signature": "def GetRating(self, request, context)"
},
{
"docstring": "Gets a user's ratin... | 3 | null | Implement the Python class `RatingsServiceServicer` described below.
Class description:
Service that manages user's ratings of videos
Method signatures and docstrings:
- def RateVideo(self, request, context): Rate a video
- def GetRating(self, request, context): Gets the current rating stats for a video
- def GetUser... | Implement the Python class `RatingsServiceServicer` described below.
Class description:
Service that manages user's ratings of videos
Method signatures and docstrings:
- def RateVideo(self, request, context): Rate a video
- def GetRating(self, request, context): Gets the current rating stats for a video
- def GetUser... | 55a610c97fd53c405edb2459c2722fc03857cb83 | <|skeleton|>
class RatingsServiceServicer:
"""Service that manages user's ratings of videos"""
def RateVideo(self, request, context):
"""Rate a video"""
<|body_0|>
def GetRating(self, request, context):
"""Gets the current rating stats for a video"""
<|body_1|>
def Get... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RatingsServiceServicer:
"""Service that manages user's ratings of videos"""
def RateVideo(self, request, context):
"""Rate a video"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implem... | the_stack_v2_python_sparse | killrvideo/ratings/ratings_service_pb2_grpc.py | krzysztof-adamski/killrvideo-python | train | 0 |
5fea1b69b688322c6e64fbc4afe002af1b92a4fe | [
"flags.GetSpannerMigrationSourceFlag().AddToParser(parser)\nflags.GetSpannerMigrationPrefixFlag().AddToParser(parser)\nflags.GetSpannerMigrationSkipForeignKeysFlag().AddToParser(parser)\nflags.GetSpannerMigrationSourceProfileFlag().AddToParser(parser)\nflags.GetSpannerMigrationTargetFlag().AddToParser(parser)\nflag... | <|body_start_0|>
flags.GetSpannerMigrationSourceFlag().AddToParser(parser)
flags.GetSpannerMigrationPrefixFlag().AddToParser(parser)
flags.GetSpannerMigrationSkipForeignKeysFlag().AddToParser(parser)
flags.GetSpannerMigrationSourceProfileFlag().AddToParser(parser)
flags.GetSpanne... | Migrate data from a source database to Cloud Spanner given a schema. | SchemaAndData | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SchemaAndData:
"""Migrate data from a source database to Cloud Spanner given a schema."""
def Args(parser):
"""Register the flags for this command."""
<|body_0|>
def Run(self, args):
"""Run the schema-and-data command."""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_75kplus_train_073788 | 2,811 | permissive | [
{
"docstring": "Register the flags for this command.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "Run the schema-and-data command.",
"name": "Run",
"signature": "def Run(self, args)"
}
] | 2 | stack_v2_sparse_classes_30k_train_035537 | Implement the Python class `SchemaAndData` described below.
Class description:
Migrate data from a source database to Cloud Spanner given a schema.
Method signatures and docstrings:
- def Args(parser): Register the flags for this command.
- def Run(self, args): Run the schema-and-data command. | Implement the Python class `SchemaAndData` described below.
Class description:
Migrate data from a source database to Cloud Spanner given a schema.
Method signatures and docstrings:
- def Args(parser): Register the flags for this command.
- def Run(self, args): Run the schema-and-data command.
<|skeleton|>
class Sch... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class SchemaAndData:
"""Migrate data from a source database to Cloud Spanner given a schema."""
def Args(parser):
"""Register the flags for this command."""
<|body_0|>
def Run(self, args):
"""Run the schema-and-data command."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SchemaAndData:
"""Migrate data from a source database to Cloud Spanner given a schema."""
def Args(parser):
"""Register the flags for this command."""
flags.GetSpannerMigrationSourceFlag().AddToParser(parser)
flags.GetSpannerMigrationPrefixFlag().AddToParser(parser)
flags.... | the_stack_v2_python_sparse | lib/surface/spanner/migrate/schema_and_data.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
c12cc8edced5c7170aeb97fec5f1cbe1fcb7f283 | [
"Feature.__init__(self)\nafile = join_path(DATA_PATH, 'genres.pkl.bz2'.format(subset))\nafile_mapper = join_path(DATA_PATH, 'track_uri2artist_uri.pkl.bz2'.format(subset))\nif logging:\n print('LOADING GENRE..')\nself.df = cpick.load(afile)\nself.mapper = cpick.load(afile_mapper)\nif logging:\n print('LOADING ... | <|body_start_0|>
Feature.__init__(self)
afile = join_path(DATA_PATH, 'genres.pkl.bz2'.format(subset))
afile_mapper = join_path(DATA_PATH, 'track_uri2artist_uri.pkl.bz2'.format(subset))
if logging:
print('LOADING GENRE..')
self.df = cpick.load(afile)
self.mappe... | GenreFeatures | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenreFeatures:
def __init__(self, subset='', fasttext_path=FASTTEXT_PATH, logging=True):
"""PATH: PATH to your gensim generated word embedding. Default is artist path."""
<|body_0|>
def transform(self, turis):
"""Convert track a list of turis to a vector representati... | stack_v2_sparse_classes_75kplus_train_073789 | 2,939 | no_license | [
{
"docstring": "PATH: PATH to your gensim generated word embedding. Default is artist path.",
"name": "__init__",
"signature": "def __init__(self, subset='', fasttext_path=FASTTEXT_PATH, logging=True)"
},
{
"docstring": "Convert track a list of turis to a vector representation. Input: turis is a... | 2 | null | Implement the Python class `GenreFeatures` described below.
Class description:
Implement the GenreFeatures class.
Method signatures and docstrings:
- def __init__(self, subset='', fasttext_path=FASTTEXT_PATH, logging=True): PATH: PATH to your gensim generated word embedding. Default is artist path.
- def transform(se... | Implement the Python class `GenreFeatures` described below.
Class description:
Implement the GenreFeatures class.
Method signatures and docstrings:
- def __init__(self, subset='', fasttext_path=FASTTEXT_PATH, logging=True): PATH: PATH to your gensim generated word embedding. Default is artist path.
- def transform(se... | 3893795bb08f95bf2e3f86b27adaac12f8145e8f | <|skeleton|>
class GenreFeatures:
def __init__(self, subset='', fasttext_path=FASTTEXT_PATH, logging=True):
"""PATH: PATH to your gensim generated word embedding. Default is artist path."""
<|body_0|>
def transform(self, turis):
"""Convert track a list of turis to a vector representati... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GenreFeatures:
def __init__(self, subset='', fasttext_path=FASTTEXT_PATH, logging=True):
"""PATH: PATH to your gensim generated word embedding. Default is artist path."""
Feature.__init__(self)
afile = join_path(DATA_PATH, 'genres.pkl.bz2'.format(subset))
afile_mapper = join_pa... | the_stack_v2_python_sparse | src/features/genre_features.py | Spandan-Madan/Spotify | train | 8 | |
36d121cf4ab8c4a21fac3cad275776852e5ea7a7 | [
"super().__init__()\nself.fps = fps\nself.m_dims = m_dims\nself.bins = bins\nself.delay = delay\nself.cutter = aseg.Segmentation(n_perseg, n_overlap)\nif pp_params:\n self._ppkr = FilterPeakPicker(**pp_params)\nelse:\n self._ppkr = FilterPeakPicker()",
"segs = self.cutter.transform(inp)\nodf = np.empty((seg... | <|body_start_0|>
super().__init__()
self.fps = fps
self.m_dims = m_dims
self.bins = bins
self.delay = delay
self.cutter = aseg.Segmentation(n_perseg, n_overlap)
if pp_params:
self._ppkr = FilterPeakPicker(**pp_params)
else:
self._pp... | Detect onsets based on entropy maxima. | EntropyOnsetDetector | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EntropyOnsetDetector:
"""Detect onsets based on entropy maxima."""
def __init__(self, fps: int, m_dims: int=3, delay: int=10, bins: int=10, n_perseg: int=1024, n_overlap: int=512, pp_params: Optional[dict]=None) -> None:
"""Detect onsets as local maxima of information entropy of cons... | stack_v2_sparse_classes_75kplus_train_073790 | 8,907 | permissive | [
{
"docstring": "Detect onsets as local maxima of information entropy of consecutive windows. Be sure to set ``n_perseg`` and ``hop_size`` according to the sampling rate of the input signal. Params: fps: Audio signal. m_dim: Embedding dimension. bins: Boxes per axis. delay: Embedding delay. n_perseg: Length of s... | 2 | stack_v2_sparse_classes_30k_train_026485 | Implement the Python class `EntropyOnsetDetector` described below.
Class description:
Detect onsets based on entropy maxima.
Method signatures and docstrings:
- def __init__(self, fps: int, m_dims: int=3, delay: int=10, bins: int=10, n_perseg: int=1024, n_overlap: int=512, pp_params: Optional[dict]=None) -> None: Det... | Implement the Python class `EntropyOnsetDetector` described below.
Class description:
Detect onsets based on entropy maxima.
Method signatures and docstrings:
- def __init__(self, fps: int, m_dims: int=3, delay: int=10, bins: int=10, n_perseg: int=1024, n_overlap: int=512, pp_params: Optional[dict]=None) -> None: Det... | c733591240f3a4d3825d61385bd19262bd76b43b | <|skeleton|>
class EntropyOnsetDetector:
"""Detect onsets based on entropy maxima."""
def __init__(self, fps: int, m_dims: int=3, delay: int=10, bins: int=10, n_perseg: int=1024, n_overlap: int=512, pp_params: Optional[dict]=None) -> None:
"""Detect onsets as local maxima of information entropy of cons... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EntropyOnsetDetector:
"""Detect onsets based on entropy maxima."""
def __init__(self, fps: int, m_dims: int=3, delay: int=10, bins: int=10, n_perseg: int=1024, n_overlap: int=512, pp_params: Optional[dict]=None) -> None:
"""Detect onsets as local maxima of information entropy of consecutive windo... | the_stack_v2_python_sparse | src/apollon/onsets.py | TimZiemer/apollon | train | 0 |
a8f692c5ccc1fb8d13e313b95847776a77df2470 | [
"s = s.strip()\nif not s:\n return 0\nsign = -1 if s[0] == '-' else 1\nval = 0\nfor c in s:\n if c.isdigit():\n val = val * 10 + ord(c) - ord('0')\nreturn sign * val",
"s = s.strip()\nif not s:\n return 0\nsign = -1 if s[0] == '-' else 1\nval, index = (0, 0)\nif s[0] in ['+', '-']:\n index = 1\... | <|body_start_0|>
s = s.strip()
if not s:
return 0
sign = -1 if s[0] == '-' else 1
val = 0
for c in s:
if c.isdigit():
val = val * 10 + ord(c) - ord('0')
return sign * val
<|end_body_0|>
<|body_start_1|>
s = s.strip()
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def myAtoi(self, s):
""":type str: str :rtype: int This is the sane version of the Idea ATOI where illegal chars in the given string 's' are ignored as one would. The version leetcode required was to quit when an illegal char is encountered and can be found here https://discuss... | stack_v2_sparse_classes_75kplus_train_073791 | 1,416 | no_license | [
{
"docstring": ":type str: str :rtype: int This is the sane version of the Idea ATOI where illegal chars in the given string 's' are ignored as one would. The version leetcode required was to quit when an illegal char is encountered and can be found here https://discuss.leetcode.com/topic/26920/60ms-python-solu... | 2 | stack_v2_sparse_classes_30k_train_028047 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myAtoi(self, s): :type str: str :rtype: int This is the sane version of the Idea ATOI where illegal chars in the given string 's' are ignored as one would. The version leetco... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myAtoi(self, s): :type str: str :rtype: int This is the sane version of the Idea ATOI where illegal chars in the given string 's' are ignored as one would. The version leetco... | 57212d700dfba0db4925d9d4896f7f0b9635a5b5 | <|skeleton|>
class Solution:
def myAtoi(self, s):
""":type str: str :rtype: int This is the sane version of the Idea ATOI where illegal chars in the given string 's' are ignored as one would. The version leetcode required was to quit when an illegal char is encountered and can be found here https://discuss... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def myAtoi(self, s):
""":type str: str :rtype: int This is the sane version of the Idea ATOI where illegal chars in the given string 's' are ignored as one would. The version leetcode required was to quit when an illegal char is encountered and can be found here https://discuss.leetcode.com/... | the_stack_v2_python_sparse | atoi.py | baloooo/coding_practice | train | 0 | |
925728d2e77969ec05442d537a08d16b4526c9e7 | [
"self.row_selection = row\nself.col_selection = col\nself.cutoff = None\nself.row_group = None\nself.col_group = None\nself.shift = None\nself.isInitialized = False\nself.byres = False\nself.reducer = np.any\nself.filter = None\nself.n_residues = None\nself.atom2res = list()\n'\\n #One example of filtering c... | <|body_start_0|>
self.row_selection = row
self.col_selection = col
self.cutoff = None
self.row_group = None
self.col_group = None
self.shift = None
self.isInitialized = False
self.byres = False
self.reducer = np.any
self.filter = None
... | Rules to generate a contact map between two sets of atoms | ContactMapProtocol | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContactMapProtocol:
"""Rules to generate a contact map between two sets of atoms"""
def __init__(self, row=None, col=None, **kwargs):
"""Instantiate the various attributes :param row: atom selection string for the row index of the Contact map :param col: atom selection string for the... | stack_v2_sparse_classes_75kplus_train_073792 | 11,614 | no_license | [
{
"docstring": "Instantiate the various attributes :param row: atom selection string for the row index of the Contact map :param col: atom selection string for the column index of the Contact map :param kwargs: additional arguments to update self.__dict__",
"name": "__init__",
"signature": "def __init__... | 2 | null | Implement the Python class `ContactMapProtocol` described below.
Class description:
Rules to generate a contact map between two sets of atoms
Method signatures and docstrings:
- def __init__(self, row=None, col=None, **kwargs): Instantiate the various attributes :param row: atom selection string for the row index of ... | Implement the Python class `ContactMapProtocol` described below.
Class description:
Rules to generate a contact map between two sets of atoms
Method signatures and docstrings:
- def __init__(self, row=None, col=None, **kwargs): Instantiate the various attributes :param row: atom selection string for the row index of ... | 32720b57699bf01803367566cdc5fff2b6bce810 | <|skeleton|>
class ContactMapProtocol:
"""Rules to generate a contact map between two sets of atoms"""
def __init__(self, row=None, col=None, **kwargs):
"""Instantiate the various attributes :param row: atom selection string for the row index of the Contact map :param col: atom selection string for the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ContactMapProtocol:
"""Rules to generate a contact map between two sets of atoms"""
def __init__(self, row=None, col=None, **kwargs):
"""Instantiate the various attributes :param row: atom selection string for the row index of the Contact map :param col: atom selection string for the column index... | the_stack_v2_python_sparse | python/myMDAnalysis/ContactMapAnalysis/ContactMapAnalysisAPI.py | jmborr/code | train | 0 |
c85dc4ee458c38a2bd3a8826419bc0d5d8c3bd57 | [
"for user, tenant_id in self._iterate_per_tenants():\n senlin_scenario = senlin_utils.SenlinScenario({'user': user, 'task': self.context['task']})\n profile = senlin_scenario._create_profile(self.config)\n self.context['tenants'][tenant_id]['profile'] = profile.id",
"for user, tenant_id in self._iterate_... | <|body_start_0|>
for user, tenant_id in self._iterate_per_tenants():
senlin_scenario = senlin_utils.SenlinScenario({'user': user, 'task': self.context['task']})
profile = senlin_scenario._create_profile(self.config)
self.context['tenants'][tenant_id]['profile'] = profile.id
<... | Context creates a temporary profile for Senlin test. | ProfilesGenerator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfilesGenerator:
"""Context creates a temporary profile for Senlin test."""
def setup(self):
"""Create test profiles."""
<|body_0|>
def cleanup(self):
"""Delete created test profiles."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for user, t... | stack_v2_sparse_classes_75kplus_train_073793 | 2,305 | permissive | [
{
"docstring": "Create test profiles.",
"name": "setup",
"signature": "def setup(self)"
},
{
"docstring": "Delete created test profiles.",
"name": "cleanup",
"signature": "def cleanup(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_033612 | Implement the Python class `ProfilesGenerator` described below.
Class description:
Context creates a temporary profile for Senlin test.
Method signatures and docstrings:
- def setup(self): Create test profiles.
- def cleanup(self): Delete created test profiles. | Implement the Python class `ProfilesGenerator` described below.
Class description:
Context creates a temporary profile for Senlin test.
Method signatures and docstrings:
- def setup(self): Create test profiles.
- def cleanup(self): Delete created test profiles.
<|skeleton|>
class ProfilesGenerator:
"""Context cr... | 9ff67887bf848c5966bb4a2f37018500d30dbe45 | <|skeleton|>
class ProfilesGenerator:
"""Context creates a temporary profile for Senlin test."""
def setup(self):
"""Create test profiles."""
<|body_0|>
def cleanup(self):
"""Delete created test profiles."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProfilesGenerator:
"""Context creates a temporary profile for Senlin test."""
def setup(self):
"""Create test profiles."""
for user, tenant_id in self._iterate_per_tenants():
senlin_scenario = senlin_utils.SenlinScenario({'user': user, 'task': self.context['task']})
... | the_stack_v2_python_sparse | rally_openstack/task/contexts/senlin/profiles.py | openstack/rally-openstack | train | 41 |
3e0d46b3d458357cd1bd17242ffcfd3e598e7d64 | [
"def test_case_with_logging(*args, **kwargs):\n \"\"\"Wraps the test cases and add a stream handler for logging\n \"\"\"\n stream_handler = StreamHandler(sys.stdout)\n package_filter = PackageLogFilter(packages=[os.path.basename(os.path.abspath(os.curdir))])\n stream_handler.addFilter(package... | <|body_start_0|>
def test_case_with_logging(*args, **kwargs):
"""Wraps the test cases and add a stream handler for logging
"""
stream_handler = StreamHandler(sys.stdout)
package_filter = PackageLogFilter(packages=[os.path.basename(os.path.abspath(os.curdir... | Customized TestCase: 1. A stream handler is added to the root logger to output debug messages. 2. Test outputs are buffered. Outputs for passing tests are discard. Only outputs for failed tests will be displayed. By default, the steam handler will be added to the root logger. This can be changed by override the "logger... | AriesTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AriesTest:
"""Customized TestCase: 1. A stream handler is added to the root logger to output debug messages. 2. Test outputs are buffered. Outputs for passing tests are discard. Only outputs for failed tests will be displayed. By default, the steam handler will be added to the root logger. This c... | stack_v2_sparse_classes_75kplus_train_073794 | 4,342 | permissive | [
{
"docstring": "A decorator for test case. 1. Adds additional logging handler to test case so that logging will be streamed to stdout. 2. Set logger level to DEBUG Args: func: test case function. Returns: A function.",
"name": "__decorate_test_case",
"signature": "def __decorate_test_case(cls, func)"
... | 3 | stack_v2_sparse_classes_30k_test_000177 | Implement the Python class `AriesTest` described below.
Class description:
Customized TestCase: 1. A stream handler is added to the root logger to output debug messages. 2. Test outputs are buffered. Outputs for passing tests are discard. Only outputs for failed tests will be displayed. By default, the steam handler w... | Implement the Python class `AriesTest` described below.
Class description:
Customized TestCase: 1. A stream handler is added to the root logger to output debug messages. 2. Test outputs are buffered. Outputs for passing tests are discard. Only outputs for failed tests will be displayed. By default, the steam handler w... | 62f66d69ff00af37368a87f41dda8e7be042f119 | <|skeleton|>
class AriesTest:
"""Customized TestCase: 1. A stream handler is added to the root logger to output debug messages. 2. Test outputs are buffered. Outputs for passing tests are discard. Only outputs for failed tests will be displayed. By default, the steam handler will be added to the root logger. This c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AriesTest:
"""Customized TestCase: 1. A stream handler is added to the root logger to output debug messages. 2. Test outputs are buffered. Outputs for passing tests are discard. Only outputs for failed tests will be displayed. By default, the steam handler will be added to the root logger. This can be changed... | the_stack_v2_python_sparse | test.py | qiuosier/Aries | train | 5 |
d9d1c28b357f32864c12b653072b0fbc322c04b1 | [
"customer_obj = Customer.objects.filter(pk=c_id).first()\nforms = CustomerModelForm(request, instance=customer_obj)\nreturn render(request, 'add_edit_customer.html', {'forms': forms, 'customer_obj': customer_obj})",
"customer_obj = Customer.objects.filter(pk=c_id).first()\nforms = CustomerModelForm(request, data=... | <|body_start_0|>
customer_obj = Customer.objects.filter(pk=c_id).first()
forms = CustomerModelForm(request, instance=customer_obj)
return render(request, 'add_edit_customer.html', {'forms': forms, 'customer_obj': customer_obj})
<|end_body_0|>
<|body_start_1|>
customer_obj = Customer.obj... | 添加,编辑客户 | AddEditCustomerView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddEditCustomerView:
"""添加,编辑客户"""
def get(self, request, c_id=None):
"""添加/编辑客户页面 :param request: :param c_id: :return:"""
<|body_0|>
def post(self, request, c_id=None):
"""提交添加/编辑页面数据 :param request: :param c_id: 编辑的客户id :return:"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus_train_073795 | 9,537 | no_license | [
{
"docstring": "添加/编辑客户页面 :param request: :param c_id: :return:",
"name": "get",
"signature": "def get(self, request, c_id=None)"
},
{
"docstring": "提交添加/编辑页面数据 :param request: :param c_id: 编辑的客户id :return:",
"name": "post",
"signature": "def post(self, request, c_id=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_045398 | Implement the Python class `AddEditCustomerView` described below.
Class description:
添加,编辑客户
Method signatures and docstrings:
- def get(self, request, c_id=None): 添加/编辑客户页面 :param request: :param c_id: :return:
- def post(self, request, c_id=None): 提交添加/编辑页面数据 :param request: :param c_id: 编辑的客户id :return: | Implement the Python class `AddEditCustomerView` described below.
Class description:
添加,编辑客户
Method signatures and docstrings:
- def get(self, request, c_id=None): 添加/编辑客户页面 :param request: :param c_id: :return:
- def post(self, request, c_id=None): 提交添加/编辑页面数据 :param request: :param c_id: 编辑的客户id :return:
<|skeleto... | 7fe6cd16f45750fbfed0082eae57d5877e85c4e5 | <|skeleton|>
class AddEditCustomerView:
"""添加,编辑客户"""
def get(self, request, c_id=None):
"""添加/编辑客户页面 :param request: :param c_id: :return:"""
<|body_0|>
def post(self, request, c_id=None):
"""提交添加/编辑页面数据 :param request: :param c_id: 编辑的客户id :return:"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AddEditCustomerView:
"""添加,编辑客户"""
def get(self, request, c_id=None):
"""添加/编辑客户页面 :param request: :param c_id: :return:"""
customer_obj = Customer.objects.filter(pk=c_id).first()
forms = CustomerModelForm(request, instance=customer_obj)
return render(request, 'add_edit_cu... | the_stack_v2_python_sparse | app01/views.py | ITzhang/CRM-Django | train | 0 |
b459bd01991ea70b519f992cd26bf277c9037df9 | [
"if the_date is None:\n the_date = datetime.date.today()\nreturn self.get_queryset().filter(year__lte=the_date.year - 1, month__isnull=True).order_by('-year').first()",
"if year is None:\n year = datetime.date.today().year\nreturn self.get_queryset().filter(year__lte=year - 1, month__isnull=True).order_by('... | <|body_start_0|>
if the_date is None:
the_date = datetime.date.today()
return self.get_queryset().filter(year__lte=the_date.year - 1, month__isnull=True).order_by('-year').first()
<|end_body_0|>
<|body_start_1|>
if year is None:
year = datetime.date.today().year
... | IndexManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IndexManager:
def get_latest_for_date(self, the_date=None):
"""Returns the latest year average index"""
<|body_0|>
def get_latest_for_year(self, year=None):
"""Returns the latest year average index for year"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_073796 | 35,874 | permissive | [
{
"docstring": "Returns the latest year average index",
"name": "get_latest_for_date",
"signature": "def get_latest_for_date(self, the_date=None)"
},
{
"docstring": "Returns the latest year average index for year",
"name": "get_latest_for_year",
"signature": "def get_latest_for_year(self... | 2 | stack_v2_sparse_classes_30k_train_010358 | Implement the Python class `IndexManager` described below.
Class description:
Implement the IndexManager class.
Method signatures and docstrings:
- def get_latest_for_date(self, the_date=None): Returns the latest year average index
- def get_latest_for_year(self, year=None): Returns the latest year average index for ... | Implement the Python class `IndexManager` described below.
Class description:
Implement the IndexManager class.
Method signatures and docstrings:
- def get_latest_for_date(self, the_date=None): Returns the latest year average index
- def get_latest_for_year(self, year=None): Returns the latest year average index for ... | b467c6229f9d458d56b66f628b0841adb67a2970 | <|skeleton|>
class IndexManager:
def get_latest_for_date(self, the_date=None):
"""Returns the latest year average index"""
<|body_0|>
def get_latest_for_year(self, year=None):
"""Returns the latest year average index for year"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IndexManager:
def get_latest_for_date(self, the_date=None):
"""Returns the latest year average index"""
if the_date is None:
the_date = datetime.date.today()
return self.get_queryset().filter(year__lte=the_date.year - 1, month__isnull=True).order_by('-year').first()
de... | the_stack_v2_python_sparse | leasing/models/rent.py | igordavydsson/mvj | train | 0 | |
0c9b75fb2b361fc1b82d3c8360ea5a77244597f1 | [
"if item.collection_name == 'youyaoqi':\n yield Request(item['cover'])\nelse:\n pass",
"url = request.url\nfile_name = url.split('/')[-1]\nreturn file_name",
"image_paths = [x['path'] for ok, x in results if ok]\nif not image_paths:\n raise DropItem('Image Downloaded Failed')\nreturn item"
] | <|body_start_0|>
if item.collection_name == 'youyaoqi':
yield Request(item['cover'])
else:
pass
<|end_body_0|>
<|body_start_1|>
url = request.url
file_name = url.split('/')[-1]
return file_name
<|end_body_1|>
<|body_start_2|>
image_paths = [x['pa... | 构造一个图片管道类 | YouyaoqiImgPipeline | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class YouyaoqiImgPipeline:
"""构造一个图片管道类"""
def get_media_requests(self, item, info=None):
"""指明图片下载链接,包装成request对象"""
<|body_0|>
def file_path(self, request, response=None, info=None):
"""生成下载下来的图片的文件名"""
<|body_1|>
def item_completed(self, results, item, ... | stack_v2_sparse_classes_75kplus_train_073797 | 3,316 | no_license | [
{
"docstring": "指明图片下载链接,包装成request对象",
"name": "get_media_requests",
"signature": "def get_media_requests(self, item, info=None)"
},
{
"docstring": "生成下载下来的图片的文件名",
"name": "file_path",
"signature": "def file_path(self, request, response=None, info=None)"
},
{
"docstring": "判断图片... | 3 | null | Implement the Python class `YouyaoqiImgPipeline` described below.
Class description:
构造一个图片管道类
Method signatures and docstrings:
- def get_media_requests(self, item, info=None): 指明图片下载链接,包装成request对象
- def file_path(self, request, response=None, info=None): 生成下载下来的图片的文件名
- def item_completed(self, results, item, info... | Implement the Python class `YouyaoqiImgPipeline` described below.
Class description:
构造一个图片管道类
Method signatures and docstrings:
- def get_media_requests(self, item, info=None): 指明图片下载链接,包装成request对象
- def file_path(self, request, response=None, info=None): 生成下载下来的图片的文件名
- def item_completed(self, results, item, info... | e812eb63fe5db402f79961f4c1d00d31c851a689 | <|skeleton|>
class YouyaoqiImgPipeline:
"""构造一个图片管道类"""
def get_media_requests(self, item, info=None):
"""指明图片下载链接,包装成request对象"""
<|body_0|>
def file_path(self, request, response=None, info=None):
"""生成下载下来的图片的文件名"""
<|body_1|>
def item_completed(self, results, item, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class YouyaoqiImgPipeline:
"""构造一个图片管道类"""
def get_media_requests(self, item, info=None):
"""指明图片下载链接,包装成request对象"""
if item.collection_name == 'youyaoqi':
yield Request(item['cover'])
else:
pass
def file_path(self, request, response=None, info=None):
... | the_stack_v2_python_sparse | scrapy项目/youyaoqi/youyaoqi/pipelines.py | Huigehao/python-spiders | train | 1 |
3d14c30c66305bf99117a896ed69b8d0cd701f4f | [
"signals = []\nfor candle in self.candles:\n candles_df = self.get_processed_df(candle.candles_df)\n last_row = candles_df.iloc[-1]\n sma_rsi_normalized = -1 * (last_row['RSI_21_SMA_10'].item() - 50) / 50\n bb_percentage_normalized = -1 * (last_row['BBP_21_2.0'].item() - 0.5) / 0.5\n signal_value = (... | <|body_start_0|>
signals = []
for candle in self.candles:
candles_df = self.get_processed_df(candle.candles_df)
last_row = candles_df.iloc[-1]
sma_rsi_normalized = -1 * (last_row['RSI_21_SMA_10'].item() - 50) / 50
bb_percentage_normalized = -1 * (last_row[... | MultiTimeframeBBRSI strategy implementation based on the DirectionalStrategyBase. This strategy combines multiple timeframes of Bollinger Bands (BB) and Relative Strength Index (RSI) indicators to generate trading signals and execute trades based on the composed signal value. It defines the specific parameters and conf... | MultiTimeframeBBRSI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiTimeframeBBRSI:
"""MultiTimeframeBBRSI strategy implementation based on the DirectionalStrategyBase. This strategy combines multiple timeframes of Bollinger Bands (BB) and Relative Strength Index (RSI) indicators to generate trading signals and execute trades based on the composed signal val... | stack_v2_sparse_classes_75kplus_train_073798 | 5,708 | permissive | [
{
"docstring": "Generates the trading signal based on the composed signal value from multiple timeframes. Returns: int: The trading signal (-1 for sell, 0 for hold, 1 for buy).",
"name": "get_signal",
"signature": "def get_signal(self)"
},
{
"docstring": "Retrieves the processed dataframe with B... | 3 | stack_v2_sparse_classes_30k_train_005513 | Implement the Python class `MultiTimeframeBBRSI` described below.
Class description:
MultiTimeframeBBRSI strategy implementation based on the DirectionalStrategyBase. This strategy combines multiple timeframes of Bollinger Bands (BB) and Relative Strength Index (RSI) indicators to generate trading signals and execute ... | Implement the Python class `MultiTimeframeBBRSI` described below.
Class description:
MultiTimeframeBBRSI strategy implementation based on the DirectionalStrategyBase. This strategy combines multiple timeframes of Bollinger Bands (BB) and Relative Strength Index (RSI) indicators to generate trading signals and execute ... | c3f101759ab7e7a2165cd23a3a3e94c90c642a9b | <|skeleton|>
class MultiTimeframeBBRSI:
"""MultiTimeframeBBRSI strategy implementation based on the DirectionalStrategyBase. This strategy combines multiple timeframes of Bollinger Bands (BB) and Relative Strength Index (RSI) indicators to generate trading signals and execute trades based on the composed signal val... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiTimeframeBBRSI:
"""MultiTimeframeBBRSI strategy implementation based on the DirectionalStrategyBase. This strategy combines multiple timeframes of Bollinger Bands (BB) and Relative Strength Index (RSI) indicators to generate trading signals and execute trades based on the composed signal value. It define... | the_stack_v2_python_sparse | scripts/directional_strategy_bb_rsi_multi_timeframe.py | CoinAlpha/hummingbot | train | 135 |
0fcd1ba56648690953e55bef6368ddbf3332ca88 | [
"n = len(nums) - 1\nwhile k > 0:\n temp = nums[-1]\n for j in range(n, 0, -1):\n nums[j] = nums[j - 1]\n nums[0] = temp\n k -= 1\nprint(nums)",
"k %= len(nums)\nnums[:] = nums[::-1]\nnums[:k] = nums[:k][::-1]\nnums[k:] = nums[k:][::-1]\nprint(nums)"
] | <|body_start_0|>
n = len(nums) - 1
while k > 0:
temp = nums[-1]
for j in range(n, 0, -1):
nums[j] = nums[j - 1]
nums[0] = temp
k -= 1
print(nums)
<|end_body_0|>
<|body_start_1|>
k %= len(nums)
nums[:] = nums[::-1]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate(self, nums, k):
"""暴力法,时间复杂度O(n^k),空间复杂度O(1) :type nums: List[int] :type k: int :rtype: None Do not return anything, modify nums in-place instead."""
<|body_0|>
def rotate2(self, nums, k):
"""反转法,时间复杂度O(n),空间复杂度O(1) :type nums: List[int] :type k:... | stack_v2_sparse_classes_75kplus_train_073799 | 1,646 | no_license | [
{
"docstring": "暴力法,时间复杂度O(n^k),空间复杂度O(1) :type nums: List[int] :type k: int :rtype: None Do not return anything, modify nums in-place instead.",
"name": "rotate",
"signature": "def rotate(self, nums, k)"
},
{
"docstring": "反转法,时间复杂度O(n),空间复杂度O(1) :type nums: List[int] :type k: int :rtype: None ... | 2 | stack_v2_sparse_classes_30k_train_038070 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums, k): 暴力法,时间复杂度O(n^k),空间复杂度O(1) :type nums: List[int] :type k: int :rtype: None Do not return anything, modify nums in-place instead.
- def rotate2(self, num... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums, k): 暴力法,时间复杂度O(n^k),空间复杂度O(1) :type nums: List[int] :type k: int :rtype: None Do not return anything, modify nums in-place instead.
- def rotate2(self, num... | f564806bd8e18831eeb20f2fd4bdd2d4aaa829ce | <|skeleton|>
class Solution:
def rotate(self, nums, k):
"""暴力法,时间复杂度O(n^k),空间复杂度O(1) :type nums: List[int] :type k: int :rtype: None Do not return anything, modify nums in-place instead."""
<|body_0|>
def rotate2(self, nums, k):
"""反转法,时间复杂度O(n),空间复杂度O(1) :type nums: List[int] :type k:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def rotate(self, nums, k):
"""暴力法,时间复杂度O(n^k),空间复杂度O(1) :type nums: List[int] :type k: int :rtype: None Do not return anything, modify nums in-place instead."""
n = len(nums) - 1
while k > 0:
temp = nums[-1]
for j in range(n, 0, -1):
nu... | the_stack_v2_python_sparse | Week 01/id_684/LeetCode_189_684.py | cboopen/algorithm004-04 | train | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.