blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e5cc2bd1aac5a5ae339a5003a638bd63a7cf0bc8 | [
"super().__init__()\nself.from_layout = from_layout\nself.to_layout = to_layout\nif isinstance(coupling_map, Target):\n self.target = coupling_map\n self.coupling_map = self.target.build_coupling_map()\nelse:\n self.target = None\n self.coupling_map = coupling_map\nif self.coupling_map is None:\n sel... | <|body_start_0|>
super().__init__()
self.from_layout = from_layout
self.to_layout = to_layout
if isinstance(coupling_map, Target):
self.target = coupling_map
self.coupling_map = self.target.build_coupling_map()
else:
self.target = None
... | Adds a Swap circuit for a given (partial) permutation to the circuit. This circuit is found by a 4-approximation algorithm for Token Swapping. More details are available in the routing code. | LayoutTransformation | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LayoutTransformation:
"""Adds a Swap circuit for a given (partial) permutation to the circuit. This circuit is found by a 4-approximation algorithm for Token Swapping. More details are available in the routing code."""
def __init__(self, coupling_map: CouplingMap | Target | None, from_layout... | stack_v2_sparse_classes_36k_train_023100 | 4,636 | permissive | [
{
"docstring": "LayoutTransformation initializer. Args: coupling_map: Directed graph representing a coupling map. from_layout (Union[Layout, str]): The starting layout of qubits onto physical qubits. If the type is str, look up `property_set` when this pass runs. to_layout (Union[Layout, str]): The final layout... | 2 | null | Implement the Python class `LayoutTransformation` described below.
Class description:
Adds a Swap circuit for a given (partial) permutation to the circuit. This circuit is found by a 4-approximation algorithm for Token Swapping. More details are available in the routing code.
Method signatures and docstrings:
- def _... | Implement the Python class `LayoutTransformation` described below.
Class description:
Adds a Swap circuit for a given (partial) permutation to the circuit. This circuit is found by a 4-approximation algorithm for Token Swapping. More details are available in the routing code.
Method signatures and docstrings:
- def _... | 0b51250e219ca303654fc28a318c21366584ccd3 | <|skeleton|>
class LayoutTransformation:
"""Adds a Swap circuit for a given (partial) permutation to the circuit. This circuit is found by a 4-approximation algorithm for Token Swapping. More details are available in the routing code."""
def __init__(self, coupling_map: CouplingMap | Target | None, from_layout... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LayoutTransformation:
"""Adds a Swap circuit for a given (partial) permutation to the circuit. This circuit is found by a 4-approximation algorithm for Token Swapping. More details are available in the routing code."""
def __init__(self, coupling_map: CouplingMap | Target | None, from_layout: Layout | st... | the_stack_v2_python_sparse | qiskit/transpiler/passes/routing/layout_transformation.py | 1ucian0/qiskit-terra | train | 6 |
15f653a284dadeca37efc9ab6238865f0db0998a | [
"self.deg, self.ntheta, self.nphi = (deg, ntheta, nphi)\nif self.ntheta < deg:\n self.ntheta = deg\nif self.nphi < 2 * deg - 1:\n self.nphi = 2 * deg - 1\nself.thetas, self.weights = quad.gaussleg(self.ntheta)",
"if forward:\n cscale = (1j ** (i % 4) for i in range(1, self.deg + 1))\nelse:\n cscale = ... | <|body_start_0|>
self.deg, self.ntheta, self.nphi = (deg, ntheta, nphi)
if self.ntheta < deg:
self.ntheta = deg
if self.nphi < 2 * deg - 1:
self.nphi = 2 * deg - 1
self.thetas, self.weights = quad.gaussleg(self.ntheta)
<|end_body_0|>
<|body_start_1|>
if f... | Encapsulates a spherical harmonic transform to convert between spherical harmonic coefficients and plane-wave coefficients. | SHTransform | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SHTransform:
"""Encapsulates a spherical harmonic transform to convert between spherical harmonic coefficients and plane-wave coefficients."""
def __init__(self, deg, ntheta=0, nphi=0):
"""Establishes a harmonic transform between coefficients of maximum degree deg with ntheta polar a... | stack_v2_sparse_classes_36k_train_023101 | 4,016 | permissive | [
{
"docstring": "Establishes a harmonic transform between coefficients of maximum degree deg with ntheta polar and nphi azimuthal angular samples.",
"name": "__init__",
"signature": "def __init__(self, deg, ntheta=0, nphi=0)"
},
{
"docstring": "Scale the spherical harmonic coefficients to relate ... | 4 | null | Implement the Python class `SHTransform` described below.
Class description:
Encapsulates a spherical harmonic transform to convert between spherical harmonic coefficients and plane-wave coefficients.
Method signatures and docstrings:
- def __init__(self, deg, ntheta=0, nphi=0): Establishes a harmonic transform betwe... | Implement the Python class `SHTransform` described below.
Class description:
Encapsulates a spherical harmonic transform to convert between spherical harmonic coefficients and plane-wave coefficients.
Method signatures and docstrings:
- def __init__(self, deg, ntheta=0, nphi=0): Establishes a harmonic transform betwe... | 5fabc9c1f410bf49b674bfb4427fe1f05ad251ed | <|skeleton|>
class SHTransform:
"""Encapsulates a spherical harmonic transform to convert between spherical harmonic coefficients and plane-wave coefficients."""
def __init__(self, deg, ntheta=0, nphi=0):
"""Establishes a harmonic transform between coefficients of maximum degree deg with ntheta polar a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SHTransform:
"""Encapsulates a spherical harmonic transform to convert between spherical harmonic coefficients and plane-wave coefficients."""
def __init__(self, deg, ntheta=0, nphi=0):
"""Establishes a harmonic transform between coefficients of maximum degree deg with ntheta polar and nphi azimu... | the_stack_v2_python_sparse | pycwp/shtransform.py | ahesford/pycwp | train | 0 |
667426322e8b20be95be8415c8b544312fa8f4f5 | [
"q = g.session.query(db.Role)\nauth_org_id = self.obtain_organization_id()\nargs = request.args\norg_filters = args.getlist('organization_id')\nif org_filters:\n if 'include_root' in args and args['include_root']:\n q = q.filter(or_(db.Role.organization_id.in_(org_filters), db.Role.organization_id == None... | <|body_start_0|>
q = g.session.query(db.Role)
auth_org_id = self.obtain_organization_id()
args = request.args
org_filters = args.getlist('organization_id')
if org_filters:
if 'include_root' in args and args['include_root']:
q = q.filter(or_(db.Role.org... | Roles | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Roles:
def get(self):
"""Returns a list of roles --- description: >- Returns a list of roles. Depending on your permission, you get all the roles at the server or only the roles that belong to your organization. ### Permission Table |Rule name|Scope|Operation|Assigned to node|Assigned to... | stack_v2_sparse_classes_36k_train_023102 | 26,260 | permissive | [
{
"docstring": "Returns a list of roles --- description: >- Returns a list of roles. Depending on your permission, you get all the roles at the server or only the roles that belong to your organization. ### Permission Table |Rule name|Scope|Operation|Assigned to node|Assigned to container| Description| |--|--|-... | 2 | stack_v2_sparse_classes_30k_train_000592 | Implement the Python class `Roles` described below.
Class description:
Implement the Roles class.
Method signatures and docstrings:
- def get(self): Returns a list of roles --- description: >- Returns a list of roles. Depending on your permission, you get all the roles at the server or only the roles that belong to y... | Implement the Python class `Roles` described below.
Class description:
Implement the Roles class.
Method signatures and docstrings:
- def get(self): Returns a list of roles --- description: >- Returns a list of roles. Depending on your permission, you get all the roles at the server or only the roles that belong to y... | b3ff6e91ac4caeaf31c12c20f73dfc61cfd9baca | <|skeleton|>
class Roles:
def get(self):
"""Returns a list of roles --- description: >- Returns a list of roles. Depending on your permission, you get all the roles at the server or only the roles that belong to your organization. ### Permission Table |Rule name|Scope|Operation|Assigned to node|Assigned to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Roles:
def get(self):
"""Returns a list of roles --- description: >- Returns a list of roles. Depending on your permission, you get all the roles at the server or only the roles that belong to your organization. ### Permission Table |Rule name|Scope|Operation|Assigned to node|Assigned to container| De... | the_stack_v2_python_sparse | vantage6-server/vantage6/server/resource/role.py | vantage6/vantage6 | train | 15 | |
74e5c00dc399a0e241c416a4322a12f8a3d93523 | [
"ny = Basket.create_from_string('New York')\nnyc = Basket.create_from_string('New York City')\nself.assertEqual(Basket.objects.count(), 2)\nmerged = merge_baskets(ny, nyc)\nself.assertEqual(Basket.objects.count(), 1)\nself.assertEqual(merged.topic_hits.count(), 2)",
"ny = Basket.create_from_string('New York')\nny... | <|body_start_0|>
ny = Basket.create_from_string('New York')
nyc = Basket.create_from_string('New York City')
self.assertEqual(Basket.objects.count(), 2)
merged = merge_baskets(ny, nyc)
self.assertEqual(Basket.objects.count(), 1)
self.assertEqual(merged.topic_hits.count(),... | MergeTests | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MergeTests:
def test_basic_merge(self):
"""Creates two separate baskets. Merging should create only one basket"""
<|body_0|>
def test_merge_with_baskets_related_to_each_other(self):
"""If you merge two baskets related to each other, the relation between them should b... | stack_v2_sparse_classes_36k_train_023103 | 11,225 | permissive | [
{
"docstring": "Creates two separate baskets. Merging should create only one basket",
"name": "test_basic_merge",
"signature": "def test_basic_merge(self)"
},
{
"docstring": "If you merge two baskets related to each other, the relation between them should be deleted",
"name": "test_merge_wit... | 6 | null | Implement the Python class `MergeTests` described below.
Class description:
Implement the MergeTests class.
Method signatures and docstrings:
- def test_basic_merge(self): Creates two separate baskets. Merging should create only one basket
- def test_merge_with_baskets_related_to_each_other(self): If you merge two ba... | Implement the Python class `MergeTests` described below.
Class description:
Implement the MergeTests class.
Method signatures and docstrings:
- def test_basic_merge(self): Creates two separate baskets. Merging should create only one basket
- def test_merge_with_baskets_related_to_each_other(self): If you merge two ba... | 07455a660fb2cb8bc91a54f7f12d150923678157 | <|skeleton|>
class MergeTests:
def test_basic_merge(self):
"""Creates two separate baskets. Merging should create only one basket"""
<|body_0|>
def test_merge_with_baskets_related_to_each_other(self):
"""If you merge two baskets related to each other, the relation between them should b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MergeTests:
def test_basic_merge(self):
"""Creates two separate baskets. Merging should create only one basket"""
ny = Basket.create_from_string('New York')
nyc = Basket.create_from_string('New York City')
self.assertEqual(Basket.objects.count(), 2)
merged = merge_baske... | the_stack_v2_python_sparse | otcore/hit/tests.py | NYULibraries/dlts-enm-tct-backend | train | 0 | |
f92a4dab1f91439884e39972da495684ad0c8c11 | [
"assert n_stages % 2 == 0\nself.n_stages = n_stages\nself.mu0 = mu0\nself.sigma0 = sigma0\nself.sigma_tilde = sigma_tilde\nself.epsilon = epsilon\nself.internal_env = IndependentBinomialBridge(n_stages, mu0, sigma0)\nself.posterior = copy.deepcopy(self.internal_env.graph)\nfor start_node in self.posterior:\n for... | <|body_start_0|>
assert n_stages % 2 == 0
self.n_stages = n_stages
self.mu0 = mu0
self.sigma0 = sigma0
self.sigma_tilde = sigma_tilde
self.epsilon = epsilon
self.internal_env = IndependentBinomialBridge(n_stages, mu0, sigma0)
self.posterior = copy.deepcopy... | Independent Binomial Bridge Epsilon Greedy | IndependentBBEpsilonGreedy | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IndependentBBEpsilonGreedy:
"""Independent Binomial Bridge Epsilon Greedy"""
def __init__(self, n_stages, mu0, sigma0, sigma_tilde, epsilon=0.0):
"""An agent for graph bandits. Args: n_stages - number of stages of the binomial bridge (must be even) mu0 - prior mean sigma0 - prior std... | stack_v2_sparse_classes_36k_train_023104 | 5,536 | permissive | [
{
"docstring": "An agent for graph bandits. Args: n_stages - number of stages of the binomial bridge (must be even) mu0 - prior mean sigma0 - prior stddev sigma_tilde - noise on observation epsilon - probability of random path selection",
"name": "__init__",
"signature": "def __init__(self, n_stages, mu... | 6 | stack_v2_sparse_classes_30k_val_000656 | Implement the Python class `IndependentBBEpsilonGreedy` described below.
Class description:
Independent Binomial Bridge Epsilon Greedy
Method signatures and docstrings:
- def __init__(self, n_stages, mu0, sigma0, sigma_tilde, epsilon=0.0): An agent for graph bandits. Args: n_stages - number of stages of the binomial ... | Implement the Python class `IndependentBBEpsilonGreedy` described below.
Class description:
Independent Binomial Bridge Epsilon Greedy
Method signatures and docstrings:
- def __init__(self, n_stages, mu0, sigma0, sigma_tilde, epsilon=0.0): An agent for graph bandits. Args: n_stages - number of stages of the binomial ... | 147ff28dc507172774693f225071f8e244e5994e | <|skeleton|>
class IndependentBBEpsilonGreedy:
"""Independent Binomial Bridge Epsilon Greedy"""
def __init__(self, n_stages, mu0, sigma0, sigma_tilde, epsilon=0.0):
"""An agent for graph bandits. Args: n_stages - number of stages of the binomial bridge (must be even) mu0 - prior mean sigma0 - prior std... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IndependentBBEpsilonGreedy:
"""Independent Binomial Bridge Epsilon Greedy"""
def __init__(self, n_stages, mu0, sigma0, sigma_tilde, epsilon=0.0):
"""An agent for graph bandits. Args: n_stages - number of stages of the binomial bridge (must be even) mu0 - prior mean sigma0 - prior stddev sigma_til... | the_stack_v2_python_sparse | src/graph/agent_indep.py | AbhinavGopal/ts_tutorial | train | 0 |
c32c42ab4926d403e45b5a49266aa218e0a646ff | [
"Process.__init__(self)\nself.rojo = array_rojo\nself.verde = array_verde\nself.azul = array_azul\nself.inicio = inicio\nself.final = final\nself.cola_roja = cola_roja\nself.cola_verde = cola_verde\nself.cola_azul = cola_azul",
"max_val = self.rojo[0]\nmin_val = self.rojo[0]\nfor j in range(self.inicio, self.fina... | <|body_start_0|>
Process.__init__(self)
self.rojo = array_rojo
self.verde = array_verde
self.azul = array_azul
self.inicio = inicio
self.final = final
self.cola_roja = cola_roja
self.cola_verde = cola_verde
self.cola_azul = cola_azul
<|end_body_0|>... | Clase que hereda del objeto Process (módulo multiprocessing). | MaxMin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaxMin:
"""Clase que hereda del objeto Process (módulo multiprocessing)."""
def __init__(self, array_rojo, array_verde, array_azul, inicio, final, cola_roja, cola_verde, cola_azul):
"""Inicializa el objeto."""
<|body_0|>
def run(self):
"""Código que se ejecuta al... | stack_v2_sparse_classes_36k_train_023105 | 14,973 | no_license | [
{
"docstring": "Inicializa el objeto.",
"name": "__init__",
"signature": "def __init__(self, array_rojo, array_verde, array_azul, inicio, final, cola_roja, cola_verde, cola_azul)"
},
{
"docstring": "Código que se ejecuta al lanzar el proceso. Se añaden máximos y mínimos a la cola del color corre... | 2 | stack_v2_sparse_classes_30k_train_012431 | Implement the Python class `MaxMin` described below.
Class description:
Clase que hereda del objeto Process (módulo multiprocessing).
Method signatures and docstrings:
- def __init__(self, array_rojo, array_verde, array_azul, inicio, final, cola_roja, cola_verde, cola_azul): Inicializa el objeto.
- def run(self): Cód... | Implement the Python class `MaxMin` described below.
Class description:
Clase que hereda del objeto Process (módulo multiprocessing).
Method signatures and docstrings:
- def __init__(self, array_rojo, array_verde, array_azul, inicio, final, cola_roja, cola_verde, cola_azul): Inicializa el objeto.
- def run(self): Cód... | bb906dcdaa39c0580f14bb6cef0956e7acd536ea | <|skeleton|>
class MaxMin:
"""Clase que hereda del objeto Process (módulo multiprocessing)."""
def __init__(self, array_rojo, array_verde, array_azul, inicio, final, cola_roja, cola_verde, cola_azul):
"""Inicializa el objeto."""
<|body_0|>
def run(self):
"""Código que se ejecuta al... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MaxMin:
"""Clase que hereda del objeto Process (módulo multiprocessing)."""
def __init__(self, array_rojo, array_verde, array_azul, inicio, final, cola_roja, cola_verde, cola_azul):
"""Inicializa el objeto."""
Process.__init__(self)
self.rojo = array_rojo
self.verde = arra... | the_stack_v2_python_sparse | images-equalization/ecualizador.py | nevinwu/IT-code | train | 0 |
bc740bb531bba1558bd7eeb83d17e09538d66feb | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn MembershipOutlierInsight()",
"from .directory_object import DirectoryObject\nfrom .governance_insight import GovernanceInsight\nfrom .outlier_container_type import OutlierContainerType\nfrom .outlier_member_type import OutlierMemberTyp... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return MembershipOutlierInsight()
<|end_body_0|>
<|body_start_1|>
from .directory_object import DirectoryObject
from .governance_insight import GovernanceInsight
from .outlier_container... | MembershipOutlierInsight | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MembershipOutlierInsight:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MembershipOutlierInsight:
"""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 cre... | stack_v2_sparse_classes_36k_train_023106 | 4,503 | 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: MembershipOutlierInsight",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrimi... | 3 | null | Implement the Python class `MembershipOutlierInsight` described below.
Class description:
Implement the MembershipOutlierInsight class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MembershipOutlierInsight: Creates a new instance of the appropriate c... | Implement the Python class `MembershipOutlierInsight` described below.
Class description:
Implement the MembershipOutlierInsight class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MembershipOutlierInsight: Creates a new instance of the appropriate c... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class MembershipOutlierInsight:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MembershipOutlierInsight:
"""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 cre... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MembershipOutlierInsight:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MembershipOutlierInsight:
"""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... | the_stack_v2_python_sparse | msgraph/generated/models/membership_outlier_insight.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
31cd6c25b910234173185184a304ce48d4dc6de1 | [
"legacy_pip = LooseVersion(pip_version) < LooseVersion('10.0')\nfor part in ('pip', '-q'):\n yield part\nyield ('install' if legacy_pip else 'download')",
"for part in cmd_root:\n yield part\nfor part in ('--no-deps', '-i', index, '-d', destdir):\n yield part\nyield '{}=={}'.format(pkg_name, pkg_version)... | <|body_start_0|>
legacy_pip = LooseVersion(pip_version) < LooseVersion('10.0')
for part in ('pip', '-q'):
yield part
yield ('install' if legacy_pip else 'download')
<|end_body_0|>
<|body_start_1|>
for part in cmd_root:
yield part
for part in ('--no-deps',... | Methods for generating pip commands. | PipCmd | [
"Zlib",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PipCmd:
"""Methods for generating pip commands."""
def update_root(pip_version):
"""Yield an appropriate root command depending on pip version."""
<|body_0|>
def update(cmd_root, destdir, pkg_name, pkg_version, index='https://pypi.org/simple'):
"""Yield an update... | stack_v2_sparse_classes_36k_train_023107 | 5,040 | permissive | [
{
"docstring": "Yield an appropriate root command depending on pip version.",
"name": "update_root",
"signature": "def update_root(pip_version)"
},
{
"docstring": "Yield an update command for pip.",
"name": "update",
"signature": "def update(cmd_root, destdir, pkg_name, pkg_version, inde... | 2 | stack_v2_sparse_classes_30k_train_017504 | Implement the Python class `PipCmd` described below.
Class description:
Methods for generating pip commands.
Method signatures and docstrings:
- def update_root(pip_version): Yield an appropriate root command depending on pip version.
- def update(cmd_root, destdir, pkg_name, pkg_version, index='https://pypi.org/simp... | Implement the Python class `PipCmd` described below.
Class description:
Methods for generating pip commands.
Method signatures and docstrings:
- def update_root(pip_version): Yield an appropriate root command depending on pip version.
- def update(cmd_root, destdir, pkg_name, pkg_version, index='https://pypi.org/simp... | 4645f7b10a7ea92e254c3ad1a15d3f0949be6b82 | <|skeleton|>
class PipCmd:
"""Methods for generating pip commands."""
def update_root(pip_version):
"""Yield an appropriate root command depending on pip version."""
<|body_0|>
def update(cmd_root, destdir, pkg_name, pkg_version, index='https://pypi.org/simple'):
"""Yield an update... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PipCmd:
"""Methods for generating pip commands."""
def update_root(pip_version):
"""Yield an appropriate root command depending on pip version."""
legacy_pip = LooseVersion(pip_version) < LooseVersion('10.0')
for part in ('pip', '-q'):
yield part
yield ('instal... | the_stack_v2_python_sparse | pypiserver/manage.py | pypiserver/pypiserver | train | 1,545 |
c617f04672fad8564a6935c73a1c8b5bb90d4c4a | [
"if not self.LIST:\n check_login(lambda x: True)(self)\n logic = AssociationLogic(self.auth, sid, aid)\n logic.association.choosing_code = AssociationLogic.elective_code()\n logic.association.save()\n return Result(id=aid)\nparams = ParamsParser(request.GET)\nlimit = params.int('limit', desc='每页最大渲染数... | <|body_start_0|>
if not self.LIST:
check_login(lambda x: True)(self)
logic = AssociationLogic(self.auth, sid, aid)
logic.association.choosing_code = AssociationLogic.elective_code()
logic.association.save()
return Result(id=aid)
params = Params... | AssociationVerification | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AssociationVerification:
def get(self, request, sid, aid=''):
"""重置协会码 or 获取协会列表 :param request: :param sid: :param aid: :return:"""
<|body_0|>
def post(self, request, sid):
"""批量获取协会信息 :param request: :param sid: :return:"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_023108 | 7,404 | no_license | [
{
"docstring": "重置协会码 or 获取协会列表 :param request: :param sid: :param aid: :return:",
"name": "get",
"signature": "def get(self, request, sid, aid='')"
},
{
"docstring": "批量获取协会信息 :param request: :param sid: :return:",
"name": "post",
"signature": "def post(self, request, sid)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006428 | Implement the Python class `AssociationVerification` described below.
Class description:
Implement the AssociationVerification class.
Method signatures and docstrings:
- def get(self, request, sid, aid=''): 重置协会码 or 获取协会列表 :param request: :param sid: :param aid: :return:
- def post(self, request, sid): 批量获取协会信息 :para... | Implement the Python class `AssociationVerification` described below.
Class description:
Implement the AssociationVerification class.
Method signatures and docstrings:
- def get(self, request, sid, aid=''): 重置协会码 or 获取协会列表 :param request: :param sid: :param aid: :return:
- def post(self, request, sid): 批量获取协会信息 :para... | a0553be3c259712de1fe5517b06317ad5756f79d | <|skeleton|>
class AssociationVerification:
def get(self, request, sid, aid=''):
"""重置协会码 or 获取协会列表 :param request: :param sid: :param aid: :return:"""
<|body_0|>
def post(self, request, sid):
"""批量获取协会信息 :param request: :param sid: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AssociationVerification:
def get(self, request, sid, aid=''):
"""重置协会码 or 获取协会列表 :param request: :param sid: :param aid: :return:"""
if not self.LIST:
check_login(lambda x: True)(self)
logic = AssociationLogic(self.auth, sid, aid)
logic.association.choosing_... | the_stack_v2_python_sparse | LittlePigHoHo/server/association/views/info.py | shoogoome/hoho | train | 1 | |
f1b8532cae571a0c4aa05f668c99b9738ced9584 | [
"expected_topic = 'Freshping'\nexpected_message = 'Freshping webhook has been successfully configured.'\nself.check_webhook('freshping_check_test', expected_topic, expected_message)",
"expected_topic = 'Test Check'\nexpected_message = '\\nhttps://example.com has just become unreachable.\\nError code: 521.\\n'.str... | <|body_start_0|>
expected_topic = 'Freshping'
expected_message = 'Freshping webhook has been successfully configured.'
self.check_webhook('freshping_check_test', expected_topic, expected_message)
<|end_body_0|>
<|body_start_1|>
expected_topic = 'Test Check'
expected_message = '\... | FreshpingHookTests | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FreshpingHookTests:
def test_freshping_check_test(self) -> None:
"""Tests if freshping check test is handled correctly"""
<|body_0|>
def test_freshping_check_unreachable(self) -> None:
"""Tests if freshping check unreachable is handled correctly"""
<|body_1|>... | stack_v2_sparse_classes_36k_train_023109 | 1,324 | permissive | [
{
"docstring": "Tests if freshping check test is handled correctly",
"name": "test_freshping_check_test",
"signature": "def test_freshping_check_test(self) -> None"
},
{
"docstring": "Tests if freshping check unreachable is handled correctly",
"name": "test_freshping_check_unreachable",
... | 3 | null | Implement the Python class `FreshpingHookTests` described below.
Class description:
Implement the FreshpingHookTests class.
Method signatures and docstrings:
- def test_freshping_check_test(self) -> None: Tests if freshping check test is handled correctly
- def test_freshping_check_unreachable(self) -> None: Tests if... | Implement the Python class `FreshpingHookTests` described below.
Class description:
Implement the FreshpingHookTests class.
Method signatures and docstrings:
- def test_freshping_check_test(self) -> None: Tests if freshping check test is handled correctly
- def test_freshping_check_unreachable(self) -> None: Tests if... | 965a25d91b6ee2db54038f5df855215fa25146b0 | <|skeleton|>
class FreshpingHookTests:
def test_freshping_check_test(self) -> None:
"""Tests if freshping check test is handled correctly"""
<|body_0|>
def test_freshping_check_unreachable(self) -> None:
"""Tests if freshping check unreachable is handled correctly"""
<|body_1|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FreshpingHookTests:
def test_freshping_check_test(self) -> None:
"""Tests if freshping check test is handled correctly"""
expected_topic = 'Freshping'
expected_message = 'Freshping webhook has been successfully configured.'
self.check_webhook('freshping_check_test', expected_to... | the_stack_v2_python_sparse | zerver/webhooks/freshping/tests.py | zulip/zulip | train | 20,239 | |
7d4715f046ba76cd9f00469602f7f2bed4b20c67 | [
"parents = set([])\nfor child in children:\n parent = getattr(child, parent_name, None)\n if not parent:\n continue\n if parent and parent not in parents:\n if not by_len:\n setattr(parent, counter_name, getattr(parent, children_name).order_by(None).count())\n else:\n ... | <|body_start_0|>
parents = set([])
for child in children:
parent = getattr(child, parent_name, None)
if not parent:
continue
if parent and parent not in parents:
if not by_len:
setattr(parent, counter_name, getattr(p... | CommonEntityHook | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommonEntityHook:
def update_children_count(self, children, parent_name, children_name, counter_name, by_len=False):
"""全量式更新统计表的count值,效率低,有一致性保证"""
<|body_0|>
def increase_children_count(self, children, parent_name, counter_name, sign):
"""增量式更新统计表的count值,效率高,缺乏一致性... | stack_v2_sparse_classes_36k_train_023110 | 6,540 | no_license | [
{
"docstring": "全量式更新统计表的count值,效率低,有一致性保证",
"name": "update_children_count",
"signature": "def update_children_count(self, children, parent_name, children_name, counter_name, by_len=False)"
},
{
"docstring": "增量式更新统计表的count值,效率高,缺乏一致性",
"name": "increase_children_count",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_001813 | Implement the Python class `CommonEntityHook` described below.
Class description:
Implement the CommonEntityHook class.
Method signatures and docstrings:
- def update_children_count(self, children, parent_name, children_name, counter_name, by_len=False): 全量式更新统计表的count值,效率低,有一致性保证
- def increase_children_count(self, ... | Implement the Python class `CommonEntityHook` described below.
Class description:
Implement the CommonEntityHook class.
Method signatures and docstrings:
- def update_children_count(self, children, parent_name, children_name, counter_name, by_len=False): 全量式更新统计表的count值,效率低,有一致性保证
- def increase_children_count(self, ... | 44be892ed657f462fb441d785c8550fc144f8896 | <|skeleton|>
class CommonEntityHook:
def update_children_count(self, children, parent_name, children_name, counter_name, by_len=False):
"""全量式更新统计表的count值,效率低,有一致性保证"""
<|body_0|>
def increase_children_count(self, children, parent_name, counter_name, sign):
"""增量式更新统计表的count值,效率高,缺乏一致性... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommonEntityHook:
def update_children_count(self, children, parent_name, children_name, counter_name, by_len=False):
"""全量式更新统计表的count值,效率低,有一致性保证"""
parents = set([])
for child in children:
parent = getattr(child, parent_name, None)
if not parent:
... | the_stack_v2_python_sparse | oj/models/hook.py | zrq495/OnlineJudge | train | 1 | |
4726374eb30794637207177dd5bf595c18523db9 | [
"self.capacity = capacity\nself.dict = {}\nself.cache = []",
"if key in self.cache:\n self.cache.remove(key)\n self.cache.append(key)\nreturn self.dict.get(key) if self.dict.get(key) else -1",
"if key not in self.cache:\n if len(self.cache) >= self.capacity:\n pop_key = self.cache.pop(0)\n ... | <|body_start_0|>
self.capacity = capacity
self.dict = {}
self.cache = []
<|end_body_0|>
<|body_start_1|>
if key in self.cache:
self.cache.remove(key)
self.cache.append(key)
return self.dict.get(key) if self.dict.get(key) else -1
<|end_body_1|>
<|body_sta... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_023111 | 1,231 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: None",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_000702 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None
<|sk... | 47911c354145d9867774aeb3358de20e55cf89ad | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.dict = {}
self.cache = []
def get(self, key):
""":type key: int :rtype: int"""
if key in self.cache:
self.cache.remove(key)
self.cache.ap... | the_stack_v2_python_sparse | rsc/ByteDance/146_LRUCache.py | VincentGaoHJ/Sword-For-Offer | train | 1 | |
6c3b0896585a2b834791b7db54084116cb9587fc | [
"self.ide = identity_element\nself.lide = lazy_ide\nself.func = segfunc\nn = len(ls)\nself.num = 2 ** (n - 1).bit_length()\nself.tree = [self.ide] * (2 * self.num)\nself.lazy = [self.lide] * (2 * self.num)\nfor i, l in enumerate(ls):\n self.tree[i + self.num - 1] = l\nfor i in range(self.num - 2, -1, -1):\n s... | <|body_start_0|>
self.ide = identity_element
self.lide = lazy_ide
self.func = segfunc
n = len(ls)
self.num = 2 ** (n - 1).bit_length()
self.tree = [self.ide] * (2 * self.num)
self.lazy = [self.lide] * (2 * self.num)
for i, l in enumerate(ls):
s... | SegmentTreeForRSQandRAQ | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SegmentTreeForRSQandRAQ:
def __init__(self, ls: list, segfunc=operator.add, identity_element=0, lazy_ide=0):
"""セグ木 もしかしたらバグがあるかも 一次元のリストlsを受け取り初期化する。O(len(ls)) 区間のルールはsegfuncによって定義される identity elementは単位元。e.g., 最小値を求めたい→inf, 和→0, 積→1, gcd→0 [単位元](https://ja.wikipedia.org/wiki/%E5%8D%98%... | stack_v2_sparse_classes_36k_train_023112 | 23,273 | no_license | [
{
"docstring": "セグ木 もしかしたらバグがあるかも 一次元のリストlsを受け取り初期化する。O(len(ls)) 区間のルールはsegfuncによって定義される identity elementは単位元。e.g., 最小値を求めたい→inf, 和→0, 積→1, gcd→0 [単位元](https://ja.wikipedia.org/wiki/%E5%8D%98%E4%BD%8D%E5%85%83)",
"name": "__init__",
"signature": "def __init__(self, ls: list, segfunc=operator.add, identi... | 4 | null | Implement the Python class `SegmentTreeForRSQandRAQ` described below.
Class description:
Implement the SegmentTreeForRSQandRAQ class.
Method signatures and docstrings:
- def __init__(self, ls: list, segfunc=operator.add, identity_element=0, lazy_ide=0): セグ木 もしかしたらバグがあるかも 一次元のリストlsを受け取り初期化する。O(len(ls)) 区間のルールはsegfuncに... | Implement the Python class `SegmentTreeForRSQandRAQ` described below.
Class description:
Implement the SegmentTreeForRSQandRAQ class.
Method signatures and docstrings:
- def __init__(self, ls: list, segfunc=operator.add, identity_element=0, lazy_ide=0): セグ木 もしかしたらバグがあるかも 一次元のリストlsを受け取り初期化する。O(len(ls)) 区間のルールはsegfuncに... | 74915a40ac157f89fe400e3f98e9bf3c10012cd7 | <|skeleton|>
class SegmentTreeForRSQandRAQ:
def __init__(self, ls: list, segfunc=operator.add, identity_element=0, lazy_ide=0):
"""セグ木 もしかしたらバグがあるかも 一次元のリストlsを受け取り初期化する。O(len(ls)) 区間のルールはsegfuncによって定義される identity elementは単位元。e.g., 最小値を求めたい→inf, 和→0, 積→1, gcd→0 [単位元](https://ja.wikipedia.org/wiki/%E5%8D%98%... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SegmentTreeForRSQandRAQ:
def __init__(self, ls: list, segfunc=operator.add, identity_element=0, lazy_ide=0):
"""セグ木 もしかしたらバグがあるかも 一次元のリストlsを受け取り初期化する。O(len(ls)) 区間のルールはsegfuncによって定義される identity elementは単位元。e.g., 最小値を求めたい→inf, 和→0, 積→1, gcd→0 [単位元](https://ja.wikipedia.org/wiki/%E5%8D%98%E4%BD%8D%E5%85... | the_stack_v2_python_sparse | algorithm/SegmentTree.py | masakiaota/kyoupuro | train | 1 | |
670677a1944144a38893e73d21b249d35ced7c0f | [
"table = {n: i for i, n in enumerate(nums2)}\nnext_greater_element_index = {}\nheap = []\nfor i, n in enumerate(nums2):\n while heap and heap[0][0] < n:\n _, j = heappop(heap)\n next_greater_element_index[j] = i\n heappush(heap, (n, i))\nret = []\nfor n in nums1:\n if n not in table or table[... | <|body_start_0|>
table = {n: i for i, n in enumerate(nums2)}
next_greater_element_index = {}
heap = []
for i, n in enumerate(nums2):
while heap and heap[0][0] < n:
_, j = heappop(heap)
next_greater_element_index[j] = i
heappush(heap... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""Use heap"""
<|body_0|>
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""Use stack"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_023113 | 3,206 | no_license | [
{
"docstring": "Use heap",
"name": "nextGreaterElement",
"signature": "def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]"
},
{
"docstring": "Use stack",
"name": "nextGreaterElement",
"signature": "def nextGreaterElement(self, nums1: List[int], nums2: List[int]... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: Use heap
- def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: Use stack | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: Use heap
- def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: Use stack... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""Use heap"""
<|body_0|>
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""Use stack"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""Use heap"""
table = {n: i for i, n in enumerate(nums2)}
next_greater_element_index = {}
heap = []
for i, n in enumerate(nums2):
while heap and heap[0][0] < n:
... | the_stack_v2_python_sparse | leetcode/solved/496_Next_Greater_Element_I/solution.py | sungminoh/algorithms | train | 0 | |
a03ce1c3066f78c7e37f60d4707d795043f79d05 | [
"if diff == False:\n res = func(lst)\nelse:\n res = func(lst, diff)\nres.sort()\nreturn res",
"df = pd.read_csv('data_outlierdetection/stationarytrend.csv')['Temp']\nself.assertEqual(self.sorted_output(Outliers_StdDev, df, 3), [])\nself.assertEqual(self.sorted_output(Outliers_IQR, df), [])",
"df = pd.read... | <|body_start_0|>
if diff == False:
res = func(lst)
else:
res = func(lst, diff)
res.sort()
return res
<|end_body_0|>
<|body_start_1|>
df = pd.read_csv('data_outlierdetection/stationarytrend.csv')['Temp']
self.assertEqual(self.sorted_output(Outliers... | TestUniGlobOutliers | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestUniGlobOutliers:
def sorted_output(self, func, lst, diff=False):
"""This function gives sorted output. Default value for `diff` is False."""
<|body_0|>
def test_stationarytrend(self):
"""This test ensures that if no outliers are found, empty list is the output. R... | stack_v2_sparse_classes_36k_train_023114 | 3,951 | permissive | [
{
"docstring": "This function gives sorted output. Default value for `diff` is False.",
"name": "sorted_output",
"signature": "def sorted_output(self, func, lst, diff=False)"
},
{
"docstring": "This test ensures that if no outliers are found, empty list is the output. Results have been verfied u... | 6 | stack_v2_sparse_classes_30k_train_015649 | Implement the Python class `TestUniGlobOutliers` described below.
Class description:
Implement the TestUniGlobOutliers class.
Method signatures and docstrings:
- def sorted_output(self, func, lst, diff=False): This function gives sorted output. Default value for `diff` is False.
- def test_stationarytrend(self): This... | Implement the Python class `TestUniGlobOutliers` described below.
Class description:
Implement the TestUniGlobOutliers class.
Method signatures and docstrings:
- def sorted_output(self, func, lst, diff=False): This function gives sorted output. Default value for `diff` is False.
- def test_stationarytrend(self): This... | 2c5495deb6d31eef556e7f410ac1c1632bffa961 | <|skeleton|>
class TestUniGlobOutliers:
def sorted_output(self, func, lst, diff=False):
"""This function gives sorted output. Default value for `diff` is False."""
<|body_0|>
def test_stationarytrend(self):
"""This test ensures that if no outliers are found, empty list is the output. R... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestUniGlobOutliers:
def sorted_output(self, func, lst, diff=False):
"""This function gives sorted output. Default value for `diff` is False."""
if diff == False:
res = func(lst)
else:
res = func(lst, diff)
res.sort()
return res
def test_sta... | the_stack_v2_python_sparse | mvtsdatatoolkit/outlier_detection/test_Univariate_GlobalPointOutliers.py | skad00sh/gsudmlab-mvtsdata_toolkit | train | 0 | |
bc61ce953e5bcf9ecb85ab0fa4669ed2fdc90767 | [
"if reduced_model:\n dim_param = 2\nelse:\n dim_param = 8\nsuper().__init__(dim_param=dim_param, seed=seed)\nself.I = I\nself.cython = cython\nself.dt = dt\nself.t = np.arange(0, len(self.I), 1) * self.dt\nself.prior_log = prior_log\nif cython:\n import model.HodgkinHuxleyBioPhysCython as bm\nelse:\n im... | <|body_start_0|>
if reduced_model:
dim_param = 2
else:
dim_param = 8
super().__init__(dim_param=dim_param, seed=seed)
self.I = I
self.cython = cython
self.dt = dt
self.t = np.arange(0, len(self.I), 1) * self.dt
self.prior_log = prio... | HodgkinHuxley | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HodgkinHuxley:
def __init__(self, I, dt, V0, cython=False, prior_log=False, reduced_model=False, seed=None):
"""Hodgkin-Huxley simulator Parameters ---------- I : array Numpy array with the input I dt : float Timestep V0 : float Voltage at first time step cython : bool If True, will use ... | stack_v2_sparse_classes_36k_train_023115 | 2,395 | permissive | [
{
"docstring": "Hodgkin-Huxley simulator Parameters ---------- I : array Numpy array with the input I dt : float Timestep V0 : float Voltage at first time step cython : bool If True, will use cython version of simulator (different import) reduced_model : bool If True, model with 2 parameters instead of 8 seed :... | 2 | stack_v2_sparse_classes_30k_train_014139 | Implement the Python class `HodgkinHuxley` described below.
Class description:
Implement the HodgkinHuxley class.
Method signatures and docstrings:
- def __init__(self, I, dt, V0, cython=False, prior_log=False, reduced_model=False, seed=None): Hodgkin-Huxley simulator Parameters ---------- I : array Numpy array with ... | Implement the Python class `HodgkinHuxley` described below.
Class description:
Implement the HodgkinHuxley class.
Method signatures and docstrings:
- def __init__(self, I, dt, V0, cython=False, prior_log=False, reduced_model=False, seed=None): Hodgkin-Huxley simulator Parameters ---------- I : array Numpy array with ... | b93c90ec6156ae5f8afee6aaac7317373e9caf5e | <|skeleton|>
class HodgkinHuxley:
def __init__(self, I, dt, V0, cython=False, prior_log=False, reduced_model=False, seed=None):
"""Hodgkin-Huxley simulator Parameters ---------- I : array Numpy array with the input I dt : float Timestep V0 : float Voltage at first time step cython : bool If True, will use ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HodgkinHuxley:
def __init__(self, I, dt, V0, cython=False, prior_log=False, reduced_model=False, seed=None):
"""Hodgkin-Huxley simulator Parameters ---------- I : array Numpy array with the input I dt : float Timestep V0 : float Voltage at first time step cython : bool If True, will use cython version... | the_stack_v2_python_sparse | 5_hh/model/HodgkinHuxley.py | daesungc/IdentifyMechanisticModels_2020 | train | 0 | |
a3becf808b6350e89b60189663b9be864b363b61 | [
"self.snake = set([])\nself.head = self.tail = node(0, 0)\nself.dirs = {'U': (-1, 0), 'L': (0, -1), 'R': (0, 1), 'D': (1, 0)}\nself.width = width\nself.height = height\nself.eaten = 0\nself.food = food\nself.cur_food = None\nif food:\n self.cur_food = food.pop(0)",
"i, j = [x + y for x, y in zip([self.head.x, ... | <|body_start_0|>
self.snake = set([])
self.head = self.tail = node(0, 0)
self.dirs = {'U': (-1, 0), 'L': (0, -1), 'R': (0, 1), 'D': (1, 0)}
self.width = width
self.height = height
self.eaten = 0
self.food = food
self.cur_food = None
if food:
... | SnakeGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :typ... | stack_v2_sparse_classes_36k_train_023116 | 2,605 | no_license | [
{
"docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :type width: int :type height: int :type food: List[List[int]]",
... | 2 | null | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E... | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E... | 16468a4397430b24b685cab02570ff3f5849e86f | <|skeleton|>
class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :typ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :type width: int :... | the_stack_v2_python_sparse | design-snake-game/s1.py | fingerroll/wip | train | 0 | |
cebf97271ebba0dff0b53dfeb9dcd95ffb82d77f | [
"if '_method' in request.form and request.form['_method'] == 'put':\n if build_campaign(request, create=False):\n return (None, status.HTTP_200_OK)\nelif build_campaign(request, create=True):\n return (None, status.HTTP_200_OK)\nreturn (None, status.HTTP_500_INTERNAL_SERVER_ERROR)",
"if build_campaig... | <|body_start_0|>
if '_method' in request.form and request.form['_method'] == 'put':
if build_campaign(request, create=False):
return (None, status.HTTP_200_OK)
elif build_campaign(request, create=True):
return (None, status.HTTP_200_OK)
return (None, statu... | Flask-RESTful resource endpoints for CampaignModel by ID. | ManageCampaigns | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ManageCampaigns:
"""Flask-RESTful resource endpoints for CampaignModel by ID."""
def post(self):
"""Endpoint to post a campaign."""
<|body_0|>
def put(self):
"""Endpoint to update a campaign."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if '_... | stack_v2_sparse_classes_36k_train_023117 | 3,941 | no_license | [
{
"docstring": "Endpoint to post a campaign.",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Endpoint to update a campaign.",
"name": "put",
"signature": "def put(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021310 | Implement the Python class `ManageCampaigns` described below.
Class description:
Flask-RESTful resource endpoints for CampaignModel by ID.
Method signatures and docstrings:
- def post(self): Endpoint to post a campaign.
- def put(self): Endpoint to update a campaign. | Implement the Python class `ManageCampaigns` described below.
Class description:
Flask-RESTful resource endpoints for CampaignModel by ID.
Method signatures and docstrings:
- def post(self): Endpoint to post a campaign.
- def put(self): Endpoint to update a campaign.
<|skeleton|>
class ManageCampaigns:
"""Flask-... | d5ffcc5d276692d1578cea704125b1b3952beb1c | <|skeleton|>
class ManageCampaigns:
"""Flask-RESTful resource endpoints for CampaignModel by ID."""
def post(self):
"""Endpoint to post a campaign."""
<|body_0|>
def put(self):
"""Endpoint to update a campaign."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ManageCampaigns:
"""Flask-RESTful resource endpoints for CampaignModel by ID."""
def post(self):
"""Endpoint to post a campaign."""
if '_method' in request.form and request.form['_method'] == 'put':
if build_campaign(request, create=False):
return (None, status... | the_stack_v2_python_sparse | application/resources/campaign.py | transreductionist/API-Project-1 | train | 0 |
8c19f57628619fa4276a5e980ca9a11c04360a71 | [
"hparams = self.hparams\nwith tf.compat.v1.variable_scope('sum'):\n self.history_embedding = tf.concat([self.item_history_embedding, self.cate_history_embedding], 2)\n cell = self._create_sumcell()\n self.cell = cell\n cell.model = self\n final_state = self._build_sum(cell)\n for _p in cell.parame... | <|body_start_0|>
hparams = self.hparams
with tf.compat.v1.variable_scope('sum'):
self.history_embedding = tf.concat([self.item_history_embedding, self.cate_history_embedding], 2)
cell = self._create_sumcell()
self.cell = cell
cell.model = self
... | Sequential User Matrix Model :Citation: Lian, J., Batal, I., Liu, Z., Soni, A., Kang, E. Y., Wang, Y., & Xie, X., "Multi-Interest-Aware User Modeling for Large-Scale Sequential Recommendations", arXiv preprint arXiv:2102.09211, 2021. | SUMModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SUMModel:
"""Sequential User Matrix Model :Citation: Lian, J., Batal, I., Liu, Z., Soni, A., Kang, E. Y., Wang, Y., & Xie, X., "Multi-Interest-Aware User Modeling for Large-Scale Sequential Recommendations", arXiv preprint arXiv:2102.09211, 2021."""
def _build_seq_graph(self):
"""The... | stack_v2_sparse_classes_36k_train_023118 | 5,699 | permissive | [
{
"docstring": "The main function to create SUM model. Returns: object: The output of SUM section, which is a concatenation of user vector and target item vector.",
"name": "_build_seq_graph",
"signature": "def _build_seq_graph(self)"
},
{
"docstring": "Merge a user's memory states conditioned b... | 4 | stack_v2_sparse_classes_30k_train_007380 | Implement the Python class `SUMModel` described below.
Class description:
Sequential User Matrix Model :Citation: Lian, J., Batal, I., Liu, Z., Soni, A., Kang, E. Y., Wang, Y., & Xie, X., "Multi-Interest-Aware User Modeling for Large-Scale Sequential Recommendations", arXiv preprint arXiv:2102.09211, 2021.
Method sig... | Implement the Python class `SUMModel` described below.
Class description:
Sequential User Matrix Model :Citation: Lian, J., Batal, I., Liu, Z., Soni, A., Kang, E. Y., Wang, Y., & Xie, X., "Multi-Interest-Aware User Modeling for Large-Scale Sequential Recommendations", arXiv preprint arXiv:2102.09211, 2021.
Method sig... | 787ae309ec78a9b2b1f58931931cb117affc4ea9 | <|skeleton|>
class SUMModel:
"""Sequential User Matrix Model :Citation: Lian, J., Batal, I., Liu, Z., Soni, A., Kang, E. Y., Wang, Y., & Xie, X., "Multi-Interest-Aware User Modeling for Large-Scale Sequential Recommendations", arXiv preprint arXiv:2102.09211, 2021."""
def _build_seq_graph(self):
"""The... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SUMModel:
"""Sequential User Matrix Model :Citation: Lian, J., Batal, I., Liu, Z., Soni, A., Kang, E. Y., Wang, Y., & Xie, X., "Multi-Interest-Aware User Modeling for Large-Scale Sequential Recommendations", arXiv preprint arXiv:2102.09211, 2021."""
def _build_seq_graph(self):
"""The main functio... | the_stack_v2_python_sparse | recommenders/models/deeprec/models/sequential/sum.py | DaniBunny/recommenders | train | 1 |
873a7a1d658535c24f4ac6f2c37bfb47b326acb8 | [
"self.text_format = text_format\nself.justify: JustifyMethod = justify\nself.style = style\nself.markup = markup\nself.highlighter = highlighter\nself.overflow: Optional[OverflowMethod] = overflow\nself.width = width\nsuper().__init__()",
"_text = self.text_format.format(task=task)\nif self.markup:\n text = Te... | <|body_start_0|>
self.text_format = text_format
self.justify: JustifyMethod = justify
self.style = style
self.markup = markup
self.highlighter = highlighter
self.overflow: Optional[OverflowMethod] = overflow
self.width = width
super().__init__()
<|end_body... | Custom sized text column based on the Rich library. | SizedTextColumn | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SizedTextColumn:
"""Custom sized text column based on the Rich library."""
def __init__(self, text_format: str, style: StyleType='none', justify: JustifyMethod='left', markup: bool=True, highlighter: Optional[Highlighter]=None, overflow: Optional[OverflowMethod]=None, width: int=20) -> None:... | stack_v2_sparse_classes_36k_train_023119 | 13,137 | permissive | [
{
"docstring": "A column containing text. ### Arguments - text_format: The format string to use for the text. - style: The style to use for the text. - justify: The justification to use for the text. - markup: Whether or not the text should be rendered as markup. - highlighter: A Highlighter to use for highligh... | 2 | stack_v2_sparse_classes_30k_train_016633 | Implement the Python class `SizedTextColumn` described below.
Class description:
Custom sized text column based on the Rich library.
Method signatures and docstrings:
- def __init__(self, text_format: str, style: StyleType='none', justify: JustifyMethod='left', markup: bool=True, highlighter: Optional[Highlighter]=No... | Implement the Python class `SizedTextColumn` described below.
Class description:
Custom sized text column based on the Rich library.
Method signatures and docstrings:
- def __init__(self, text_format: str, style: StyleType='none', justify: JustifyMethod='left', markup: bool=True, highlighter: Optional[Highlighter]=No... | 1924fbe6d5fdc4cd9132464f377fce150750730e | <|skeleton|>
class SizedTextColumn:
"""Custom sized text column based on the Rich library."""
def __init__(self, text_format: str, style: StyleType='none', justify: JustifyMethod='left', markup: bool=True, highlighter: Optional[Highlighter]=None, overflow: Optional[OverflowMethod]=None, width: int=20) -> None:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SizedTextColumn:
"""Custom sized text column based on the Rich library."""
def __init__(self, text_format: str, style: StyleType='none', justify: JustifyMethod='left', markup: bool=True, highlighter: Optional[Highlighter]=None, overflow: Optional[OverflowMethod]=None, width: int=20) -> None:
"""A... | the_stack_v2_python_sparse | spotdl/download/progress_handler.py | phcreery/spotify-downloader | train | 2 |
3ce2495efc5d5b97ba92d2eca3e1b8c5eee3f9db | [
"super(Dpkg, self).__init__()\nself._release = release\nself._arch = arch\nself._executor = executor",
"_ubuntu_urls = [(_UBUNTU_MAIN_ARCHS, _UBUNTU_MAIN_ARCHIVE), (_UBUNTU_PORT_ARCHS, _UBUNTU_PORT_ARCHIVE)]\n\ndef _format_user_line(line, kwargs):\n \"\"\"Format a line and turns it into a valid repository line... | <|body_start_0|>
super(Dpkg, self).__init__()
self._release = release
self._arch = arch
self._executor = executor
<|end_body_0|>
<|body_start_1|>
_ubuntu_urls = [(_UBUNTU_MAIN_ARCHS, _UBUNTU_MAIN_ARCHIVE), (_UBUNTU_PORT_ARCHS, _UBUNTU_PORT_ARCHIVE)]
def _format_user_lin... | Debian Packaging System. | Dpkg | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dpkg:
"""Debian Packaging System."""
def __init__(self, release, arch, executor):
"""Initialize Dpkg with release and arch."""
<|body_0|>
def format_repositories(repos, release, arch):
"""Take a list of APT lines and format them. There are certain shortcuts that ... | stack_v2_sparse_classes_36k_train_023120 | 19,882 | permissive | [
{
"docstring": "Initialize Dpkg with release and arch.",
"name": "__init__",
"signature": "def __init__(self, release, arch, executor)"
},
{
"docstring": "Take a list of APT lines and format them. There are certain shortcuts that you can use. {ubuntu} will be replaced by http://archive.ubuntu.co... | 4 | stack_v2_sparse_classes_30k_train_016272 | Implement the Python class `Dpkg` described below.
Class description:
Debian Packaging System.
Method signatures and docstrings:
- def __init__(self, release, arch, executor): Initialize Dpkg with release and arch.
- def format_repositories(repos, release, arch): Take a list of APT lines and format them. There are ce... | Implement the Python class `Dpkg` described below.
Class description:
Debian Packaging System.
Method signatures and docstrings:
- def __init__(self, release, arch, executor): Initialize Dpkg with release and arch.
- def format_repositories(repos, release, arch): Take a list of APT lines and format them. There are ce... | bb31302cfc48f55da56c12ab27b88644380209b9 | <|skeleton|>
class Dpkg:
"""Debian Packaging System."""
def __init__(self, release, arch, executor):
"""Initialize Dpkg with release and arch."""
<|body_0|>
def format_repositories(repos, release, arch):
"""Take a list of APT lines and format them. There are certain shortcuts that ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Dpkg:
"""Debian Packaging System."""
def __init__(self, release, arch, executor):
"""Initialize Dpkg with release and arch."""
super(Dpkg, self).__init__()
self._release = release
self._arch = arch
self._executor = executor
def format_repositories(repos, relea... | the_stack_v2_python_sparse | psqtraviscontainer/package_system.py | violethaze74/polysquare-travis-container | train | 0 |
82ba59cb5ccc331af05d3cf2014a300eebea8f3e | [
"if not (obj and len(Variable.objects.filter(version=obj))):\n return admin.ModelAdmin.get_fieldsets(self, request, obj=obj)\nelse:\n return ((None, {'fields': ('name', 'application'), 'description': '<div style=\"font-size: 16px;color: red;\">This version will be deleted when all linked variables will be del... | <|body_start_0|>
if not (obj and len(Variable.objects.filter(version=obj))):
return admin.ModelAdmin.get_fieldsets(self, request, obj=obj)
else:
return ((None, {'fields': ('name', 'application'), 'description': '<div style="font-size: 16px;color: red;">This version will be delete... | VersionAdmin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VersionAdmin:
def get_fieldsets(self, request, obj=None):
"""Display error message when it's impossible to delete the version"""
<|body_0|>
def has_delete_permission(self, request, obj=None):
"""Do not display delete button if some tests / variables are linked to thi... | stack_v2_sparse_classes_36k_train_023121 | 21,881 | permissive | [
{
"docstring": "Display error message when it's impossible to delete the version",
"name": "get_fieldsets",
"signature": "def get_fieldsets(self, request, obj=None)"
},
{
"docstring": "Do not display delete button if some tests / variables are linked to this application",
"name": "has_delete... | 3 | stack_v2_sparse_classes_30k_train_001166 | Implement the Python class `VersionAdmin` described below.
Class description:
Implement the VersionAdmin class.
Method signatures and docstrings:
- def get_fieldsets(self, request, obj=None): Display error message when it's impossible to delete the version
- def has_delete_permission(self, request, obj=None): Do not ... | Implement the Python class `VersionAdmin` described below.
Class description:
Implement the VersionAdmin class.
Method signatures and docstrings:
- def get_fieldsets(self, request, obj=None): Display error message when it's impossible to delete the version
- def has_delete_permission(self, request, obj=None): Do not ... | 590c84d5078fee4021fa23956390eb612b5f123d | <|skeleton|>
class VersionAdmin:
def get_fieldsets(self, request, obj=None):
"""Display error message when it's impossible to delete the version"""
<|body_0|>
def has_delete_permission(self, request, obj=None):
"""Do not display delete button if some tests / variables are linked to thi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VersionAdmin:
def get_fieldsets(self, request, obj=None):
"""Display error message when it's impossible to delete the version"""
if not (obj and len(Variable.objects.filter(version=obj))):
return admin.ModelAdmin.get_fieldsets(self, request, obj=obj)
else:
retur... | the_stack_v2_python_sparse | variableServer/admin.py | bhecquet/seleniumRobot-server | train | 0 | |
ec07d5c5713bb83d50412c120871113a2e103d9b | [
"if root != None:\n sum_n = 0\nelse:\n sum_n = 1\nstack = [root]\nres = ''\nwhile stack.__len__() != 0 and stack.__len__() != sum_n:\n node = stack.pop(0)\n if node == None:\n sum_n += 1\n res += 'None/'\n stack.append(None)\n stack.append(None)\n else:\n if node.le... | <|body_start_0|>
if root != None:
sum_n = 0
else:
sum_n = 1
stack = [root]
res = ''
while stack.__len__() != 0 and stack.__len__() != sum_n:
node = stack.pop(0)
if node == None:
sum_n += 1
res += 'Non... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_023122 | 2,205 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_003409 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | a9fb28f7cfcae8d9c9a460462ec9ee8b5f3b40d8 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if root != None:
sum_n = 0
else:
sum_n = 1
stack = [root]
res = ''
while stack.__len__() != 0 and stack.__len__() != sum_n:
... | the_stack_v2_python_sparse | code/Codec.py | 3wh1te/Leecode | train | 0 | |
dbf695dd17fc94fd4031e9b8fc57ef5896311ea6 | [
"dp, s1_ascii, s2_ascii, f = ([[0 for i in range(len(s2) + 1)] for j in range(len(s1) + 1)], 0, 0, 0)\nfor i in range(1, len(s1) + 1):\n s1_ascii += ord(s1[i - 1])\n for j in range(1, len(s2) + 1):\n if not f:\n s2_ascii += ord(s2[j - 1])\n if s1[i - 1] == s2[j - 1]:\n dp[i... | <|body_start_0|>
dp, s1_ascii, s2_ascii, f = ([[0 for i in range(len(s2) + 1)] for j in range(len(s1) + 1)], 0, 0, 0)
for i in range(1, len(s1) + 1):
s1_ascii += ord(s1[i - 1])
for j in range(1, len(s2) + 1):
if not f:
s2_ascii += ord(s2[j - 1]... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minimumDeleteSum(self, s1, s2):
""":type s1: str :type s2: str :rtype: int 802MS"""
<|body_0|>
def minimumDeleteSum_1(self, s1, s2):
""":type s1: str :type s2: str :rtype: int 458MS"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dp, s... | stack_v2_sparse_classes_36k_train_023123 | 2,190 | no_license | [
{
"docstring": ":type s1: str :type s2: str :rtype: int 802MS",
"name": "minimumDeleteSum",
"signature": "def minimumDeleteSum(self, s1, s2)"
},
{
"docstring": ":type s1: str :type s2: str :rtype: int 458MS",
"name": "minimumDeleteSum_1",
"signature": "def minimumDeleteSum_1(self, s1, s2... | 2 | stack_v2_sparse_classes_30k_train_001367 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumDeleteSum(self, s1, s2): :type s1: str :type s2: str :rtype: int 802MS
- def minimumDeleteSum_1(self, s1, s2): :type s1: str :type s2: str :rtype: int 458MS | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumDeleteSum(self, s1, s2): :type s1: str :type s2: str :rtype: int 802MS
- def minimumDeleteSum_1(self, s1, s2): :type s1: str :type s2: str :rtype: int 458MS
<|skeleto... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def minimumDeleteSum(self, s1, s2):
""":type s1: str :type s2: str :rtype: int 802MS"""
<|body_0|>
def minimumDeleteSum_1(self, s1, s2):
""":type s1: str :type s2: str :rtype: int 458MS"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minimumDeleteSum(self, s1, s2):
""":type s1: str :type s2: str :rtype: int 802MS"""
dp, s1_ascii, s2_ascii, f = ([[0 for i in range(len(s2) + 1)] for j in range(len(s1) + 1)], 0, 0, 0)
for i in range(1, len(s1) + 1):
s1_ascii += ord(s1[i - 1])
for ... | the_stack_v2_python_sparse | MinimumASCIIDeleteSumForTwoStrings_MID_712.py | 953250587/leetcode-python | train | 2 | |
167e5dd1c2d002c169af23ef5c2bb398ce70b0e9 | [
"assert 'model' in dss_args.keys(), \"'model' is a compulsory argument. Include it as a key in dss_args\"\nassert 'loss' in dss_args.keys(), \"'loss' is a compulsory argument. Include it as a key in dss_args\"\nif dss_args.loss.reduction != 'none':\n raise ValueError(\"Please set 'reduction' of loss function to ... | <|body_start_0|>
assert 'model' in dss_args.keys(), "'model' is a compulsory argument. Include it as a key in dss_args"
assert 'loss' in dss_args.keys(), "'loss' is a compulsory argument. Include it as a key in dss_args"
if dss_args.loss.reduction != 'none':
raise ValueError("Please ... | Implements of GLISTERDataLoader that serves as the dataloader for the adaptive GLISTER subset selection strategy from the paper :footcite:`killamsetty2021glister`. Parameters ----------- train_loader: torch.utils.data.DataLoader class Dataloader of the training dataset val_loader: torch.utils.data.DataLoader class Data... | GLISTERDataLoader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GLISTERDataLoader:
"""Implements of GLISTERDataLoader that serves as the dataloader for the adaptive GLISTER subset selection strategy from the paper :footcite:`killamsetty2021glister`. Parameters ----------- train_loader: torch.utils.data.DataLoader class Dataloader of the training dataset val_l... | stack_v2_sparse_classes_36k_train_023124 | 3,603 | permissive | [
{
"docstring": "Constructor function",
"name": "__init__",
"signature": "def __init__(self, train_loader, val_loader, dss_args, logger, *args, **kwargs)"
},
{
"docstring": "Function that calls the GLISTER subset selection strategy to sample new subset indices and the corresponding subset weights... | 2 | stack_v2_sparse_classes_30k_train_008864 | Implement the Python class `GLISTERDataLoader` described below.
Class description:
Implements of GLISTERDataLoader that serves as the dataloader for the adaptive GLISTER subset selection strategy from the paper :footcite:`killamsetty2021glister`. Parameters ----------- train_loader: torch.utils.data.DataLoader class D... | Implement the Python class `GLISTERDataLoader` described below.
Class description:
Implements of GLISTERDataLoader that serves as the dataloader for the adaptive GLISTER subset selection strategy from the paper :footcite:`killamsetty2021glister`. Parameters ----------- train_loader: torch.utils.data.DataLoader class D... | 8d10c7f5d96e071f98c20e4e9ff4c41c2c4ea2af | <|skeleton|>
class GLISTERDataLoader:
"""Implements of GLISTERDataLoader that serves as the dataloader for the adaptive GLISTER subset selection strategy from the paper :footcite:`killamsetty2021glister`. Parameters ----------- train_loader: torch.utils.data.DataLoader class Dataloader of the training dataset val_l... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GLISTERDataLoader:
"""Implements of GLISTERDataLoader that serves as the dataloader for the adaptive GLISTER subset selection strategy from the paper :footcite:`killamsetty2021glister`. Parameters ----------- train_loader: torch.utils.data.DataLoader class Dataloader of the training dataset val_loader: torch.... | the_stack_v2_python_sparse | cords/utils/data/dataloader/SL/adaptive/glisterdataloader.py | decile-team/cords | train | 289 |
9fc2e2d2a04916ed2e683e2c2e320ee2092d3296 | [
"if not nums1 or not nums2:\n return\nfor i in range(len(nums2)):\n nums1[m + i] = nums2[i]\n\ndef _sort_once(nums, left, right):\n x = left\n y = right\n pivot = nums[left]\n while x < y:\n while x < y and nums[y] >= pivot:\n y -= 1\n nums[x] = nums[y]\n while x < ... | <|body_start_0|>
if not nums1 or not nums2:
return
for i in range(len(nums2)):
nums1[m + i] = nums2[i]
def _sort_once(nums, left, right):
x = left
y = right
pivot = nums[left]
while x < y:
while x < y and nu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def merge(self, nums1: 'List[int]', m: int, nums2: 'List[int]', n: int) -> None:
"""先合并,在使用快速排序 执行用时 : 60 ms, 在Merge Sorted Array的Python3提交中击败了49.81% 的用户 内存消耗 : 12.9 MB, 在Merge Sorted Array的Python3提交中击败了99.08% 的用户"""
<|body_0|>
def merge1(self, nums1: 'List[int]', ... | stack_v2_sparse_classes_36k_train_023125 | 4,411 | no_license | [
{
"docstring": "先合并,在使用快速排序 执行用时 : 60 ms, 在Merge Sorted Array的Python3提交中击败了49.81% 的用户 内存消耗 : 12.9 MB, 在Merge Sorted Array的Python3提交中击败了99.08% 的用户",
"name": "merge",
"signature": "def merge(self, nums1: 'List[int]', m: int, nums2: 'List[int]', n: int) -> None"
},
{
"docstring": "先合并,在使用 sort 排序",... | 3 | stack_v2_sparse_classes_30k_train_004242 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge(self, nums1: 'List[int]', m: int, nums2: 'List[int]', n: int) -> None: 先合并,在使用快速排序 执行用时 : 60 ms, 在Merge Sorted Array的Python3提交中击败了49.81% 的用户 内存消耗 : 12.9 MB, 在Merge Sort... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge(self, nums1: 'List[int]', m: int, nums2: 'List[int]', n: int) -> None: 先合并,在使用快速排序 执行用时 : 60 ms, 在Merge Sorted Array的Python3提交中击败了49.81% 的用户 内存消耗 : 12.9 MB, 在Merge Sort... | 7bca9dc8ec211be15c12f89bffbb680d639f87bf | <|skeleton|>
class Solution:
def merge(self, nums1: 'List[int]', m: int, nums2: 'List[int]', n: int) -> None:
"""先合并,在使用快速排序 执行用时 : 60 ms, 在Merge Sorted Array的Python3提交中击败了49.81% 的用户 内存消耗 : 12.9 MB, 在Merge Sorted Array的Python3提交中击败了99.08% 的用户"""
<|body_0|>
def merge1(self, nums1: 'List[int]', ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def merge(self, nums1: 'List[int]', m: int, nums2: 'List[int]', n: int) -> None:
"""先合并,在使用快速排序 执行用时 : 60 ms, 在Merge Sorted Array的Python3提交中击败了49.81% 的用户 内存消耗 : 12.9 MB, 在Merge Sorted Array的Python3提交中击败了99.08% 的用户"""
if not nums1 or not nums2:
return
for i in rang... | the_stack_v2_python_sparse | python/leetcode/88-merge-sorted-array.py | wxnacy/study | train | 18 | |
46cd9f84e080b768279232e913c4a675ec288dba | [
"if not root:\n return []\nqueue = [root]\nindex = 0\nwhile index < len(queue):\n node = queue[index]\n if node:\n queue.append(node.left)\n queue.append(node.right)\n index += 1\nwhile not queue[-1]:\n queue.pop()\nreturn ','.join([str(node.val) if node else 'null' for node in queue])"... | <|body_start_0|>
if not root:
return []
queue = [root]
index = 0
while index < len(queue):
node = queue[index]
if node:
queue.append(node.left)
queue.append(node.right)
index += 1
while not queue[-1]:... | Codec | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_023126 | 1,617 | permissive | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_015688 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | cb2ed3524431aea2b204fe66797f9850bbe506a9 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return []
queue = [root]
index = 0
while index < len(queue):
node = queue[index]
if node:
queue.a... | the_stack_v2_python_sparse | archive/python/Python/breadth_first_search/297.serialize-and-deserialize-binary-tree.py | linfengzhou/LeetCode | train | 0 | |
3ceb2508bd521f24c76178c55d01e5a72ab9efb8 | [
"if 'output' in results:\n self.data = P.YamboOutputParser(results['output'], verbose=verbose, extendOut=extendOut)\nelse:\n print('There are no o-* files in the %s dictionary. Please check...' % results)\nfor key, value in results.items():\n if key == 'dipoles':\n self.dipoles = P.YamboDipolesParse... | <|body_start_0|>
if 'output' in results:
self.data = P.YamboOutputParser(results['output'], verbose=verbose, extendOut=extendOut)
else:
print('There are no o-* files in the %s dictionary. Please check...' % results)
for key, value in results.items():
if key ==... | Class that perform the parsing starting from the results :py:class:`dict` built by the :class:`YamboCalculator` class. In the actual implementation of the class the parser is able to deal with the o- files, the dipoles database, the ``ndb.RT_G_PAR`` and the ``ns.db1`` database written in the SAVE folder. Args: results ... | YamboParser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class YamboParser:
"""Class that perform the parsing starting from the results :py:class:`dict` built by the :class:`YamboCalculator` class. In the actual implementation of the class the parser is able to deal with the o- files, the dipoles database, the ``ndb.RT_G_PAR`` and the ``ns.db1`` database wri... | stack_v2_sparse_classes_36k_train_023127 | 4,923 | permissive | [
{
"docstring": "Initialize the data member of the class.",
"name": "__init__",
"signature": "def __init__(self, results, verbose=False, extendOut=True)"
},
{
"docstring": "Init the a :class:`YamboParser` instance using the 'o-' files found inside the outputPath, the ``ns.db1`` database in the SA... | 3 | stack_v2_sparse_classes_30k_train_018069 | Implement the Python class `YamboParser` described below.
Class description:
Class that perform the parsing starting from the results :py:class:`dict` built by the :class:`YamboCalculator` class. In the actual implementation of the class the parser is able to deal with the o- files, the dipoles database, the ``ndb.RT_... | Implement the Python class `YamboParser` described below.
Class description:
Class that perform the parsing starting from the results :py:class:`dict` built by the :class:`YamboCalculator` class. In the actual implementation of the class the parser is able to deal with the o- files, the dipoles database, the ``ndb.RT_... | 6ddac37ce8da1c7e1e0291cc5e49591a0e230389 | <|skeleton|>
class YamboParser:
"""Class that perform the parsing starting from the results :py:class:`dict` built by the :class:`YamboCalculator` class. In the actual implementation of the class the parser is able to deal with the o- files, the dipoles database, the ``ndb.RT_G_PAR`` and the ``ns.db1`` database wri... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class YamboParser:
"""Class that perform the parsing starting from the results :py:class:`dict` built by the :class:`YamboCalculator` class. In the actual implementation of the class the parser is able to deal with the o- files, the dipoles database, the ``ndb.RT_G_PAR`` and the ``ns.db1`` database written in the S... | the_stack_v2_python_sparse | mppi/Parsers/YamboParser.py | marcodalessandro76/MPPI | train | 1 |
8cbd9627fbb74cf13f6c462830488a50b9707f56 | [
"if type(dataset) is pd.DataFrame:\n self.data = dataset\nelse:\n filename = kwargs.get('filename', 'test-data.xlsx')\n self.data = pd.read_excel(filename, sheet_name=dataset)\nif len(self.data.columns) == 4:\n self.data.columns = ['asat', 'date', 'mv.all', 'net.all']\nself.data['date'] = as_date(self.d... | <|body_start_0|>
if type(dataset) is pd.DataFrame:
self.data = dataset
else:
filename = kwargs.get('filename', 'test-data.xlsx')
self.data = pd.read_excel(filename, sheet_name=dataset)
if len(self.data.columns) == 4:
self.data.columns = ['asat', 'd... | This class mocks a source of data | MockSource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MockSource:
"""This class mocks a source of data"""
def __init__(self, dataset: Any, **kwargs):
""":param Any dataset: The DataFrame or sheet name to use"""
<|body_0|>
def get_perf_data(self, entity_scope, entity_code, from_date, to_date, asat, **kwargs):
"""Gets... | stack_v2_sparse_classes_36k_train_023128 | 10,680 | no_license | [
{
"docstring": ":param Any dataset: The DataFrame or sheet name to use",
"name": "__init__",
"signature": "def __init__(self, dataset: Any, **kwargs)"
},
{
"docstring": "Gets the relevant performance data from the mock source relevant to the requested bi-temporal window :param str entity_scope: ... | 2 | stack_v2_sparse_classes_30k_train_002640 | Implement the Python class `MockSource` described below.
Class description:
This class mocks a source of data
Method signatures and docstrings:
- def __init__(self, dataset: Any, **kwargs): :param Any dataset: The DataFrame or sheet name to use
- def get_perf_data(self, entity_scope, entity_code, from_date, to_date, ... | Implement the Python class `MockSource` described below.
Class description:
This class mocks a source of data
Method signatures and docstrings:
- def __init__(self, dataset: Any, **kwargs): :param Any dataset: The DataFrame or sheet name to use
- def get_perf_data(self, entity_scope, entity_code, from_date, to_date, ... | b15d2ba0b604ddb94848d5c0353129c2b7229f1e | <|skeleton|>
class MockSource:
"""This class mocks a source of data"""
def __init__(self, dataset: Any, **kwargs):
""":param Any dataset: The DataFrame or sheet name to use"""
<|body_0|>
def get_perf_data(self, entity_scope, entity_code, from_date, to_date, asat, **kwargs):
"""Gets... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MockSource:
"""This class mocks a source of data"""
def __init__(self, dataset: Any, **kwargs):
""":param Any dataset: The DataFrame or sheet name to use"""
if type(dataset) is pd.DataFrame:
self.data = dataset
else:
filename = kwargs.get('filename', 'test-... | the_stack_v2_python_sparse | performance_engine/performance_sources/mock_src.py | finbourne/performance-engine-poc | train | 0 |
2f6bddfbb382c9083cf8cd976bc89deaa43a489c | [
"candles_df = self.get_processed_df()\nlast_candle = candles_df.iloc[-1]\nbbp = last_candle['BBP_100_2.0']\nmacdh = last_candle['MACDh_21_42_9']\nmacd = last_candle['MACD_21_42_9']\nif bbp < 0.4 and macdh > 0 and (macd < 0):\n signal_value = 1\nelif bbp > 0.6 and macdh < 0 and (macd > 0):\n signal_value = -1\... | <|body_start_0|>
candles_df = self.get_processed_df()
last_candle = candles_df.iloc[-1]
bbp = last_candle['BBP_100_2.0']
macdh = last_candle['MACDh_21_42_9']
macd = last_candle['MACD_21_42_9']
if bbp < 0.4 and macdh > 0 and (macd < 0):
signal_value = 1
... | MacdBB strategy implementation based on the DirectionalStrategyBase. This strategy combines the MACD (Moving Average Convergence Divergence) and Bollinger Bands indicators to generate trading signals and execute trades based on the indicator values. It defines the specific parameters and configurations for the MacdBB s... | MacdBB | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MacdBB:
"""MacdBB strategy implementation based on the DirectionalStrategyBase. This strategy combines the MACD (Moving Average Convergence Divergence) and Bollinger Bands indicators to generate trading signals and execute trades based on the indicator values. It defines the specific parameters a... | stack_v2_sparse_classes_36k_train_023129 | 4,188 | permissive | [
{
"docstring": "Generates the trading signal based on the MACD and Bollinger Bands indicators. 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 MACD and Bol... | 3 | null | Implement the Python class `MacdBB` described below.
Class description:
MacdBB strategy implementation based on the DirectionalStrategyBase. This strategy combines the MACD (Moving Average Convergence Divergence) and Bollinger Bands indicators to generate trading signals and execute trades based on the indicator value... | Implement the Python class `MacdBB` described below.
Class description:
MacdBB strategy implementation based on the DirectionalStrategyBase. This strategy combines the MACD (Moving Average Convergence Divergence) and Bollinger Bands indicators to generate trading signals and execute trades based on the indicator value... | c3f101759ab7e7a2165cd23a3a3e94c90c642a9b | <|skeleton|>
class MacdBB:
"""MacdBB strategy implementation based on the DirectionalStrategyBase. This strategy combines the MACD (Moving Average Convergence Divergence) and Bollinger Bands indicators to generate trading signals and execute trades based on the indicator values. It defines the specific parameters a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MacdBB:
"""MacdBB strategy implementation based on the DirectionalStrategyBase. This strategy combines the MACD (Moving Average Convergence Divergence) and Bollinger Bands indicators to generate trading signals and execute trades based on the indicator values. It defines the specific parameters and configurat... | the_stack_v2_python_sparse | scripts/directional_strategy_macd_bb.py | CoinAlpha/hummingbot | train | 135 |
2f80ed59e6982d102ac0cff039fe373199d06090 | [
"log.debug('Outputting %s for query %s', mdseries, query)\nself._qfdomain = 'geckoboard_rag'\nself._write_options()\nself._write_colors()",
"if self.query:\n try:\n qformat = self.query.qformat\n self.jout['prefix'] = qformat.get(self._qfdomain, 'prefix')\n except KeyError:\n pass",
"... | <|body_start_0|>
log.debug('Outputting %s for query %s', mdseries, query)
self._qfdomain = 'geckoboard_rag'
self._write_options()
self._write_colors()
<|end_body_0|>
<|body_start_1|>
if self.query:
try:
qformat = self.query.qformat
sel... | EROut (Extensible Report Outputter) Plugin for Geckoboard RAG. Adds JSON-serializable output to extinfo['jout'] dict. Typical usage is with 1 collapsed query with 3 QMetrics, or several collapsed queries totalling 3 QMetrics, default 'LAST' reduce function, and ghosts disabled. This prevent needless queries from runnin... | EROut_geckoboard_rag | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EROut_geckoboard_rag:
"""EROut (Extensible Report Outputter) Plugin for Geckoboard RAG. Adds JSON-serializable output to extinfo['jout'] dict. Typical usage is with 1 collapsed query with 3 QMetrics, or several collapsed queries totalling 3 QMetrics, default 'LAST' reduce function, and ghosts dis... | stack_v2_sparse_classes_36k_train_023130 | 5,238 | permissive | [
{
"docstring": "EROut plugins must implement this abstract method. Invoked to output MultiDataSeries as specified. Returns nothing. Output target should be configured separately.",
"name": "plugin_output",
"signature": "def plugin_output(self, mdseries, query=None)"
},
{
"docstring": "Write opti... | 4 | stack_v2_sparse_classes_30k_train_019600 | Implement the Python class `EROut_geckoboard_rag` described below.
Class description:
EROut (Extensible Report Outputter) Plugin for Geckoboard RAG. Adds JSON-serializable output to extinfo['jout'] dict. Typical usage is with 1 collapsed query with 3 QMetrics, or several collapsed queries totalling 3 QMetrics, default... | Implement the Python class `EROut_geckoboard_rag` described below.
Class description:
EROut (Extensible Report Outputter) Plugin for Geckoboard RAG. Adds JSON-serializable output to extinfo['jout'] dict. Typical usage is with 1 collapsed query with 3 QMetrics, or several collapsed queries totalling 3 QMetrics, default... | a2db75c9ef9a9752997ccb112e8db68c1c8584a0 | <|skeleton|>
class EROut_geckoboard_rag:
"""EROut (Extensible Report Outputter) Plugin for Geckoboard RAG. Adds JSON-serializable output to extinfo['jout'] dict. Typical usage is with 1 collapsed query with 3 QMetrics, or several collapsed queries totalling 3 QMetrics, default 'LAST' reduce function, and ghosts dis... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EROut_geckoboard_rag:
"""EROut (Extensible Report Outputter) Plugin for Geckoboard RAG. Adds JSON-serializable output to extinfo['jout'] dict. Typical usage is with 1 collapsed query with 3 QMetrics, or several collapsed queries totalling 3 QMetrics, default 'LAST' reduce function, and ghosts disabled. This p... | the_stack_v2_python_sparse | py/axonchisel/metrics/io/erout/plugins/ero_geckoboard/rag.py | dkamins/ax_metrics | train | 0 |
eb92c549142e0a37025937949a3b5bfb67912ecf | [
"filterfile = functions.launchcmd('grep -v \"^#\" ' + filename).readlines()\nhostsinfo = []\nfor t in filterfile:\n oneinfo = t.split(':', 2)\n if len(oneinfo) == 3:\n hostsinfo.append(oneinfo)\n elif len(oneinfo) == 2:\n oneinfo.append('')\n hostsinfo.append(oneinfo)\n elif len(one... | <|body_start_0|>
filterfile = functions.launchcmd('grep -v "^#" ' + filename).readlines()
hostsinfo = []
for t in filterfile:
oneinfo = t.split(':', 2)
if len(oneinfo) == 3:
hostsinfo.append(oneinfo)
elif len(oneinfo) == 2:
onei... | tcp business | TcpBusiness | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TcpBusiness:
"""tcp business"""
def getlistinfo(cls, filename):
"""read info from sys :param filename: :return:"""
<|body_0|>
def putlistinfo(cls, request, filename):
"""write info to sys :param request: :param filename: :return:"""
<|body_1|>
def de... | stack_v2_sparse_classes_36k_train_023131 | 3,237 | no_license | [
{
"docstring": "read info from sys :param filename: :return:",
"name": "getlistinfo",
"signature": "def getlistinfo(cls, filename)"
},
{
"docstring": "write info to sys :param request: :param filename: :return:",
"name": "putlistinfo",
"signature": "def putlistinfo(cls, request, filename... | 3 | null | Implement the Python class `TcpBusiness` described below.
Class description:
tcp business
Method signatures and docstrings:
- def getlistinfo(cls, filename): read info from sys :param filename: :return:
- def putlistinfo(cls, request, filename): write info to sys :param request: :param filename: :return:
- def delete... | Implement the Python class `TcpBusiness` described below.
Class description:
tcp business
Method signatures and docstrings:
- def getlistinfo(cls, filename): read info from sys :param filename: :return:
- def putlistinfo(cls, request, filename): write info to sys :param request: :param filename: :return:
- def delete... | 7f801a569a396a27371d0831752595877c224a6b | <|skeleton|>
class TcpBusiness:
"""tcp business"""
def getlistinfo(cls, filename):
"""read info from sys :param filename: :return:"""
<|body_0|>
def putlistinfo(cls, request, filename):
"""write info to sys :param request: :param filename: :return:"""
<|body_1|>
def de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TcpBusiness:
"""tcp business"""
def getlistinfo(cls, filename):
"""read info from sys :param filename: :return:"""
filterfile = functions.launchcmd('grep -v "^#" ' + filename).readlines()
hostsinfo = []
for t in filterfile:
oneinfo = t.split(':', 2)
... | the_stack_v2_python_sparse | Python_projects/flask_projects/unicorn_project/tcp/business.py | sdtimothy8/Coding | train | 0 |
9fbd46dca840142afd7ee971875deec53dd23af8 | [
"Algorithm.__init__(self)\nself.name = 'Fast nl Means Denoising'\nself.parent = 'Preprocessing'\nself.filter_strength = FloatSlider('filter strength', 1.0, 100.0, 0.1, 1.0)\nself.template_window_size = IntegerSlider('template window size', 1, 20, 1, 3)\nself.search_window_size = IntegerSlider('search window size', ... | <|body_start_0|>
Algorithm.__init__(self)
self.name = 'Fast nl Means Denoising'
self.parent = 'Preprocessing'
self.filter_strength = FloatSlider('filter strength', 1.0, 100.0, 0.1, 1.0)
self.template_window_size = IntegerSlider('template window size', 1, 20, 1, 3)
self.se... | Fast nl Means Denoising algorithm implementation | AlgBody | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlgBody:
"""Fast nl Means Denoising algorithm implementation"""
def __init__(self):
"""Fast nl Means Denoising object constructor Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriated category | *filterStrength* : Parameter regulating filter strength. ... | stack_v2_sparse_classes_36k_train_023132 | 3,364 | no_license | [
{
"docstring": "Fast nl Means Denoising object constructor Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriated category | *filterStrength* : Parameter regulating filter strength. A larger value of the parameter means that more noise and also more image details will be removed |... | 2 | stack_v2_sparse_classes_30k_train_002318 | Implement the Python class `AlgBody` described below.
Class description:
Fast nl Means Denoising algorithm implementation
Method signatures and docstrings:
- def __init__(self): Fast nl Means Denoising object constructor Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriated category | ... | Implement the Python class `AlgBody` described below.
Class description:
Fast nl Means Denoising algorithm implementation
Method signatures and docstrings:
- def __init__(self): Fast nl Means Denoising object constructor Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriated category | ... | 0dc9becc09da22af3edac90b81b1dd9b1f44fd5b | <|skeleton|>
class AlgBody:
"""Fast nl Means Denoising algorithm implementation"""
def __init__(self):
"""Fast nl Means Denoising object constructor Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriated category | *filterStrength* : Parameter regulating filter strength. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlgBody:
"""Fast nl Means Denoising algorithm implementation"""
def __init__(self):
"""Fast nl Means Denoising object constructor Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriated category | *filterStrength* : Parameter regulating filter strength. A larger valu... | the_stack_v2_python_sparse | Sebastian_Algorithms_untested/fast_nl_denoise.py | andreasfirczynski/NetworkExtractionFromImages | train | 0 |
a482d65f643be8f0ba671e7f37c217eee3c7cbb7 | [
"if not request.json:\n abort(400)\nfor expected in request_keys:\n if expected not in request.json:\n abort(400)",
"options = {}\nif 'options' in request.json:\n options = request.json.get('options')\n if len(options) > 0:\n options = json.loads(options)\nreturn options",
"FlaskWebSer... | <|body_start_0|>
if not request.json:
abort(400)
for expected in request_keys:
if expected not in request.json:
abort(400)
<|end_body_0|>
<|body_start_1|>
options = {}
if 'options' in request.json:
options = request.json.get('options')... | Flask Web Services Invoice Manager | FlaskWebServicesInvoiceManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlaskWebServicesInvoiceManager:
"""Flask Web Services Invoice Manager"""
def check_service_requirements(request_keys):
"""Checks service request minimal requirements."""
<|body_0|>
def get_service_options():
"""Returns service options."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_023133 | 7,699 | no_license | [
{
"docstring": "Checks service request minimal requirements.",
"name": "check_service_requirements",
"signature": "def check_service_requirements(request_keys)"
},
{
"docstring": "Returns service options.",
"name": "get_service_options",
"signature": "def get_service_options()"
},
{
... | 6 | stack_v2_sparse_classes_30k_train_011332 | Implement the Python class `FlaskWebServicesInvoiceManager` described below.
Class description:
Flask Web Services Invoice Manager
Method signatures and docstrings:
- def check_service_requirements(request_keys): Checks service request minimal requirements.
- def get_service_options(): Returns service options.
- def ... | Implement the Python class `FlaskWebServicesInvoiceManager` described below.
Class description:
Flask Web Services Invoice Manager
Method signatures and docstrings:
- def check_service_requirements(request_keys): Checks service request minimal requirements.
- def get_service_options(): Returns service options.
- def ... | a2ee333d2a4fe9821f3d24ee15d458f226ffcde5 | <|skeleton|>
class FlaskWebServicesInvoiceManager:
"""Flask Web Services Invoice Manager"""
def check_service_requirements(request_keys):
"""Checks service request minimal requirements."""
<|body_0|>
def get_service_options():
"""Returns service options."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FlaskWebServicesInvoiceManager:
"""Flask Web Services Invoice Manager"""
def check_service_requirements(request_keys):
"""Checks service request minimal requirements."""
if not request.json:
abort(400)
for expected in request_keys:
if expected not in reques... | the_stack_v2_python_sparse | src/server/wsdl/invoice_manager.py | hamed1361554/sportmagazine-server | train | 0 |
40cc93c73c7358a03e501acc0f7007eb0f1a487d | [
"self._displayLists = {}\nself.fontStyle = fontStyle or None\nif not font:\n if __debug__:\n log.info('wx.BitmapFont passed a null wxPython font, doing lookup for fontStyle %r', fontStyle)\n family, face, font = wxFontProvider.match(fontStyle)\n if not font:\n raise ValueError('Could not gene... | <|body_start_0|>
self._displayLists = {}
self.fontStyle = fontStyle or None
if not font:
if __debug__:
log.info('wx.BitmapFont passed a null wxPython font, doing lookup for fontStyle %r', fontStyle)
family, face, font = wxFontProvider.match(fontStyle)
... | A wxPython-provided Bitmap Font The wxPython fonts are image-based, non-antialiased, and available only under wxPython contexts, though on Win32 you can actually use them when using a non wxPython context (they will crash or application on GTK/Linux because the wxPython application object is not available under other c... | wxBitmapFont | [
"MIT",
"GPL-1.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-copyleft",
"LGPL-2.1-or-later",
"GPL-3.0-only",
"LGPL-2.0-or-later",
"GPL-3.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class wxBitmapFont:
"""A wxPython-provided Bitmap Font The wxPython fonts are image-based, non-antialiased, and available only under wxPython contexts, though on Win32 you can actually use them when using a non wxPython context (they will crash or application on GTK/Linux because the wxPython applicati... | stack_v2_sparse_classes_36k_train_023134 | 11,262 | permissive | [
{
"docstring": "Initialize the wxBitmapFont object fontStyle -- the FontStyle node which generates this font, can be None, in which case VRML97 default semantics are used. font -- the wxPython font used to render the bitmaps on which we are based. Can be None, in which case we will find the appropriate font usi... | 6 | stack_v2_sparse_classes_30k_train_001158 | Implement the Python class `wxBitmapFont` described below.
Class description:
A wxPython-provided Bitmap Font The wxPython fonts are image-based, non-antialiased, and available only under wxPython contexts, though on Win32 you can actually use them when using a non wxPython context (they will crash or application on G... | Implement the Python class `wxBitmapFont` described below.
Class description:
A wxPython-provided Bitmap Font The wxPython fonts are image-based, non-antialiased, and available only under wxPython contexts, though on Win32 you can actually use them when using a non wxPython context (they will crash or application on G... | 7f600ad153270feff12aa7aa86d7ed0a49ebc71c | <|skeleton|>
class wxBitmapFont:
"""A wxPython-provided Bitmap Font The wxPython fonts are image-based, non-antialiased, and available only under wxPython contexts, though on Win32 you can actually use them when using a non wxPython context (they will crash or application on GTK/Linux because the wxPython applicati... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class wxBitmapFont:
"""A wxPython-provided Bitmap Font The wxPython fonts are image-based, non-antialiased, and available only under wxPython contexts, though on Win32 you can actually use them when using a non wxPython context (they will crash or application on GTK/Linux because the wxPython application object is ... | the_stack_v2_python_sparse | pythonAnimations/pyOpenGLChess/engineDirectory/oglc-env/lib/python2.7/site-packages/OpenGLContext/scenegraph/text/wxfont.py | alexus37/AugmentedRealityChess | train | 1 |
a06f113778d77cd4bb59df738bcc33f6b9f12e70 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn CallTranscriptEventMessageDetail()",
"from .event_message_detail import EventMessageDetail\nfrom .identity_set import IdentitySet\nfrom .event_message_detail import EventMessageDetail\nfrom .identity_set import IdentitySet\nfields: Dic... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return CallTranscriptEventMessageDetail()
<|end_body_0|>
<|body_start_1|>
from .event_message_detail import EventMessageDetail
from .identity_set import IdentitySet
from .event_message_... | CallTranscriptEventMessageDetail | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CallTranscriptEventMessageDetail:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CallTranscriptEventMessageDetail:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminat... | stack_v2_sparse_classes_36k_train_023135 | 2,890 | 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: CallTranscriptEventMessageDetail",
"name": "create_from_discriminator_value",
"signature": "def create_from_... | 3 | null | Implement the Python class `CallTranscriptEventMessageDetail` described below.
Class description:
Implement the CallTranscriptEventMessageDetail class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CallTranscriptEventMessageDetail: Creates a new insta... | Implement the Python class `CallTranscriptEventMessageDetail` described below.
Class description:
Implement the CallTranscriptEventMessageDetail class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CallTranscriptEventMessageDetail: Creates a new insta... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class CallTranscriptEventMessageDetail:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CallTranscriptEventMessageDetail:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CallTranscriptEventMessageDetail:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CallTranscriptEventMessageDetail:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and c... | the_stack_v2_python_sparse | msgraph/generated/models/call_transcript_event_message_detail.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
aabd6b0aea8fff1be5959ee22c29e20327a1a17d | [
"local_var_params = locals()\nall_params = ['wid', 'uuid']\nall_params.append('async_req')\nall_params.append('_return_http_data_only')\nall_params.append('_preload_content')\nall_params.append('_request_timeout')\nall_params.append('_accept')\nfor key, val in six.iteritems(local_var_params['kwargs']):\n if key ... | <|body_start_0|>
local_var_params = locals()
all_params = ['wid', 'uuid']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('_accept')
fo... | Custom DataApi object for some OpenAPI workarounds The code generated by the OpenAPI generator has a particular problem (bug?) that immediately falls back to a json response if the accept header has "application/json" even if we want "application/octet-stream". This is handled by re-writing the workspace_file_details_w... | CustomDataApi | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomDataApi:
"""Custom DataApi object for some OpenAPI workarounds The code generated by the OpenAPI generator has a particular problem (bug?) that immediately falls back to a json response if the accept header has "application/json" even if we want "application/octet-stream". This is handled b... | stack_v2_sparse_classes_36k_train_023136 | 15,066 | permissive | [
{
"docstring": "Copy/paste and workaround the original workspace_file_details_with_http_info Accepts an application/octet-stream according to the _accept kwarg",
"name": "workspace_file_details_with_http_info",
"signature": "def workspace_file_details_with_http_info(self, wid, uuid, **kwargs)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_019988 | Implement the Python class `CustomDataApi` described below.
Class description:
Custom DataApi object for some OpenAPI workarounds The code generated by the OpenAPI generator has a particular problem (bug?) that immediately falls back to a json response if the accept header has "application/json" even if we want "appli... | Implement the Python class `CustomDataApi` described below.
Class description:
Custom DataApi object for some OpenAPI workarounds The code generated by the OpenAPI generator has a particular problem (bug?) that immediately falls back to a json response if the accept header has "application/json" even if we want "appli... | ae6b38baff7c695e2a01bf83d3eff48543bd7f57 | <|skeleton|>
class CustomDataApi:
"""Custom DataApi object for some OpenAPI workarounds The code generated by the OpenAPI generator has a particular problem (bug?) that immediately falls back to a json response if the accept header has "application/json" even if we want "application/octet-stream". This is handled b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomDataApi:
"""Custom DataApi object for some OpenAPI workarounds The code generated by the OpenAPI generator has a particular problem (bug?) that immediately falls back to a json response if the accept header has "application/json" even if we want "application/octet-stream". This is handled by re-writing ... | the_stack_v2_python_sparse | quetzal/client/base.py | quetz-al/quetzal-client | train | 2 |
a6db9661d5ebece04fac8c41453a221b4c32f71f | [
"self.virtual = virtual\nif self.virtual and kwargs.get('visalib', None) is not None:\n raise ValueError('The visalib should not be changed for the virtual E8527D.')\nif frequency_option not in self.FREQUENCY_OPTIONS:\n raise ValueError(f\"Invalid parameter 'frequency_option={frequency_option!r}'. Possible va... | <|body_start_0|>
self.virtual = virtual
if self.virtual and kwargs.get('visalib', None) is not None:
raise ValueError('The visalib should not be changed for the virtual E8527D.')
if frequency_option not in self.FREQUENCY_OPTIONS:
raise ValueError(f"Invalid parameter 'freq... | Modified version of the QCoDeS Agilent_E8527D driver with higher maximal power and with parameter pulsemod_state for using Pulse Modulation. See :class:`qcodes.instrument_drivers.agilent.Agilent_E8527D.AgilentE8257D` | Agilent_E8527D | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Agilent_E8527D:
"""Modified version of the QCoDeS Agilent_E8527D driver with higher maximal power and with parameter pulsemod_state for using Pulse Modulation. See :class:`qcodes.instrument_drivers.agilent.Agilent_E8527D.AgilentE8257D`"""
def __init__(self, *args, virtual=False, frequency_op... | stack_v2_sparse_classes_36k_train_023137 | 6,216 | permissive | [
{
"docstring": "Constructor. Arguments: virtual: Set it to True for virtual (mocked) device. frequency_option: Useful only if ``virtual=True``, this corresponds to the model variant (possible values: see :attr:`FREQUENCY_OPTIONS`). args, kwargs: Same arguments as the parent class, see :class:`qcodes.instrument_... | 5 | stack_v2_sparse_classes_30k_train_018476 | Implement the Python class `Agilent_E8527D` described below.
Class description:
Modified version of the QCoDeS Agilent_E8527D driver with higher maximal power and with parameter pulsemod_state for using Pulse Modulation. See :class:`qcodes.instrument_drivers.agilent.Agilent_E8527D.AgilentE8257D`
Method signatures and... | Implement the Python class `Agilent_E8527D` described below.
Class description:
Modified version of the QCoDeS Agilent_E8527D driver with higher maximal power and with parameter pulsemod_state for using Pulse Modulation. See :class:`qcodes.instrument_drivers.agilent.Agilent_E8527D.AgilentE8257D`
Method signatures and... | bc6733d774fe31a23f4c7e73e5eb0beed8d30e7d | <|skeleton|>
class Agilent_E8527D:
"""Modified version of the QCoDeS Agilent_E8527D driver with higher maximal power and with parameter pulsemod_state for using Pulse Modulation. See :class:`qcodes.instrument_drivers.agilent.Agilent_E8527D.AgilentE8257D`"""
def __init__(self, *args, virtual=False, frequency_op... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Agilent_E8527D:
"""Modified version of the QCoDeS Agilent_E8527D driver with higher maximal power and with parameter pulsemod_state for using Pulse Modulation. See :class:`qcodes.instrument_drivers.agilent.Agilent_E8527D.AgilentE8257D`"""
def __init__(self, *args, virtual=False, frequency_option='513', *... | the_stack_v2_python_sparse | pycqed/instrument_drivers/physical_instruments/E8527D.py | QudevETH/PycQED_py3 | train | 8 |
d5da6fe8e88aff17647d3c6f5cf02807e642e453 | [
"if len(nums) < k:\n return 0\ni = k\nsums = 0\nsums = sum(nums[:k])\nmax_avg = sums / k\navg = max_avg\nwhile i < len(nums):\n sums = sums + nums[i] - nums[i - k]\n avg = sums / k\n if avg > max_avg:\n max_avg = avg\n i = i + 1\nreturn max(max_avg, sums / k)",
"k = len(nums1) - 1\nm = m - 1... | <|body_start_0|>
if len(nums) < k:
return 0
i = k
sums = 0
sums = sum(nums[:k])
max_avg = sums / k
avg = max_avg
while i < len(nums):
sums = sums + nums[i] - nums[i - k]
avg = sums / k
if avg > max_avg:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMaxAverage(self, nums, k):
""":type nums: List[int] :type k: int :rtype: float"""
<|body_0|>
def merge(self, nums1, m, nums2, n):
""":type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify ... | stack_v2_sparse_classes_36k_train_023138 | 1,998 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: float",
"name": "findMaxAverage",
"signature": "def findMaxAverage(self, nums, k)"
},
{
"docstring": ":type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place inst... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMaxAverage(self, nums, k): :type nums: List[int] :type k: int :rtype: float
- def merge(self, nums1, m, nums2, n): :type nums1: List[int] :type m: int :type nums2: List[i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMaxAverage(self, nums, k): :type nums: List[int] :type k: int :rtype: float
- def merge(self, nums1, m, nums2, n): :type nums1: List[int] :type m: int :type nums2: List[i... | 2337b5031d4dfe033a471cea8ab4aa5ab66122d0 | <|skeleton|>
class Solution:
def findMaxAverage(self, nums, k):
""":type nums: List[int] :type k: int :rtype: float"""
<|body_0|>
def merge(self, nums1, m, nums2, n):
""":type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findMaxAverage(self, nums, k):
""":type nums: List[int] :type k: int :rtype: float"""
if len(nums) < k:
return 0
i = k
sums = 0
sums = sum(nums[:k])
max_avg = sums / k
avg = max_avg
while i < len(nums):
sums ... | the_stack_v2_python_sparse | ArrayEasy.py | shants/LeetCodePy | train | 0 | |
08d3685d1eeabced68dc29df9ab5d0144a239061 | [
"super(Langmuir, self).__init__(**kwargs)\nself.array_types.update(('area', 'fay_area', 'frac_coverage', 'spill_num', 'bulk_init_volume', 'density', 'positions'))\nself.wind = wind\nself.water = water",
"v_max = np.max(self.get_wind_speed(points, model_time) * 0.005)\ncr_k = (v_max ** 2 * 4 * np.pi ** 2 / (thickn... | <|body_start_0|>
super(Langmuir, self).__init__(**kwargs)
self.array_types.update(('area', 'fay_area', 'frac_coverage', 'spill_num', 'bulk_init_volume', 'density', 'positions'))
self.wind = wind
self.water = water
<|end_body_0|>
<|body_start_1|>
v_max = np.max(self.get_wind_spee... | Easiest to define this as a weathering process that updates 'area' array | Langmuir | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Langmuir:
"""Easiest to define this as a weathering process that updates 'area' array"""
def __init__(self, water=None, wind=None, **kwargs):
"""initialize wind to (0, 0) if it is None"""
<|body_0|>
def _get_frac_coverage(self, points, model_time, rel_buoy, thickness):
... | stack_v2_sparse_classes_36k_train_023139 | 26,568 | no_license | [
{
"docstring": "initialize wind to (0, 0) if it is None",
"name": "__init__",
"signature": "def __init__(self, water=None, wind=None, **kwargs)"
},
{
"docstring": "return fractional coverage for a blob of oil with inputs; relative_buoyancy, and thickness Assumes the thickness is the minimum oil ... | 4 | stack_v2_sparse_classes_30k_train_016172 | Implement the Python class `Langmuir` described below.
Class description:
Easiest to define this as a weathering process that updates 'area' array
Method signatures and docstrings:
- def __init__(self, water=None, wind=None, **kwargs): initialize wind to (0, 0) if it is None
- def _get_frac_coverage(self, points, mod... | Implement the Python class `Langmuir` described below.
Class description:
Easiest to define this as a weathering process that updates 'area' array
Method signatures and docstrings:
- def __init__(self, water=None, wind=None, **kwargs): initialize wind to (0, 0) if it is None
- def _get_frac_coverage(self, points, mod... | 2e24d53b8b1099022a08ad73377ed6d1c7838f0f | <|skeleton|>
class Langmuir:
"""Easiest to define this as a weathering process that updates 'area' array"""
def __init__(self, water=None, wind=None, **kwargs):
"""initialize wind to (0, 0) if it is None"""
<|body_0|>
def _get_frac_coverage(self, points, model_time, rel_buoy, thickness):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Langmuir:
"""Easiest to define this as a weathering process that updates 'area' array"""
def __init__(self, water=None, wind=None, **kwargs):
"""initialize wind to (0, 0) if it is None"""
super(Langmuir, self).__init__(**kwargs)
self.array_types.update(('area', 'fay_area', 'frac_c... | the_stack_v2_python_sparse | py_gnome/gnome/weatherers/spreading.py | bhattvihang/PyGnome | train | 1 |
c72bc7da77279c44bbce212bca987b6e57de76dc | [
"flags.GetRepoArg().AddToParser(parser)\nbase.ASYNC_FLAG.AddToParser(parser)\nparser.add_argument('--source', metavar='SOURCE', required=True, help=' The path of a package to upload.')",
"client = apis.GetClientInstance('artifactregistry', self.api_version)\nmessages = client.MESSAGES_MODULE\nclient.ad... | <|body_start_0|>
flags.GetRepoArg().AddToParser(parser)
base.ASYNC_FLAG.AddToParser(parser)
parser.add_argument('--source', metavar='SOURCE', required=True, help=' The path of a package to upload.')
<|end_body_0|>
<|body_start_1|>
client = apis.GetClientInstance('artifactregi... | Upload an RPM package to an artifact repository. | Upload | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Upload:
"""Upload an RPM package to an artifact repository."""
def Args(parser):
"""Set up arguements for this command. Args: parser: An argparse.ArgumentPaser."""
<|body_0|>
def Run(self, args):
"""Run package import command."""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k_train_023140 | 3,131 | permissive | [
{
"docstring": "Set up arguements for this command. Args: parser: An argparse.ArgumentPaser.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "Run package import command.",
"name": "Run",
"signature": "def Run(self, args)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007720 | Implement the Python class `Upload` described below.
Class description:
Upload an RPM package to an artifact repository.
Method signatures and docstrings:
- def Args(parser): Set up arguements for this command. Args: parser: An argparse.ArgumentPaser.
- def Run(self, args): Run package import command. | Implement the Python class `Upload` described below.
Class description:
Upload an RPM package to an artifact repository.
Method signatures and docstrings:
- def Args(parser): Set up arguements for this command. Args: parser: An argparse.ArgumentPaser.
- def Run(self, args): Run package import command.
<|skeleton|>
c... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class Upload:
"""Upload an RPM package to an artifact repository."""
def Args(parser):
"""Set up arguements for this command. Args: parser: An argparse.ArgumentPaser."""
<|body_0|>
def Run(self, args):
"""Run package import command."""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Upload:
"""Upload an RPM package to an artifact repository."""
def Args(parser):
"""Set up arguements for this command. Args: parser: An argparse.ArgumentPaser."""
flags.GetRepoArg().AddToParser(parser)
base.ASYNC_FLAG.AddToParser(parser)
parser.add_argument('--source', me... | the_stack_v2_python_sparse | lib/surface/artifacts/yum/upload.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
bc5f77ef18fe5de788287c53bccb5c650829d303 | [
"if original_price or customer.next_package_original_price != 0:\n if original_price != 0:\n pass\n else:\n original_price = customer.invoice_product_original_price\nelse:\n original_price = customer.invoice_product_original_price\nif package:\n original_price = package.list_price\npackage... | <|body_start_0|>
if original_price or customer.next_package_original_price != 0:
if original_price != 0:
pass
else:
original_price = customer.invoice_product_original_price
else:
original_price = customer.invoice_product_original_price
... | Saves the customer Package history | CustomerPackageHistory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomerPackageHistory:
"""Saves the customer Package history"""
def create_new_package_history(self, customer, package=None, start_date=None, price=None, original_price=None):
"""Returns created package history according to given customer and package info :param customer: customer o... | stack_v2_sparse_classes_36k_train_023141 | 6,032 | no_license | [
{
"docstring": "Returns created package history according to given customer and package info :param customer: customer obj :param package: package obj :param start_date: start date of the package :param price: price of the package :param original_price: original price of the package :return: package history obj... | 2 | stack_v2_sparse_classes_30k_train_002042 | Implement the Python class `CustomerPackageHistory` described below.
Class description:
Saves the customer Package history
Method signatures and docstrings:
- def create_new_package_history(self, customer, package=None, start_date=None, price=None, original_price=None): Returns created package history according to gi... | Implement the Python class `CustomerPackageHistory` described below.
Class description:
Saves the customer Package history
Method signatures and docstrings:
- def create_new_package_history(self, customer, package=None, start_date=None, price=None, original_price=None): Returns created package history according to gi... | ddbc84a20262bbe638862d1b1e63ae76972a9182 | <|skeleton|>
class CustomerPackageHistory:
"""Saves the customer Package history"""
def create_new_package_history(self, customer, package=None, start_date=None, price=None, original_price=None):
"""Returns created package history according to given customer and package info :param customer: customer o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomerPackageHistory:
"""Saves the customer Package history"""
def create_new_package_history(self, customer, package=None, start_date=None, price=None, original_price=None):
"""Returns created package history according to given customer and package info :param customer: customer obj :param pac... | the_stack_v2_python_sparse | isp_crm_module/models/isp_crm_customer_package_history.py | DigiconTelecommunicationLtd/custom-addons | train | 1 |
2b87986897b4c1a914fc6d44e0fd0a9501f56877 | [
"self.split_by_line = split_by_line\nself.eol = end_of_line_token\nself.remove_headers = remove_headers\nresponse = requests.get(self.WIKI_URL, stream=True)\nwith ZipFile(BytesIO(response.content), 'r') as z:\n train = self._process(z.read('wikitext-103/wiki.train.tokens'))\n val = self._process(z.read('wikit... | <|body_start_0|>
self.split_by_line = split_by_line
self.eol = end_of_line_token
self.remove_headers = remove_headers
response = requests.get(self.WIKI_URL, stream=True)
with ZipFile(BytesIO(response.content), 'r') as z:
train = self._process(z.read('wikitext-103/wiki... | The official WikiText103 dataset. | Wiki103 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Wiki103:
"""The official WikiText103 dataset."""
def __init__(self, split_by_line: bool=False, end_of_line_token: Optional[str]='<eol>', remove_headers: bool=False, cache: bool=False, transform: Dict[str, Union[Field, Dict]]=None) -> None:
"""Initialize the Wiki103 built-in. Paramete... | stack_v2_sparse_classes_36k_train_023142 | 6,879 | permissive | [
{
"docstring": "Initialize the Wiki103 built-in. Parameters ---------- split_by_sentence: bool, Optional If true, tokenizes per sentence. Default ``False``. end_of_line_token: str, Optional Token added at the end of every line. see TabularDataset for other arguments.",
"name": "__init__",
"signature": "... | 2 | stack_v2_sparse_classes_30k_val_000047 | Implement the Python class `Wiki103` described below.
Class description:
The official WikiText103 dataset.
Method signatures and docstrings:
- def __init__(self, split_by_line: bool=False, end_of_line_token: Optional[str]='<eol>', remove_headers: bool=False, cache: bool=False, transform: Dict[str, Union[Field, Dict]]... | Implement the Python class `Wiki103` described below.
Class description:
The official WikiText103 dataset.
Method signatures and docstrings:
- def __init__(self, split_by_line: bool=False, end_of_line_token: Optional[str]='<eol>', remove_headers: bool=False, cache: bool=False, transform: Dict[str, Union[Field, Dict]]... | 0dc2f5b2b286694defe8abf450fe5be9ae12c097 | <|skeleton|>
class Wiki103:
"""The official WikiText103 dataset."""
def __init__(self, split_by_line: bool=False, end_of_line_token: Optional[str]='<eol>', remove_headers: bool=False, cache: bool=False, transform: Dict[str, Union[Field, Dict]]=None) -> None:
"""Initialize the Wiki103 built-in. Paramete... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Wiki103:
"""The official WikiText103 dataset."""
def __init__(self, split_by_line: bool=False, end_of_line_token: Optional[str]='<eol>', remove_headers: bool=False, cache: bool=False, transform: Dict[str, Union[Field, Dict]]=None) -> None:
"""Initialize the Wiki103 built-in. Parameters ----------... | the_stack_v2_python_sparse | flambe/nlp/language_modeling/datasets.py | cle-ros/flambe | train | 1 |
8f3acc97bb4a060670adfcbc31f9008c689bfa0c | [
"for obj in objs:\n obj.save_tracked_fields()\nobjs = super().bulk_create(objs, **kwargs)\nif objs:\n model = type(objs[0])\n model.call_post_bulk_create(objs, using=self.db)\nreturn objs",
"with transaction.atomic():\n current_dt = timezone.now()\n result = queryset.update(cqrs_revision=F('cqrs_re... | <|body_start_0|>
for obj in objs:
obj.save_tracked_fields()
objs = super().bulk_create(objs, **kwargs)
if objs:
model = type(objs[0])
model.call_post_bulk_create(objs, using=self.db)
return objs
<|end_body_0|>
<|body_start_1|>
with transaction... | MasterManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MasterManager:
def bulk_create(self, objs, **kwargs):
"""Custom bulk create method to support sending of create signals. This can be used only in cases, when IDs are generated on client or DB returns IDs. :param django.db.models.Model objs: List of objects for creation :param kwargs: Bul... | stack_v2_sparse_classes_36k_train_023143 | 11,329 | permissive | [
{
"docstring": "Custom bulk create method to support sending of create signals. This can be used only in cases, when IDs are generated on client or DB returns IDs. :param django.db.models.Model objs: List of objects for creation :param kwargs: Bulk create kwargs",
"name": "bulk_create",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_010800 | Implement the Python class `MasterManager` described below.
Class description:
Implement the MasterManager class.
Method signatures and docstrings:
- def bulk_create(self, objs, **kwargs): Custom bulk create method to support sending of create signals. This can be used only in cases, when IDs are generated on client ... | Implement the Python class `MasterManager` described below.
Class description:
Implement the MasterManager class.
Method signatures and docstrings:
- def bulk_create(self, objs, **kwargs): Custom bulk create method to support sending of create signals. This can be used only in cases, when IDs are generated on client ... | c69c81fec47f469e539ed4dc1faa543a7cfd491d | <|skeleton|>
class MasterManager:
def bulk_create(self, objs, **kwargs):
"""Custom bulk create method to support sending of create signals. This can be used only in cases, when IDs are generated on client or DB returns IDs. :param django.db.models.Model objs: List of objects for creation :param kwargs: Bul... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MasterManager:
def bulk_create(self, objs, **kwargs):
"""Custom bulk create method to support sending of create signals. This can be used only in cases, when IDs are generated on client or DB returns IDs. :param django.db.models.Model objs: List of objects for creation :param kwargs: Bulk create kwarg... | the_stack_v2_python_sparse | dj_cqrs/managers.py | net-free/django-cqrs | train | 0 | |
927db745b956f60fdbed533e1269df829da449d5 | [
"actual = divisors.get_divisors(8, [1, 2, 3])\nexpected = [1, 2]\nself.assertEqual(actual, expected)",
"actual = divisors.get_divisors(4, [-2, 0, 2])\nexpected = [-2, 2]\nself.assertEqual(actual, expected)"
] | <|body_start_0|>
actual = divisors.get_divisors(8, [1, 2, 3])
expected = [1, 2]
self.assertEqual(actual, expected)
<|end_body_0|>
<|body_start_1|>
actual = divisors.get_divisors(4, [-2, 0, 2])
expected = [-2, 2]
self.assertEqual(actual, expected)
<|end_body_1|>
| Example unittest test methods for get_divisors. | TestDivisors | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDivisors:
"""Example unittest test methods for get_divisors."""
def test_divisors_example_1(self):
"""Test get_divisors with 8 and [1,2,3]."""
<|body_0|>
def test_divisors_example_2(self):
"""Test get_divisors with 4 and [-2,0,2]."""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k_train_023144 | 1,309 | no_license | [
{
"docstring": "Test get_divisors with 8 and [1,2,3].",
"name": "test_divisors_example_1",
"signature": "def test_divisors_example_1(self)"
},
{
"docstring": "Test get_divisors with 4 and [-2,0,2].",
"name": "test_divisors_example_2",
"signature": "def test_divisors_example_2(self)"
}
... | 2 | stack_v2_sparse_classes_30k_train_017926 | Implement the Python class `TestDivisors` described below.
Class description:
Example unittest test methods for get_divisors.
Method signatures and docstrings:
- def test_divisors_example_1(self): Test get_divisors with 8 and [1,2,3].
- def test_divisors_example_2(self): Test get_divisors with 4 and [-2,0,2]. | Implement the Python class `TestDivisors` described below.
Class description:
Example unittest test methods for get_divisors.
Method signatures and docstrings:
- def test_divisors_example_1(self): Test get_divisors with 8 and [1,2,3].
- def test_divisors_example_2(self): Test get_divisors with 4 and [-2,0,2].
<|skel... | 242d80f313ee590540e7992910b7cc01be8df721 | <|skeleton|>
class TestDivisors:
"""Example unittest test methods for get_divisors."""
def test_divisors_example_1(self):
"""Test get_divisors with 8 and [1,2,3]."""
<|body_0|>
def test_divisors_example_2(self):
"""Test get_divisors with 4 and [-2,0,2]."""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestDivisors:
"""Example unittest test methods for get_divisors."""
def test_divisors_example_1(self):
"""Test get_divisors with 8 and [1,2,3]."""
actual = divisors.get_divisors(8, [1, 2, 3])
expected = [1, 2]
self.assertEqual(actual, expected)
def test_divisors_examp... | the_stack_v2_python_sparse | wk 2 lecture code/test_divisors.py | JenniferCallahan/LTP2 | train | 0 |
2b25e47f29bf8b885c0f9f607f263a959cb36501 | [
"matrix = [list(map(int, list(x))) for x in matrix]\nres = 0\nfor i in range(len(matrix)):\n vector = [0] * len(matrix[0])\n for j in range(len(matrix[i])):\n t = i\n while t < len(matrix) and matrix[t][j] == 1:\n vector[j] += 1\n t += 1\n res = max(self.largestRectangle... | <|body_start_0|>
matrix = [list(map(int, list(x))) for x in matrix]
res = 0
for i in range(len(matrix)):
vector = [0] * len(matrix[0])
for j in range(len(matrix[i])):
t = i
while t < len(matrix) and matrix[t][j] == 1:
ve... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maximalRectangle(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_0|>
def largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
matrix = [list(... | stack_v2_sparse_classes_36k_train_023145 | 1,729 | no_license | [
{
"docstring": ":type matrix: List[List[str]] :rtype: int",
"name": "maximalRectangle",
"signature": "def maximalRectangle(self, matrix)"
},
{
"docstring": ":type heights: List[int] :rtype: int",
"name": "largestRectangleArea",
"signature": "def largestRectangleArea(self, heights)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006692 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalRectangle(self, matrix): :type matrix: List[List[str]] :rtype: int
- def largestRectangleArea(self, heights): :type heights: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalRectangle(self, matrix): :type matrix: List[List[str]] :rtype: int
- def largestRectangleArea(self, heights): :type heights: List[int] :rtype: int
<|skeleton|>
class ... | d1d49a34b3c2a1ba5c6962923fc74be9a1eff668 | <|skeleton|>
class Solution:
def maximalRectangle(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_0|>
def largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maximalRectangle(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
matrix = [list(map(int, list(x))) for x in matrix]
res = 0
for i in range(len(matrix)):
vector = [0] * len(matrix[0])
for j in range(len(matrix[i])):
... | the_stack_v2_python_sparse | 85.Maximal_Rectangle.py | daquexian/leetcode | train | 0 | |
d1f7f5c5c28ba3a1de583aea2fc2d6f03dd2b821 | [
"flags.GetRequiredRepoFlag().AddToParser(parser)\nbase.ASYNC_FLAG.AddToParser(parser)\nparser.add_argument('--source', metavar='SOURCE', required=False, default='.', help='The root directory of the go module source code, defaults to the current directory.')\nparser.add_argument('--module-path', metavar='MODULE_PATH... | <|body_start_0|>
flags.GetRequiredRepoFlag().AddToParser(parser)
base.ASYNC_FLAG.AddToParser(parser)
parser.add_argument('--source', metavar='SOURCE', required=False, default='.', help='The root directory of the go module source code, defaults to the current directory.')
parser.add_argum... | Upload a Go module to an artifact repository. | Upload | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Upload:
"""Upload a Go module to an artifact repository."""
def Args(parser):
"""Set up arguements for this command. Args: parser: An argparse.ArgumentPaser."""
<|body_0|>
def Run(self, args):
"""Run the go module upload command."""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k_train_023146 | 4,133 | permissive | [
{
"docstring": "Set up arguements for this command. Args: parser: An argparse.ArgumentPaser.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "Run the go module upload command.",
"name": "Run",
"signature": "def Run(self, args)"
}
] | 2 | null | Implement the Python class `Upload` described below.
Class description:
Upload a Go module to an artifact repository.
Method signatures and docstrings:
- def Args(parser): Set up arguements for this command. Args: parser: An argparse.ArgumentPaser.
- def Run(self, args): Run the go module upload command. | Implement the Python class `Upload` described below.
Class description:
Upload a Go module to an artifact repository.
Method signatures and docstrings:
- def Args(parser): Set up arguements for this command. Args: parser: An argparse.ArgumentPaser.
- def Run(self, args): Run the go module upload command.
<|skeleton|... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class Upload:
"""Upload a Go module to an artifact repository."""
def Args(parser):
"""Set up arguements for this command. Args: parser: An argparse.ArgumentPaser."""
<|body_0|>
def Run(self, args):
"""Run the go module upload command."""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Upload:
"""Upload a Go module to an artifact repository."""
def Args(parser):
"""Set up arguements for this command. Args: parser: An argparse.ArgumentPaser."""
flags.GetRequiredRepoFlag().AddToParser(parser)
base.ASYNC_FLAG.AddToParser(parser)
parser.add_argument('--sourc... | the_stack_v2_python_sparse | lib/surface/artifacts/go/upload.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
dabb4b405eb88bdbb1304adde116f707797e5bc8 | [
"super(LMF, self).__init__()\nself.audio_in = input_dims[0]\nself.video_in = input_dims[1]\nself.text_in = input_dims[2]\nself.audio_hidden = hidden_dims[0]\nself.video_hidden = hidden_dims[1]\nself.text_hidden = hidden_dims[2]\nself.text_out = text_out\nself.output_dim = output_dim\nself.rank = rank\nself.use_soft... | <|body_start_0|>
super(LMF, self).__init__()
self.audio_in = input_dims[0]
self.video_in = input_dims[1]
self.text_in = input_dims[2]
self.audio_hidden = hidden_dims[0]
self.video_hidden = hidden_dims[1]
self.text_hidden = hidden_dims[2]
self.text_out = te... | Low-rank Multimodal Fusion | LMF | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference",
"GPL-1.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LMF:
"""Low-rank Multimodal Fusion"""
def __init__(self, input_dims, hidden_dims, text_out, dropouts, output_dim, rank, use_softmax=False):
"""Args: input_dims - a length-3 tuple, contains (audio_dim, video_dim, text_dim) hidden_dims - another length-3 tuple, hidden dims of the sub-n... | stack_v2_sparse_classes_36k_train_023147 | 7,292 | permissive | [
{
"docstring": "Args: input_dims - a length-3 tuple, contains (audio_dim, video_dim, text_dim) hidden_dims - another length-3 tuple, hidden dims of the sub-networks text_out - int, specifying the resulting dimensions of the text subnetwork dropouts - a length-4 tuple, contains (audio_dropout, video_dropout, tex... | 2 | stack_v2_sparse_classes_30k_train_001946 | Implement the Python class `LMF` described below.
Class description:
Low-rank Multimodal Fusion
Method signatures and docstrings:
- def __init__(self, input_dims, hidden_dims, text_out, dropouts, output_dim, rank, use_softmax=False): Args: input_dims - a length-3 tuple, contains (audio_dim, video_dim, text_dim) hidde... | Implement the Python class `LMF` described below.
Class description:
Low-rank Multimodal Fusion
Method signatures and docstrings:
- def __init__(self, input_dims, hidden_dims, text_out, dropouts, output_dim, rank, use_softmax=False): Args: input_dims - a length-3 tuple, contains (audio_dim, video_dim, text_dim) hidde... | 92acc188d3a0f634de58463b6676e70df83ef808 | <|skeleton|>
class LMF:
"""Low-rank Multimodal Fusion"""
def __init__(self, input_dims, hidden_dims, text_out, dropouts, output_dim, rank, use_softmax=False):
"""Args: input_dims - a length-3 tuple, contains (audio_dim, video_dim, text_dim) hidden_dims - another length-3 tuple, hidden dims of the sub-n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LMF:
"""Low-rank Multimodal Fusion"""
def __init__(self, input_dims, hidden_dims, text_out, dropouts, output_dim, rank, use_softmax=False):
"""Args: input_dims - a length-3 tuple, contains (audio_dim, video_dim, text_dim) hidden_dims - another length-3 tuple, hidden dims of the sub-networks text_... | the_stack_v2_python_sparse | PyTorch/contrib/others/Low-rank-Multimodal-Fusion_ID2983_for_Pytorch/model.py | Ascend/ModelZoo-PyTorch | train | 23 |
be7c9168e4b071e94b6fb08daccdc01aa0c1e913 | [
"responce_map = {QUESTION: 'Sure.', ALLCAPS: 'Woah, chill out!', EMPTY: 'Fine. Be that way!', OTHER: 'Whatever.'}\nif message:\n message = message.strip()\nmessage_type = self.define_message_type(message)\nreturn responce_map[message_type]",
"if not message:\n return EMPTY\nelif message.isupper():\n retu... | <|body_start_0|>
responce_map = {QUESTION: 'Sure.', ALLCAPS: 'Woah, chill out!', EMPTY: 'Fine. Be that way!', OTHER: 'Whatever.'}
if message:
message = message.strip()
message_type = self.define_message_type(message)
return responce_map[message_type]
<|end_body_0|>
<|body_st... | Lackadaisical teenager that responds in some special way to your messages | Bob | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bob:
"""Lackadaisical teenager that responds in some special way to your messages"""
def hey(self, message):
"""Send Bob a message @param message: string that represents an inbound message to Bob @return: responce string from Bob"""
<|body_0|>
def define_message_type(sel... | stack_v2_sparse_classes_36k_train_023148 | 1,205 | no_license | [
{
"docstring": "Send Bob a message @param message: string that represents an inbound message to Bob @return: responce string from Bob",
"name": "hey",
"signature": "def hey(self, message)"
},
{
"docstring": "Determine the type of the inbound message @param message: string that represents an inbo... | 2 | stack_v2_sparse_classes_30k_train_010962 | Implement the Python class `Bob` described below.
Class description:
Lackadaisical teenager that responds in some special way to your messages
Method signatures and docstrings:
- def hey(self, message): Send Bob a message @param message: string that represents an inbound message to Bob @return: responce string from B... | Implement the Python class `Bob` described below.
Class description:
Lackadaisical teenager that responds in some special way to your messages
Method signatures and docstrings:
- def hey(self, message): Send Bob a message @param message: string that represents an inbound message to Bob @return: responce string from B... | be0e2f635a7558f56c61bc0b36c6146b01d1e6e6 | <|skeleton|>
class Bob:
"""Lackadaisical teenager that responds in some special way to your messages"""
def hey(self, message):
"""Send Bob a message @param message: string that represents an inbound message to Bob @return: responce string from Bob"""
<|body_0|>
def define_message_type(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Bob:
"""Lackadaisical teenager that responds in some special way to your messages"""
def hey(self, message):
"""Send Bob a message @param message: string that represents an inbound message to Bob @return: responce string from Bob"""
responce_map = {QUESTION: 'Sure.', ALLCAPS: 'Woah, chill... | the_stack_v2_python_sparse | all_data/exercism_data/python/bob/400e65344f394a858eff065f563709b4.py | itsolutionscorp/AutoStyle-Clustering | train | 4 |
0210827486969a7cc3b2265141370854334e5f7b | [
"if not nums:\n return 0\ndp = [1] * len(nums)\nfor i in range(len(nums)):\n for j in range(i):\n if nums[i] > nums[j]:\n dp[i] = max(dp[i], dp[j] + 1)\nreturn max(dp)",
"size = len(nums)\nif size < 2:\n return size\ntail = [nums[0]]\nfor i in range(1, size):\n if nums[i] > tail[-1]:... | <|body_start_0|>
if not nums:
return 0
dp = [1] * len(nums)
for i in range(len(nums)):
for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
<|end_body_0|>
<|body_start_1|>
size = len(num... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLIS1(self, nums: List[int]) -> int:
"""思路:动态规划法 1. 判断每个点构成的最大长度时,判断前面比自己小的元素构成的最大长度 2. 当前状态由前面状态决定,容易想到动态规划法"""
<|body_0|>
def lengthOfLIS2(self, nums: List[int]) -> int:
"""思路:二分 时间复杂度:O(NlogN)"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_36k_train_023149 | 2,864 | no_license | [
{
"docstring": "思路:动态规划法 1. 判断每个点构成的最大长度时,判断前面比自己小的元素构成的最大长度 2. 当前状态由前面状态决定,容易想到动态规划法",
"name": "lengthOfLIS1",
"signature": "def lengthOfLIS1(self, nums: List[int]) -> int"
},
{
"docstring": "思路:二分 时间复杂度:O(NlogN)",
"name": "lengthOfLIS2",
"signature": "def lengthOfLIS2(self, nums: List[... | 2 | stack_v2_sparse_classes_30k_train_006570 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS1(self, nums: List[int]) -> int: 思路:动态规划法 1. 判断每个点构成的最大长度时,判断前面比自己小的元素构成的最大长度 2. 当前状态由前面状态决定,容易想到动态规划法
- def lengthOfLIS2(self, nums: List[int]) -> int: 思路:二分 时间复杂... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS1(self, nums: List[int]) -> int: 思路:动态规划法 1. 判断每个点构成的最大长度时,判断前面比自己小的元素构成的最大长度 2. 当前状态由前面状态决定,容易想到动态规划法
- def lengthOfLIS2(self, nums: List[int]) -> int: 思路:二分 时间复杂... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def lengthOfLIS1(self, nums: List[int]) -> int:
"""思路:动态规划法 1. 判断每个点构成的最大长度时,判断前面比自己小的元素构成的最大长度 2. 当前状态由前面状态决定,容易想到动态规划法"""
<|body_0|>
def lengthOfLIS2(self, nums: List[int]) -> int:
"""思路:二分 时间复杂度:O(NlogN)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lengthOfLIS1(self, nums: List[int]) -> int:
"""思路:动态规划法 1. 判断每个点构成的最大长度时,判断前面比自己小的元素构成的最大长度 2. 当前状态由前面状态决定,容易想到动态规划法"""
if not nums:
return 0
dp = [1] * len(nums)
for i in range(len(nums)):
for j in range(i):
if nums[i] > nu... | the_stack_v2_python_sparse | LeetCode/动态规划法(dp)/300. Longest Increasing Subsequence.py | yiming1012/MyLeetCode | train | 2 | |
abce315d17b908297a366f0c835a9c58aff88735 | [
"self._remove_spcPts()\nspcPct = self.get_or_add_spcPct()\nspcPct.val = value",
"self._remove_spcPct()\nspcPts = self.get_or_add_spcPts()\nspcPts.val = value"
] | <|body_start_0|>
self._remove_spcPts()
spcPct = self.get_or_add_spcPct()
spcPct.val = value
<|end_body_0|>
<|body_start_1|>
self._remove_spcPct()
spcPts = self.get_or_add_spcPts()
spcPts.val = value
<|end_body_1|>
| Used for <a:lnSpc>, <a:spcBef>, and <a:spcAft> elements. | CT_TextSpacing | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CT_TextSpacing:
"""Used for <a:lnSpc>, <a:spcBef>, and <a:spcAft> elements."""
def set_spcPct(self, value):
"""Set spacing to *value* lines, e.g. 1.75 lines. A ./a:spcPts child is removed if present."""
<|body_0|>
def set_spcPts(self, value):
"""Set spacing to *v... | stack_v2_sparse_classes_36k_train_023150 | 15,294 | permissive | [
{
"docstring": "Set spacing to *value* lines, e.g. 1.75 lines. A ./a:spcPts child is removed if present.",
"name": "set_spcPct",
"signature": "def set_spcPct(self, value)"
},
{
"docstring": "Set spacing to *value* points. A ./a:spcPct child is removed if present.",
"name": "set_spcPts",
... | 2 | stack_v2_sparse_classes_30k_train_008548 | Implement the Python class `CT_TextSpacing` described below.
Class description:
Used for <a:lnSpc>, <a:spcBef>, and <a:spcAft> elements.
Method signatures and docstrings:
- def set_spcPct(self, value): Set spacing to *value* lines, e.g. 1.75 lines. A ./a:spcPts child is removed if present.
- def set_spcPts(self, valu... | Implement the Python class `CT_TextSpacing` described below.
Class description:
Used for <a:lnSpc>, <a:spcBef>, and <a:spcAft> elements.
Method signatures and docstrings:
- def set_spcPct(self, value): Set spacing to *value* lines, e.g. 1.75 lines. A ./a:spcPts child is removed if present.
- def set_spcPts(self, valu... | cabf6e4f1970dc14302f87414f170de19944bac2 | <|skeleton|>
class CT_TextSpacing:
"""Used for <a:lnSpc>, <a:spcBef>, and <a:spcAft> elements."""
def set_spcPct(self, value):
"""Set spacing to *value* lines, e.g. 1.75 lines. A ./a:spcPts child is removed if present."""
<|body_0|>
def set_spcPts(self, value):
"""Set spacing to *v... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CT_TextSpacing:
"""Used for <a:lnSpc>, <a:spcBef>, and <a:spcAft> elements."""
def set_spcPct(self, value):
"""Set spacing to *value* lines, e.g. 1.75 lines. A ./a:spcPts child is removed if present."""
self._remove_spcPts()
spcPct = self.get_or_add_spcPct()
spcPct.val = v... | the_stack_v2_python_sparse | Pdf_docx_pptx_xlsx_epub_png/source/pptx/oxml/text.py | ryfeus/lambda-packs | train | 1,283 |
052106bdada2345d0269fe4fa56f1d47dfe15708 | [
"super().__init__()\nself.fft_centered = fft_centered\nself.fft_normalization = fft_normalization\nself.spatial_dims = spatial_dims if spatial_dims is not None else [-2, -1]\nself.coil_dim = coil_dim\nself.num_iterations = num_iterations\nself.recurrent_module_unet = unet_model\nself.recurrent_module_attention = at... | <|body_start_0|>
super().__init__()
self.fft_centered = fft_centered
self.fft_normalization = fft_normalization
self.spatial_dims = spatial_dims if spatial_dims is not None else [-2, -1]
self.coil_dim = coil_dim
self.num_iterations = num_iterations
self.recurrent_... | RecurrentModel block for End-to-End Recurrent Attention Network. This model applies a combination of soft data consistency with the input model as a regularizer. A series of these blocks can be stacked to form the full variational network. | SERANetRecurrentBlock | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SERANetRecurrentBlock:
"""RecurrentModel block for End-to-End Recurrent Attention Network. This model applies a combination of soft data consistency with the input model as a regularizer. A series of these blocks can be stacked to form the full variational network."""
def __init__(self, num_... | stack_v2_sparse_classes_36k_train_023151 | 9,773 | permissive | [
{
"docstring": "Initialize the model block. Parameters ---------- num_iterations: Number of reconstruction blocks. attention_model: Attention model. unet_model: UNet model. fft_centered: Whether to center the fft. fft_normalization: The normalization of the fft. spatial_dims: The spatial dimensions of the data.... | 4 | null | Implement the Python class `SERANetRecurrentBlock` described below.
Class description:
RecurrentModel block for End-to-End Recurrent Attention Network. This model applies a combination of soft data consistency with the input model as a regularizer. A series of these blocks can be stacked to form the full variational n... | Implement the Python class `SERANetRecurrentBlock` described below.
Class description:
RecurrentModel block for End-to-End Recurrent Attention Network. This model applies a combination of soft data consistency with the input model as a regularizer. A series of these blocks can be stacked to form the full variational n... | 6d15dd55ca5ed6fc9fbfd31d8488ee7bab453066 | <|skeleton|>
class SERANetRecurrentBlock:
"""RecurrentModel block for End-to-End Recurrent Attention Network. This model applies a combination of soft data consistency with the input model as a regularizer. A series of these blocks can be stacked to form the full variational network."""
def __init__(self, num_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SERANetRecurrentBlock:
"""RecurrentModel block for End-to-End Recurrent Attention Network. This model applies a combination of soft data consistency with the input model as a regularizer. A series of these blocks can be stacked to form the full variational network."""
def __init__(self, num_iterations: i... | the_stack_v2_python_sparse | mridc/collections/segmentation/models/seranet_base/recon_block.py | wdika/mridc | train | 40 |
38603ef08b999a2ea644b28054d4b631ceac36f1 | [
"rndstate = randstate(seed)\nrnd = lambda x, *y: rndstate.rand(*y) * (x[1] - x[0]) + x[0]\nnbindings = rndstate.choice(self.nbindings)\nsize = rnd(self.size)\nbins = self.bins[1] * scale\nmaxv = min(self.bins[0] - bias, int(size / bins))\npos = np.empty(0, 'f4')\nwhile len(pos) != nbindings:\n pos = np.unique(rn... | <|body_start_0|>
rndstate = randstate(seed)
rnd = lambda x, *y: rndstate.rand(*y) * (x[1] - x[0]) + x[0]
nbindings = rndstate.choice(self.nbindings)
size = rnd(self.size)
bins = self.bins[1] * scale
maxv = min(self.bins[0] - bias, int(size / bins))
pos = np.empty(... | Create random experiments & images | ExperimentCreator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExperimentCreator:
"""Create random experiments & images"""
def experiment(self, seed=None, bias=10, scale=2):
"""create an experiment"""
<|body_0|>
def createimage(self, info, bead):
"""transform bead data into an image"""
<|body_1|>
def createtruth... | stack_v2_sparse_classes_36k_train_023152 | 26,924 | no_license | [
{
"docstring": "create an experiment",
"name": "experiment",
"signature": "def experiment(self, seed=None, bias=10, scale=2)"
},
{
"docstring": "transform bead data into an image",
"name": "createimage",
"signature": "def createimage(self, info, bead)"
},
{
"docstring": "transfor... | 4 | stack_v2_sparse_classes_30k_train_011077 | Implement the Python class `ExperimentCreator` described below.
Class description:
Create random experiments & images
Method signatures and docstrings:
- def experiment(self, seed=None, bias=10, scale=2): create an experiment
- def createimage(self, info, bead): transform bead data into an image
- def createtruth(sel... | Implement the Python class `ExperimentCreator` described below.
Class description:
Create random experiments & images
Method signatures and docstrings:
- def experiment(self, seed=None, bias=10, scale=2): create an experiment
- def createimage(self, info, bead): transform bead data into an image
- def createtruth(sel... | f9534e4fff9775ff45d08d401de61015d4a69e76 | <|skeleton|>
class ExperimentCreator:
"""Create random experiments & images"""
def experiment(self, seed=None, bias=10, scale=2):
"""create an experiment"""
<|body_0|>
def createimage(self, info, bead):
"""transform bead data into an image"""
<|body_1|>
def createtruth... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExperimentCreator:
"""Create random experiments & images"""
def experiment(self, seed=None, bias=10, scale=2):
"""create an experiment"""
rndstate = randstate(seed)
rnd = lambda x, *y: rndstate.rand(*y) * (x[1] - x[0]) + x[0]
nbindings = rndstate.choice(self.nbindings)
... | the_stack_v2_python_sparse | src/simulator/bindings.py | depixusgenome/trackanalysis | train | 0 |
0d644b91f5b55cc3d6453f3bafdca8739b0c568d | [
"table = (('no comment', False), ('a ( comment ) here', True), ('( beginning ) comment', True), ('( broken comment', False), ('.( print command)', False), ('a final ( comment)', True), ('a ( comment ) with .( print )', True))\nfor entry in table:\n given = entry[0]\n expected = entry[1]\n self.assertEqual(... | <|body_start_0|>
table = (('no comment', False), ('a ( comment ) here', True), ('( beginning ) comment', True), ('( broken comment', False), ('.( print command)', False), ('a final ( comment)', True), ('a ( comment ) with .( print )', True))
for entry in table:
given = entry[0]
e... | Tests functions that support | HelperTestCase | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HelperTestCase:
"""Tests functions that support"""
def test_has_bracket_comment(self):
"""Test routine to detect inline comments"""
<|body_0|>
def test_remove_bracket_comment(self):
"""Test routine to remove inline comments"""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_36k_train_023153 | 1,559 | permissive | [
{
"docstring": "Test routine to detect inline comments",
"name": "test_has_bracket_comment",
"signature": "def test_has_bracket_comment(self)"
},
{
"docstring": "Test routine to remove inline comments",
"name": "test_remove_bracket_comment",
"signature": "def test_remove_bracket_comment(... | 2 | stack_v2_sparse_classes_30k_train_001057 | Implement the Python class `HelperTestCase` described below.
Class description:
Tests functions that support
Method signatures and docstrings:
- def test_has_bracket_comment(self): Test routine to detect inline comments
- def test_remove_bracket_comment(self): Test routine to remove inline comments | Implement the Python class `HelperTestCase` described below.
Class description:
Tests functions that support
Method signatures and docstrings:
- def test_has_bracket_comment(self): Test routine to detect inline comments
- def test_remove_bracket_comment(self): Test routine to remove inline comments
<|skeleton|>
clas... | b5eebdae06f5953c12ddfff5fd1f97ac6528a5ab | <|skeleton|>
class HelperTestCase:
"""Tests functions that support"""
def test_has_bracket_comment(self):
"""Test routine to detect inline comments"""
<|body_0|>
def test_remove_bracket_comment(self):
"""Test routine to remove inline comments"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HelperTestCase:
"""Tests functions that support"""
def test_has_bracket_comment(self):
"""Test routine to detect inline comments"""
table = (('no comment', False), ('a ( comment ) here', True), ('( beginning ) comment', True), ('( broken comment', False), ('.( print command)', False), ('a... | the_stack_v2_python_sparse | forth_code/test_forth_to_ophisbin.py | scotws/TaliForth2 | train | 80 |
18e5561eab74af2f4a66d42c479c093b5de3113e | [
"first, boards_raw = parse(filename)\nboards = [Board(board_raw) for board_raw in boards_raw]\nnums = ints(first)\nfor num in nums:\n for board in boards:\n winner = board.mark(num)\n if winner:\n return num * board.unmarked_sum()\nraise ValueError",
"first, boards_raw = parse(filename... | <|body_start_0|>
first, boards_raw = parse(filename)
boards = [Board(board_raw) for board_raw in boards_raw]
nums = ints(first)
for num in nums:
for board in boards:
winner = board.mark(num)
if winner:
return num * board.unm... | AoC 2021 Day 04 | Day04 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Day04:
"""AoC 2021 Day 04"""
def part1(filename: str) -> int:
"""Given a filename, solve 2021 day 04 part 1"""
<|body_0|>
def part2(filename: str) -> int:
"""Given a filename, solve 2021 day 04 part 2"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_023154 | 3,100 | no_license | [
{
"docstring": "Given a filename, solve 2021 day 04 part 1",
"name": "part1",
"signature": "def part1(filename: str) -> int"
},
{
"docstring": "Given a filename, solve 2021 day 04 part 2",
"name": "part2",
"signature": "def part2(filename: str) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_000982 | Implement the Python class `Day04` described below.
Class description:
AoC 2021 Day 04
Method signatures and docstrings:
- def part1(filename: str) -> int: Given a filename, solve 2021 day 04 part 1
- def part2(filename: str) -> int: Given a filename, solve 2021 day 04 part 2 | Implement the Python class `Day04` described below.
Class description:
AoC 2021 Day 04
Method signatures and docstrings:
- def part1(filename: str) -> int: Given a filename, solve 2021 day 04 part 1
- def part2(filename: str) -> int: Given a filename, solve 2021 day 04 part 2
<|skeleton|>
class Day04:
"""AoC 202... | e89db235837d2d05848210a18c9c2a4456085570 | <|skeleton|>
class Day04:
"""AoC 2021 Day 04"""
def part1(filename: str) -> int:
"""Given a filename, solve 2021 day 04 part 1"""
<|body_0|>
def part2(filename: str) -> int:
"""Given a filename, solve 2021 day 04 part 2"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Day04:
"""AoC 2021 Day 04"""
def part1(filename: str) -> int:
"""Given a filename, solve 2021 day 04 part 1"""
first, boards_raw = parse(filename)
boards = [Board(board_raw) for board_raw in boards_raw]
nums = ints(first)
for num in nums:
for board in b... | the_stack_v2_python_sparse | 2021/python2021/aoc/day04.py | mreishus/aoc | train | 16 |
0b6838b5cca1b08a0174c806f58db117ec9a68fb | [
"N = N\nomega1 = omega\nc = np.zeros((L, N))\nb = np.zeros((L,))\nreturn (N, omega1, c, b)",
"for i in range(L):\n for j in range(N):\n c[i, j] = np.sqrt(2.0 / (L + 1)) * np.sin((j + 1) * np.pi * (i + 1) / (L + 1))\n b[i] = np.sqrt(1.0 / (2.0 * omega1)) * (np.sqrt(omega1) * i + 1j)\nK = np.zeros((N *... | <|body_start_0|>
N = N
omega1 = omega
c = np.zeros((L, N))
b = np.zeros((L,))
return (N, omega1, c, b)
<|end_body_0|>
<|body_start_1|>
for i in range(L):
for j in range(N):
c[i, j] = np.sqrt(2.0 / (L + 1)) * np.sin((j + 1) * np.pi * (i + 1) / ... | This class solves the hamiltonian. | problemsolving | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class problemsolving:
"""This class solves the hamiltonian."""
def matrixmaking(N, omega):
"""This function makes the matrixes. Args: c (matrix): Fermion opperator b (matrix): Phonon opperator N (float): number of electrons omega1 (float): Frequency Returns: c (matrix): Fermion opperator b... | stack_v2_sparse_classes_36k_train_023155 | 3,762 | no_license | [
{
"docstring": "This function makes the matrixes. Args: c (matrix): Fermion opperator b (matrix): Phonon opperator N (float): number of electrons omega1 (float): Frequency Returns: c (matrix): Fermion opperator b (matrix): Phonon opperator N (float): number of electrons omega1 (float): Frequency",
"name": "... | 4 | stack_v2_sparse_classes_30k_train_021405 | Implement the Python class `problemsolving` described below.
Class description:
This class solves the hamiltonian.
Method signatures and docstrings:
- def matrixmaking(N, omega): This function makes the matrixes. Args: c (matrix): Fermion opperator b (matrix): Phonon opperator N (float): number of electrons omega1 (f... | Implement the Python class `problemsolving` described below.
Class description:
This class solves the hamiltonian.
Method signatures and docstrings:
- def matrixmaking(N, omega): This function makes the matrixes. Args: c (matrix): Fermion opperator b (matrix): Phonon opperator N (float): number of electrons omega1 (f... | 0228f225873fb79bcc91bc3c7f4437a480e1004d | <|skeleton|>
class problemsolving:
"""This class solves the hamiltonian."""
def matrixmaking(N, omega):
"""This function makes the matrixes. Args: c (matrix): Fermion opperator b (matrix): Phonon opperator N (float): number of electrons omega1 (float): Frequency Returns: c (matrix): Fermion opperator b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class problemsolving:
"""This class solves the hamiltonian."""
def matrixmaking(N, omega):
"""This function makes the matrixes. Args: c (matrix): Fermion opperator b (matrix): Phonon opperator N (float): number of electrons omega1 (float): Frequency Returns: c (matrix): Fermion opperator b (matrix): Ph... | the_stack_v2_python_sparse | MitchellStry/Homework/Homework8/homework8.py | AkimovLab/CHE512-Spring2023 | train | 0 |
6fb77d74489784244762ad08722f64884730ce46 | [
"if not piles:\n return False\nN = len(piles)\ndp = [[0 for i in range(N)] for i in range(N)]\nfor i in range(N):\n dp[i][i] = piles[i]\nfor i in range(N - 2, -1, -1):\n for j in range(i + 1, N):\n if abs(i - j) == 1:\n dp[i][j] = max(piles[i], piles[j])\n else:\n dp[i][... | <|body_start_0|>
if not piles:
return False
N = len(piles)
dp = [[0 for i in range(N)] for i in range(N)]
for i in range(N):
dp[i][i] = piles[i]
for i in range(N - 2, -1, -1):
for j in range(i + 1, N):
if abs(i - j) == 1:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def stoneGame(self, piles):
""":type piles: List[int] :rtype: bool This problem also called coins in a line"""
<|body_0|>
def coins_in_lines(self, coins):
""": How many coins can the first player get? : coins: list[int]"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k_train_023156 | 1,889 | no_license | [
{
"docstring": ":type piles: List[int] :rtype: bool This problem also called coins in a line",
"name": "stoneGame",
"signature": "def stoneGame(self, piles)"
},
{
"docstring": ": How many coins can the first player get? : coins: list[int]",
"name": "coins_in_lines",
"signature": "def coi... | 2 | stack_v2_sparse_classes_30k_train_008619 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def stoneGame(self, piles): :type piles: List[int] :rtype: bool This problem also called coins in a line
- def coins_in_lines(self, coins): : How many coins can the first player ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def stoneGame(self, piles): :type piles: List[int] :rtype: bool This problem also called coins in a line
- def coins_in_lines(self, coins): : How many coins can the first player ... | 1a3c1f4d6e9d3444039f087763b93241f4ba7892 | <|skeleton|>
class Solution:
def stoneGame(self, piles):
""":type piles: List[int] :rtype: bool This problem also called coins in a line"""
<|body_0|>
def coins_in_lines(self, coins):
""": How many coins can the first player get? : coins: list[int]"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def stoneGame(self, piles):
""":type piles: List[int] :rtype: bool This problem also called coins in a line"""
if not piles:
return False
N = len(piles)
dp = [[0 for i in range(N)] for i in range(N)]
for i in range(N):
dp[i][i] = piles[... | the_stack_v2_python_sparse | Algorithm/877_Stone_Game.py | Gi1ia/TechNoteBook | train | 7 | |
d14ba088452d54e63fe79800457692f698df9bb2 | [
"for observable in observables:\n if not isinstance(observable, Observable):\n continue\n observable.addObserver(self)\nreturn self",
"for observable in observables:\n if not isinstance(observable, Observable):\n continue\n observable.removeObserver(self)\nreturn self"
] | <|body_start_0|>
for observable in observables:
if not isinstance(observable, Observable):
continue
observable.addObserver(self)
return self
<|end_body_0|>
<|body_start_1|>
for observable in observables:
if not isinstance(observable, Observabl... | Mix-in class that enables a node to be notified when the value of its dependents change | Observer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Observer:
"""Mix-in class that enables a node to be notified when the value of its dependents change"""
def observe(self, observables):
"""Add me as an observer to all {observables}"""
<|body_0|>
def ignore(self, observables):
"""Stop observing the {observables}"... | stack_v2_sparse_classes_36k_train_023157 | 1,250 | permissive | [
{
"docstring": "Add me as an observer to all {observables}",
"name": "observe",
"signature": "def observe(self, observables)"
},
{
"docstring": "Stop observing the {observables}",
"name": "ignore",
"signature": "def ignore(self, observables)"
}
] | 2 | null | Implement the Python class `Observer` described below.
Class description:
Mix-in class that enables a node to be notified when the value of its dependents change
Method signatures and docstrings:
- def observe(self, observables): Add me as an observer to all {observables}
- def ignore(self, observables): Stop observi... | Implement the Python class `Observer` described below.
Class description:
Mix-in class that enables a node to be notified when the value of its dependents change
Method signatures and docstrings:
- def observe(self, observables): Add me as an observer to all {observables}
- def ignore(self, observables): Stop observi... | d741c44ffb3e9e1f726bf492202ac8738bb4aa1c | <|skeleton|>
class Observer:
"""Mix-in class that enables a node to be notified when the value of its dependents change"""
def observe(self, observables):
"""Add me as an observer to all {observables}"""
<|body_0|>
def ignore(self, observables):
"""Stop observing the {observables}"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Observer:
"""Mix-in class that enables a node to be notified when the value of its dependents change"""
def observe(self, observables):
"""Add me as an observer to all {observables}"""
for observable in observables:
if not isinstance(observable, Observable):
co... | the_stack_v2_python_sparse | packages/pyre/calc/Observer.py | pyre/pyre | train | 27 |
dbf8940ed3023eb789da4e9bf24c4b8d091529ff | [
"deployable_obj = Deployable(context=context, name=self.name, num_accelerators=self.num_accelerators, device_id=device_id, driver_name=self.driver_name)\ndeployable_obj.create(context)\nif hasattr(self, 'attribute_list'):\n for driver_attr in self.attribute_list:\n driver_attr.create(context, deployable_o... | <|body_start_0|>
deployable_obj = Deployable(context=context, name=self.name, num_accelerators=self.num_accelerators, device_id=device_id, driver_name=self.driver_name)
deployable_obj.create(context)
if hasattr(self, 'attribute_list'):
for driver_attr in self.attribute_list:
... | DriverDeployable | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DriverDeployable:
def create(self, context, device_id, cpid_id):
"""Create a driver-side Deployable object into DB. This object will be stored in separate db tables: deployable & attach_handle & attribute table."""
<|body_0|>
def destroy(self, context, device_id):
""... | stack_v2_sparse_classes_36k_train_023158 | 5,621 | permissive | [
{
"docstring": "Create a driver-side Deployable object into DB. This object will be stored in separate db tables: deployable & attach_handle & attribute table.",
"name": "create",
"signature": "def create(self, context, device_id, cpid_id)"
},
{
"docstring": "delete one driver-side deployable by... | 4 | stack_v2_sparse_classes_30k_train_019096 | Implement the Python class `DriverDeployable` described below.
Class description:
Implement the DriverDeployable class.
Method signatures and docstrings:
- def create(self, context, device_id, cpid_id): Create a driver-side Deployable object into DB. This object will be stored in separate db tables: deployable & atta... | Implement the Python class `DriverDeployable` described below.
Class description:
Implement the DriverDeployable class.
Method signatures and docstrings:
- def create(self, context, device_id, cpid_id): Create a driver-side Deployable object into DB. This object will be stored in separate db tables: deployable & atta... | ab8b8514242895b8adc2ec3dfbbb63a49f02c89e | <|skeleton|>
class DriverDeployable:
def create(self, context, device_id, cpid_id):
"""Create a driver-side Deployable object into DB. This object will be stored in separate db tables: deployable & attach_handle & attribute table."""
<|body_0|>
def destroy(self, context, device_id):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DriverDeployable:
def create(self, context, device_id, cpid_id):
"""Create a driver-side Deployable object into DB. This object will be stored in separate db tables: deployable & attach_handle & attribute table."""
deployable_obj = Deployable(context=context, name=self.name, num_accelerators=s... | the_stack_v2_python_sparse | cyborg/objects/driver_objects/driver_deployable.py | openstack/cyborg | train | 41 | |
97926ae80ecc36e28db58bc398ae474e411a2763 | [
"super(AnalysisThread, self).__init__(parent)\nself.checker = checker\nself.results = None\nself.source_code = source_code",
"try:\n self.results = self.checker(self.source_code)\nexcept Exception as e:\n logger.error(e, exc_info=True)"
] | <|body_start_0|>
super(AnalysisThread, self).__init__(parent)
self.checker = checker
self.results = None
self.source_code = source_code
<|end_body_0|>
<|body_start_1|>
try:
self.results = self.checker(self.source_code)
except Exception as e:
logge... | Analysis thread. | AnalysisThread | [
"LGPL-2.0-or-later",
"BSD-3-Clause",
"LGPL-3.0-only",
"LicenseRef-scancode-free-unknown",
"LGPL-3.0-or-later",
"LicenseRef-scancode-proprietary-license",
"LGPL-2.1-or-later",
"CC-BY-2.5",
"CC-BY-4.0",
"MIT",
"LGPL-2.1-only",
"CC-BY-3.0",
"LicenseRef-scancode-unknown-license-reference",
"OF... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnalysisThread:
"""Analysis thread."""
def __init__(self, parent, checker, source_code):
"""Initialize the Analysis thread."""
<|body_0|>
def run(self):
"""Run analysis."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(AnalysisThread, self)... | stack_v2_sparse_classes_36k_train_023159 | 9,480 | permissive | [
{
"docstring": "Initialize the Analysis thread.",
"name": "__init__",
"signature": "def __init__(self, parent, checker, source_code)"
},
{
"docstring": "Run analysis.",
"name": "run",
"signature": "def run(self)"
}
] | 2 | null | Implement the Python class `AnalysisThread` described below.
Class description:
Analysis thread.
Method signatures and docstrings:
- def __init__(self, parent, checker, source_code): Initialize the Analysis thread.
- def run(self): Run analysis. | Implement the Python class `AnalysisThread` described below.
Class description:
Analysis thread.
Method signatures and docstrings:
- def __init__(self, parent, checker, source_code): Initialize the Analysis thread.
- def run(self): Run analysis.
<|skeleton|>
class AnalysisThread:
"""Analysis thread."""
def ... | 0b4929cef420ba6c625566e52200e959f3566f33 | <|skeleton|>
class AnalysisThread:
"""Analysis thread."""
def __init__(self, parent, checker, source_code):
"""Initialize the Analysis thread."""
<|body_0|>
def run(self):
"""Run analysis."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AnalysisThread:
"""Analysis thread."""
def __init__(self, parent, checker, source_code):
"""Initialize the Analysis thread."""
super(AnalysisThread, self).__init__(parent)
self.checker = checker
self.results = None
self.source_code = source_code
def run(self):... | the_stack_v2_python_sparse | spyder/plugins/editor/widgets/editorstack_helpers.py | juanis2112/spyder | train | 1 |
e832d0ffc01a1c460266ae9c81a205f339bc7b4e | [
"m, n = (len(grid), len(grid[0]) if grid else 0)\nans = 0\nfor i in range(m):\n for j in range(n):\n if grid[i][j] == '1':\n ans += 1\n q = deque([(i, j)])\n self.markIsland(grid, q, m, n)\nreturn ans",
"while q:\n row, col = q.popleft()\n if row < 0 or row == rows... | <|body_start_0|>
m, n = (len(grid), len(grid[0]) if grid else 0)
ans = 0
for i in range(m):
for j in range(n):
if grid[i][j] == '1':
ans += 1
q = deque([(i, j)])
self.markIsland(grid, q, m, n)
return ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numIslands(self, grid):
""":type grid: List[List[str]] :rtype: int"""
<|body_0|>
def markIsland(self, grid, q, rows, cols):
"""Precondition: queue holds a tuple of the form (row, col), or is empty"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_023160 | 1,277 | no_license | [
{
"docstring": ":type grid: List[List[str]] :rtype: int",
"name": "numIslands",
"signature": "def numIslands(self, grid)"
},
{
"docstring": "Precondition: queue holds a tuple of the form (row, col), or is empty",
"name": "markIsland",
"signature": "def markIsland(self, grid, q, rows, col... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numIslands(self, grid): :type grid: List[List[str]] :rtype: int
- def markIsland(self, grid, q, rows, cols): Precondition: queue holds a tuple of the form (row, col), or is e... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numIslands(self, grid): :type grid: List[List[str]] :rtype: int
- def markIsland(self, grid, q, rows, cols): Precondition: queue holds a tuple of the form (row, col), or is e... | 9043762d685d284d2934d60841704ee7df9838cf | <|skeleton|>
class Solution:
def numIslands(self, grid):
""":type grid: List[List[str]] :rtype: int"""
<|body_0|>
def markIsland(self, grid, q, rows, cols):
"""Precondition: queue holds a tuple of the form (row, col), or is empty"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numIslands(self, grid):
""":type grid: List[List[str]] :rtype: int"""
m, n = (len(grid), len(grid[0]) if grid else 0)
ans = 0
for i in range(m):
for j in range(n):
if grid[i][j] == '1':
ans += 1
q... | the_stack_v2_python_sparse | python/numIslands.py | AndersonHuang95/CodePractice | train | 0 | |
78e3b8669c3d1d90a704fb1da0deeacee79bdf0e | [
"super(WeightedMinkowski, self).__init__(**kwargs)\nif rho_initializer is None:\n rho_initializer = tf.random_uniform_initializer(1.01, 3.0)\nself.rho_initializer = tf.keras.initializers.get(rho_initializer)\nself.rho = self.add_weight(shape=[], initializer=self.rho_initializer, trainable=self.trainable, name='r... | <|body_start_0|>
super(WeightedMinkowski, self).__init__(**kwargs)
if rho_initializer is None:
rho_initializer = tf.random_uniform_initializer(1.01, 3.0)
self.rho_initializer = tf.keras.initializers.get(rho_initializer)
self.rho = self.add_weight(shape=[], initializer=self.rh... | Weighted Minkowski distance. | WeightedMinkowski | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WeightedMinkowski:
"""Weighted Minkowski distance."""
def __init__(self, rho_initializer=None, **kwargs):
"""Initialize. Arguments: rho_initializer (optional): Initializer for rho."""
<|body_0|>
def call(self, inputs):
"""Call. Arguments: inputs: z_0: A tf.Tensor... | stack_v2_sparse_classes_36k_train_023161 | 3,152 | permissive | [
{
"docstring": "Initialize. Arguments: rho_initializer (optional): Initializer for rho.",
"name": "__init__",
"signature": "def __init__(self, rho_initializer=None, **kwargs)"
},
{
"docstring": "Call. Arguments: inputs: z_0: A tf.Tensor denoting a set of vectors. shape = (batch_size, [n, m, ...]... | 3 | stack_v2_sparse_classes_30k_train_017889 | Implement the Python class `WeightedMinkowski` described below.
Class description:
Weighted Minkowski distance.
Method signatures and docstrings:
- def __init__(self, rho_initializer=None, **kwargs): Initialize. Arguments: rho_initializer (optional): Initializer for rho.
- def call(self, inputs): Call. Arguments: inp... | Implement the Python class `WeightedMinkowski` described below.
Class description:
Weighted Minkowski distance.
Method signatures and docstrings:
- def __init__(self, rho_initializer=None, **kwargs): Initialize. Arguments: rho_initializer (optional): Initializer for rho.
- def call(self, inputs): Call. Arguments: inp... | 4f05348cf43d2d53ff9cc6dee633de385df883e3 | <|skeleton|>
class WeightedMinkowski:
"""Weighted Minkowski distance."""
def __init__(self, rho_initializer=None, **kwargs):
"""Initialize. Arguments: rho_initializer (optional): Initializer for rho."""
<|body_0|>
def call(self, inputs):
"""Call. Arguments: inputs: z_0: A tf.Tensor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WeightedMinkowski:
"""Weighted Minkowski distance."""
def __init__(self, rho_initializer=None, **kwargs):
"""Initialize. Arguments: rho_initializer (optional): Initializer for rho."""
super(WeightedMinkowski, self).__init__(**kwargs)
if rho_initializer is None:
rho_ini... | the_stack_v2_python_sparse | psiz/keras/layers/distances/minkowski.py | asuiconlab/psiz | train | 0 |
c01e92b3ea8ef07f7243188f319fc6dc0efd4c5b | [
"super(ConfigurationBuilder, self).__init__(self.DEFAULT_PATH)\nself._init_default()\nif survey:\n for other_survey in Survey.objects.all():\n unwanted_survey = survey.name != other_survey.name\n if unwanted_survey:\n del self._conf[other_survey.name]",
"default_value_generic = self._c... | <|body_start_0|>
super(ConfigurationBuilder, self).__init__(self.DEFAULT_PATH)
self._init_default()
if survey:
for other_survey in Survey.objects.all():
unwanted_survey = survey.name != other_survey.name
if unwanted_survey:
del self... | Permit to create serializable uninitialized configuration easily. We just use the default dict for a Builder, the user will be able to modify value from the default. We delete unwanted survey in self._conf in order to print only what the user want. | ConfigurationBuilder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigurationBuilder:
"""Permit to create serializable uninitialized configuration easily. We just use the default dict for a Builder, the user will be able to modify value from the default. We delete unwanted survey in self._conf in order to print only what the user want."""
def __init__(se... | stack_v2_sparse_classes_36k_train_023162 | 1,787 | permissive | [
{
"docstring": "Initialize a configuration file. :param Survey survey: If survey is defined we generate configuration only for this survey.",
"name": "__init__",
"signature": "def __init__(self, survey=None)"
},
{
"docstring": "Return the default configuration.",
"name": "_init_default",
... | 2 | stack_v2_sparse_classes_30k_train_001856 | Implement the Python class `ConfigurationBuilder` described below.
Class description:
Permit to create serializable uninitialized configuration easily. We just use the default dict for a Builder, the user will be able to modify value from the default. We delete unwanted survey in self._conf in order to print only what... | Implement the Python class `ConfigurationBuilder` described below.
Class description:
Permit to create serializable uninitialized configuration easily. We just use the default dict for a Builder, the user will be able to modify value from the default. We delete unwanted survey in self._conf in order to print only what... | 2f08b87a7cde6d180e16d6f37d0b8019b8361638 | <|skeleton|>
class ConfigurationBuilder:
"""Permit to create serializable uninitialized configuration easily. We just use the default dict for a Builder, the user will be able to modify value from the default. We delete unwanted survey in self._conf in order to print only what the user want."""
def __init__(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigurationBuilder:
"""Permit to create serializable uninitialized configuration easily. We just use the default dict for a Builder, the user will be able to modify value from the default. We delete unwanted survey in self._conf in order to print only what the user want."""
def __init__(self, survey=No... | the_stack_v2_python_sparse | survey/exporter/tex/configuration_builder.py | TheWITProject/MentorApp | train | 0 |
7f9c3abf82a5242f76e083da63e45bfc1a939677 | [
"if 'args_rdf_name' in result:\n result['payload_type'] = result['args_rdf_name']\n del result['args_rdf_name']\nif 'args' in result:\n result['payload'] = self._PassThrough(value.payload)\n del result['args']\nreturn result",
"for f in fields:\n if f.name == 'args_rdf_name':\n f.name = 'pay... | <|body_start_0|>
if 'args_rdf_name' in result:
result['payload_type'] = result['args_rdf_name']
del result['args_rdf_name']
if 'args' in result:
result['payload'] = self._PassThrough(value.payload)
del result['args']
return result
<|end_body_0|>
<... | Renderer for GrrMessage objects. | ApiGrrMessageRenderer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApiGrrMessageRenderer:
"""Renderer for GrrMessage objects."""
def RenderPayload(self, result, value):
"""Renders GrrMessage payload and renames args_rdf_name field."""
<|body_0|>
def AdjustDescriptor(self, fields):
"""Payload-aware metadata processor."""
... | stack_v2_sparse_classes_36k_train_023163 | 17,447 | permissive | [
{
"docstring": "Renders GrrMessage payload and renames args_rdf_name field.",
"name": "RenderPayload",
"signature": "def RenderPayload(self, result, value)"
},
{
"docstring": "Payload-aware metadata processor.",
"name": "AdjustDescriptor",
"signature": "def AdjustDescriptor(self, fields)... | 2 | null | Implement the Python class `ApiGrrMessageRenderer` described below.
Class description:
Renderer for GrrMessage objects.
Method signatures and docstrings:
- def RenderPayload(self, result, value): Renders GrrMessage payload and renames args_rdf_name field.
- def AdjustDescriptor(self, fields): Payload-aware metadata p... | Implement the Python class `ApiGrrMessageRenderer` described below.
Class description:
Renderer for GrrMessage objects.
Method signatures and docstrings:
- def RenderPayload(self, result, value): Renders GrrMessage payload and renames args_rdf_name field.
- def AdjustDescriptor(self, fields): Payload-aware metadata p... | 44c0eb8c938302098ef7efae8cfd6b90bcfbb2d6 | <|skeleton|>
class ApiGrrMessageRenderer:
"""Renderer for GrrMessage objects."""
def RenderPayload(self, result, value):
"""Renders GrrMessage payload and renames args_rdf_name field."""
<|body_0|>
def AdjustDescriptor(self, fields):
"""Payload-aware metadata processor."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ApiGrrMessageRenderer:
"""Renderer for GrrMessage objects."""
def RenderPayload(self, result, value):
"""Renders GrrMessage payload and renames args_rdf_name field."""
if 'args_rdf_name' in result:
result['payload_type'] = result['args_rdf_name']
del result['args_r... | the_stack_v2_python_sparse | grr/server/grr_response_server/gui/api_value_renderers.py | google/grr | train | 4,683 |
0b263e755b4086f0a77716c001ac0c52c4775874 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AccessReviewStage()",
"from .access_review_instance_decision_item import AccessReviewInstanceDecisionItem\nfrom .access_review_reviewer_scope import AccessReviewReviewerScope\nfrom .entity import Entity\nfrom .access_review_instance_de... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AccessReviewStage()
<|end_body_0|>
<|body_start_1|>
from .access_review_instance_decision_item import AccessReviewInstanceDecisionItem
from .access_review_reviewer_scope import AccessRev... | AccessReviewStage | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccessReviewStage:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessReviewStage:
"""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... | stack_v2_sparse_classes_36k_train_023164 | 5,005 | 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: AccessReviewStage",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_v... | 3 | stack_v2_sparse_classes_30k_train_013081 | Implement the Python class `AccessReviewStage` described below.
Class description:
Implement the AccessReviewStage class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessReviewStage: Creates a new instance of the appropriate class based on discrim... | Implement the Python class `AccessReviewStage` described below.
Class description:
Implement the AccessReviewStage class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessReviewStage: Creates a new instance of the appropriate class based on discrim... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AccessReviewStage:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessReviewStage:
"""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... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccessReviewStage:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessReviewStage:
"""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: Acce... | the_stack_v2_python_sparse | msgraph/generated/models/access_review_stage.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
3a21d16cf6ba406eec741a3c38080c363fa031ab | [
"if isinstance(f, Transform):\n return f\nelse:\n return cls(f)",
"self.mask, self.is_tuple = (mask, is_tuple)\nif encodes:\n self.encodes = encodes\n self.order = getattr(encodes, 'order', 0)"
] | <|body_start_0|>
if isinstance(f, Transform):
return f
else:
return cls(f)
<|end_body_0|>
<|body_start_1|>
self.mask, self.is_tuple = (mask, is_tuple)
if encodes:
self.encodes = encodes
self.order = getattr(encodes, 'order', 0)
<|end_body_... | "A function that `encodes` if `filt` matches, and optionally `decodes`, with an optional `setup`" 1. every tfm's `order` default to 0 2. `assoc`, `is_tuple`, `prev` default to None 3. `filt`, `mask`, default to None 4. `_is_setup`,`_done_setup`, default to None | Transform | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Transform:
""""A function that `encodes` if `filt` matches, and optionally `decodes`, with an optional `setup`" 1. every tfm's `order` default to 0 2. `assoc`, `is_tuple`, `prev` default to None 3. `filt`, `mask`, default to None 4. `_is_setup`,`_done_setup`, default to None"""
def create(cl... | stack_v2_sparse_classes_36k_train_023165 | 14,141 | no_license | [
{
"docstring": "purpose: - why `Transform.create`? 1. we need a slight revised version of __init__ 2. `@classmethod` help to create another __init__ without __init__ if `f` is already an instance of `Transform`, just return `f`; if not, turn `f` into a `Transform`",
"name": "create",
"signature": "def c... | 2 | null | Implement the Python class `Transform` described below.
Class description:
"A function that `encodes` if `filt` matches, and optionally `decodes`, with an optional `setup`" 1. every tfm's `order` default to 0 2. `assoc`, `is_tuple`, `prev` default to None 3. `filt`, `mask`, default to None 4. `_is_setup`,`_done_setup`... | Implement the Python class `Transform` described below.
Class description:
"A function that `encodes` if `filt` matches, and optionally `decodes`, with an optional `setup`" 1. every tfm's `order` default to 0 2. `assoc`, `is_tuple`, `prev` default to None 3. `filt`, `mask`, default to None 4. `_is_setup`,`_done_setup`... | 4230be915e70a7e5a22f2f7e5137cca7045754fd | <|skeleton|>
class Transform:
""""A function that `encodes` if `filt` matches, and optionally `decodes`, with an optional `setup`" 1. every tfm's `order` default to 0 2. `assoc`, `is_tuple`, `prev` default to None 3. `filt`, `mask`, default to None 4. `_is_setup`,`_done_setup`, default to None"""
def create(cl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Transform:
""""A function that `encodes` if `filt` matches, and optionally `decodes`, with an optional `setup`" 1. every tfm's `order` default to 0 2. `assoc`, `is_tuple`, `prev` default to None 3. `filt`, `mask`, default to None 4. `_is_setup`,`_done_setup`, default to None"""
def create(cls, f, filt=No... | the_stack_v2_python_sparse | my_workstation/my-v2/data.pipeline.Transform.py | EmbraceLife/fastai_treasures | train | 21 |
d258a7fefe0a4a5227c1fa73db5153454e8e90e1 | [
"def backtrack(arr, k, start, path):\n if len(path) == k:\n self.res.append(path[:])\n return\n for i in range(start, len(arr)):\n path.append(arr[i])\n backtrack(arr, k, start + 1, path)\n path.pop()\nself.res = []\nbacktrack(arr, k, 0, [])\nreturn self.res",
"def backtra... | <|body_start_0|>
def backtrack(arr, k, start, path):
if len(path) == k:
self.res.append(path[:])
return
for i in range(start, len(arr)):
path.append(arr[i])
backtrack(arr, k, start + 1, path)
path.pop()
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def genCombinations(arr, k):
"""Purpose: Generates all combinations of elements in `arr`, using backtracking."""
<|body_0|>
def genCombinations(arr, k):
"""Purpose: Generates all INCREASING combinations of elements in `arr`, using backtracking."""
<... | stack_v2_sparse_classes_36k_train_023166 | 2,449 | no_license | [
{
"docstring": "Purpose: Generates all combinations of elements in `arr`, using backtracking.",
"name": "genCombinations",
"signature": "def genCombinations(arr, k)"
},
{
"docstring": "Purpose: Generates all INCREASING combinations of elements in `arr`, using backtracking.",
"name": "genComb... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def genCombinations(arr, k): Purpose: Generates all combinations of elements in `arr`, using backtracking.
- def genCombinations(arr, k): Purpose: Generates all INCREASING combin... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def genCombinations(arr, k): Purpose: Generates all combinations of elements in `arr`, using backtracking.
- def genCombinations(arr, k): Purpose: Generates all INCREASING combin... | 95a86cbbca28d0c0f6d72d28a2f1cb5a86327934 | <|skeleton|>
class Solution:
def genCombinations(arr, k):
"""Purpose: Generates all combinations of elements in `arr`, using backtracking."""
<|body_0|>
def genCombinations(arr, k):
"""Purpose: Generates all INCREASING combinations of elements in `arr`, using backtracking."""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def genCombinations(arr, k):
"""Purpose: Generates all combinations of elements in `arr`, using backtracking."""
def backtrack(arr, k, start, path):
if len(path) == k:
self.res.append(path[:])
return
for i in range(start, len(ar... | the_stack_v2_python_sparse | backtrackCombinations.py | tashakim/puzzles_python | train | 8 | |
735dade4c3ea0b8a592f2eaddf064a5e2891c50c | [
"sample_size = len(samples)\nassert sample_size <= self.config.num_accumulated_batches\nmodel = state.model\nself.zero_grads(state)\nfor idx, (batch_id, (raw_batch, batch)) in enumerate(samples):\n with contextlib_ExitStack() as exit_stack:\n maybe_accumulate_gradients(exit_stack, model, idx, sample_size)... | <|body_start_0|>
sample_size = len(samples)
assert sample_size <= self.config.num_accumulated_batches
model = state.model
self.zero_grads(state)
for idx, (batch_id, (raw_batch, batch)) in enumerate(samples):
with contextlib_ExitStack() as exit_stack:
m... | TaskTrainer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaskTrainer:
def run_step(self, samples: List[Any], state: TrainingState, metric_reporter: MetricReporter, report_metric: bool):
"""Our run_step is a bit different, because we're wrapping the model forward call with model.train_batch, which arranges tensors and gets loss, etc. Whenever "... | stack_v2_sparse_classes_36k_train_023167 | 26,177 | permissive | [
{
"docstring": "Our run_step is a bit different, because we're wrapping the model forward call with model.train_batch, which arranges tensors and gets loss, etc. Whenever \"samples\" contains more than one mini-batch (sample_size > 1), we want to accumulate gradients locally and only call all-reduce in the last... | 2 | stack_v2_sparse_classes_30k_train_020029 | Implement the Python class `TaskTrainer` described below.
Class description:
Implement the TaskTrainer class.
Method signatures and docstrings:
- def run_step(self, samples: List[Any], state: TrainingState, metric_reporter: MetricReporter, report_metric: bool): Our run_step is a bit different, because we're wrapping ... | Implement the Python class `TaskTrainer` described below.
Class description:
Implement the TaskTrainer class.
Method signatures and docstrings:
- def run_step(self, samples: List[Any], state: TrainingState, metric_reporter: MetricReporter, report_metric: bool): Our run_step is a bit different, because we're wrapping ... | f82830da00339392fd17c70572cf1920262d6d74 | <|skeleton|>
class TaskTrainer:
def run_step(self, samples: List[Any], state: TrainingState, metric_reporter: MetricReporter, report_metric: bool):
"""Our run_step is a bit different, because we're wrapping the model forward call with model.train_batch, which arranges tensors and gets loss, etc. Whenever "... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TaskTrainer:
def run_step(self, samples: List[Any], state: TrainingState, metric_reporter: MetricReporter, report_metric: bool):
"""Our run_step is a bit different, because we're wrapping the model forward call with model.train_batch, which arranges tensors and gets loss, etc. Whenever "samples" conta... | the_stack_v2_python_sparse | pytext/trainers/trainer.py | appatsekhar/pytext | train | 3 | |
6985fbcc9d3f5a87986d7c327d6f9d9a1bf6859a | [
"self.model = torch_model.to(device)\nself.model.eval()\nself.dev = device\nself.transform = x_transform",
"arm_dataset = data_utils.DatasetNumpy(np_x, np_y, transform=self.transform)\narm_loader = torch.utils.data.DataLoader(arm_dataset, batch_size=128)\nreturn train_utils.evaluate(self.model, arm_loader, self.d... | <|body_start_0|>
self.model = torch_model.to(device)
self.model.eval()
self.dev = device
self.transform = x_transform
<|end_body_0|>
<|body_start_1|>
arm_dataset = data_utils.DatasetNumpy(np_x, np_y, transform=self.transform)
arm_loader = torch.utils.data.DataLoader(arm_... | Model | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Model:
def __init__(self, torch_model, device, x_transform=None):
""":args: Torch model and device, the forward of model should give logits(classification)/scalar(regression) :x_transform: Any needed transform before we obtain predictions."""
<|body_0|>
def evaluate(self, np... | stack_v2_sparse_classes_36k_train_023168 | 5,605 | no_license | [
{
"docstring": ":args: Torch model and device, the forward of model should give logits(classification)/scalar(regression) :x_transform: Any needed transform before we obtain predictions.",
"name": "__init__",
"signature": "def __init__(self, torch_model, device, x_transform=None)"
},
{
"docstrin... | 4 | stack_v2_sparse_classes_30k_train_016965 | Implement the Python class `Model` described below.
Class description:
Implement the Model class.
Method signatures and docstrings:
- def __init__(self, torch_model, device, x_transform=None): :args: Torch model and device, the forward of model should give logits(classification)/scalar(regression) :x_transform: Any n... | Implement the Python class `Model` described below.
Class description:
Implement the Model class.
Method signatures and docstrings:
- def __init__(self, torch_model, device, x_transform=None): :args: Torch model and device, the forward of model should give logits(classification)/scalar(regression) :x_transform: Any n... | 9782f6705a779d20323eb5a0132aeabffa5fbf92 | <|skeleton|>
class Model:
def __init__(self, torch_model, device, x_transform=None):
""":args: Torch model and device, the forward of model should give logits(classification)/scalar(regression) :x_transform: Any needed transform before we obtain predictions."""
<|body_0|>
def evaluate(self, np... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Model:
def __init__(self, torch_model, device, x_transform=None):
""":args: Torch model and device, the forward of model should give logits(classification)/scalar(regression) :x_transform: Any needed transform before we obtain predictions."""
self.model = torch_model.to(device)
self.mo... | the_stack_v2_python_sparse | src/dataset.py | vihari/AAA | train | 3 | |
b55798b5079ff47e5b7312df18b06c3ef7a72ad6 | [
"try:\n return_data = AutoMlRule().set_graph_type_list(graph_id, request.data)\n return Response(json.dumps(return_data))\nexcept Exception as e:\n return_data = {'status': '404', 'result': str(e)}\n return Response(json.dumps(return_data))",
"try:\n if graph_id == 'all':\n return_data = Aut... | <|body_start_0|>
try:
return_data = AutoMlRule().set_graph_type_list(graph_id, request.data)
return Response(json.dumps(return_data))
except Exception as e:
return_data = {'status': '404', 'result': str(e)}
return Response(json.dumps(return_data))
<|end_bo... | RunManagerAutoRule | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RunManagerAutoRule:
def post(self, request, graph_id):
"""- desc : insert cnn configuration data"""
<|body_0|>
def get(self, request, graph_id):
"""- desc : get cnn configuration data"""
<|body_1|>
def put(self, request, graph_id):
"""- desc ; up... | stack_v2_sparse_classes_36k_train_023169 | 2,006 | no_license | [
{
"docstring": "- desc : insert cnn configuration data",
"name": "post",
"signature": "def post(self, request, graph_id)"
},
{
"docstring": "- desc : get cnn configuration data",
"name": "get",
"signature": "def get(self, request, graph_id)"
},
{
"docstring": "- desc ; update cnn... | 4 | stack_v2_sparse_classes_30k_train_007910 | Implement the Python class `RunManagerAutoRule` described below.
Class description:
Implement the RunManagerAutoRule class.
Method signatures and docstrings:
- def post(self, request, graph_id): - desc : insert cnn configuration data
- def get(self, request, graph_id): - desc : get cnn configuration data
- def put(se... | Implement the Python class `RunManagerAutoRule` described below.
Class description:
Implement the RunManagerAutoRule class.
Method signatures and docstrings:
- def post(self, request, graph_id): - desc : insert cnn configuration data
- def get(self, request, graph_id): - desc : get cnn configuration data
- def put(se... | 9fda5e4487ccb6b1cbfea3066b8f1e18162aa090 | <|skeleton|>
class RunManagerAutoRule:
def post(self, request, graph_id):
"""- desc : insert cnn configuration data"""
<|body_0|>
def get(self, request, graph_id):
"""- desc : get cnn configuration data"""
<|body_1|>
def put(self, request, graph_id):
"""- desc ; up... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RunManagerAutoRule:
def post(self, request, graph_id):
"""- desc : insert cnn configuration data"""
try:
return_data = AutoMlRule().set_graph_type_list(graph_id, request.data)
return Response(json.dumps(return_data))
except Exception as e:
return_dat... | the_stack_v2_python_sparse | api/views/runmanager_auto_rule.py | JamieMoon/tensormsa | train | 0 | |
6cc4ec51c925de0573ce6257b0ee58f69178311f | [
"item = Event.get_by_id(item_id)\nif item is None:\n abort(404)\nreturn item",
"item = Event.get_by_id(item_id)\nif item is None:\n abort(404)\nblp.check_etag(item, EventSchema)\nitem.delete()"
] | <|body_start_0|>
item = Event.get_by_id(item_id)
if item is None:
abort(404)
return item
<|end_body_0|>
<|body_start_1|>
item = Event.get_by_id(item_id)
if item is None:
abort(404)
blp.check_etag(item, EventSchema)
item.delete()
<|end_body... | EventsByIdViews | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventsByIdViews:
def get(self, item_id):
"""Get en event by its ID"""
<|body_0|>
def delete(self, item_id):
"""Delete an event"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
item = Event.get_by_id(item_id)
if item is None:
abort... | stack_v2_sparse_classes_36k_train_023170 | 3,771 | no_license | [
{
"docstring": "Get en event by its ID",
"name": "get",
"signature": "def get(self, item_id)"
},
{
"docstring": "Delete an event",
"name": "delete",
"signature": "def delete(self, item_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018853 | Implement the Python class `EventsByIdViews` described below.
Class description:
Implement the EventsByIdViews class.
Method signatures and docstrings:
- def get(self, item_id): Get en event by its ID
- def delete(self, item_id): Delete an event | Implement the Python class `EventsByIdViews` described below.
Class description:
Implement the EventsByIdViews class.
Method signatures and docstrings:
- def get(self, item_id): Get en event by its ID
- def delete(self, item_id): Delete an event
<|skeleton|>
class EventsByIdViews:
def get(self, item_id):
... | 96768e453c2714085bb4cb8ae2253139bd61f9a3 | <|skeleton|>
class EventsByIdViews:
def get(self, item_id):
"""Get en event by its ID"""
<|body_0|>
def delete(self, item_id):
"""Delete an event"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EventsByIdViews:
def get(self, item_id):
"""Get en event by its ID"""
item = Event.get_by_id(item_id)
if item is None:
abort(404)
return item
def delete(self, item_id):
"""Delete an event"""
item = Event.get_by_id(item_id)
if item is Non... | the_stack_v2_python_sparse | bemserver/app/api/resources/events/routes.py | Nobatek/bemserver | train | 0 | |
8e44173ef5f3ed99712d265f31bca6a985dfb02e | [
"self.aws_usage_bytes = aws_usage_bytes\nself.azure_usage_bytes = azure_usage_bytes\nself.gcp_usage_bytes = gcp_usage_bytes\nself.nas_usage_bytes = nas_usage_bytes\nself.oracle_usage_bytes = oracle_usage_bytes\nself.qstar_usage_bytes = qstar_usage_bytes\nself.s3_c_usage_bytes = s3_c_usage_bytes\nself.vault_stats_li... | <|body_start_0|>
self.aws_usage_bytes = aws_usage_bytes
self.azure_usage_bytes = azure_usage_bytes
self.gcp_usage_bytes = gcp_usage_bytes
self.nas_usage_bytes = nas_usage_bytes
self.oracle_usage_bytes = oracle_usage_bytes
self.qstar_usage_bytes = qstar_usage_bytes
... | Implementation of the 'VaultStats' model. Specifies the storage usage on vaults. Attributes: aws_usage_bytes (long|int): Specifies the usage on AWS vaults. azure_usage_bytes (long|int): Specifies the usage on Azure vaults. gcp_usage_bytes (long|int): Specifies the usage on GCP vaults. nas_usage_bytes (long|int): Specif... | VaultStats | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VaultStats:
"""Implementation of the 'VaultStats' model. Specifies the storage usage on vaults. Attributes: aws_usage_bytes (long|int): Specifies the usage on AWS vaults. azure_usage_bytes (long|int): Specifies the usage on Azure vaults. gcp_usage_bytes (long|int): Specifies the usage on GCP vaul... | stack_v2_sparse_classes_36k_train_023171 | 3,835 | permissive | [
{
"docstring": "Constructor for the VaultStats class",
"name": "__init__",
"signature": "def __init__(self, aws_usage_bytes=None, azure_usage_bytes=None, gcp_usage_bytes=None, nas_usage_bytes=None, oracle_usage_bytes=None, qstar_usage_bytes=None, s3_c_usage_bytes=None, vault_stats_list=None)"
},
{
... | 2 | null | Implement the Python class `VaultStats` described below.
Class description:
Implementation of the 'VaultStats' model. Specifies the storage usage on vaults. Attributes: aws_usage_bytes (long|int): Specifies the usage on AWS vaults. azure_usage_bytes (long|int): Specifies the usage on Azure vaults. gcp_usage_bytes (lon... | Implement the Python class `VaultStats` described below.
Class description:
Implementation of the 'VaultStats' model. Specifies the storage usage on vaults. Attributes: aws_usage_bytes (long|int): Specifies the usage on AWS vaults. azure_usage_bytes (long|int): Specifies the usage on Azure vaults. gcp_usage_bytes (lon... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class VaultStats:
"""Implementation of the 'VaultStats' model. Specifies the storage usage on vaults. Attributes: aws_usage_bytes (long|int): Specifies the usage on AWS vaults. azure_usage_bytes (long|int): Specifies the usage on Azure vaults. gcp_usage_bytes (long|int): Specifies the usage on GCP vaul... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VaultStats:
"""Implementation of the 'VaultStats' model. Specifies the storage usage on vaults. Attributes: aws_usage_bytes (long|int): Specifies the usage on AWS vaults. azure_usage_bytes (long|int): Specifies the usage on Azure vaults. gcp_usage_bytes (long|int): Specifies the usage on GCP vaults. nas_usage... | the_stack_v2_python_sparse | cohesity_management_sdk/models/vault_stats.py | cohesity/management-sdk-python | train | 24 |
924d1c938bd0ba5912840f26fae6e74db2256bcd | [
"num_stack = []\nopear_stack = []\nopeard = {'+': add, '-': sub}\nlevel = {')': 1, '+': 1, '-': 1, '(': 2, '$': 0}\ni = n = 0\ns += '$'\nfor i, c in enumerate(s):\n if c == ' ':\n continue\n if c.isdigit():\n n = n * 10 + int(c)\n if not s[i + 1].isdigit():\n num_stack.append(n... | <|body_start_0|>
num_stack = []
opear_stack = []
opeard = {'+': add, '-': sub}
level = {')': 1, '+': 1, '-': 1, '(': 2, '$': 0}
i = n = 0
s += '$'
for i, c in enumerate(s):
if c == ' ':
continue
if c.isdigit():
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def calculate(self, s: str) -> int:
"""使用双栈的方式,为了避免陷入判断的泥潭,需要每次运算完成后,不管什么情况,都把结果入栈"""
<|body_0|>
def calculate(self, s: str) -> int:
"""双栈的方法比较通用,因为只涉及加减法,可以把问题 简化,只需要将第一个操作数当做正数,然后后面就每次加上一个符号数。 遇到括号就把符号和操作数一起入栈,遇到右括号,再逐步出栈"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k_train_023172 | 3,812 | no_license | [
{
"docstring": "使用双栈的方式,为了避免陷入判断的泥潭,需要每次运算完成后,不管什么情况,都把结果入栈",
"name": "calculate",
"signature": "def calculate(self, s: str) -> int"
},
{
"docstring": "双栈的方法比较通用,因为只涉及加减法,可以把问题 简化,只需要将第一个操作数当做正数,然后后面就每次加上一个符号数。 遇到括号就把符号和操作数一起入栈,遇到右括号,再逐步出栈",
"name": "calculate",
"signature": "def calcula... | 2 | stack_v2_sparse_classes_30k_train_002450 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calculate(self, s: str) -> int: 使用双栈的方式,为了避免陷入判断的泥潭,需要每次运算完成后,不管什么情况,都把结果入栈
- def calculate(self, s: str) -> int: 双栈的方法比较通用,因为只涉及加减法,可以把问题 简化,只需要将第一个操作数当做正数,然后后面就每次加上一个符号数。 遇... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calculate(self, s: str) -> int: 使用双栈的方式,为了避免陷入判断的泥潭,需要每次运算完成后,不管什么情况,都把结果入栈
- def calculate(self, s: str) -> int: 双栈的方法比较通用,因为只涉及加减法,可以把问题 简化,只需要将第一个操作数当做正数,然后后面就每次加上一个符号数。 遇... | 092a800a15bdd0f3d0c8f521a5e0fc90f964e8a8 | <|skeleton|>
class Solution:
def calculate(self, s: str) -> int:
"""使用双栈的方式,为了避免陷入判断的泥潭,需要每次运算完成后,不管什么情况,都把结果入栈"""
<|body_0|>
def calculate(self, s: str) -> int:
"""双栈的方法比较通用,因为只涉及加减法,可以把问题 简化,只需要将第一个操作数当做正数,然后后面就每次加上一个符号数。 遇到括号就把符号和操作数一起入栈,遇到右括号,再逐步出栈"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def calculate(self, s: str) -> int:
"""使用双栈的方式,为了避免陷入判断的泥潭,需要每次运算完成后,不管什么情况,都把结果入栈"""
num_stack = []
opear_stack = []
opeard = {'+': add, '-': sub}
level = {')': 1, '+': 1, '-': 1, '(': 2, '$': 0}
i = n = 0
s += '$'
for i, c in enumerat... | the_stack_v2_python_sparse | leetcode/400/224. 基本计算器.py | August-us/exam | train | 1 | |
982229c702b0bc02857703c4a9f44661336f7a54 | [
"self.num_p = num_particles\nself.num_d = num_dimensions\nself.alpha = alpha\nself.alpha4 = alpha ** 4\nself.alpha5 = alpha ** 5\nself.s = system",
"term = 0.0\nself.s.positions_distances_PBC(positions)\nfor i in range(self.num_p):\n for j in range(i, self.num_p - 1):\n distance = self.s.distances[i, j ... | <|body_start_0|>
self.num_p = num_particles
self.num_d = num_dimensions
self.alpha = alpha
self.alpha4 = alpha ** 4
self.alpha5 = alpha ** 5
self.s = system
<|end_body_0|>
<|body_start_1|>
term = 0.0
self.s.positions_distances_PBC(positions)
for i... | Contains parameters of wavefunction and wave equation. | McMillian_Wavefunction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class McMillian_Wavefunction:
"""Contains parameters of wavefunction and wave equation."""
def __init__(self, num_particles, num_dimensions, alpha, system):
"""Instance of class."""
<|body_0|>
def wavefunction(self, positions):
"""Return wave equation."""
<|bod... | stack_v2_sparse_classes_36k_train_023173 | 4,374 | no_license | [
{
"docstring": "Instance of class.",
"name": "__init__",
"signature": "def __init__(self, num_particles, num_dimensions, alpha, system)"
},
{
"docstring": "Return wave equation.",
"name": "wavefunction",
"signature": "def wavefunction(self, positions)"
},
{
"docstring": "Calculat... | 6 | stack_v2_sparse_classes_30k_train_009439 | Implement the Python class `McMillian_Wavefunction` described below.
Class description:
Contains parameters of wavefunction and wave equation.
Method signatures and docstrings:
- def __init__(self, num_particles, num_dimensions, alpha, system): Instance of class.
- def wavefunction(self, positions): Return wave equat... | Implement the Python class `McMillian_Wavefunction` described below.
Class description:
Contains parameters of wavefunction and wave equation.
Method signatures and docstrings:
- def __init__(self, num_particles, num_dimensions, alpha, system): Instance of class.
- def wavefunction(self, positions): Return wave equat... | bed19421ceef6203d089b67a657ca3290740300a | <|skeleton|>
class McMillian_Wavefunction:
"""Contains parameters of wavefunction and wave equation."""
def __init__(self, num_particles, num_dimensions, alpha, system):
"""Instance of class."""
<|body_0|>
def wavefunction(self, positions):
"""Return wave equation."""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class McMillian_Wavefunction:
"""Contains parameters of wavefunction and wave equation."""
def __init__(self, num_particles, num_dimensions, alpha, system):
"""Instance of class."""
self.num_p = num_particles
self.num_d = num_dimensions
self.alpha = alpha
self.alpha4 = a... | the_stack_v2_python_sparse | src/Wavefunction/mcmillian.py | KariEriksen/VMC | train | 6 |
f919ce4e61746c101ff0ae68e9cbd853f083091c | [
"self._with_bkg_par = bool(with_bkg_par)\nself._t_start = float(t_start)\nself._exposure = float(exposure)\nself._seed = int(seed)\nself._simput = simput\nself._simput2 = simput2\nself._simput3 = simput3\nself._data_dir = data_dir\nself._ra_cen = ra_cen\nself._dec_cen = dec_cen",
"try:\n os.makedirs(self._data... | <|body_start_0|>
self._with_bkg_par = bool(with_bkg_par)
self._t_start = float(t_start)
self._exposure = float(exposure)
self._seed = int(seed)
self._simput = simput
self._simput2 = simput2
self._simput3 = simput3
self._data_dir = data_dir
self._ra... | SIXTE simulator for eROSITA observations. 1. Compute GTI file for given simput 2. Simulate eROSITA observations of simput, using GTI to speed things up. | Simulator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Simulator:
"""SIXTE simulator for eROSITA observations. 1. Compute GTI file for given simput 2. Simulate eROSITA observations of simput, using GTI to speed things up."""
def __init__(self, with_bkg_par, t_start, exposure, seed, simput, simput2, simput3, data_dir, ra_cen, dec_cen):
""... | stack_v2_sparse_classes_36k_train_023174 | 6,902 | no_license | [
{
"docstring": ":param with_bkg_par: Simulate with particle background. :param t_start: Start time of simulation. Input units of [s] :param exposure: Length of time to simulate for after t_start :param seed: Seed for random number generator. :param simput: Simput file (ie. the sky model)",
"name": "__init__... | 5 | null | Implement the Python class `Simulator` described below.
Class description:
SIXTE simulator for eROSITA observations. 1. Compute GTI file for given simput 2. Simulate eROSITA observations of simput, using GTI to speed things up.
Method signatures and docstrings:
- def __init__(self, with_bkg_par, t_start, exposure, se... | Implement the Python class `Simulator` described below.
Class description:
SIXTE simulator for eROSITA observations. 1. Compute GTI file for given simput 2. Simulate eROSITA observations of simput, using GTI to speed things up.
Method signatures and docstrings:
- def __init__(self, with_bkg_par, t_start, exposure, se... | 2b8ac686b1d445a39fcd28dbe07ef467c0b14c7e | <|skeleton|>
class Simulator:
"""SIXTE simulator for eROSITA observations. 1. Compute GTI file for given simput 2. Simulate eROSITA observations of simput, using GTI to speed things up."""
def __init__(self, with_bkg_par, t_start, exposure, seed, simput, simput2, simput3, data_dir, ra_cen, dec_cen):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Simulator:
"""SIXTE simulator for eROSITA observations. 1. Compute GTI file for given simput 2. Simulate eROSITA observations of simput, using GTI to speed things up."""
def __init__(self, with_bkg_par, t_start, exposure, seed, simput, simput2, simput3, data_dir, ra_cen, dec_cen):
""":param with_... | the_stack_v2_python_sparse | python/sixte/simulate.py | HuiboZhou/mocks_high_fidelity | train | 0 |
36d179906a24584a7fef28f6aa6b9161ef3a0b21 | [
"super().__init__(msg, event_type, cost_mgmt_id)\nself.source_id = int(self.value.get('source_id'))\nself.application_type_id = int(self.value.get('application_type_id', -1))",
"if self.event_type in (KAFKA_APPLICATION_CREATE,):\n LOG.debug(f'[ApplicationMsgProcessor] creating source for source_id: {self.sourc... | <|body_start_0|>
super().__init__(msg, event_type, cost_mgmt_id)
self.source_id = int(self.value.get('source_id'))
self.application_type_id = int(self.value.get('application_type_id', -1))
<|end_body_0|>
<|body_start_1|>
if self.event_type in (KAFKA_APPLICATION_CREATE,):
LOG... | Processor for Application events. | ApplicationMsgProcessor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApplicationMsgProcessor:
"""Processor for Application events."""
def __init__(self, msg, event_type, cost_mgmt_id):
"""Constructor for ApplicationMsgProcessor."""
<|body_0|>
def process(self):
"""Process the message."""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_36k_train_023175 | 16,664 | permissive | [
{
"docstring": "Constructor for ApplicationMsgProcessor.",
"name": "__init__",
"signature": "def __init__(self, msg, event_type, cost_mgmt_id)"
},
{
"docstring": "Process the message.",
"name": "process",
"signature": "def process(self)"
}
] | 2 | null | Implement the Python class `ApplicationMsgProcessor` described below.
Class description:
Processor for Application events.
Method signatures and docstrings:
- def __init__(self, msg, event_type, cost_mgmt_id): Constructor for ApplicationMsgProcessor.
- def process(self): Process the message. | Implement the Python class `ApplicationMsgProcessor` described below.
Class description:
Processor for Application events.
Method signatures and docstrings:
- def __init__(self, msg, event_type, cost_mgmt_id): Constructor for ApplicationMsgProcessor.
- def process(self): Process the message.
<|skeleton|>
class Appli... | 0416e5216eb1ec4b41c8dd4999adde218b1ab2e1 | <|skeleton|>
class ApplicationMsgProcessor:
"""Processor for Application events."""
def __init__(self, msg, event_type, cost_mgmt_id):
"""Constructor for ApplicationMsgProcessor."""
<|body_0|>
def process(self):
"""Process the message."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ApplicationMsgProcessor:
"""Processor for Application events."""
def __init__(self, msg, event_type, cost_mgmt_id):
"""Constructor for ApplicationMsgProcessor."""
super().__init__(msg, event_type, cost_mgmt_id)
self.source_id = int(self.value.get('source_id'))
self.applica... | the_stack_v2_python_sparse | koku/sources/kafka_message_processor.py | project-koku/koku | train | 225 |
837c551cb7005c6c4865b82bd7cce06cfdc2f8ca | [
"super(SequentialResNet, self).__init__(name=name)\nself.boosting_modules = []\nwith self._enter_variable_scope():\n self._base_hypothesis = tf.get_variable('base_hypothesis', shape=class_num)\n self._base_alpha = tf.zeros(class_num)\n self._base_repr_module = snt.Conv2D(representation_channels, 3, name='b... | <|body_start_0|>
super(SequentialResNet, self).__init__(name=name)
self.boosting_modules = []
with self._enter_variable_scope():
self._base_hypothesis = tf.get_variable('base_hypothesis', shape=class_num)
self._base_alpha = tf.zeros(class_num)
self._base_repr_... | Implementation of boosted residual network introduced in Huang et al. 2017 Usage steps: 1) SequentialResNet() to create module 2) `build()` to initialize network with input data 3) `add_module()` to add a ResidualBoostingModule to network 4) `get_hypothesis_loss()` to get loss of the new module's hypothesis 5) `module.... | SequentialResNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequentialResNet:
"""Implementation of boosted residual network introduced in Huang et al. 2017 Usage steps: 1) SequentialResNet() to create module 2) `build()` to initialize network with input data 3) `add_module()` to add a ResidualBoostingModule to network 4) `get_hypothesis_loss()` to get los... | stack_v2_sparse_classes_36k_train_023176 | 6,326 | no_license | [
{
"docstring": "Args: class_num (int): number of classes in classification problem representation_channels (int): number of channels for residual representation",
"name": "__init__",
"signature": "def __init__(self, class_num, representation_channels, name='sequential_resnet')"
},
{
"docstring":... | 4 | null | Implement the Python class `SequentialResNet` described below.
Class description:
Implementation of boosted residual network introduced in Huang et al. 2017 Usage steps: 1) SequentialResNet() to create module 2) `build()` to initialize network with input data 3) `add_module()` to add a ResidualBoostingModule to networ... | Implement the Python class `SequentialResNet` described below.
Class description:
Implementation of boosted residual network introduced in Huang et al. 2017 Usage steps: 1) SequentialResNet() to create module 2) `build()` to initialize network with input data 3) `add_module()` to add a ResidualBoostingModule to networ... | 11b322af306daf60c6d3b1784c3cf348f0eed778 | <|skeleton|>
class SequentialResNet:
"""Implementation of boosted residual network introduced in Huang et al. 2017 Usage steps: 1) SequentialResNet() to create module 2) `build()` to initialize network with input data 3) `add_module()` to add a ResidualBoostingModule to network 4) `get_hypothesis_loss()` to get los... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SequentialResNet:
"""Implementation of boosted residual network introduced in Huang et al. 2017 Usage steps: 1) SequentialResNet() to create module 2) `build()` to initialize network with input data 3) `add_module()` to add a ResidualBoostingModule to network 4) `get_hypothesis_loss()` to get loss of the new ... | the_stack_v2_python_sparse | pyroclast/selfboosting/sequential_resnet.py | DrKwint/pyroclast | train | 9 |
d9780cc95b09051e2d77ad2ed07aaa3e384d165a | [
"super().__init__()\nself.deep = DNNLayer(inputs_size=inputs_size, output_size=deep_output_size, layer_sizes=deep_layer_sizes, dropout_p=deep_dropout_p, activation=deep_activation)\nself.cross = CrossNetworkLayer(inputs_size=inputs_size, num_layers=cross_num_layers)\ncat_size = (deep_output_size + inputs_size) * nu... | <|body_start_0|>
super().__init__()
self.deep = DNNLayer(inputs_size=inputs_size, output_size=deep_output_size, layer_sizes=deep_layer_sizes, dropout_p=deep_dropout_p, activation=deep_activation)
self.cross = CrossNetworkLayer(inputs_size=inputs_size, num_layers=cross_num_layers)
cat_siz... | Model class of Deep & Cross Network (DCN), which is a concatenation of dense network (deep part) and cross network (cross part). :Reference: #. `Ruoxi Wang et al, 2017. Deep & Cross Network for Ad Click Predictions <https://arxiv.org/abs/1708.05123>`_. | DeepAndCrossNetworkModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeepAndCrossNetworkModel:
"""Model class of Deep & Cross Network (DCN), which is a concatenation of dense network (deep part) and cross network (cross part). :Reference: #. `Ruoxi Wang et al, 2017. Deep & Cross Network for Ad Click Predictions <https://arxiv.org/abs/1708.05123>`_."""
def __i... | stack_v2_sparse_classes_36k_train_023177 | 3,708 | permissive | [
{
"docstring": "Initialize DeepAndCrossNetworkModel Args: inputs_size (int): inputs size of dense network and cross network, i.e. number of fields * embedding size deep_output_size (int): output size of dense network deep_layer_sizes (List[int]): layer sizes of dense network cross_num_layers (int): number of la... | 2 | stack_v2_sparse_classes_30k_test_000150 | Implement the Python class `DeepAndCrossNetworkModel` described below.
Class description:
Model class of Deep & Cross Network (DCN), which is a concatenation of dense network (deep part) and cross network (cross part). :Reference: #. `Ruoxi Wang et al, 2017. Deep & Cross Network for Ad Click Predictions <https://arxiv... | Implement the Python class `DeepAndCrossNetworkModel` described below.
Class description:
Model class of Deep & Cross Network (DCN), which is a concatenation of dense network (deep part) and cross network (cross part). :Reference: #. `Ruoxi Wang et al, 2017. Deep & Cross Network for Ad Click Predictions <https://arxiv... | 751a43b9cd35e951d81c0d9cf46507b1777bb7ff | <|skeleton|>
class DeepAndCrossNetworkModel:
"""Model class of Deep & Cross Network (DCN), which is a concatenation of dense network (deep part) and cross network (cross part). :Reference: #. `Ruoxi Wang et al, 2017. Deep & Cross Network for Ad Click Predictions <https://arxiv.org/abs/1708.05123>`_."""
def __i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeepAndCrossNetworkModel:
"""Model class of Deep & Cross Network (DCN), which is a concatenation of dense network (deep part) and cross network (cross part). :Reference: #. `Ruoxi Wang et al, 2017. Deep & Cross Network for Ad Click Predictions <https://arxiv.org/abs/1708.05123>`_."""
def __init__(self, i... | the_stack_v2_python_sparse | torecsys/models/ctr/deep_and_cross_network.py | p768lwy3/torecsys | train | 98 |
5593bea058acff78672a3ff2d952182eb2c9dbf7 | [
"self._stop_atcocode = stop_atcocode\nself._bus_direction = bus_direction\nself._next_buses = []\nself._destination_re = re.compile(f'{bus_direction}', re.IGNORECASE)\nsensor_name = f'Next bus to {bus_direction}'\nstop_url = f'bus/stop/{stop_atcocode}/live.json'\nUkTransportSensor.__init__(self, sensor_name, api_ap... | <|body_start_0|>
self._stop_atcocode = stop_atcocode
self._bus_direction = bus_direction
self._next_buses = []
self._destination_re = re.compile(f'{bus_direction}', re.IGNORECASE)
sensor_name = f'Next bus to {bus_direction}'
stop_url = f'bus/stop/{stop_atcocode}/live.json... | Live bus time sensor from UK transportapi.com. | UkTransportLiveBusTimeSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UkTransportLiveBusTimeSensor:
"""Live bus time sensor from UK transportapi.com."""
def __init__(self, api_app_id, api_app_key, stop_atcocode, bus_direction, interval):
"""Construct a live bus time sensor."""
<|body_0|>
def _update(self):
"""Get the latest live de... | stack_v2_sparse_classes_36k_train_023178 | 9,762 | permissive | [
{
"docstring": "Construct a live bus time sensor.",
"name": "__init__",
"signature": "def __init__(self, api_app_id, api_app_key, stop_atcocode, bus_direction, interval)"
},
{
"docstring": "Get the latest live departure data for the specified stop.",
"name": "_update",
"signature": "def ... | 3 | null | Implement the Python class `UkTransportLiveBusTimeSensor` described below.
Class description:
Live bus time sensor from UK transportapi.com.
Method signatures and docstrings:
- def __init__(self, api_app_id, api_app_key, stop_atcocode, bus_direction, interval): Construct a live bus time sensor.
- def _update(self): G... | Implement the Python class `UkTransportLiveBusTimeSensor` described below.
Class description:
Live bus time sensor from UK transportapi.com.
Method signatures and docstrings:
- def __init__(self, api_app_id, api_app_key, stop_atcocode, bus_direction, interval): Construct a live bus time sensor.
- def _update(self): G... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class UkTransportLiveBusTimeSensor:
"""Live bus time sensor from UK transportapi.com."""
def __init__(self, api_app_id, api_app_key, stop_atcocode, bus_direction, interval):
"""Construct a live bus time sensor."""
<|body_0|>
def _update(self):
"""Get the latest live de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UkTransportLiveBusTimeSensor:
"""Live bus time sensor from UK transportapi.com."""
def __init__(self, api_app_id, api_app_key, stop_atcocode, bus_direction, interval):
"""Construct a live bus time sensor."""
self._stop_atcocode = stop_atcocode
self._bus_direction = bus_direction
... | the_stack_v2_python_sparse | homeassistant/components/uk_transport/sensor.py | home-assistant/core | train | 35,501 |
fd3dc4c28d021d65f093d0b11b6ce48628d4b80c | [
"def dfs(node):\n if node:\n res.append(str(node.val))\n dfs(node.left)\n dfs(node.right)\n else:\n res.append('#')\nres = []\ndfs(root)\nreturn ' '.join(res)",
"def helper(vals):\n cur = vals.pop(0)\n if cur == '#':\n return None\n node = TreeNode(cur)\n node.... | <|body_start_0|>
def dfs(node):
if node:
res.append(str(node.val))
dfs(node.left)
dfs(node.right)
else:
res.append('#')
res = []
dfs(root)
return ' '.join(res)
<|end_body_0|>
<|body_start_1|>
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_023179 | 3,428 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 56383c2b07448a9017a7a707afb66e08b403ee76 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def dfs(node):
if node:
res.append(str(node.val))
dfs(node.left)
dfs(node.right)
else:
res.append(... | the_stack_v2_python_sparse | _Google/297_O_Serialize_and_Deserialize_Binary_Tree.py | jamiezeminzhang/Leetcode_Python | train | 2 | |
86f7ec526e6b23ee43b1720db853010c6d9f9135 | [
"self._max_repeat = max_repeat\nself._sleep_time = sleep_time\nself._session = None\nreturn",
"if not self._session:\n self._session = aiohttp.ClientSession(loop=loop, headers={'User-Agent': make_random_useragent(), 'Accept-Encoding': 'gzip'})\nreturn",
"if not self._session.closed:\n self._session.close(... | <|body_start_0|>
self._max_repeat = max_repeat
self._sleep_time = sleep_time
self._session = None
return
<|end_body_0|>
<|body_start_1|>
if not self._session:
self._session = aiohttp.ClientSession(loop=loop, headers={'User-Agent': make_random_useragent(), 'Accept-Enc... | class of FetcherAsync | FetcherAsync | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FetcherAsync:
"""class of FetcherAsync"""
def __init__(self, max_repeat=3, sleep_time=0):
"""constructor"""
<|body_0|>
def init_session(self, loop):
"""initial self._session based on loop"""
<|body_1|>
def close_session(self):
"""close the se... | stack_v2_sparse_classes_36k_train_023180 | 5,766 | no_license | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self, max_repeat=3, sleep_time=0)"
},
{
"docstring": "initial self._session based on loop",
"name": "init_session",
"signature": "def init_session(self, loop)"
},
{
"docstring": "close the session object... | 4 | null | Implement the Python class `FetcherAsync` described below.
Class description:
class of FetcherAsync
Method signatures and docstrings:
- def __init__(self, max_repeat=3, sleep_time=0): constructor
- def init_session(self, loop): initial self._session based on loop
- def close_session(self): close the session object of... | Implement the Python class `FetcherAsync` described below.
Class description:
class of FetcherAsync
Method signatures and docstrings:
- def __init__(self, max_repeat=3, sleep_time=0): constructor
- def init_session(self, loop): initial self._session based on loop
- def close_session(self): close the session object of... | d494b3041069d377d6a7a9c296a14334f2fa5acc | <|skeleton|>
class FetcherAsync:
"""class of FetcherAsync"""
def __init__(self, max_repeat=3, sleep_time=0):
"""constructor"""
<|body_0|>
def init_session(self, loop):
"""initial self._session based on loop"""
<|body_1|>
def close_session(self):
"""close the se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FetcherAsync:
"""class of FetcherAsync"""
def __init__(self, max_repeat=3, sleep_time=0):
"""constructor"""
self._max_repeat = max_repeat
self._sleep_time = sleep_time
self._session = None
return
def init_session(self, loop):
"""initial self._session b... | the_stack_v2_python_sparse | python/xianhu_PSpider/PSpider-master/spider/concurrent/concur_async_insts.py | LiuFang816/SALSTM_py_data | train | 10 |
09b2ef93e69f5b221452a362485eb126231eb96e | [
"if length is None:\n length = config_services.get('security', 'general', 'rsa_default_key_length')\nkey = rsa.generate_private_key(public_exponent=65537, key_size=length, backend=default_backend())\nprivate = key.private_bytes(encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOp... | <|body_start_0|>
if length is None:
length = config_services.get('security', 'general', 'rsa_default_key_length')
key = rsa.generate_private_key(public_exponent=65537, key_size=length, backend=default_backend())
private = key.private_bytes(encoding=serialization.Encoding.PEM, format=... | security utils manager class. | SecurityUtilsManager | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SecurityUtilsManager:
"""security utils manager class."""
def generate_rsa_key(self, length=None, **options):
"""generates a pair of public/private rsa keys. :param int length: key length in bits. if not provided, `rsa_default_key_length` config will be used. :returns: tuple[str publ... | stack_v2_sparse_classes_36k_train_023181 | 4,563 | permissive | [
{
"docstring": "generates a pair of public/private rsa keys. :param int length: key length in bits. if not provided, `rsa_default_key_length` config will be used. :returns: tuple[str public_key, str private_key] :rtype: tuple[str, str]",
"name": "generate_rsa_key",
"signature": "def generate_rsa_key(sel... | 5 | null | Implement the Python class `SecurityUtilsManager` described below.
Class description:
security utils manager class.
Method signatures and docstrings:
- def generate_rsa_key(self, length=None, **options): generates a pair of public/private rsa keys. :param int length: key length in bits. if not provided, `rsa_default_... | Implement the Python class `SecurityUtilsManager` described below.
Class description:
security utils manager class.
Method signatures and docstrings:
- def generate_rsa_key(self, length=None, **options): generates a pair of public/private rsa keys. :param int length: key length in bits. if not provided, `rsa_default_... | 9d4776498225de4f3d16a4600b5b19212abe8562 | <|skeleton|>
class SecurityUtilsManager:
"""security utils manager class."""
def generate_rsa_key(self, length=None, **options):
"""generates a pair of public/private rsa keys. :param int length: key length in bits. if not provided, `rsa_default_key_length` config will be used. :returns: tuple[str publ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SecurityUtilsManager:
"""security utils manager class."""
def generate_rsa_key(self, length=None, **options):
"""generates a pair of public/private rsa keys. :param int length: key length in bits. if not provided, `rsa_default_key_length` config will be used. :returns: tuple[str public_key, str p... | the_stack_v2_python_sparse | src/pyrin/security/utils/manager.py | mononobi/pyrin | train | 20 |
818de292b96c398eb5fef5bd3d58cc38c66f02f9 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn IosMobileAppConfiguration()",
"from .app_configuration_setting_item import AppConfigurationSettingItem\nfrom .managed_device_mobile_app_configuration import ManagedDeviceMobileAppConfiguration\nfrom .app_configuration_setting_item impo... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return IosMobileAppConfiguration()
<|end_body_0|>
<|body_start_1|>
from .app_configuration_setting_item import AppConfigurationSettingItem
from .managed_device_mobile_app_configuration import M... | Contains properties, inherited properties and actions for iOS mobile app configurations. | IosMobileAppConfiguration | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IosMobileAppConfiguration:
"""Contains properties, inherited properties and actions for iOS mobile app configurations."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosMobileAppConfiguration:
"""Creates a new instance of the appropriate class based o... | stack_v2_sparse_classes_36k_train_023182 | 3,027 | 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: IosMobileAppConfiguration",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrim... | 3 | null | Implement the Python class `IosMobileAppConfiguration` described below.
Class description:
Contains properties, inherited properties and actions for iOS mobile app configurations.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosMobileAppConfiguration... | Implement the Python class `IosMobileAppConfiguration` described below.
Class description:
Contains properties, inherited properties and actions for iOS mobile app configurations.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosMobileAppConfiguration... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class IosMobileAppConfiguration:
"""Contains properties, inherited properties and actions for iOS mobile app configurations."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosMobileAppConfiguration:
"""Creates a new instance of the appropriate class based o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IosMobileAppConfiguration:
"""Contains properties, inherited properties and actions for iOS mobile app configurations."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosMobileAppConfiguration:
"""Creates a new instance of the appropriate class based on discriminat... | the_stack_v2_python_sparse | msgraph/generated/models/ios_mobile_app_configuration.py | microsoftgraph/msgraph-sdk-python | train | 135 |
bfe842722dd7a3de77080ef6d8b16f18ddd28507 | [
"if not request.is_json:\n parser = reqparse.RequestParser()\n parser.add_argument(constants.COORD_PID_KEY, type=str, help='Coordinator PID')\n parser.add_argument(constants.COORD_IP_KEY, type=str, help='Coordinator IP')\n parser.add_argument(constants.MEMBERS_KEY, type=list, help='List of tuples (proce... | <|body_start_0|>
if not request.is_json:
parser = reqparse.RequestParser()
parser.add_argument(constants.COORD_PID_KEY, type=str, help='Coordinator PID')
parser.add_argument(constants.COORD_IP_KEY, type=str, help='Coordinator IP')
parser.add_argument(constants.MEM... | Message handler for operations particular to a specific process and a specific group: group membership update, commit, and abort | GroupMembershipRes | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupMembershipRes:
"""Message handler for operations particular to a specific process and a specific group: group membership update, commit, and abort"""
def put(self, process_id=None, group_id=None):
"""Handler that listens for group membership updates, which inform of group state ... | stack_v2_sparse_classes_36k_train_023183 | 8,983 | no_license | [
{
"docstring": "Handler that listens for group membership updates, which inform of group state changes such as process joining, or leaving A group is represented by a dict with 3 entries: - constants.COORD_PID_KEY, which has the coordinator's process id - constants.COORD_IP_KEY, which has the coordinator's IP -... | 2 | stack_v2_sparse_classes_30k_train_010843 | Implement the Python class `GroupMembershipRes` described below.
Class description:
Message handler for operations particular to a specific process and a specific group: group membership update, commit, and abort
Method signatures and docstrings:
- def put(self, process_id=None, group_id=None): Handler that listens f... | Implement the Python class `GroupMembershipRes` described below.
Class description:
Message handler for operations particular to a specific process and a specific group: group membership update, commit, and abort
Method signatures and docstrings:
- def put(self, process_id=None, group_id=None): Handler that listens f... | 45df130f30bcf106d863efe800ab22a5ef56cbea | <|skeleton|>
class GroupMembershipRes:
"""Message handler for operations particular to a specific process and a specific group: group membership update, commit, and abort"""
def put(self, process_id=None, group_id=None):
"""Handler that listens for group membership updates, which inform of group state ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GroupMembershipRes:
"""Message handler for operations particular to a specific process and a specific group: group membership update, commit, and abort"""
def put(self, process_id=None, group_id=None):
"""Handler that listens for group membership updates, which inform of group state changes such ... | the_stack_v2_python_sparse | src/client_comms_rx.py | lavelle96/group-management-system | train | 0 |
45a198a120472b8c3f4dcf75dd05c0e2d50a3b67 | [
"self.sessionsByKey = {}\nfor session in sessions:\n key = session.getKey()\n if not key in self.sessionsByKey:\n self.sessionsByKey[key] = [session]\n else:\n self.sessionsByKey[key].append(session)",
"succeeded, failed = (0, 0)\ntaskDurations = []\nsessionDurations = []\nlastSession = Non... | <|body_start_0|>
self.sessionsByKey = {}
for session in sessions:
key = session.getKey()
if not key in self.sessionsByKey:
self.sessionsByKey[key] = [session]
else:
self.sessionsByKey[key].append(session)
<|end_body_0|>
<|body_start_1|... | provides functionality to print summary and detailed statistic | Statistic | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Statistic:
"""provides functionality to print summary and detailed statistic"""
def __init__(self, sessions):
"""stores sessions by session key"""
<|body_0|>
def printSummary(self):
"""independent of type of session or task you get an overview"""
<|body_1... | stack_v2_sparse_classes_36k_train_023184 | 19,342 | permissive | [
{
"docstring": "stores sessions by session key",
"name": "__init__",
"signature": "def __init__(self, sessions)"
},
{
"docstring": "independent of type of session or task you get an overview",
"name": "printSummary",
"signature": "def printSummary(self)"
},
{
"docstring": "prints... | 3 | null | Implement the Python class `Statistic` described below.
Class description:
provides functionality to print summary and detailed statistic
Method signatures and docstrings:
- def __init__(self, sessions): stores sessions by session key
- def printSummary(self): independent of type of session or task you get an overvie... | Implement the Python class `Statistic` described below.
Class description:
provides functionality to print summary and detailed statistic
Method signatures and docstrings:
- def __init__(self, sessions): stores sessions by session key
- def printSummary(self): independent of type of session or task you get an overvie... | d097ca0ad6a6aee2180d32dce6a3322621f655fd | <|skeleton|>
class Statistic:
"""provides functionality to print summary and detailed statistic"""
def __init__(self, sessions):
"""stores sessions by session key"""
<|body_0|>
def printSummary(self):
"""independent of type of session or task you get an overview"""
<|body_1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Statistic:
"""provides functionality to print summary and detailed statistic"""
def __init__(self, sessions):
"""stores sessions by session key"""
self.sessionsByKey = {}
for session in sessions:
key = session.getKey()
if not key in self.sessionsByKey:
... | the_stack_v2_python_sparse | recipes/Python/578111_Learning_calculate_mental/recipe-578111.py | betty29/code-1 | train | 0 |
2f27f180076d85ede96ce548b4fe470e54cce54b | [
"pattern = 'data:(?P<mime>[\\\\w/]+);(?P<encoding>\\\\w+),(?P<data>.*)'\nm = re.search(pattern, data_uri)\nreturn (m.group('mime'), m.group('encoding'), m.group('data'))",
"def file_size(f):\n f.seek(0, os.SEEK_END)\n return f.tell()\nfile_uri = bundle.data.get(file_field, None)\nif file_uri:\n content_t... | <|body_start_0|>
pattern = 'data:(?P<mime>[\\w/]+);(?P<encoding>\\w+),(?P<data>.*)'
m = re.search(pattern, data_uri)
return (m.group('mime'), m.group('encoding'), m.group('data'))
<|end_body_0|>
<|body_start_1|>
def file_size(f):
f.seek(0, os.SEEK_END)
return f.t... | DataUriResourceMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataUriResourceMixin:
def parse_data_uri(self, data_uri):
"""Parse a data URI string Returns a tuple of (mime_type, encoding, data) represented in the URI See http://tools.ietf.org/html/rfc2397"""
<|body_0|>
def _hydrate_file(self, bundle, file_model_class, file_field, filen... | stack_v2_sparse_classes_36k_train_023185 | 22,939 | permissive | [
{
"docstring": "Parse a data URI string Returns a tuple of (mime_type, encoding, data) represented in the URI See http://tools.ietf.org/html/rfc2397",
"name": "parse_data_uri",
"signature": "def parse_data_uri(self, data_uri)"
},
{
"docstring": "Decode the base-64 encoded file",
"name": "_hy... | 2 | null | Implement the Python class `DataUriResourceMixin` described below.
Class description:
Implement the DataUriResourceMixin class.
Method signatures and docstrings:
- def parse_data_uri(self, data_uri): Parse a data URI string Returns a tuple of (mime_type, encoding, data) represented in the URI See http://tools.ietf.or... | Implement the Python class `DataUriResourceMixin` described below.
Class description:
Implement the DataUriResourceMixin class.
Method signatures and docstrings:
- def parse_data_uri(self, data_uri): Parse a data URI string Returns a tuple of (mime_type, encoding, data) represented in the URI See http://tools.ietf.or... | 15e429df850b68ee107a9b8206adc44fe1174370 | <|skeleton|>
class DataUriResourceMixin:
def parse_data_uri(self, data_uri):
"""Parse a data URI string Returns a tuple of (mime_type, encoding, data) represented in the URI See http://tools.ietf.org/html/rfc2397"""
<|body_0|>
def _hydrate_file(self, bundle, file_model_class, file_field, filen... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataUriResourceMixin:
def parse_data_uri(self, data_uri):
"""Parse a data URI string Returns a tuple of (mime_type, encoding, data) represented in the URI See http://tools.ietf.org/html/rfc2397"""
pattern = 'data:(?P<mime>[\\w/]+);(?P<encoding>\\w+),(?P<data>.*)'
m = re.search(pattern,... | the_stack_v2_python_sparse | apps/storybase/api/resources.py | denverfoundation/storybase | train | 3 | |
a976eafa980de63ac1e621c760c317abf49cff5f | [
"if isinstance(key, int):\n return TransType(key)\nif key not in TransType._member_map_:\n extend_enum(TransType, key, default)\nreturn TransType[key]",
"if not (isinstance(value, int) and 0 <= value <= 255):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nif 143 <= value <= 252:\n ... | <|body_start_0|>
if isinstance(key, int):
return TransType(key)
if key not in TransType._member_map_:
extend_enum(TransType, key, default)
return TransType[key]
<|end_body_0|>
<|body_start_1|>
if not (isinstance(value, int) and 0 <= value <= 255):
rai... | Enumeration class for TransType. | TransType | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransType:
"""Enumeration class for TransType."""
def get(key, default=-1):
"""Backport support for original codes."""
<|body_0|>
def _missing_(cls, value):
"""Lookup function used when value is not found."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_023186 | 20,068 | no_license | [
{
"docstring": "Backport support for original codes.",
"name": "get",
"signature": "def get(key, default=-1)"
},
{
"docstring": "Lookup function used when value is not found.",
"name": "_missing_",
"signature": "def _missing_(cls, value)"
}
] | 2 | null | Implement the Python class `TransType` described below.
Class description:
Enumeration class for TransType.
Method signatures and docstrings:
- def get(key, default=-1): Backport support for original codes.
- def _missing_(cls, value): Lookup function used when value is not found. | Implement the Python class `TransType` described below.
Class description:
Enumeration class for TransType.
Method signatures and docstrings:
- def get(key, default=-1): Backport support for original codes.
- def _missing_(cls, value): Lookup function used when value is not found.
<|skeleton|>
class TransType:
"... | fd43ccca1d032f8f230c4467dcb5df757669ef13 | <|skeleton|>
class TransType:
"""Enumeration class for TransType."""
def get(key, default=-1):
"""Backport support for original codes."""
<|body_0|>
def _missing_(cls, value):
"""Lookup function used when value is not found."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransType:
"""Enumeration class for TransType."""
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return TransType(key)
if key not in TransType._member_map_:
extend_enum(TransType, key, default)
return T... | the_stack_v2_python_sparse | venv/lib/python3.6/site-packages/pcapkit/const/misc/transtype.py | IvanLetteri/MLfeaturesExtractor | train | 0 |
aa880751c64ad6161f08f7a9b461cd8ed30f9a25 | [
"self.is_installed = is_installed\nself.reboot_status = reboot_status\nself.service_state = service_state",
"if dictionary is None:\n return None\nis_installed = dictionary.get('isInstalled')\nreboot_status = dictionary.get('rebootStatus')\nservice_state = dictionary.get('serviceState')\nreturn cls(is_installe... | <|body_start_0|>
self.is_installed = is_installed
self.reboot_status = reboot_status
self.service_state = service_state
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
is_installed = dictionary.get('isInstalled')
reboot_status = dictionary.... | Implementation of the 'CbtInfo' model. Specifies information about the Cbt Driver associated with agent. Attributes: is_installed (bool): Specifies whether the cbt driver is installed or not. reboot_status (RebootStatusEnum): Specifies the reboot status of the host post cbt driver installation. Only applicable for volc... | CbtInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CbtInfo:
"""Implementation of the 'CbtInfo' model. Specifies information about the Cbt Driver associated with agent. Attributes: is_installed (bool): Specifies whether the cbt driver is installed or not. reboot_status (RebootStatusEnum): Specifies the reboot status of the host post cbt driver ins... | stack_v2_sparse_classes_36k_train_023187 | 2,799 | permissive | [
{
"docstring": "Constructor for the CbtInfo class",
"name": "__init__",
"signature": "def __init__(self, is_installed=None, reboot_status=None, service_state=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation o... | 2 | stack_v2_sparse_classes_30k_train_007555 | Implement the Python class `CbtInfo` described below.
Class description:
Implementation of the 'CbtInfo' model. Specifies information about the Cbt Driver associated with agent. Attributes: is_installed (bool): Specifies whether the cbt driver is installed or not. reboot_status (RebootStatusEnum): Specifies the reboot... | Implement the Python class `CbtInfo` described below.
Class description:
Implementation of the 'CbtInfo' model. Specifies information about the Cbt Driver associated with agent. Attributes: is_installed (bool): Specifies whether the cbt driver is installed or not. reboot_status (RebootStatusEnum): Specifies the reboot... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class CbtInfo:
"""Implementation of the 'CbtInfo' model. Specifies information about the Cbt Driver associated with agent. Attributes: is_installed (bool): Specifies whether the cbt driver is installed or not. reboot_status (RebootStatusEnum): Specifies the reboot status of the host post cbt driver ins... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CbtInfo:
"""Implementation of the 'CbtInfo' model. Specifies information about the Cbt Driver associated with agent. Attributes: is_installed (bool): Specifies whether the cbt driver is installed or not. reboot_status (RebootStatusEnum): Specifies the reboot status of the host post cbt driver installation. On... | the_stack_v2_python_sparse | cohesity_management_sdk/models/cbt_info.py | cohesity/management-sdk-python | train | 24 |
a6bae47c9c4a941bbf4612836085308b298e6ee1 | [
"if os.path.exists(settings.GOVERNOR_INTERFACE):\n interface = settings.GOVERNOR_INTERFACE\n path = '/snapd/' + '/'.join(request.postpath)\nelse:\n interface = settings.SNAPD_INTERFACE\n path = '/' + '/'.join(request.postpath)\nbody = None\nheaders = {}\nctype = request.requestHeaders.getRawHeaders('Con... | <|body_start_0|>
if os.path.exists(settings.GOVERNOR_INTERFACE):
interface = settings.GOVERNOR_INTERFACE
path = '/snapd/' + '/'.join(request.postpath)
else:
interface = settings.SNAPD_INTERFACE
path = '/' + '/'.join(request.postpath)
body = None
... | Expose the snapd API by forwarding requests. Changed in 0.13: we try to send the request through the governor service so that paradrop can be installed in strict mode. https://github.com/snapcore/snapd/wiki/REST-API | SnapdResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnapdResource:
"""Expose the snapd API by forwarding requests. Changed in 0.13: we try to send the request through the governor service so that paradrop can be installed in strict mode. https://github.com/snapcore/snapd/wiki/REST-API"""
def do_snapd_request(self, request):
"""Forward... | stack_v2_sparse_classes_36k_train_023188 | 2,158 | permissive | [
{
"docstring": "Forward the API request to snapd.",
"name": "do_snapd_request",
"signature": "def do_snapd_request(self, request)"
},
{
"docstring": "Fulfill requests by forwarding them to snapd. We use a synchronous implementation of HTTP over Unix sockets, so we do the request in a worker thre... | 2 | stack_v2_sparse_classes_30k_train_016341 | Implement the Python class `SnapdResource` described below.
Class description:
Expose the snapd API by forwarding requests. Changed in 0.13: we try to send the request through the governor service so that paradrop can be installed in strict mode. https://github.com/snapcore/snapd/wiki/REST-API
Method signatures and d... | Implement the Python class `SnapdResource` described below.
Class description:
Expose the snapd API by forwarding requests. Changed in 0.13: we try to send the request through the governor service so that paradrop can be installed in strict mode. https://github.com/snapcore/snapd/wiki/REST-API
Method signatures and d... | c910fd5ac1d1b5e234f40f9f5592cc981e9bb5db | <|skeleton|>
class SnapdResource:
"""Expose the snapd API by forwarding requests. Changed in 0.13: we try to send the request through the governor service so that paradrop can be installed in strict mode. https://github.com/snapcore/snapd/wiki/REST-API"""
def do_snapd_request(self, request):
"""Forward... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SnapdResource:
"""Expose the snapd API by forwarding requests. Changed in 0.13: we try to send the request through the governor service so that paradrop can be installed in strict mode. https://github.com/snapcore/snapd/wiki/REST-API"""
def do_snapd_request(self, request):
"""Forward the API requ... | the_stack_v2_python_sparse | paradrop/daemon/paradrop/backend/snapd_resource.py | ParadropLabs/Paradrop | train | 88 |
98a2a76de4a904eb87205ca6e87511f9213b88c4 | [
"result = []\nnodes = collections.deque([root]) if root else None\nwhile nodes:\n node = nodes.popleft()\n result.append(getattr(node, 'val', 'null'))\n if node:\n for child in (node.left, node.right):\n nodes.append(child)\nwhile result and (not result[-1]):\n result.pop()\nreturn res... | <|body_start_0|>
result = []
nodes = collections.deque([root]) if root else None
while nodes:
node = nodes.popleft()
result.append(getattr(node, 'val', 'null'))
if node:
for child in (node.left, node.right):
nodes.append(chi... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_023189 | 1,387 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | c27f19fac14b4acef8c631ad5569e1a5c29e9e1f | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
result = []
nodes = collections.deque([root]) if root else None
while nodes:
node = nodes.popleft()
result.append(getattr(node, 'val', 'null'))
... | the_stack_v2_python_sparse | leetcode/p0297 - Serialize and Deserialize Binary Tree.py | liseyko/CtCI | train | 0 | |
2ca63ecbb53378397a91ae97e669f638326c1f8c | [
"python = sys.executable\nif sys.platform == 'win32':\n python = '\"' + python + '\"'\nelse:\n python = shlex.quote(python)\nself.shell.system(' '.join([python, '-m', 'pip', line]))\nprint('Note: you may need to restart the kernel to use updated packages.')",
"if not _is_conda_environment():\n raise Valu... | <|body_start_0|>
python = sys.executable
if sys.platform == 'win32':
python = '"' + python + '"'
else:
python = shlex.quote(python)
self.shell.system(' '.join([python, '-m', 'pip', line]))
print('Note: you may need to restart the kernel to use updated pack... | Magics related to packaging & installation | PackagingMagics | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PackagingMagics:
"""Magics related to packaging & installation"""
def pip(self, line):
"""Run the pip package manager within the current kernel. Usage: %pip install [pkgs]"""
<|body_0|>
def conda(self, line):
"""Run the conda package manager within the current ke... | stack_v2_sparse_classes_36k_train_023190 | 3,916 | permissive | [
{
"docstring": "Run the pip package manager within the current kernel. Usage: %pip install [pkgs]",
"name": "pip",
"signature": "def pip(self, line)"
},
{
"docstring": "Run the conda package manager within the current kernel. Usage: %conda install [pkgs]",
"name": "conda",
"signature": "... | 2 | null | Implement the Python class `PackagingMagics` described below.
Class description:
Magics related to packaging & installation
Method signatures and docstrings:
- def pip(self, line): Run the pip package manager within the current kernel. Usage: %pip install [pkgs]
- def conda(self, line): Run the conda package manager ... | Implement the Python class `PackagingMagics` described below.
Class description:
Magics related to packaging & installation
Method signatures and docstrings:
- def pip(self, line): Run the pip package manager within the current kernel. Usage: %pip install [pkgs]
- def conda(self, line): Run the conda package manager ... | e5103f971233fd66b558585cce7a4f52a716cd56 | <|skeleton|>
class PackagingMagics:
"""Magics related to packaging & installation"""
def pip(self, line):
"""Run the pip package manager within the current kernel. Usage: %pip install [pkgs]"""
<|body_0|>
def conda(self, line):
"""Run the conda package manager within the current ke... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PackagingMagics:
"""Magics related to packaging & installation"""
def pip(self, line):
"""Run the pip package manager within the current kernel. Usage: %pip install [pkgs]"""
python = sys.executable
if sys.platform == 'win32':
python = '"' + python + '"'
else:
... | the_stack_v2_python_sparse | IPython/core/magics/packaging.py | ipython/ipython | train | 13,673 |
66cf999653b1083b98ff7497b4755e49fbd78b9a | [
"print('Loading pipeline...')\nsafety_checker = StableDiffusionSafetyChecker.from_pretrained(SAFETY_MODEL_ID, cache_dir=MODEL_CACHE, local_files_only=True)\nself.pipe = StableDiffusionPipeline.from_pretrained(MODEL_ID, safety_checker=safety_checker, cache_dir=MODEL_CACHE, local_files_only=True).to('cuda')\nself.pip... | <|body_start_0|>
print('Loading pipeline...')
safety_checker = StableDiffusionSafetyChecker.from_pretrained(SAFETY_MODEL_ID, cache_dir=MODEL_CACHE, local_files_only=True)
self.pipe = StableDiffusionPipeline.from_pretrained(MODEL_ID, safety_checker=safety_checker, cache_dir=MODEL_CACHE, local_fil... | Predictor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Predictor:
def setup(self):
"""Load the model into memory to make running multiple predictions efficient"""
<|body_0|>
def predict(self, prompt: str=Input(description='Input prompt', default='a photo of an astronaut riding a horse on mars'), negative_prompt: str=Input(descri... | stack_v2_sparse_classes_36k_train_023191 | 5,108 | permissive | [
{
"docstring": "Load the model into memory to make running multiple predictions efficient",
"name": "setup",
"signature": "def setup(self)"
},
{
"docstring": "Run a single prediction on the model",
"name": "predict",
"signature": "def predict(self, prompt: str=Input(description='Input pr... | 2 | stack_v2_sparse_classes_30k_train_009772 | Implement the Python class `Predictor` described below.
Class description:
Implement the Predictor class.
Method signatures and docstrings:
- def setup(self): Load the model into memory to make running multiple predictions efficient
- def predict(self, prompt: str=Input(description='Input prompt', default='a photo of... | Implement the Python class `Predictor` described below.
Class description:
Implement the Predictor class.
Method signatures and docstrings:
- def setup(self): Load the model into memory to make running multiple predictions efficient
- def predict(self, prompt: str=Input(description='Input prompt', default='a photo of... | 414a26603db4b80020a966c564d2ab124dd22f7c | <|skeleton|>
class Predictor:
def setup(self):
"""Load the model into memory to make running multiple predictions efficient"""
<|body_0|>
def predict(self, prompt: str=Input(description='Input prompt', default='a photo of an astronaut riding a horse on mars'), negative_prompt: str=Input(descri... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Predictor:
def setup(self):
"""Load the model into memory to make running multiple predictions efficient"""
print('Loading pipeline...')
safety_checker = StableDiffusionSafetyChecker.from_pretrained(SAFETY_MODEL_ID, cache_dir=MODEL_CACHE, local_files_only=True)
self.pipe = Stab... | the_stack_v2_python_sparse | workers/StableDiffusion-v2/cog_example/predict.py | runpod/serverless-workers | train | 43 | |
afa538276d631350fdd1cdb3382b31c4ca426b2b | [
"assert field in formset.form.base_fields\nqs = formset.form.base_fields[field].queryset\nif empty:\n formset.form.base_fields[field].queryset = qs.none()\nelse:\n qs = qs.filter(**filters)\n formset.form.base_fields[field].queryset = qs",
"formset = super(LimitedAdminInlineMixin, self).get_formset(reque... | <|body_start_0|>
assert field in formset.form.base_fields
qs = formset.form.base_fields[field].queryset
if empty:
formset.form.base_fields[field].queryset = qs.none()
else:
qs = qs.filter(**filters)
formset.form.base_fields[field].queryset = qs
<|end_b... | InlineAdmin mixin limiting the selection of related items according to criteria which can depend on the current parent object being edited. A typical use case would be selecting a subset of related items from other inlines, ie. images, to have some relation to other inlines. Use as follows:: class MyInline(LimitedAdmin... | LimitedAdminInlineMixin | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LimitedAdminInlineMixin:
"""InlineAdmin mixin limiting the selection of related items according to criteria which can depend on the current parent object being edited. A typical use case would be selecting a subset of related items from other inlines, ie. images, to have some relation to other in... | stack_v2_sparse_classes_36k_train_023192 | 2,152 | permissive | [
{
"docstring": "This function fetches the queryset with available choices for a given `field` and filters it based on the criteria specified in filters, unless `empty=True`. In this case, no choices will be made available.",
"name": "limit_inline_choices",
"signature": "def limit_inline_choices(formset,... | 2 | null | Implement the Python class `LimitedAdminInlineMixin` described below.
Class description:
InlineAdmin mixin limiting the selection of related items according to criteria which can depend on the current parent object being edited. A typical use case would be selecting a subset of related items from other inlines, ie. im... | Implement the Python class `LimitedAdminInlineMixin` described below.
Class description:
InlineAdmin mixin limiting the selection of related items according to criteria which can depend on the current parent object being edited. A typical use case would be selecting a subset of related items from other inlines, ie. im... | 6d0230a0f192bb7126c42db59ecfc4369a765a7a | <|skeleton|>
class LimitedAdminInlineMixin:
"""InlineAdmin mixin limiting the selection of related items according to criteria which can depend on the current parent object being edited. A typical use case would be selecting a subset of related items from other inlines, ie. images, to have some relation to other in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LimitedAdminInlineMixin:
"""InlineAdmin mixin limiting the selection of related items according to criteria which can depend on the current parent object being edited. A typical use case would be selecting a subset of related items from other inlines, ie. images, to have some relation to other inlines. Use as... | the_stack_v2_python_sparse | koalixcrm/crm/inlinemixin.py | Shikhar10000/koalixcrm | train | 1 |
2ab23337e0bb25280feb3b12f9db6b615aee0307 | [
"vals = []\n\ndef doit(root):\n if root is not None:\n vals.append(str(root.val))\n doit(root.left)\n doit(root.right)\n else:\n vals.append('#')\ndoit(root)\nreturn ' '.join(vals)",
"vals = data.split(' ')\n\ndef doit(ind):\n if vals[ind[0]] != '#':\n root = TreeNode(v... | <|body_start_0|>
vals = []
def doit(root):
if root is not None:
vals.append(str(root.val))
doit(root.left)
doit(root.right)
else:
vals.append('#')
doit(root)
return ' '.join(vals)
<|end_body_0|>
<|b... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_023193 | 1,420 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_004167 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | bedaf22edf8d239298593d3bcbffaa19e72c58cb | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
vals = []
def doit(root):
if root is not None:
vals.append(str(root.val))
doit(root.left)
doit(root.right)
... | the_stack_v2_python_sparse | Serialize and Deserialize Binary Tree.py | AVenkat4/LeetCode-Problems-Solutions | train | 0 | |
be03a8751b9802d45a18cf9ec1f9c1a52dab242e | [
"rcounter = 0\nlcounter = len(str) - 1\nself.reverseString(str, rcounter, lcounter)\nfor i in range(len(str)):\n if str[i] == ' ':\n self.reverseString(str, rcounter, i - 1)\n rcounter = i + 1\n elif i == len(str) - 1:\n self.reverseString(str, rcounter, i)\nprint(str)",
"while rcounter... | <|body_start_0|>
rcounter = 0
lcounter = len(str) - 1
self.reverseString(str, rcounter, lcounter)
for i in range(len(str)):
if str[i] == ' ':
self.reverseString(str, rcounter, i - 1)
rcounter = i + 1
elif i == len(str) - 1:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseWords(self, str):
""":type str: List[str] :rtype: None Do not return anything, modify str in-place instead."""
<|body_0|>
def reverseString(self, s, rcounter, lcounter):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_023194 | 1,633 | no_license | [
{
"docstring": ":type str: List[str] :rtype: None Do not return anything, modify str in-place instead.",
"name": "reverseWords",
"signature": "def reverseWords(self, str)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "reverseString",
"signature": "def reverseString(self, s, rcou... | 2 | stack_v2_sparse_classes_30k_train_002560 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseWords(self, str): :type str: List[str] :rtype: None Do not return anything, modify str in-place instead.
- def reverseString(self, s, rcounter, lcounter): :type s: str... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseWords(self, str): :type str: List[str] :rtype: None Do not return anything, modify str in-place instead.
- def reverseString(self, s, rcounter, lcounter): :type s: str... | 786075e0f9f61cf062703bc0b41cc3191d77f033 | <|skeleton|>
class Solution:
def reverseWords(self, str):
""":type str: List[str] :rtype: None Do not return anything, modify str in-place instead."""
<|body_0|>
def reverseString(self, s, rcounter, lcounter):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseWords(self, str):
""":type str: List[str] :rtype: None Do not return anything, modify str in-place instead."""
rcounter = 0
lcounter = len(str) - 1
self.reverseString(str, rcounter, lcounter)
for i in range(len(str)):
if str[i] == ' ':
... | the_stack_v2_python_sparse | reverseWords2.py | Anirban2404/LeetCodePractice | train | 1 | |
5651499124c41a07112ab3ae02d71076204266eb | [
"arr = list(s)\nself.reverse_string(arr, 0, len(arr) - 1)\nself.reverse_word(arr)\nword = self.trim_sides(arr)\nres = self.trim_space(word)\nreturn ''.join(res)",
"while l < r:\n arr[l], arr[r] = (arr[r], arr[l])\n l += 1\n r -= 1\nreturn arr",
"l, r = (0, 0)\nwhile r < len(arr):\n while r < len(arr... | <|body_start_0|>
arr = list(s)
self.reverse_string(arr, 0, len(arr) - 1)
self.reverse_word(arr)
word = self.trim_sides(arr)
res = self.trim_space(word)
return ''.join(res)
<|end_body_0|>
<|body_start_1|>
while l < r:
arr[l], arr[r] = (arr[r], arr[l])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseWords(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def reverse_string(self, arr, l, r):
"""reverse a given string"""
<|body_1|>
def reverse_word(self, arr):
"""reverse every words in a string"""
<|body_2|>
... | stack_v2_sparse_classes_36k_train_023195 | 2,029 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "reverseWords",
"signature": "def reverseWords(self, s)"
},
{
"docstring": "reverse a given string",
"name": "reverse_string",
"signature": "def reverse_string(self, arr, l, r)"
},
{
"docstring": "reverse every words in a string"... | 5 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseWords(self, s): :type s: str :rtype: str
- def reverse_string(self, arr, l, r): reverse a given string
- def reverse_word(self, arr): reverse every words in a string
-... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseWords(self, s): :type s: str :rtype: str
- def reverse_string(self, arr, l, r): reverse a given string
- def reverse_word(self, arr): reverse every words in a string
-... | db2cd34ee759721858a96d123e3cab4084e69129 | <|skeleton|>
class Solution:
def reverseWords(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def reverse_string(self, arr, l, r):
"""reverse a given string"""
<|body_1|>
def reverse_word(self, arr):
"""reverse every words in a string"""
<|body_2|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseWords(self, s):
""":type s: str :rtype: str"""
arr = list(s)
self.reverse_string(arr, 0, len(arr) - 1)
self.reverse_word(arr)
word = self.trim_sides(arr)
res = self.trim_space(word)
return ''.join(res)
def reverse_string(self, a... | the_stack_v2_python_sparse | Algorithm-Medium/151_Reverse_Words_in_a_String.py | yz5308/Python_Leetcode | train | 0 | |
188e7030e26a9691e304946f3b4405638dc5197e | [
"d = defaultdict(int)\nfor bill in bills:\n val = bill - 5\n if val == 0:\n d[bill] += 1\n elif val == 5:\n d[bill] += 1\n d[5] -= 1\n if d[5] < 0:\n return False\n elif d[10] > 0:\n if d[5] < 1:\n return False\n d[10] -= 1\n d[5] -=... | <|body_start_0|>
d = defaultdict(int)
for bill in bills:
val = bill - 5
if val == 0:
d[bill] += 1
elif val == 5:
d[bill] += 1
d[5] -= 1
if d[5] < 0:
return False
elif d[10]... | 在柠檬水摊上,每一杯柠檬水的售价为 5 美元。 顾客排队购买你的产品,(按账单 bills 支付的顺序)一次购买一杯。 每位顾客只买一杯柠檬水,然后向你付 5 美元、10 美元或 20 美元。你必须给每个顾客正确找零,也就是说净交易是每位顾客向你支付 5 美元。 注意,一开始你手头没有任何零钱。 如果你能给每位顾客正确找零,返回 true ,否则返回 false 。 示例 1: 输入:[5,5,5,10,20] 输出:true 解释: 前 3 位顾客那里,我们按顺序收取 3 张 5 美元的钞票。 第 4 位顾客那里,我们收取一张 10 美元的钞票,并返还 5 美元。 第 5 位顾客那里,我们找还一张 10 美元的钞票和一张 5 美元... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""在柠檬水摊上,每一杯柠檬水的售价为 5 美元。 顾客排队购买你的产品,(按账单 bills 支付的顺序)一次购买一杯。 每位顾客只买一杯柠檬水,然后向你付 5 美元、10 美元或 20 美元。你必须给每个顾客正确找零,也就是说净交易是每位顾客向你支付 5 美元。 注意,一开始你手头没有任何零钱。 如果你能给每位顾客正确找零,返回 true ,否则返回 false 。 示例 1: 输入:[5,5,5,10,20] 输出:true 解释: 前 3 位顾客那里,我们按顺序收取 3 张 5 美元的钞票。 第 4 位顾客那里,我们收取一张 10 美元的钞票,并返还 5 美... | stack_v2_sparse_classes_36k_train_023196 | 4,137 | no_license | [
{
"docstring": ":type bills: List[int] :rtype: bool 暴力破解",
"name": "lemonade_change",
"signature": "def lemonade_change(self, bills)"
},
{
"docstring": ":type bills: List[int] :rtype: bool 改进官方题解答案",
"name": "lemonade_change2",
"signature": "def lemonade_change2(self, bills)"
},
{
... | 3 | null | Implement the Python class `Solution` described below.
Class description:
在柠檬水摊上,每一杯柠檬水的售价为 5 美元。 顾客排队购买你的产品,(按账单 bills 支付的顺序)一次购买一杯。 每位顾客只买一杯柠檬水,然后向你付 5 美元、10 美元或 20 美元。你必须给每个顾客正确找零,也就是说净交易是每位顾客向你支付 5 美元。 注意,一开始你手头没有任何零钱。 如果你能给每位顾客正确找零,返回 true ,否则返回 false 。 示例 1: 输入:[5,5,5,10,20] 输出:true 解释: 前 3 位顾客那里,我们按顺序收取 3 张 5 美... | Implement the Python class `Solution` described below.
Class description:
在柠檬水摊上,每一杯柠檬水的售价为 5 美元。 顾客排队购买你的产品,(按账单 bills 支付的顺序)一次购买一杯。 每位顾客只买一杯柠檬水,然后向你付 5 美元、10 美元或 20 美元。你必须给每个顾客正确找零,也就是说净交易是每位顾客向你支付 5 美元。 注意,一开始你手头没有任何零钱。 如果你能给每位顾客正确找零,返回 true ,否则返回 false 。 示例 1: 输入:[5,5,5,10,20] 输出:true 解释: 前 3 位顾客那里,我们按顺序收取 3 张 5 美... | 2c534185854c1a6f5ffdb2698f9db9989f30a25b | <|skeleton|>
class Solution:
"""在柠檬水摊上,每一杯柠檬水的售价为 5 美元。 顾客排队购买你的产品,(按账单 bills 支付的顺序)一次购买一杯。 每位顾客只买一杯柠檬水,然后向你付 5 美元、10 美元或 20 美元。你必须给每个顾客正确找零,也就是说净交易是每位顾客向你支付 5 美元。 注意,一开始你手头没有任何零钱。 如果你能给每位顾客正确找零,返回 true ,否则返回 false 。 示例 1: 输入:[5,5,5,10,20] 输出:true 解释: 前 3 位顾客那里,我们按顺序收取 3 张 5 美元的钞票。 第 4 位顾客那里,我们收取一张 10 美元的钞票,并返还 5 美... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""在柠檬水摊上,每一杯柠檬水的售价为 5 美元。 顾客排队购买你的产品,(按账单 bills 支付的顺序)一次购买一杯。 每位顾客只买一杯柠檬水,然后向你付 5 美元、10 美元或 20 美元。你必须给每个顾客正确找零,也就是说净交易是每位顾客向你支付 5 美元。 注意,一开始你手头没有任何零钱。 如果你能给每位顾客正确找零,返回 true ,否则返回 false 。 示例 1: 输入:[5,5,5,10,20] 输出:true 解释: 前 3 位顾客那里,我们按顺序收取 3 张 5 美元的钞票。 第 4 位顾客那里,我们收取一张 10 美元的钞票,并返还 5 美元。 第 5 位顾客那里,... | the_stack_v2_python_sparse | Week 03/id_668/leetcode_860_668.py | Carryours/algorithm004-03 | train | 2 |
357e1fa24a370ffcf205f182607c445837987422 | [
"i, j = (0, 0)\nwidth, height = (len(matrix[0]), len(matrix))\nwhile i < height and j < width:\n while j + 1 < width and matrix[i][j + 1] <= target:\n j += 1\n width = j + 1\n print(matrix[i][j])\n if matrix[i][j] == target:\n return True\n i += 1\n j = 0\nreturn False",
"i, j = (l... | <|body_start_0|>
i, j = (0, 0)
width, height = (len(matrix[0]), len(matrix))
while i < height and j < width:
while j + 1 < width and matrix[i][j + 1] <= target:
j += 1
width = j + 1
print(matrix[i][j])
if matrix[i][j] == target:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrix1(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k_train_023197 | 1,221 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix",
"signature": "def searchMatrix(self, matrix, target)"
},
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix1",
"signature": "def search... | 2 | stack_v2_sparse_classes_30k_train_012324 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def searchMatrix1(self, matrix, target): :type matrix: List[List[int]] :typ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def searchMatrix1(self, matrix, target): :type matrix: List[List[int]] :typ... | 8e963bbf37f4cc5942d1c7bf2c29d3fe61b655f2 | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrix1(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
i, j = (0, 0)
width, height = (len(matrix[0]), len(matrix))
while i < height and j < width:
while j + 1 < width and matrix[i][j + 1] <= target:
... | the_stack_v2_python_sparse | 240. Search a 2D Matrix II.py | hlcr/Leetcode | train | 0 | |
dac9584ccc71340d96818eb5c8ed3e6b60aa24d4 | [
"if self.immutable:\n return\nself._snapshot = self._copy_container(self.__dict__)",
"self.immutable = True\ntry:\n del self._snapshot\nexcept AttributeError:\n pass",
"new_container = copy.copy(container)\nfor k, v in self.containerItems[type(new_container)](new_container):\n if type(v) in self.con... | <|body_start_0|>
if self.immutable:
return
self._snapshot = self._copy_container(self.__dict__)
<|end_body_0|>
<|body_start_1|>
self.immutable = True
try:
del self._snapshot
except AttributeError:
pass
<|end_body_1|>
<|body_start_2|>
... | ChangeCheckerMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChangeCheckerMixin:
def snapshot(self):
"""create a snapshot of self's state -- like a shallow copy, but recursing over container types (not over general instances: instances must keep track of their own changes if needed)."""
<|body_0|>
def makeImmutable(self):
"""t... | stack_v2_sparse_classes_36k_train_023198 | 2,769 | no_license | [
{
"docstring": "create a snapshot of self's state -- like a shallow copy, but recursing over container types (not over general instances: instances must keep track of their own changes if needed).",
"name": "snapshot",
"signature": "def snapshot(self)"
},
{
"docstring": "the instance state can't... | 6 | null | Implement the Python class `ChangeCheckerMixin` described below.
Class description:
Implement the ChangeCheckerMixin class.
Method signatures and docstrings:
- def snapshot(self): create a snapshot of self's state -- like a shallow copy, but recursing over container types (not over general instances: instances must k... | Implement the Python class `ChangeCheckerMixin` described below.
Class description:
Implement the ChangeCheckerMixin class.
Method signatures and docstrings:
- def snapshot(self): create a snapshot of self's state -- like a shallow copy, but recursing over container types (not over general instances: instances must k... | 42d2ade2d47917ece0759ad83153baba1119cfa1 | <|skeleton|>
class ChangeCheckerMixin:
def snapshot(self):
"""create a snapshot of self's state -- like a shallow copy, but recursing over container types (not over general instances: instances must keep track of their own changes if needed)."""
<|body_0|>
def makeImmutable(self):
"""t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChangeCheckerMixin:
def snapshot(self):
"""create a snapshot of self's state -- like a shallow copy, but recursing over container types (not over general instances: instances must keep track of their own changes if needed)."""
if self.immutable:
return
self._snapshot = self... | the_stack_v2_python_sparse | Python-cookbook-2nd/cb2_06/cb2_6_12_sol_1.py | mahavivo/Python | train | 5 | |
90df319fe3828a41e093c3cf1750d0cb985b4698 | [
"if target_vector is None:\n target_vector = np.zeros(len(cluster_subspace))\nif target_weights is None:\n target_weights = np.ones(len(cluster_subspace) - 1)\nsuper().__init__(cluster_subspace, supercell_matrix, target_vector=target_vector, match_weight=match_weight, target_weights=target_weights, match_tol=... | <|body_start_0|>
if target_vector is None:
target_vector = np.zeros(len(cluster_subspace))
if target_weights is None:
target_weights = np.ones(len(cluster_subspace) - 1)
super().__init__(cluster_subspace, supercell_matrix, target_vector=target_vector, match_weight=match_w... | CorrelationDistanceProcessor to compute distance from a fixed correlation vector. The distance used to measure distance is, .. math:: d = -wL + ||W^T(f - f_T)||_1 where f is the correlation vector, f_T is the target correlation vector, and L is the diameter for which all correlation values of clusters of smaller diamet... | CorrelationDistanceProcessor | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CorrelationDistanceProcessor:
"""CorrelationDistanceProcessor to compute distance from a fixed correlation vector. The distance used to measure distance is, .. math:: d = -wL + ||W^T(f - f_T)||_1 where f is the correlation vector, f_T is the target correlation vector, and L is the diameter for wh... | stack_v2_sparse_classes_36k_train_023199 | 17,001 | permissive | [
{
"docstring": "Initialize a CorrelationDistanceProcessor. Args: cluster_subspace (ClusterSubspace): a cluster subspace supercell_matrix (ndarray): an array representing the supercell matrix with respect to the Cluster Expansion prim structure. target_vector (ndarray): optional target correlation vector, if Non... | 3 | null | Implement the Python class `CorrelationDistanceProcessor` described below.
Class description:
CorrelationDistanceProcessor to compute distance from a fixed correlation vector. The distance used to measure distance is, .. math:: d = -wL + ||W^T(f - f_T)||_1 where f is the correlation vector, f_T is the target correlati... | Implement the Python class `CorrelationDistanceProcessor` described below.
Class description:
CorrelationDistanceProcessor to compute distance from a fixed correlation vector. The distance used to measure distance is, .. math:: d = -wL + ||W^T(f - f_T)||_1 where f is the correlation vector, f_T is the target correlati... | 457518b9a27729fd4d5c1c23231bd37f8fee364b | <|skeleton|>
class CorrelationDistanceProcessor:
"""CorrelationDistanceProcessor to compute distance from a fixed correlation vector. The distance used to measure distance is, .. math:: d = -wL + ||W^T(f - f_T)||_1 where f is the correlation vector, f_T is the target correlation vector, and L is the diameter for wh... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CorrelationDistanceProcessor:
"""CorrelationDistanceProcessor to compute distance from a fixed correlation vector. The distance used to measure distance is, .. math:: d = -wL + ||W^T(f - f_T)||_1 where f is the correlation vector, f_T is the target correlation vector, and L is the diameter for which all corre... | the_stack_v2_python_sparse | smol/moca/processor/distance.py | CederGroupHub/smol | train | 40 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.