blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
daa3f6113876514e274699cd404d39b40f3807da | [
"result = []\nfor a in A:\n al, ar = (a[0], a[1])\n for b in B:\n bl, br = (b[0], b[1])\n if bl > ar:\n break\n if br < al:\n continue\n l = max(al, bl)\n r = min(ar, br)\n result.append([l, r])\nreturn result",
"i = 0\nj = 0\nresult = []\nwhil... | <|body_start_0|>
result = []
for a in A:
al, ar = (a[0], a[1])
for b in B:
bl, br = (b[0], b[1])
if bl > ar:
break
if br < al:
continue
l = max(al, bl)
r = min(... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def intervalIntersection(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] O(M*N)"""
<|body_0|>
def rewrite(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] O(M+N)"""
<... | stack_v2_sparse_classes_75kplus_train_004900 | 2,879 | no_license | [
{
"docstring": ":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] O(M*N)",
"name": "intervalIntersection",
"signature": "def intervalIntersection(self, A, B)"
},
{
"docstring": ":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] O(M+N)",
"name":... | 2 | stack_v2_sparse_classes_30k_train_000372 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intervalIntersection(self, A, B): :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] O(M*N)
- def rewrite(self, A, B): :type A: List[List[int]] :type B... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intervalIntersection(self, A, B): :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] O(M*N)
- def rewrite(self, A, B): :type A: List[List[int]] :type B... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def intervalIntersection(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] O(M*N)"""
<|body_0|>
def rewrite(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] O(M+N)"""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def intervalIntersection(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] O(M*N)"""
result = []
for a in A:
al, ar = (a[0], a[1])
for b in B:
bl, br = (b[0], b[1])
if bl > ar:
... | the_stack_v2_python_sparse | two-pointers/986_Interval_List_Intersections.py | vsdrun/lc_public | train | 6 | |
c6c2d01db5c4093f6b325c8dd9fd8c5501ba34dc | [
"fetch_full_feed = is_incremental_feed = False\nwith pytest.raises(DemistoException) as e:\n assert_incremental_feed_params(fetch_full_feed, is_incremental_feed)\n assert \"'Full Feed Fetch' cannot be disabled when 'Incremental Feed' is disabled.\" in str(e)",
"fetch_full_feed = is_incremental_feed = True\n... | <|body_start_0|>
fetch_full_feed = is_incremental_feed = False
with pytest.raises(DemistoException) as e:
assert_incremental_feed_params(fetch_full_feed, is_incremental_feed)
assert "'Full Feed Fetch' cannot be disabled when 'Incremental Feed' is disabled." in str(e)
<|end_body_0... | Scenario: Test assert_incremental_feed_params raises appropriate errors | TestAssertIncrementalFeedParams | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAssertIncrementalFeedParams:
"""Scenario: Test assert_incremental_feed_params raises appropriate errors"""
def test_both_params_are_false(self):
"""Scenario: Both params are False Given: - fetch_full_feed is false - feedIncremental is false When: - calling assert_incremental_feed... | stack_v2_sparse_classes_75kplus_train_004901 | 9,956 | permissive | [
{
"docstring": "Scenario: Both params are False Given: - fetch_full_feed is false - feedIncremental is false When: - calling assert_incremental_feed_params Then: - raise appropriate error",
"name": "test_both_params_are_false",
"signature": "def test_both_params_are_false(self)"
},
{
"docstring"... | 3 | stack_v2_sparse_classes_30k_train_025164 | Implement the Python class `TestAssertIncrementalFeedParams` described below.
Class description:
Scenario: Test assert_incremental_feed_params raises appropriate errors
Method signatures and docstrings:
- def test_both_params_are_false(self): Scenario: Both params are False Given: - fetch_full_feed is false - feedInc... | Implement the Python class `TestAssertIncrementalFeedParams` described below.
Class description:
Scenario: Test assert_incremental_feed_params raises appropriate errors
Method signatures and docstrings:
- def test_both_params_are_false(self): Scenario: Both params are False Given: - fetch_full_feed is false - feedInc... | 01b57f8c658c2faed047313d3034e8052ffa83ce | <|skeleton|>
class TestAssertIncrementalFeedParams:
"""Scenario: Test assert_incremental_feed_params raises appropriate errors"""
def test_both_params_are_false(self):
"""Scenario: Both params are False Given: - fetch_full_feed is false - feedIncremental is false When: - calling assert_incremental_feed... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestAssertIncrementalFeedParams:
"""Scenario: Test assert_incremental_feed_params raises appropriate errors"""
def test_both_params_are_false(self):
"""Scenario: Both params are False Given: - fetch_full_feed is false - feedIncremental is false When: - calling assert_incremental_feed_params Then:... | the_stack_v2_python_sparse | Packs/FeedTAXII/Integrations/FeedTAXII2/FeedTAXII2_test.py | adambaumeister/content | train | 2 |
204a359d3c7bcfc76c4052125f8cc8199ed730a3 | [
"if 'z' in kwargs:\n self.z = float(kwargs['z'])\n self.distance = None\nelif 'redshift' in kwargs:\n self.z = float(kwargs['redshift'])\n self.distance = None\nelif 'distance' in kwargs:\n if 'distanceUnits' not in kwargs:\n raise ValueError(\"If you specify 'distance', you must also specify ... | <|body_start_0|>
if 'z' in kwargs:
self.z = float(kwargs['z'])
self.distance = None
elif 'redshift' in kwargs:
self.z = float(kwargs['redshift'])
self.distance = None
elif 'distance' in kwargs:
if 'distanceUnits' not in kwargs:
... | Represents an RA, Dec[, z | physical distance] coordinate system. | EquatorialCoordinates | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EquatorialCoordinates:
"""Represents an RA, Dec[, z | physical distance] coordinate system."""
def __init__(self, ra, dec, **kwargs):
"""A few notes: - if the ra/dec specified are not geometry.Angle() objects, they are assumed to be in units degrees, and converted to Angle() objects.... | stack_v2_sparse_classes_75kplus_train_004902 | 21,382 | permissive | [
{
"docstring": "A few notes: - if the ra/dec specified are not geometry.Angle() objects, they are assumed to be in units degrees, and converted to Angle() objects. - if you specify distance=blah, corresponding to a physical distance to the object, you must also specify 'distanceUnits' to be pc, kpc, mpc, ly, m,... | 2 | stack_v2_sparse_classes_30k_train_015054 | Implement the Python class `EquatorialCoordinates` described below.
Class description:
Represents an RA, Dec[, z | physical distance] coordinate system.
Method signatures and docstrings:
- def __init__(self, ra, dec, **kwargs): A few notes: - if the ra/dec specified are not geometry.Angle() objects, they are assumed ... | Implement the Python class `EquatorialCoordinates` described below.
Class description:
Represents an RA, Dec[, z | physical distance] coordinate system.
Method signatures and docstrings:
- def __init__(self, ra, dec, **kwargs): A few notes: - if the ra/dec specified are not geometry.Angle() objects, they are assumed ... | f7d3ef3ccfecd87b50ce05cf6af5a564679f15f5 | <|skeleton|>
class EquatorialCoordinates:
"""Represents an RA, Dec[, z | physical distance] coordinate system."""
def __init__(self, ra, dec, **kwargs):
"""A few notes: - if the ra/dec specified are not geometry.Angle() objects, they are assumed to be in units degrees, and converted to Angle() objects.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EquatorialCoordinates:
"""Represents an RA, Dec[, z | physical distance] coordinate system."""
def __init__(self, ra, dec, **kwargs):
"""A few notes: - if the ra/dec specified are not geometry.Angle() objects, they are assumed to be in units degrees, and converted to Angle() objects. - if you spe... | the_stack_v2_python_sparse | python/sdssdb/sqlalchemy/operationsdb/tools/geometry.py | sdss/sdssdb | train | 9 |
f481fa590d36066166dbbd6871387fe48d7cf3ca | [
"res = self.create_residual(data, model, nbins=nbins, maxr=maxr, calcr=calcr, skipzero=skipzero)\nSingleHistBase.__init__(self, res, 'radialRes', fill, workinprogress)\nself._xtitle = 'r [cm]'\nself._ytitle = 'Pull'",
"if nbins is None:\n nbins = data.GetXaxis().GetNbins()\nif maxr is None:\n maxr = data.Ge... | <|body_start_0|>
res = self.create_residual(data, model, nbins=nbins, maxr=maxr, calcr=calcr, skipzero=skipzero)
SingleHistBase.__init__(self, res, 'radialRes', fill, workinprogress)
self._xtitle = 'r [cm]'
self._ytitle = 'Pull'
<|end_body_0|>
<|body_start_1|>
if nbins is None:
... | Plot residuals projected to one radial dimension. __init__: Initialize. chisq: Return the chi-squared summed over radial bins. | RadialResidualPlot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RadialResidualPlot:
"""Plot residuals projected to one radial dimension. __init__: Initialize. chisq: Return the chi-squared summed over radial bins."""
def __init__(self, data, model, nbins=None, maxr=None, calcr=None, skipzero=False, fill=4954, workinprogress=False):
"""Project res... | stack_v2_sparse_classes_75kplus_train_004903 | 8,137 | no_license | [
{
"docstring": "Project residual histogram to one-dimensional plot.",
"name": "__init__",
"signature": "def __init__(self, data, model, nbins=None, maxr=None, calcr=None, skipzero=False, fill=4954, workinprogress=False)"
},
{
"docstring": "Create radial residual histogram.",
"name": "create_... | 3 | stack_v2_sparse_classes_30k_train_029291 | Implement the Python class `RadialResidualPlot` described below.
Class description:
Plot residuals projected to one radial dimension. __init__: Initialize. chisq: Return the chi-squared summed over radial bins.
Method signatures and docstrings:
- def __init__(self, data, model, nbins=None, maxr=None, calcr=None, skip... | Implement the Python class `RadialResidualPlot` described below.
Class description:
Plot residuals projected to one radial dimension. __init__: Initialize. chisq: Return the chi-squared summed over radial bins.
Method signatures and docstrings:
- def __init__(self, data, model, nbins=None, maxr=None, calcr=None, skip... | 8eed4783e17226fd026e74e7a95c77ae88b63162 | <|skeleton|>
class RadialResidualPlot:
"""Plot residuals projected to one radial dimension. __init__: Initialize. chisq: Return the chi-squared summed over radial bins."""
def __init__(self, data, model, nbins=None, maxr=None, calcr=None, skipzero=False, fill=4954, workinprogress=False):
"""Project res... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RadialResidualPlot:
"""Plot residuals projected to one radial dimension. __init__: Initialize. chisq: Return the chi-squared summed over radial bins."""
def __init__(self, data, model, nbins=None, maxr=None, calcr=None, skipzero=False, fill=4954, workinprogress=False):
"""Project residual histogr... | the_stack_v2_python_sparse | lib/plot/residual.py | knollejo/BeamImagingAnalysis | train | 0 |
0fd476723aeb88e1a77336a1e5d17829b1b6a422 | [
"self.request = request\nself.request_manager = PokedexRequestManager()\noutput_strategy = TextFileOutputStrategy(request.output) if request.output else ConsoleOutputStrategy()\nself.report_exporter = Report(output_strategy)",
"if self.request.inputdata:\n return [self.request.inputdata]\nif self.request.input... | <|body_start_0|>
self.request = request
self.request_manager = PokedexRequestManager()
output_strategy = TextFileOutputStrategy(request.output) if request.output else ConsoleOutputStrategy()
self.report_exporter = Report(output_strategy)
<|end_body_0|>
<|body_start_1|>
if self.r... | The driver class that accepts a request and executes it. | Pokedex | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pokedex:
"""The driver class that accepts a request and executes it."""
def __init__(self, request: Request):
"""Initializes a Pokedex with a request. :param request: a Request"""
<|body_0|>
def get_request_dataset(self) -> list:
"""Returns a list of request name... | stack_v2_sparse_classes_75kplus_train_004904 | 2,848 | no_license | [
{
"docstring": "Initializes a Pokedex with a request. :param request: a Request",
"name": "__init__",
"signature": "def __init__(self, request: Request)"
},
{
"docstring": "Returns a list of request names or ids. :return: a list",
"name": "get_request_dataset",
"signature": "def get_requ... | 4 | stack_v2_sparse_classes_30k_train_015309 | Implement the Python class `Pokedex` described below.
Class description:
The driver class that accepts a request and executes it.
Method signatures and docstrings:
- def __init__(self, request: Request): Initializes a Pokedex with a request. :param request: a Request
- def get_request_dataset(self) -> list: Returns a... | Implement the Python class `Pokedex` described below.
Class description:
The driver class that accepts a request and executes it.
Method signatures and docstrings:
- def __init__(self, request: Request): Initializes a Pokedex with a request. :param request: a Request
- def get_request_dataset(self) -> list: Returns a... | e86956c69006f96221349fe9bd4925ad2255601e | <|skeleton|>
class Pokedex:
"""The driver class that accepts a request and executes it."""
def __init__(self, request: Request):
"""Initializes a Pokedex with a request. :param request: a Request"""
<|body_0|>
def get_request_dataset(self) -> list:
"""Returns a list of request name... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Pokedex:
"""The driver class that accepts a request and executes it."""
def __init__(self, request: Request):
"""Initializes a Pokedex with a request. :param request: a Request"""
self.request = request
self.request_manager = PokedexRequestManager()
output_strategy = TextF... | the_stack_v2_python_sparse | assignment-3-an-object-oriented-pokedex-pikachu/pokedex.py | lizhiquan/learning-python | train | 0 |
4ca6c49bcb8d426fb5b60526fcabbb6b14c41fd7 | [
"super(StringChunker, self).__init__(k, symbolsize)\nself.value = value\nself.bytesread = 0\nself.stringsize = len(value)",
"if self.bytesread >= self.stringsize:\n return None\nblock = SourceBlock(self.k, self.symbolsize, self.get_block_id())\nj = 0\nwhile j < self.k and self.bytesread < self.stringsize:\n ... | <|body_start_0|>
super(StringChunker, self).__init__(k, symbolsize)
self.value = value
self.bytesread = 0
self.stringsize = len(value)
<|end_body_0|>
<|body_start_1|>
if self.bytesread >= self.stringsize:
return None
block = SourceBlock(self.k, self.symbolsiz... | Chunks large strings into smaller parts similar to the file chunker | StringChunker | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StringChunker:
"""Chunks large strings into smaller parts similar to the file chunker"""
def __init__(self, k, symbolsize, value):
"""Initialized the string chunker Arguments: k -- Integer number of symbols per chunk symbolsize -- Size of each symbol in a chunk] value -- String to ch... | stack_v2_sparse_classes_75kplus_train_004905 | 7,129 | permissive | [
{
"docstring": "Initialized the string chunker Arguments: k -- Integer number of symbols per chunk symbolsize -- Size of each symbol in a chunk] value -- String to chunk",
"name": "__init__",
"signature": "def __init__(self, k, symbolsize, value)"
},
{
"docstring": "Should return a block of uint... | 3 | stack_v2_sparse_classes_30k_train_035103 | Implement the Python class `StringChunker` described below.
Class description:
Chunks large strings into smaller parts similar to the file chunker
Method signatures and docstrings:
- def __init__(self, k, symbolsize, value): Initialized the string chunker Arguments: k -- Integer number of symbols per chunk symbolsize... | Implement the Python class `StringChunker` described below.
Class description:
Chunks large strings into smaller parts similar to the file chunker
Method signatures and docstrings:
- def __init__(self, k, symbolsize, value): Initialized the string chunker Arguments: k -- Integer number of symbols per chunk symbolsize... | e103dec23f1e466c3caa850af03f0861d7dcaa33 | <|skeleton|>
class StringChunker:
"""Chunks large strings into smaller parts similar to the file chunker"""
def __init__(self, k, symbolsize, value):
"""Initialized the string chunker Arguments: k -- Integer number of symbols per chunk symbolsize -- Size of each symbol in a chunk] value -- String to ch... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StringChunker:
"""Chunks large strings into smaller parts similar to the file chunker"""
def __init__(self, k, symbolsize, value):
"""Initialized the string chunker Arguments: k -- Integer number of symbols per chunk symbolsize -- Size of each symbol in a chunk] value -- String to chunk"""
... | the_stack_v2_python_sparse | velopyraptor/chunker.py | tbfly/velopyraptor | train | 0 |
2c1bfe1fa44362618173e1200c130eeb8be0608d | [
"self._historical_info = copy.deepcopy(historical_info)\nself._subtype = subtype\nfor arm in self._historical_info.arms_sampled.itervalues():\n if not isinstance(arm, BernoulliArm):\n raise ValueError('All arms have to be Bernoulli arms!')",
"if not sampled_arm:\n raise ValueError('sampled_arm is emp... | <|body_start_0|>
self._historical_info = copy.deepcopy(historical_info)
self._subtype = subtype
for arm in self._historical_info.arms_sampled.itervalues():
if not isinstance(arm, BernoulliArm):
raise ValueError('All arms have to be Bernoulli arms!')
<|end_body_0|>
<|... | Implementation of the constructor of BLA (Bayesian Learning Automaton) and method allocate_arms. A class to encapsulate the computation of bandit BLA. The Algorithm is from the paper: A Generic Solution to Multi-Armed Bernoulli Bandit Problems, Norheim, Bradland, Granmo, OOmmen (2010) ICAART. See :class:`moe.bandit.ban... | BLA | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BLA:
"""Implementation of the constructor of BLA (Bayesian Learning Automaton) and method allocate_arms. A class to encapsulate the computation of bandit BLA. The Algorithm is from the paper: A Generic Solution to Multi-Armed Bernoulli Bandit Problems, Norheim, Bradland, Granmo, OOmmen (2010) ICA... | stack_v2_sparse_classes_75kplus_train_004906 | 5,524 | permissive | [
{
"docstring": "Construct a BLA object. BLA only supports Bernoulli trials (payoff 1 for success and 0 for failure). :param historical_info: a dictionary of arms sampled :type historical_info: dictionary of (str, SampleArm()) pairs (see :class:`moe.bandit.data_containers.SampleArm` for more details) :param subt... | 4 | null | Implement the Python class `BLA` described below.
Class description:
Implementation of the constructor of BLA (Bayesian Learning Automaton) and method allocate_arms. A class to encapsulate the computation of bandit BLA. The Algorithm is from the paper: A Generic Solution to Multi-Armed Bernoulli Bandit Problems, Norhe... | Implement the Python class `BLA` described below.
Class description:
Implementation of the constructor of BLA (Bayesian Learning Automaton) and method allocate_arms. A class to encapsulate the computation of bandit BLA. The Algorithm is from the paper: A Generic Solution to Multi-Armed Bernoulli Bandit Problems, Norhe... | 44143f25424c30d58321f8da8f60ce161bb83e67 | <|skeleton|>
class BLA:
"""Implementation of the constructor of BLA (Bayesian Learning Automaton) and method allocate_arms. A class to encapsulate the computation of bandit BLA. The Algorithm is from the paper: A Generic Solution to Multi-Armed Bernoulli Bandit Problems, Norheim, Bradland, Granmo, OOmmen (2010) ICA... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BLA:
"""Implementation of the constructor of BLA (Bayesian Learning Automaton) and method allocate_arms. A class to encapsulate the computation of bandit BLA. The Algorithm is from the paper: A Generic Solution to Multi-Armed Bernoulli Bandit Problems, Norheim, Bradland, Granmo, OOmmen (2010) ICAART. See :cla... | the_stack_v2_python_sparse | moe/bandit/bla/bla.py | melikavah/test | train | 2 |
f724f1121326177b41aa01b76c078576ff5adfc5 | [
"self.after_cursor_entity_id = after_cursor_entity_id\nself.before_cursor_entity_id = before_cursor_entity_id\nself.node_id = node_id\nself.page_size = page_size",
"if dictionary is None:\n return None\nafter_cursor_entity_id = dictionary.get('afterCursorEntityId')\nbefore_cursor_entity_id = dictionary.get('be... | <|body_start_0|>
self.after_cursor_entity_id = after_cursor_entity_id
self.before_cursor_entity_id = before_cursor_entity_id
self.node_id = node_id
self.page_size = page_size
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
after_cursor_enti... | Implementation of the 'PaginationParameters' model. Specifies the cursor based pagination parameters for Protection Source and its children. Pagination is supported at a given level within the Protection Source Hierarchy with the help of before or after cursors. A Cursor will always refer to a specific source within th... | PaginationParameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PaginationParameters:
"""Implementation of the 'PaginationParameters' model. Specifies the cursor based pagination parameters for Protection Source and its children. Pagination is supported at a given level within the Protection Source Hierarchy with the help of before or after cursors. A Cursor ... | stack_v2_sparse_classes_75kplus_train_004907 | 2,821 | permissive | [
{
"docstring": "Constructor for the PaginationParameters class",
"name": "__init__",
"signature": "def __init__(self, after_cursor_entity_id=None, before_cursor_entity_id=None, node_id=None, page_size=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary ... | 2 | stack_v2_sparse_classes_30k_train_021948 | Implement the Python class `PaginationParameters` described below.
Class description:
Implementation of the 'PaginationParameters' model. Specifies the cursor based pagination parameters for Protection Source and its children. Pagination is supported at a given level within the Protection Source Hierarchy with the hel... | Implement the Python class `PaginationParameters` described below.
Class description:
Implementation of the 'PaginationParameters' model. Specifies the cursor based pagination parameters for Protection Source and its children. Pagination is supported at a given level within the Protection Source Hierarchy with the hel... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class PaginationParameters:
"""Implementation of the 'PaginationParameters' model. Specifies the cursor based pagination parameters for Protection Source and its children. Pagination is supported at a given level within the Protection Source Hierarchy with the help of before or after cursors. A Cursor ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PaginationParameters:
"""Implementation of the 'PaginationParameters' model. Specifies the cursor based pagination parameters for Protection Source and its children. Pagination is supported at a given level within the Protection Source Hierarchy with the help of before or after cursors. A Cursor will always r... | the_stack_v2_python_sparse | cohesity_management_sdk/models/pagination_parameters.py | cohesity/management-sdk-python | train | 24 |
c6bc26e4b89f188750933739a534712cad0b282c | [
"result = get_coverage._get_oss_fuzz_latest_cov_report_info(self.PROJECT)\nself.assertEqual(result, {'coverage': 1})\nmock_error.assert_not_called()\nmock_get_json_from_url.assert_called_with(self.LATEST_REPORT_INFO_URL)",
"result = get_coverage._get_oss_fuzz_latest_cov_report_info('project')\nself.assertIsNone(r... | <|body_start_0|>
result = get_coverage._get_oss_fuzz_latest_cov_report_info(self.PROJECT)
self.assertEqual(result, {'coverage': 1})
mock_error.assert_not_called()
mock_get_json_from_url.assert_called_with(self.LATEST_REPORT_INFO_URL)
<|end_body_0|>
<|body_start_1|>
result = get_... | Tests that _get_oss_fuzz_latest_cov_report_info works as intended. | GetOssFuzzLatestCovReportInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetOssFuzzLatestCovReportInfo:
"""Tests that _get_oss_fuzz_latest_cov_report_info works as intended."""
def test_get_oss_fuzz_latest_cov_report_info(self, mock_get_json_from_url, mock_error):
"""Tests that _get_oss_fuzz_latest_cov_report_info works as intended."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_004908 | 9,610 | permissive | [
{
"docstring": "Tests that _get_oss_fuzz_latest_cov_report_info works as intended.",
"name": "test_get_oss_fuzz_latest_cov_report_info",
"signature": "def test_get_oss_fuzz_latest_cov_report_info(self, mock_get_json_from_url, mock_error)"
},
{
"docstring": "Tests that _get_oss_fuzz_latest_cov_re... | 2 | stack_v2_sparse_classes_30k_train_019404 | Implement the Python class `GetOssFuzzLatestCovReportInfo` described below.
Class description:
Tests that _get_oss_fuzz_latest_cov_report_info works as intended.
Method signatures and docstrings:
- def test_get_oss_fuzz_latest_cov_report_info(self, mock_get_json_from_url, mock_error): Tests that _get_oss_fuzz_latest_... | Implement the Python class `GetOssFuzzLatestCovReportInfo` described below.
Class description:
Tests that _get_oss_fuzz_latest_cov_report_info works as intended.
Method signatures and docstrings:
- def test_get_oss_fuzz_latest_cov_report_info(self, mock_get_json_from_url, mock_error): Tests that _get_oss_fuzz_latest_... | f0275421f84b8f80ee767fb9230134ac97cb687b | <|skeleton|>
class GetOssFuzzLatestCovReportInfo:
"""Tests that _get_oss_fuzz_latest_cov_report_info works as intended."""
def test_get_oss_fuzz_latest_cov_report_info(self, mock_get_json_from_url, mock_error):
"""Tests that _get_oss_fuzz_latest_cov_report_info works as intended."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GetOssFuzzLatestCovReportInfo:
"""Tests that _get_oss_fuzz_latest_cov_report_info works as intended."""
def test_get_oss_fuzz_latest_cov_report_info(self, mock_get_json_from_url, mock_error):
"""Tests that _get_oss_fuzz_latest_cov_report_info works as intended."""
result = get_coverage._g... | the_stack_v2_python_sparse | infra/cifuzz/get_coverage_test.py | google/oss-fuzz | train | 9,438 |
60e2d8df62f939ad42591cb2c394f79d68d09141 | [
"res = []\nif not root:\n return '[]'\nqueue = collections.deque()\nqueue.append(root)\nwhile queue:\n node = queue.popleft()\n if node:\n res.append(str(node.val))\n queue.append(node.left)\n queue.append(node.right)\n else:\n res.append('null')\nreturn '[' + ','.join(res) +... | <|body_start_0|>
res = []
if not root:
return '[]'
queue = collections.deque()
queue.append(root)
while queue:
node = queue.popleft()
if node:
res.append(str(node.val))
queue.append(node.left)
que... | 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_75kplus_train_004909 | 5,785 | 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_010683 | 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:... | e1dfd95c5bf09ffcd42934c1aca21a10337c3e7e | <|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_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
res = []
if not root:
return '[]'
queue = collections.deque()
queue.append(root)
while queue:
node = queue.popleft()
i... | the_stack_v2_python_sparse | 297. 二叉树的序列化与反序列化.py | Qinpeng96/leetcode | train | 0 | |
b413a46b77ff2e91d197fee5512e99fce9d9376e | [
"execute = Execute()\ndirectory = os.path.abspath(directory)\nparent_directory = os.path.abspath(os.path.join(directory, '..'))\ndirectory_name = os.path.relpath(directory, parent_directory)\nout, err, exitcode = execute('cd \"%s\" && zip -FSr \"%s\" \"./%s\"' % (parent_directory, target, directory_name))\nreturn e... | <|body_start_0|>
execute = Execute()
directory = os.path.abspath(directory)
parent_directory = os.path.abspath(os.path.join(directory, '..'))
directory_name = os.path.relpath(directory, parent_directory)
out, err, exitcode = execute('cd "%s" && zip -FSr "%s" "./%s"' % (parent_dir... | Archive | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Archive:
def zip(directory, target):
"""Zip a directory :param directory: The directory :param target: The target :return: The archive"""
<|body_0|>
def unzip(archive, directory):
"""Unzip a file :param archive: The zip file :param directory: The directory to unzip i... | stack_v2_sparse_classes_75kplus_train_004910 | 1,049 | permissive | [
{
"docstring": "Zip a directory :param directory: The directory :param target: The target :return: The archive",
"name": "zip",
"signature": "def zip(directory, target)"
},
{
"docstring": "Unzip a file :param archive: The zip file :param directory: The directory to unzip in :return: Success",
... | 2 | null | Implement the Python class `Archive` described below.
Class description:
Implement the Archive class.
Method signatures and docstrings:
- def zip(directory, target): Zip a directory :param directory: The directory :param target: The target :return: The archive
- def unzip(archive, directory): Unzip a file :param arch... | Implement the Python class `Archive` described below.
Class description:
Implement the Archive class.
Method signatures and docstrings:
- def zip(directory, target): Zip a directory :param directory: The directory :param target: The target :return: The archive
- def unzip(archive, directory): Unzip a file :param arch... | 0c9d94b353d4d149db9492eb4ae0aa87cc1e082c | <|skeleton|>
class Archive:
def zip(directory, target):
"""Zip a directory :param directory: The directory :param target: The target :return: The archive"""
<|body_0|>
def unzip(archive, directory):
"""Unzip a file :param archive: The zip file :param directory: The directory to unzip i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Archive:
def zip(directory, target):
"""Zip a directory :param directory: The directory :param target: The target :return: The archive"""
execute = Execute()
directory = os.path.abspath(directory)
parent_directory = os.path.abspath(os.path.join(directory, '..'))
directo... | the_stack_v2_python_sparse | scriptcore/filesystem/archive.py | LowieHuyghe/script-core | train | 0 | |
f85a7a71c03b07f4f79b3887f7c854bc20eff067 | [
"self.config = config\nself.time_step = config['model']['time_step']\nself.batch_size = config['model']['batch_size']\nself.n_neg = config['model']['n_neg']\nself.model = TVBR(config['model'])\nuser_fea = torch.tensor(config['user_fea'], requires_grad=False, device=config['model']['device_str'], dtype=torch.float32... | <|body_start_0|>
self.config = config
self.time_step = config['model']['time_step']
self.batch_size = config['model']['batch_size']
self.n_neg = config['model']['n_neg']
self.model = TVBR(config['model'])
user_fea = torch.tensor(config['user_fea'], requires_grad=False, de... | Model Engine For TVBR. Args: ModelEngine ([type]): [description] | TVBREngine | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TVBREngine:
"""Model Engine For TVBR. Args: ModelEngine ([type]): [description]"""
def __init__(self, config):
"""Initialize configs. Args: config ([type]): [description]"""
<|body_0|>
def train_single_batch(self, batch_data, ratings=None):
"""Train a single batc... | stack_v2_sparse_classes_75kplus_train_004911 | 19,594 | permissive | [
{
"docstring": "Initialize configs. Args: config ([type]): [description]",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Train a single batch. Args: batch_data ([type]): [description] ratings ([type], optional): [description]. Defaults to None. Returns: [type]:... | 3 | stack_v2_sparse_classes_30k_train_017952 | Implement the Python class `TVBREngine` described below.
Class description:
Model Engine For TVBR. Args: ModelEngine ([type]): [description]
Method signatures and docstrings:
- def __init__(self, config): Initialize configs. Args: config ([type]): [description]
- def train_single_batch(self, batch_data, ratings=None)... | Implement the Python class `TVBREngine` described below.
Class description:
Model Engine For TVBR. Args: ModelEngine ([type]): [description]
Method signatures and docstrings:
- def __init__(self, config): Initialize configs. Args: config ([type]): [description]
- def train_single_batch(self, batch_data, ratings=None)... | 625189d5e1002a3edc27c3e3ce075fddf7ae1c92 | <|skeleton|>
class TVBREngine:
"""Model Engine For TVBR. Args: ModelEngine ([type]): [description]"""
def __init__(self, config):
"""Initialize configs. Args: config ([type]): [description]"""
<|body_0|>
def train_single_batch(self, batch_data, ratings=None):
"""Train a single batc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TVBREngine:
"""Model Engine For TVBR. Args: ModelEngine ([type]): [description]"""
def __init__(self, config):
"""Initialize configs. Args: config ([type]): [description]"""
self.config = config
self.time_step = config['model']['time_step']
self.batch_size = config['model'... | the_stack_v2_python_sparse | beta_rec/models/tvbr.py | beta-team/beta-recsys | train | 156 |
56fe80889287f48f091eb77428573c05bfadb2e2 | [
"response = super().form_valid(form)\nself.object.is_active = False\nself.object.save()\nuser_email = form.cleaned_data['email']\nsend_account_activation_email.delay(user_email)\nreturn response",
"if len(form.errors) == 1 and len(form['email'].errors) == 1 and (form['email'].errors.as_data()[0].code == 'unique')... | <|body_start_0|>
response = super().form_valid(form)
self.object.is_active = False
self.object.save()
user_email = form.cleaned_data['email']
send_account_activation_email.delay(user_email)
return response
<|end_body_0|>
<|body_start_1|>
if len(form.errors) == 1 ... | Allow users to create new accounts. | Register | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Register:
"""Allow users to create new accounts."""
def form_valid(self, form):
"""Send a connection/confirmation link to the user."""
<|body_0|>
def form_invalid(self, form):
"""Handle invalid data provided. If the **only** error is that the provided email is al... | stack_v2_sparse_classes_75kplus_train_004912 | 3,277 | permissive | [
{
"docstring": "Send a connection/confirmation link to the user.",
"name": "form_valid",
"signature": "def form_valid(self, form)"
},
{
"docstring": "Handle invalid data provided. If the **only** error is that the provided email is already associated to an account, instead of displaying a \"this... | 2 | null | Implement the Python class `Register` described below.
Class description:
Allow users to create new accounts.
Method signatures and docstrings:
- def form_valid(self, form): Send a connection/confirmation link to the user.
- def form_invalid(self, form): Handle invalid data provided. If the **only** error is that the... | Implement the Python class `Register` described below.
Class description:
Allow users to create new accounts.
Method signatures and docstrings:
- def form_valid(self, form): Send a connection/confirmation link to the user.
- def form_invalid(self, form): Handle invalid data provided. If the **only** error is that the... | 3a08f780e149e900c9031f47e5e0aa983707e384 | <|skeleton|>
class Register:
"""Allow users to create new accounts."""
def form_valid(self, form):
"""Send a connection/confirmation link to the user."""
<|body_0|>
def form_invalid(self, form):
"""Handle invalid data provided. If the **only** error is that the provided email is al... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Register:
"""Allow users to create new accounts."""
def form_valid(self, form):
"""Send a connection/confirmation link to the user."""
response = super().form_valid(form)
self.object.is_active = False
self.object.save()
user_email = form.cleaned_data['email']
... | the_stack_v2_python_sparse | envergo/users/views.py | MTES-MCT/envergo | train | 3 |
9375ff595168b269b61c056e250e06e0895a8b7b | [
"self.argv = argv\nself.script_base = _getCallerPath()\nself.argsManifest = {}\ndefault_args = ['configfile', 'logfile', 'loglevel', 'logto', 'debug']\nfor arg in default_args:\n self.argsManifest[arg] = dict(type=str, default=None, help='', required=False)\n if arg == 'configfile':\n self.argsManifest... | <|body_start_0|>
self.argv = argv
self.script_base = _getCallerPath()
self.argsManifest = {}
default_args = ['configfile', 'logfile', 'loglevel', 'logto', 'debug']
for arg in default_args:
self.argsManifest[arg] = dict(type=str, default=None, help='', required=False)
... | General purpose command line arguments and config arguments handler returns a set args objects with result. Methods: __init__ - standard constructor addArgs - manifest arguments _missingArgsAlert - raise error if required args are missing handleCommandArgs - command line args handler handleArgs - config args handler Ar... | ArgumentHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArgumentHandler:
"""General purpose command line arguments and config arguments handler returns a set args objects with result. Methods: __init__ - standard constructor addArgs - manifest arguments _missingArgsAlert - raise error if required args are missing handleCommandArgs - command line args ... | stack_v2_sparse_classes_75kplus_train_004913 | 8,418 | no_license | [
{
"docstring": "Class constructor. Args: argv - command line arguments",
"name": "__init__",
"signature": "def __init__(self, argv=None)"
},
{
"docstring": "Manifest arguments in dictionary.",
"name": "addArgs",
"signature": "def addArgs(self, **kwargs)"
},
{
"docstring": "Enforc... | 5 | stack_v2_sparse_classes_30k_train_007027 | Implement the Python class `ArgumentHandler` described below.
Class description:
General purpose command line arguments and config arguments handler returns a set args objects with result. Methods: __init__ - standard constructor addArgs - manifest arguments _missingArgsAlert - raise error if required args are missing... | Implement the Python class `ArgumentHandler` described below.
Class description:
General purpose command line arguments and config arguments handler returns a set args objects with result. Methods: __init__ - standard constructor addArgs - manifest arguments _missingArgsAlert - raise error if required args are missing... | e84ba5e1ac4bd0adaf3217a4b9a0fade40601810 | <|skeleton|>
class ArgumentHandler:
"""General purpose command line arguments and config arguments handler returns a set args objects with result. Methods: __init__ - standard constructor addArgs - manifest arguments _missingArgsAlert - raise error if required args are missing handleCommandArgs - command line args ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ArgumentHandler:
"""General purpose command line arguments and config arguments handler returns a set args objects with result. Methods: __init__ - standard constructor addArgs - manifest arguments _missingArgsAlert - raise error if required args are missing handleCommandArgs - command line args handler handl... | the_stack_v2_python_sparse | utils/argsHandler.py | krishnatpatil/python-practice | train | 0 |
9a6b80f1643e8170f12845705924ff9ae86d9545 | [
"if isinstance(situation_identifier, int):\n return situation_identifier\nreturn getattr(situation_identifier, 'guid64', None)",
"if situation is None:\n return None\ntry:\n return situation.__class__.__name__ or ''\nexcept:\n return ''",
"if situations is None or not situations:\n return tuple()... | <|body_start_0|>
if isinstance(situation_identifier, int):
return situation_identifier
return getattr(situation_identifier, 'guid64', None)
<|end_body_0|>
<|body_start_1|>
if situation is None:
return None
try:
return situation.__class__.__name__ or '... | Utilities for manipulating Situations. | CommonSituationUtils | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommonSituationUtils:
"""Utilities for manipulating Situations."""
def get_situation_id(situation_identifier: Union[int, Situation]) -> Union[int, None]:
"""get_situation_id(situation_identifier) Retrieve the decimal identifier of a Situation. :param situation_identifier: The identif... | stack_v2_sparse_classes_75kplus_train_004914 | 3,319 | permissive | [
{
"docstring": "get_situation_id(situation_identifier) Retrieve the decimal identifier of a Situation. :param situation_identifier: The identifier or instance of a Situation. :type situation_identifier: Union[int, Situation] :return: The decimal identifier of the Situation or None if the Situation does not have... | 4 | stack_v2_sparse_classes_30k_train_003024 | Implement the Python class `CommonSituationUtils` described below.
Class description:
Utilities for manipulating Situations.
Method signatures and docstrings:
- def get_situation_id(situation_identifier: Union[int, Situation]) -> Union[int, None]: get_situation_id(situation_identifier) Retrieve the decimal identifier... | Implement the Python class `CommonSituationUtils` described below.
Class description:
Utilities for manipulating Situations.
Method signatures and docstrings:
- def get_situation_id(situation_identifier: Union[int, Situation]) -> Union[int, None]: get_situation_id(situation_identifier) Retrieve the decimal identifier... | b59ea7e5f4bd01d3b3bd7603843d525a9c179867 | <|skeleton|>
class CommonSituationUtils:
"""Utilities for manipulating Situations."""
def get_situation_id(situation_identifier: Union[int, Situation]) -> Union[int, None]:
"""get_situation_id(situation_identifier) Retrieve the decimal identifier of a Situation. :param situation_identifier: The identif... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CommonSituationUtils:
"""Utilities for manipulating Situations."""
def get_situation_id(situation_identifier: Union[int, Situation]) -> Union[int, None]:
"""get_situation_id(situation_identifier) Retrieve the decimal identifier of a Situation. :param situation_identifier: The identifier or instan... | the_stack_v2_python_sparse | src/sims4communitylib/utils/resources/common_situation_utils.py | velocist/TS4CheatsInfo | train | 1 |
3bae9edb576e50b6e1bcc0c8d37e47b715e60fb4 | [
"self.extractor = None\nself.stain_matrix_target = None\nself.target_concentrations = None\nself.maxC_target = None\nself.stain_matrix_target_RGB = None",
"od = rgb2od(img).reshape((-1, 3))\nx, _, _, _ = np.linalg.lstsq(stain_matrix.T, od.T, rcond=-1)\nreturn x.T",
"self.stain_matrix_target = self.extractor.get... | <|body_start_0|>
self.extractor = None
self.stain_matrix_target = None
self.target_concentrations = None
self.maxC_target = None
self.stain_matrix_target_RGB = None
<|end_body_0|>
<|body_start_1|>
od = rgb2od(img).reshape((-1, 3))
x, _, _, _ = np.linalg.lstsq(sta... | Stain normalization base class. This class contains code inspired by StainTools [https://github.com/Peter554/StainTools] written by Peter Byfield. Attributes: extractor (CustomExtractor, RuifrokExtractor): Method specific stain extractor. stain_matrix_target (:class:`numpy.ndarray`): Stain matrix of target. target_conc... | StainNormalizer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StainNormalizer:
"""Stain normalization base class. This class contains code inspired by StainTools [https://github.com/Peter554/StainTools] written by Peter Byfield. Attributes: extractor (CustomExtractor, RuifrokExtractor): Method specific stain extractor. stain_matrix_target (:class:`numpy.nda... | stack_v2_sparse_classes_75kplus_train_004915 | 13,553 | permissive | [
{
"docstring": "Initialize :class:`StainNormalizer`.",
"name": "__init__",
"signature": "def __init__(self: StainNormalizer) -> None"
},
{
"docstring": "Estimate concentration matrix given an image and stain matrix. Args: img (:class:`numpy.ndarray`): Input image. stain_matrix (:class:`numpy.nda... | 4 | stack_v2_sparse_classes_30k_train_042771 | Implement the Python class `StainNormalizer` described below.
Class description:
Stain normalization base class. This class contains code inspired by StainTools [https://github.com/Peter554/StainTools] written by Peter Byfield. Attributes: extractor (CustomExtractor, RuifrokExtractor): Method specific stain extractor.... | Implement the Python class `StainNormalizer` described below.
Class description:
Stain normalization base class. This class contains code inspired by StainTools [https://github.com/Peter554/StainTools] written by Peter Byfield. Attributes: extractor (CustomExtractor, RuifrokExtractor): Method specific stain extractor.... | f26387f46f675a7b9a8a48c95dad26e819229f2f | <|skeleton|>
class StainNormalizer:
"""Stain normalization base class. This class contains code inspired by StainTools [https://github.com/Peter554/StainTools] written by Peter Byfield. Attributes: extractor (CustomExtractor, RuifrokExtractor): Method specific stain extractor. stain_matrix_target (:class:`numpy.nda... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StainNormalizer:
"""Stain normalization base class. This class contains code inspired by StainTools [https://github.com/Peter554/StainTools] written by Peter Byfield. Attributes: extractor (CustomExtractor, RuifrokExtractor): Method specific stain extractor. stain_matrix_target (:class:`numpy.ndarray`): Stain... | the_stack_v2_python_sparse | tiatoolbox/tools/stainnorm.py | TissueImageAnalytics/tiatoolbox | train | 222 |
19e90e35aef479ad2a2aebd89bc7f944c01746f3 | [
"while run_flag.running:\n while not queue.empty():\n data = queue.get()\n for subject in [s for s in subjects if not s.is_disposed]:\n subject.on_next(data)\n time.sleep(0.1)",
"self._run_flag = RunFlag()\nself._subjects: List[Subject] = []\nm = Manager()\nq = m.Queue()\nself._shar... | <|body_start_0|>
while run_flag.running:
while not queue.empty():
data = queue.get()
for subject in [s for s in subjects if not s.is_disposed]:
subject.on_next(data)
time.sleep(0.1)
<|end_body_0|>
<|body_start_1|>
self._run_fla... | Reactive wrapper and background process for RuuviTagSensor get_data | RuuviTagReactive | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RuuviTagReactive:
"""Reactive wrapper and background process for RuuviTagSensor get_data"""
def _data_update(subjects: List[Subject], queue: Queue, run_flag: RunFlag):
"""Get data from background process and notify all subscribed observers with the new data"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_004916 | 3,494 | permissive | [
{
"docstring": "Get data from background process and notify all subscribed observers with the new data",
"name": "_data_update",
"signature": "def _data_update(subjects: List[Subject], queue: Queue, run_flag: RunFlag)"
},
{
"docstring": "Start background process for get_data and async task for n... | 4 | stack_v2_sparse_classes_30k_train_005840 | Implement the Python class `RuuviTagReactive` described below.
Class description:
Reactive wrapper and background process for RuuviTagSensor get_data
Method signatures and docstrings:
- def _data_update(subjects: List[Subject], queue: Queue, run_flag: RunFlag): Get data from background process and notify all subscrib... | Implement the Python class `RuuviTagReactive` described below.
Class description:
Reactive wrapper and background process for RuuviTagSensor get_data
Method signatures and docstrings:
- def _data_update(subjects: List[Subject], queue: Queue, run_flag: RunFlag): Get data from background process and notify all subscrib... | f8458d10f37c080c335366f2b893accaf8a2221a | <|skeleton|>
class RuuviTagReactive:
"""Reactive wrapper and background process for RuuviTagSensor get_data"""
def _data_update(subjects: List[Subject], queue: Queue, run_flag: RunFlag):
"""Get data from background process and notify all subscribed observers with the new data"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RuuviTagReactive:
"""Reactive wrapper and background process for RuuviTagSensor get_data"""
def _data_update(subjects: List[Subject], queue: Queue, run_flag: RunFlag):
"""Get data from background process and notify all subscribed observers with the new data"""
while run_flag.running:
... | the_stack_v2_python_sparse | ruuvitag_sensor/ruuvi_rx.py | ttu/ruuvitag-sensor | train | 190 |
27497175e67a23b396b5523e6ddffdfe17ca787a | [
"if hypothesis == '' or references == '':\n if self.metric.__name__ == 'wip':\n max_val = 0.0\n min_val = 1.0\n else:\n max_val = 1.0\n min_val = 0.0\n return _empty_values_score(hypothesis, references, min_val=max_val, max_val=min_val)\nscore = self.metric(truth=references, hyp... | <|body_start_0|>
if hypothesis == '' or references == '':
if self.metric.__name__ == 'wip':
max_val = 0.0
min_val = 1.0
else:
max_val = 1.0
min_val = 0.0
return _empty_values_score(hypothesis, references, min_val... | JIWERScore template metric class | JIWERScore | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JIWERScore:
"""JIWERScore template metric class"""
def __call__(self, hypothesis: Union[str, List[str]], references: Union[str, List[str]], **kwargs) -> float:
"""Compute JIWERScore score of a hypothesis and a reference. Params: hypothesis (str): a hypothesis sentence or a list of hy... | stack_v2_sparse_classes_75kplus_train_004917 | 7,252 | permissive | [
{
"docstring": "Compute JIWERScore score of a hypothesis and a reference. Params: hypothesis (str): a hypothesis sentence or a list of hypothesis sentences reference (str): a reference sentence or a list of reference sentences kwargs: see complete list at: https://github.com/jitsi/jiwer/blob/1fd2a161fd21296640c... | 2 | stack_v2_sparse_classes_30k_train_036110 | Implement the Python class `JIWERScore` described below.
Class description:
JIWERScore template metric class
Method signatures and docstrings:
- def __call__(self, hypothesis: Union[str, List[str]], references: Union[str, List[str]], **kwargs) -> float: Compute JIWERScore score of a hypothesis and a reference. Params... | Implement the Python class `JIWERScore` described below.
Class description:
JIWERScore template metric class
Method signatures and docstrings:
- def __call__(self, hypothesis: Union[str, List[str]], references: Union[str, List[str]], **kwargs) -> float: Compute JIWERScore score of a hypothesis and a reference. Params... | bef8033d9b9d7ea9797b5a0fdc7558d388bb0bfd | <|skeleton|>
class JIWERScore:
"""JIWERScore template metric class"""
def __call__(self, hypothesis: Union[str, List[str]], references: Union[str, List[str]], **kwargs) -> float:
"""Compute JIWERScore score of a hypothesis and a reference. Params: hypothesis (str): a hypothesis sentence or a list of hy... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JIWERScore:
"""JIWERScore template metric class"""
def __call__(self, hypothesis: Union[str, List[str]], references: Union[str, List[str]], **kwargs) -> float:
"""Compute JIWERScore score of a hypothesis and a reference. Params: hypothesis (str): a hypothesis sentence or a list of hypothesis sent... | the_stack_v2_python_sparse | platiagro/metrics_nlp/base.py | platiagro/sdk | train | 1 |
a94f4884adfd0d7799ba2af23f876ea46431e9ee | [
"import cv2\nself.window = window\nself.im = im.copy()\nself.keep_window_open = keep_window_open\nself.reset()\nfor pt in default_points:\n self.mouseCallback(cv2.EVENT_LBUTTONDOWN, pt.X(), pt.Y(), None, None)",
"import cv2\nglobal CALLBACK_DICT\ncv2.namedWindow(self.window)\nCALLBACK_DICT[self.window].set(sel... | <|body_start_0|>
import cv2
self.window = window
self.im = im.copy()
self.keep_window_open = keep_window_open
self.reset()
for pt in default_points:
self.mouseCallback(cv2.EVENT_LBUTTONDOWN, pt.X(), pt.Y(), None, None)
<|end_body_0|>
<|body_start_1|>
... | This object handles the data mangagement and display of the capture clicks window. | CaptureClicks | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CaptureClicks:
"""This object handles the data mangagement and display of the capture clicks window."""
def __init__(self, im, default_points=[], keep_window_open=False, window='PyVision Capture Points'):
"""Initialize the data."""
<|body_0|>
def display(self):
"... | stack_v2_sparse_classes_75kplus_train_004918 | 10,211 | permissive | [
{
"docstring": "Initialize the data.",
"name": "__init__",
"signature": "def __init__(self, im, default_points=[], keep_window_open=False, window='PyVision Capture Points')"
},
{
"docstring": "Display the window and run the main event loop.",
"name": "display",
"signature": "def display(... | 4 | stack_v2_sparse_classes_30k_test_001008 | Implement the Python class `CaptureClicks` described below.
Class description:
This object handles the data mangagement and display of the capture clicks window.
Method signatures and docstrings:
- def __init__(self, im, default_points=[], keep_window_open=False, window='PyVision Capture Points'): Initialize the data... | Implement the Python class `CaptureClicks` described below.
Class description:
This object handles the data mangagement and display of the capture clicks window.
Method signatures and docstrings:
- def __init__(self, im, default_points=[], keep_window_open=False, window='PyVision Capture Points'): Initialize the data... | caa4e0254f55c5c8f3464807556b9414ea731293 | <|skeleton|>
class CaptureClicks:
"""This object handles the data mangagement and display of the capture clicks window."""
def __init__(self, im, default_points=[], keep_window_open=False, window='PyVision Capture Points'):
"""Initialize the data."""
<|body_0|>
def display(self):
"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CaptureClicks:
"""This object handles the data mangagement and display of the capture clicks window."""
def __init__(self, im, default_points=[], keep_window_open=False, window='PyVision Capture Points'):
"""Initialize the data."""
import cv2
self.window = window
self.im =... | the_stack_v2_python_sparse | src/pyvision/analysis/gui_tools.py | bolme/pyvision | train | 47 |
cfa77988b8017324c9384e4080bba104396d72f1 | [
"super().__init__()\ninitialize(self, init_type)\nself.discriminators = nn.LayerList()\nfor period in periods:\n params = copy.deepcopy(discriminator_params)\n params['period'] = period\n self.discriminators.append(HiFiGANPeriodDiscriminator(**params))",
"outs = []\nfor f in self.discriminators:\n out... | <|body_start_0|>
super().__init__()
initialize(self, init_type)
self.discriminators = nn.LayerList()
for period in periods:
params = copy.deepcopy(discriminator_params)
params['period'] = period
self.discriminators.append(HiFiGANPeriodDiscriminator(**p... | HiFiGAN multi-period discriminator module. | HiFiGANMultiPeriodDiscriminator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HiFiGANMultiPeriodDiscriminator:
"""HiFiGAN multi-period discriminator module."""
def __init__(self, periods: List[int]=[2, 3, 5, 7, 11], discriminator_params: Dict[str, Any]={'in_channels': 1, 'out_channels': 1, 'kernel_sizes': [5, 3], 'channels': 32, 'downsample_scales': [3, 3, 3, 3, 1], '... | stack_v2_sparse_classes_75kplus_train_004919 | 30,988 | permissive | [
{
"docstring": "Initialize HiFiGANMultiPeriodDiscriminator module. Args: periods (list): List of periods. discriminator_params (dict): Parameters for hifi-gan period discriminator module. The period parameter will be overwritten.",
"name": "__init__",
"signature": "def __init__(self, periods: List[int]=... | 2 | stack_v2_sparse_classes_30k_train_036965 | Implement the Python class `HiFiGANMultiPeriodDiscriminator` described below.
Class description:
HiFiGAN multi-period discriminator module.
Method signatures and docstrings:
- def __init__(self, periods: List[int]=[2, 3, 5, 7, 11], discriminator_params: Dict[str, Any]={'in_channels': 1, 'out_channels': 1, 'kernel_siz... | Implement the Python class `HiFiGANMultiPeriodDiscriminator` described below.
Class description:
HiFiGAN multi-period discriminator module.
Method signatures and docstrings:
- def __init__(self, periods: List[int]=[2, 3, 5, 7, 11], discriminator_params: Dict[str, Any]={'in_channels': 1, 'out_channels': 1, 'kernel_siz... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class HiFiGANMultiPeriodDiscriminator:
"""HiFiGAN multi-period discriminator module."""
def __init__(self, periods: List[int]=[2, 3, 5, 7, 11], discriminator_params: Dict[str, Any]={'in_channels': 1, 'out_channels': 1, 'kernel_sizes': [5, 3], 'channels': 32, 'downsample_scales': [3, 3, 3, 3, 1], '... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HiFiGANMultiPeriodDiscriminator:
"""HiFiGAN multi-period discriminator module."""
def __init__(self, periods: List[int]=[2, 3, 5, 7, 11], discriminator_params: Dict[str, Any]={'in_channels': 1, 'out_channels': 1, 'kernel_sizes': [5, 3], 'channels': 32, 'downsample_scales': [3, 3, 3, 3, 1], 'max_downsampl... | the_stack_v2_python_sparse | paddlespeech/t2s/models/hifigan/hifigan.py | anniyanvr/DeepSpeech-1 | train | 0 |
bdc091f140eaeb47fb0b6a08dccecc8cf0a27717 | [
"course = Course.objects.create(pk=9001, semester_id=1)\nuser = UserProfile.objects.create(pk=9001)\nuser = UserProfile.objects.create(pk=9002, username='1')\nuser = UserProfile.objects.create(pk=9003, username='2')\nquestionnaire = Questionnaire.objects.create(pk=9001, index=0, is_for_contributors=True)\nContribut... | <|body_start_0|>
course = Course.objects.create(pk=9001, semester_id=1)
user = UserProfile.objects.create(pk=9001)
user = UserProfile.objects.create(pk=9002, username='1')
user = UserProfile.objects.create(pk=9003, username='2')
questionnaire = Questionnaire.objects.create(pk=900... | ContributorFormTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContributorFormTests:
def test_dont_validate_deleted_contributions(self):
"""Tests whether contributions marked for deletion are validated. Regression test for #415 and #244"""
<|body_0|>
def test_take_deleted_contributions_into_account(self):
"""Tests whether contri... | stack_v2_sparse_classes_75kplus_train_004920 | 38,195 | no_license | [
{
"docstring": "Tests whether contributions marked for deletion are validated. Regression test for #415 and #244",
"name": "test_dont_validate_deleted_contributions",
"signature": "def test_dont_validate_deleted_contributions(self)"
},
{
"docstring": "Tests whether contributions marked for delet... | 2 | stack_v2_sparse_classes_30k_train_032603 | Implement the Python class `ContributorFormTests` described below.
Class description:
Implement the ContributorFormTests class.
Method signatures and docstrings:
- def test_dont_validate_deleted_contributions(self): Tests whether contributions marked for deletion are validated. Regression test for #415 and #244
- def... | Implement the Python class `ContributorFormTests` described below.
Class description:
Implement the ContributorFormTests class.
Method signatures and docstrings:
- def test_dont_validate_deleted_contributions(self): Tests whether contributions marked for deletion are validated. Regression test for #415 and #244
- def... | 323672d06780258b6b3135f7c4f6c61a3ced1bcb | <|skeleton|>
class ContributorFormTests:
def test_dont_validate_deleted_contributions(self):
"""Tests whether contributions marked for deletion are validated. Regression test for #415 and #244"""
<|body_0|>
def test_take_deleted_contributions_into_account(self):
"""Tests whether contri... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ContributorFormTests:
def test_dont_validate_deleted_contributions(self):
"""Tests whether contributions marked for deletion are validated. Regression test for #415 and #244"""
course = Course.objects.create(pk=9001, semester_id=1)
user = UserProfile.objects.create(pk=9001)
use... | the_stack_v2_python_sparse | evap/staff/tests.py | numberpi/EvaP | train | 1 | |
a29d55f28f67e079f3bac0e8738afaf07b9f5f40 | [
"from test_selenium_1220_01.test_web_weixin.page.add_member_page import AddMember\nself.wait_click(self._location_goto_add_member)\nself.find(self._location_goto_add_member).click()\nreturn AddMember(self.driver)",
"time.sleep(1)\nelements = self.finds(*self._location_member_list)\nmember_list = [i.get_attribute(... | <|body_start_0|>
from test_selenium_1220_01.test_web_weixin.page.add_member_page import AddMember
self.wait_click(self._location_goto_add_member)
self.find(self._location_goto_add_member).click()
return AddMember(self.driver)
<|end_body_0|>
<|body_start_1|>
time.sleep(1)
... | ContactPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContactPage:
def goto_add_member(self):
"""添加成员"""
<|body_0|>
def get_member(self):
"""获取成员列表"""
<|body_1|>
def add_party(self):
"""添加部门"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
from test_selenium_1220_01.test_web_weixin.... | stack_v2_sparse_classes_75kplus_train_004921 | 1,688 | no_license | [
{
"docstring": "添加成员",
"name": "goto_add_member",
"signature": "def goto_add_member(self)"
},
{
"docstring": "获取成员列表",
"name": "get_member",
"signature": "def get_member(self)"
},
{
"docstring": "添加部门",
"name": "add_party",
"signature": "def add_party(self)"
}
] | 3 | stack_v2_sparse_classes_30k_train_034589 | Implement the Python class `ContactPage` described below.
Class description:
Implement the ContactPage class.
Method signatures and docstrings:
- def goto_add_member(self): 添加成员
- def get_member(self): 获取成员列表
- def add_party(self): 添加部门 | Implement the Python class `ContactPage` described below.
Class description:
Implement the ContactPage class.
Method signatures and docstrings:
- def goto_add_member(self): 添加成员
- def get_member(self): 获取成员列表
- def add_party(self): 添加部门
<|skeleton|>
class ContactPage:
def goto_add_member(self):
"""添加成员"... | 68ba225c6340764c21640b041248d27247ff67ef | <|skeleton|>
class ContactPage:
def goto_add_member(self):
"""添加成员"""
<|body_0|>
def get_member(self):
"""获取成员列表"""
<|body_1|>
def add_party(self):
"""添加部门"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ContactPage:
def goto_add_member(self):
"""添加成员"""
from test_selenium_1220_01.test_web_weixin.page.add_member_page import AddMember
self.wait_click(self._location_goto_add_member)
self.find(self._location_goto_add_member).click()
return AddMember(self.driver)
def g... | the_stack_v2_python_sparse | test_selenium_1220_01/test_web_weixin/page/contact_page.py | z944274972/hogwarts | train | 0 | |
075584e4f7ec214881369b5195ec045e1a89427a | [
"with self.subTest(cls=self.graph_cls_identifier):\n graph = self.graph_cls()\n for node in self._basic_nodes():\n self.assertNotIn(node, graph)\n for a, b in itertools.product(self._basic_nodes(), repeat=2):\n self.assertNotIn(edge.Edge[a:b], graph)\n self.assertEqual(len(graph), 0)\n ... | <|body_start_0|>
with self.subTest(cls=self.graph_cls_identifier):
graph = self.graph_cls()
for node in self._basic_nodes():
self.assertNotIn(node, graph)
for a, b in itertools.product(self._basic_nodes(), repeat=2):
self.assertNotIn(edge.Edge[... | GraphInitMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphInitMixin:
def test_init_empty(self):
"""Graph Interface: graph()"""
<|body_0|>
def test_init_iterable(self):
"""Graph Interface: graph(iter(...))"""
<|body_1|>
def test_init_variadic(self):
"""Graph Interface: graph(10, 12, ...)"""
... | stack_v2_sparse_classes_75kplus_train_004922 | 12,391 | permissive | [
{
"docstring": "Graph Interface: graph()",
"name": "test_init_empty",
"signature": "def test_init_empty(self)"
},
{
"docstring": "Graph Interface: graph(iter(...))",
"name": "test_init_iterable",
"signature": "def test_init_iterable(self)"
},
{
"docstring": "Graph Interface: grap... | 6 | null | Implement the Python class `GraphInitMixin` described below.
Class description:
Implement the GraphInitMixin class.
Method signatures and docstrings:
- def test_init_empty(self): Graph Interface: graph()
- def test_init_iterable(self): Graph Interface: graph(iter(...))
- def test_init_variadic(self): Graph Interface:... | Implement the Python class `GraphInitMixin` described below.
Class description:
Implement the GraphInitMixin class.
Method signatures and docstrings:
- def test_init_empty(self): Graph Interface: graph()
- def test_init_iterable(self): Graph Interface: graph(iter(...))
- def test_init_variadic(self): Graph Interface:... | 76b046f25b8cf4a229c54f4e7e830504dab81e7b | <|skeleton|>
class GraphInitMixin:
def test_init_empty(self):
"""Graph Interface: graph()"""
<|body_0|>
def test_init_iterable(self):
"""Graph Interface: graph(iter(...))"""
<|body_1|>
def test_init_variadic(self):
"""Graph Interface: graph(10, 12, ...)"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GraphInitMixin:
def test_init_empty(self):
"""Graph Interface: graph()"""
with self.subTest(cls=self.graph_cls_identifier):
graph = self.graph_cls()
for node in self._basic_nodes():
self.assertNotIn(node, graph)
for a, b in itertools.product(... | the_stack_v2_python_sparse | graphi_unittests/types_unittests/_graph_interface_mixins.py | MaineKuehn/graphi | train | 1 | |
7b59ae44e4df1e2de1517e565703d43b5556bc1e | [
"pygame.sprite.Sprite.__init__(self)\nself.image = pygame.Surface([size, size])\nself.image.fill(color)\nself.velocity = velocity\nself.rect = self.image.get_rect()\nself.rect.x = start_pos[0]\nself.rect.y = start_pos[1]\nself.floating_point_x = start_pos[0]\nself.floating_point_y = start_pos[1]\nx_diff = dest_pos[... | <|body_start_0|>
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface([size, size])
self.image.fill(color)
self.velocity = velocity
self.rect = self.image.get_rect()
self.rect.x = start_pos[0]
self.rect.y = start_pos[1]
self.floating_point_x = s... | This class represents the bullet. | Projectile | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Projectile:
"""This class represents the bullet."""
def __init__(self, start_pos, dest_pos, velocity, size, color):
"""Constructor. start_pos - (int, int) tuple denoting starting coordinates dest_pos - (int, int) tuple denoting ending coordinates velocity - int, speed size - int size... | stack_v2_sparse_classes_75kplus_train_004923 | 2,488 | no_license | [
{
"docstring": "Constructor. start_pos - (int, int) tuple denoting starting coordinates dest_pos - (int, int) tuple denoting ending coordinates velocity - int, speed size - int size of one side of the square projectile color - (int, int, int) r,g,b color of projectile",
"name": "__init__",
"signature": ... | 2 | null | Implement the Python class `Projectile` described below.
Class description:
This class represents the bullet.
Method signatures and docstrings:
- def __init__(self, start_pos, dest_pos, velocity, size, color): Constructor. start_pos - (int, int) tuple denoting starting coordinates dest_pos - (int, int) tuple denoting... | Implement the Python class `Projectile` described below.
Class description:
This class represents the bullet.
Method signatures and docstrings:
- def __init__(self, start_pos, dest_pos, velocity, size, color): Constructor. start_pos - (int, int) tuple denoting starting coordinates dest_pos - (int, int) tuple denoting... | 14d443d856a08892fcb0a7903b66ce2b0b637a33 | <|skeleton|>
class Projectile:
"""This class represents the bullet."""
def __init__(self, start_pos, dest_pos, velocity, size, color):
"""Constructor. start_pos - (int, int) tuple denoting starting coordinates dest_pos - (int, int) tuple denoting ending coordinates velocity - int, speed size - int size... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Projectile:
"""This class represents the bullet."""
def __init__(self, start_pos, dest_pos, velocity, size, color):
"""Constructor. start_pos - (int, int) tuple denoting starting coordinates dest_pos - (int, int) tuple denoting ending coordinates velocity - int, speed size - int size of one side ... | the_stack_v2_python_sparse | keep_away_game/projectile.py | mgzahara/pygame | train | 0 |
5c8858afdae7d40b663d90f047ba8184acf0ef90 | [
"try:\n registration_profile = self.get(activation_key=activation_key)\nexcept self.model.DoesNotExist:\n return None\nif not registration_profile.is_expired():\n user = registration_profile.user\n user.is_active = True\n user.save()\n registration_profile.delete()\n return user\nelse:\n ret... | <|body_start_0|>
try:
registration_profile = self.get(activation_key=activation_key)
except self.model.DoesNotExist:
return None
if not registration_profile.is_expired():
user = registration_profile.user
user.is_active = True
user.save(... | RegistrationManager Methods: activate_account create_inactive_user create_registration_profile | RegistrationManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistrationManager:
"""RegistrationManager Methods: activate_account create_inactive_user create_registration_profile"""
def activate_account(self, activation_key):
"""Activate Account Given an activation key, this function queries the DB to see if there is a matching registration p... | stack_v2_sparse_classes_75kplus_train_004924 | 4,537 | no_license | [
{
"docstring": "Activate Account Given an activation key, this function queries the DB to see if there is a matching registration profile. If there is, the associated user is activated.",
"name": "activate_account",
"signature": "def activate_account(self, activation_key)"
},
{
"docstring": "Cre... | 3 | stack_v2_sparse_classes_30k_train_012544 | Implement the Python class `RegistrationManager` described below.
Class description:
RegistrationManager Methods: activate_account create_inactive_user create_registration_profile
Method signatures and docstrings:
- def activate_account(self, activation_key): Activate Account Given an activation key, this function qu... | Implement the Python class `RegistrationManager` described below.
Class description:
RegistrationManager Methods: activate_account create_inactive_user create_registration_profile
Method signatures and docstrings:
- def activate_account(self, activation_key): Activate Account Given an activation key, this function qu... | e04aae54afb6ba6c138f4253ca7be32faea0da81 | <|skeleton|>
class RegistrationManager:
"""RegistrationManager Methods: activate_account create_inactive_user create_registration_profile"""
def activate_account(self, activation_key):
"""Activate Account Given an activation key, this function queries the DB to see if there is a matching registration p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RegistrationManager:
"""RegistrationManager Methods: activate_account create_inactive_user create_registration_profile"""
def activate_account(self, activation_key):
"""Activate Account Given an activation key, this function queries the DB to see if there is a matching registration profile. If th... | the_stack_v2_python_sparse | src/debitum/accounts/models.py | keunhong/oweapp | train | 0 |
01937a48602655b93701941497a9605e4d6d02e1 | [
"fsm = cls.FSM[operator_type]\nnext_state_info = fsm.get((current_status, event), None)\nreturn next_state_info",
"if current_status is None:\n current_status = shop.status if shop.status else cls.STATUS_INIT\nnext_state = cls.get_next_state(operator_type, current_status, event)\nnext_status = next_state['next... | <|body_start_0|>
fsm = cls.FSM[operator_type]
next_state_info = fsm.get((current_status, event), None)
return next_state_info
<|end_body_0|>
<|body_start_1|>
if current_status is None:
current_status = shop.status if shop.status else cls.STATUS_INIT
next_state = cls.... | 商户有限状态机 | ShopFSM | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShopFSM:
"""商户有限状态机"""
def get_next_state(cls, operator_type, current_status, event):
"""获取下一状态 :param operator_type: 'OUTSIDE'/'FE_INSIDE' :param current_status: 当前状态 :param event: 条件 :return: 如果返回None表示错误状态或条件"""
<|body_0|>
def update_status(cls, operator_type, shop, e... | stack_v2_sparse_classes_75kplus_train_004925 | 6,677 | permissive | [
{
"docstring": "获取下一状态 :param operator_type: 'OUTSIDE'/'FE_INSIDE' :param current_status: 当前状态 :param event: 条件 :return: 如果返回None表示错误状态或条件",
"name": "get_next_state",
"signature": "def get_next_state(cls, operator_type, current_status, event)"
},
{
"docstring": "更新对象的状态 :param operator_type: 'OU... | 2 | stack_v2_sparse_classes_30k_train_003111 | Implement the Python class `ShopFSM` described below.
Class description:
商户有限状态机
Method signatures and docstrings:
- def get_next_state(cls, operator_type, current_status, event): 获取下一状态 :param operator_type: 'OUTSIDE'/'FE_INSIDE' :param current_status: 当前状态 :param event: 条件 :return: 如果返回None表示错误状态或条件
- def update_st... | Implement the Python class `ShopFSM` described below.
Class description:
商户有限状态机
Method signatures and docstrings:
- def get_next_state(cls, operator_type, current_status, event): 获取下一状态 :param operator_type: 'OUTSIDE'/'FE_INSIDE' :param current_status: 当前状态 :param event: 条件 :return: 如果返回None表示错误状态或条件
- def update_st... | a7c9567975b5372b2edabddb0fec8d73bc01c3dc | <|skeleton|>
class ShopFSM:
"""商户有限状态机"""
def get_next_state(cls, operator_type, current_status, event):
"""获取下一状态 :param operator_type: 'OUTSIDE'/'FE_INSIDE' :param current_status: 当前状态 :param event: 条件 :return: 如果返回None表示错误状态或条件"""
<|body_0|>
def update_status(cls, operator_type, shop, e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ShopFSM:
"""商户有限状态机"""
def get_next_state(cls, operator_type, current_status, event):
"""获取下一状态 :param operator_type: 'OUTSIDE'/'FE_INSIDE' :param current_status: 当前状态 :param event: 条件 :return: 如果返回None表示错误状态或条件"""
fsm = cls.FSM[operator_type]
next_state_info = fsm.get((current_st... | the_stack_v2_python_sparse | Dispatcher/data_and_service/shop/model_logics/fsm.py | cash2one/Logistics | train | 0 |
10425653e5a0284cff59494dc06448447e5210b7 | [
"lumMod = self._add_lumMod()\nlumMod.val = value\nreturn lumMod",
"lumOff = self._add_lumOff()\nlumOff.val = value\nreturn lumOff",
"self._remove_lumMod()\nself._remove_lumOff()\nreturn self"
] | <|body_start_0|>
lumMod = self._add_lumMod()
lumMod.val = value
return lumMod
<|end_body_0|>
<|body_start_1|>
lumOff = self._add_lumOff()
lumOff.val = value
return lumOff
<|end_body_1|>
<|body_start_2|>
self._remove_lumMod()
self._remove_lumOff()
... | Base class for <a:srgbClr> and <a:schemeClr> elements. | _BaseColorElement | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _BaseColorElement:
"""Base class for <a:srgbClr> and <a:schemeClr> elements."""
def add_lumMod(self, value):
"""Return a newly added <a:lumMod> child element."""
<|body_0|>
def add_lumOff(self, value):
"""Return a newly added <a:lumOff> child element."""
... | stack_v2_sparse_classes_75kplus_train_004926 | 2,024 | permissive | [
{
"docstring": "Return a newly added <a:lumMod> child element.",
"name": "add_lumMod",
"signature": "def add_lumMod(self, value)"
},
{
"docstring": "Return a newly added <a:lumOff> child element.",
"name": "add_lumOff",
"signature": "def add_lumOff(self, value)"
},
{
"docstring":... | 3 | stack_v2_sparse_classes_30k_train_045815 | Implement the Python class `_BaseColorElement` described below.
Class description:
Base class for <a:srgbClr> and <a:schemeClr> elements.
Method signatures and docstrings:
- def add_lumMod(self, value): Return a newly added <a:lumMod> child element.
- def add_lumOff(self, value): Return a newly added <a:lumOff> child... | Implement the Python class `_BaseColorElement` described below.
Class description:
Base class for <a:srgbClr> and <a:schemeClr> elements.
Method signatures and docstrings:
- def add_lumMod(self, value): Return a newly added <a:lumMod> child element.
- def add_lumOff(self, value): Return a newly added <a:lumOff> child... | cabf6e4f1970dc14302f87414f170de19944bac2 | <|skeleton|>
class _BaseColorElement:
"""Base class for <a:srgbClr> and <a:schemeClr> elements."""
def add_lumMod(self, value):
"""Return a newly added <a:lumMod> child element."""
<|body_0|>
def add_lumOff(self, value):
"""Return a newly added <a:lumOff> child element."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _BaseColorElement:
"""Base class for <a:srgbClr> and <a:schemeClr> elements."""
def add_lumMod(self, value):
"""Return a newly added <a:lumMod> child element."""
lumMod = self._add_lumMod()
lumMod.val = value
return lumMod
def add_lumOff(self, value):
"""Retur... | the_stack_v2_python_sparse | Pdf_docx_pptx_xlsx_epub_png/source/pptx/oxml/dml/color.py | ryfeus/lambda-packs | train | 1,283 |
2d21f9023760d91292f413c50ee3d571a96bbc4b | [
"super(MultiLayerNet, self).__init__()\nself.linear1 = torch.nn.Linear(D_in, H)\nself.linear2 = torch.nn.Linear(H, H)\nself.linear3 = torch.nn.Linear(H, H)\nself.linear4 = torch.nn.Linear(H, D_out)\ntorch.nn.init.constant_(self.linear1.bias, 0.0)\ntorch.nn.init.constant_(self.linear2.bias, 0.0)\ntorch.nn.init.const... | <|body_start_0|>
super(MultiLayerNet, self).__init__()
self.linear1 = torch.nn.Linear(D_in, H)
self.linear2 = torch.nn.Linear(H, H)
self.linear3 = torch.nn.Linear(H, H)
self.linear4 = torch.nn.Linear(H, D_out)
torch.nn.init.constant_(self.linear1.bias, 0.0)
torch.... | MultiLayerNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiLayerNet:
def __init__(self, D_in, H, D_out):
"""In the constructor we instantiate two nn.Linear modules and assign them as member variables."""
<|body_0|>
def forward(self, x):
"""In the forward function we accept a Tensor of input data and we must return a Ten... | stack_v2_sparse_classes_75kplus_train_004927 | 1,418 | no_license | [
{
"docstring": "In the constructor we instantiate two nn.Linear modules and assign them as member variables.",
"name": "__init__",
"signature": "def __init__(self, D_in, H, D_out)"
},
{
"docstring": "In the forward function we accept a Tensor of input data and we must return a Tensor of output d... | 2 | stack_v2_sparse_classes_30k_train_010856 | Implement the Python class `MultiLayerNet` described below.
Class description:
Implement the MultiLayerNet class.
Method signatures and docstrings:
- def __init__(self, D_in, H, D_out): In the constructor we instantiate two nn.Linear modules and assign them as member variables.
- def forward(self, x): In the forward ... | Implement the Python class `MultiLayerNet` described below.
Class description:
Implement the MultiLayerNet class.
Method signatures and docstrings:
- def __init__(self, D_in, H, D_out): In the constructor we instantiate two nn.Linear modules and assign them as member variables.
- def forward(self, x): In the forward ... | ee57bd238820729ada21859c74356ef826641887 | <|skeleton|>
class MultiLayerNet:
def __init__(self, D_in, H, D_out):
"""In the constructor we instantiate two nn.Linear modules and assign them as member variables."""
<|body_0|>
def forward(self, x):
"""In the forward function we accept a Tensor of input data and we must return a Ten... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiLayerNet:
def __init__(self, D_in, H, D_out):
"""In the constructor we instantiate two nn.Linear modules and assign them as member variables."""
super(MultiLayerNet, self).__init__()
self.linear1 = torch.nn.Linear(D_in, H)
self.linear2 = torch.nn.Linear(H, H)
self.... | the_stack_v2_python_sparse | MultiLayerNet.py | MinhNguyenIKM/dem_hyperelasticity | train | 37 | |
23e837416edc28693732454c73afc0c88f004e8c | [
"self.__dict__['RHOST'] = {'value': RHOST, 'required': True, 'description': 'Remote host'}\nself.__dict__['RPORT'] = {'value': RPORT, 'required': True, 'description': 'Remote port'}\nself.__dict__['LHOST'] = {'value': LHOST, 'required': True, 'description': 'Local host'}\nself.__dict__['LPORT'] = {'value': LPORT, '... | <|body_start_0|>
self.__dict__['RHOST'] = {'value': RHOST, 'required': True, 'description': 'Remote host'}
self.__dict__['RPORT'] = {'value': RPORT, 'required': True, 'description': 'Remote port'}
self.__dict__['LHOST'] = {'value': LHOST, 'required': True, 'description': 'Local host'}
se... | Module Class | Module | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Module:
"""Module Class"""
def __init__(self, RHOST=None, RPORT=110, LHOST=None, LPORT=4444):
"""__init__(self, RHOST=None, RPORT=110, LHOST=None, LPORT=4444) :param RHOST: :param RPORT: :param LHOST: :param LPORT: Initialize the module with the module's desired options"""
<|... | stack_v2_sparse_classes_75kplus_train_004928 | 2,734 | no_license | [
{
"docstring": "__init__(self, RHOST=None, RPORT=110, LHOST=None, LPORT=4444) :param RHOST: :param RPORT: :param LHOST: :param LPORT: Initialize the module with the module's desired options",
"name": "__init__",
"signature": "def __init__(self, RHOST=None, RPORT=110, LHOST=None, LPORT=4444)"
},
{
... | 2 | null | Implement the Python class `Module` described below.
Class description:
Module Class
Method signatures and docstrings:
- def __init__(self, RHOST=None, RPORT=110, LHOST=None, LPORT=4444): __init__(self, RHOST=None, RPORT=110, LHOST=None, LPORT=4444) :param RHOST: :param RPORT: :param LHOST: :param LPORT: Initialize t... | Implement the Python class `Module` described below.
Class description:
Module Class
Method signatures and docstrings:
- def __init__(self, RHOST=None, RPORT=110, LHOST=None, LPORT=4444): __init__(self, RHOST=None, RPORT=110, LHOST=None, LPORT=4444) :param RHOST: :param RPORT: :param LHOST: :param LPORT: Initialize t... | 99e1d75b3d1af2e44740584be6c2ef1c1601c43c | <|skeleton|>
class Module:
"""Module Class"""
def __init__(self, RHOST=None, RPORT=110, LHOST=None, LPORT=4444):
"""__init__(self, RHOST=None, RPORT=110, LHOST=None, LPORT=4444) :param RHOST: :param RPORT: :param LHOST: :param LPORT: Initialize the module with the module's desired options"""
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Module:
"""Module Class"""
def __init__(self, RHOST=None, RPORT=110, LHOST=None, LPORT=4444):
"""__init__(self, RHOST=None, RPORT=110, LHOST=None, LPORT=4444) :param RHOST: :param RPORT: :param LHOST: :param LPORT: Initialize the module with the module's desired options"""
self.__dict__['... | the_stack_v2_python_sparse | modules/exploit/slmail_550.py | h4cklife/intrukit | train | 3 |
092bdb9a602ae0f2f00413fa5729592b6f90b7ca | [
"prop = typeFor(ref)\nif not isinstance(prop, TypeProperty):\n return False\nassert isinstance(prop, TypeProperty)\nassert isinstance(prop.parent, TypeContainer), 'Invalid parent for %s' % prop\nif prop.parent.isValid(self):\n descriptor, _clazz = getAttrAndClass(self.__class__, prop.name)\n if not isinsta... | <|body_start_0|>
prop = typeFor(ref)
if not isinstance(prop, TypeProperty):
return False
assert isinstance(prop, TypeProperty)
assert isinstance(prop.parent, TypeContainer), 'Invalid parent for %s' % prop
if prop.parent.isValid(self):
descriptor, _clazz = ... | Support class for containers. | Container | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Container:
"""Support class for containers."""
def __contains__(self, ref):
"""Checks if the object contains a value for the property even if that value is None. @param ref: TypeProperty reference The type property to check. @return: boolean True if a value for the reference is prese... | stack_v2_sparse_classes_75kplus_train_004929 | 16,647 | no_license | [
{
"docstring": "Checks if the object contains a value for the property even if that value is None. @param ref: TypeProperty reference The type property to check. @return: boolean True if a value for the reference is present, false otherwise.",
"name": "__contains__",
"signature": "def __contains__(self,... | 2 | stack_v2_sparse_classes_30k_train_042228 | Implement the Python class `Container` described below.
Class description:
Support class for containers.
Method signatures and docstrings:
- def __contains__(self, ref): Checks if the object contains a value for the property even if that value is None. @param ref: TypeProperty reference The type property to check. @r... | Implement the Python class `Container` described below.
Class description:
Support class for containers.
Method signatures and docstrings:
- def __contains__(self, ref): Checks if the object contains a value for the property even if that value is None. @param ref: TypeProperty reference The type property to check. @r... | e0b3466b34d31548996d57be4a9dac134d904380 | <|skeleton|>
class Container:
"""Support class for containers."""
def __contains__(self, ref):
"""Checks if the object contains a value for the property even if that value is None. @param ref: TypeProperty reference The type property to check. @return: boolean True if a value for the reference is prese... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Container:
"""Support class for containers."""
def __contains__(self, ref):
"""Checks if the object contains a value for the property even if that value is None. @param ref: TypeProperty reference The type property to check. @return: boolean True if a value for the reference is present, false oth... | the_stack_v2_python_sparse | components/ally-api/ally/api/operator/descriptor.py | cristidomsa/Ally-Py | train | 0 |
4f6e88dd0e5d10f92d634e895a6fa98aa80b4751 | [
"max_length = 0\ndp = [[False] * len(s) for _ in range(len(s))]\nfor i in range(len(s)):\n for j in range(i):\n if s[i] == s[j] and (dp[i - 1][j + 1] or i - j <= 2):\n dp[i][j] = True\n if i - j + 1 > max_length:\n max_length = i - j + 1\nreturn max_length",
"max_len... | <|body_start_0|>
max_length = 0
dp = [[False] * len(s) for _ in range(len(s))]
for i in range(len(s)):
for j in range(i):
if s[i] == s[j] and (dp[i - 1][j + 1] or i - j <= 2):
dp[i][j] = True
if i - j + 1 > max_length:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _longestPalindromeSubseq(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def __longestPalindromeSubseq(self, s):
""":type s: str :rtype: int"""
<|body_1|>
def ___longestPalindromeSubseq(self, s):
""":type s: str :rtype: int"""
... | stack_v2_sparse_classes_75kplus_train_004930 | 3,215 | permissive | [
{
"docstring": ":type s: str :rtype: int",
"name": "_longestPalindromeSubseq",
"signature": "def _longestPalindromeSubseq(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "__longestPalindromeSubseq",
"signature": "def __longestPalindromeSubseq(self, s)"
},
{
"docst... | 4 | stack_v2_sparse_classes_30k_train_048104 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _longestPalindromeSubseq(self, s): :type s: str :rtype: int
- def __longestPalindromeSubseq(self, s): :type s: str :rtype: int
- def ___longestPalindromeSubseq(self, s): :typ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _longestPalindromeSubseq(self, s): :type s: str :rtype: int
- def __longestPalindromeSubseq(self, s): :type s: str :rtype: int
- def ___longestPalindromeSubseq(self, s): :typ... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def _longestPalindromeSubseq(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def __longestPalindromeSubseq(self, s):
""":type s: str :rtype: int"""
<|body_1|>
def ___longestPalindromeSubseq(self, s):
""":type s: str :rtype: int"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def _longestPalindromeSubseq(self, s):
""":type s: str :rtype: int"""
max_length = 0
dp = [[False] * len(s) for _ in range(len(s))]
for i in range(len(s)):
for j in range(i):
if s[i] == s[j] and (dp[i - 1][j + 1] or i - j <= 2):
... | the_stack_v2_python_sparse | 516.longest-palindromic-subsequence.py | windard/leeeeee | train | 0 | |
0068036bcd7e6ee8478a6cfae0b47877158018b1 | [
"if file is not None:\n self.isStdin = False\n try:\n fp = open(file, 'r')\n self.lines = []\n for line in fp:\n line = line.replace('\\n', '')\n self.lines.append(line)\n fp.close()\n except:\n ErrorHandler.printError('Error with opening file', Erro... | <|body_start_0|>
if file is not None:
self.isStdin = False
try:
fp = open(file, 'r')
self.lines = []
for line in fp:
line = line.replace('\n', '')
self.lines.append(line)
fp.close()
... | FileHandled encapsulate working with standard input and input files Methods ------- GetLine() Get line from file or call input if input file is not specified Exception --------- Raise EOFError when reading from empty file | FileHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileHandler:
"""FileHandled encapsulate working with standard input and input files Methods ------- GetLine() Get line from file or call input if input file is not specified Exception --------- Raise EOFError when reading from empty file"""
def __init__(self, file):
"""If file is spe... | stack_v2_sparse_classes_75kplus_train_004931 | 1,532 | no_license | [
{
"docstring": "If file is specified, load data into array arguments --------- file - name of file used for standard input for interpreting",
"name": "__init__",
"signature": "def __init__(self, file)"
},
{
"docstring": "Return one line of file which was specified by parameter --input or call in... | 2 | stack_v2_sparse_classes_30k_test_000547 | Implement the Python class `FileHandler` described below.
Class description:
FileHandled encapsulate working with standard input and input files Methods ------- GetLine() Get line from file or call input if input file is not specified Exception --------- Raise EOFError when reading from empty file
Method signatures a... | Implement the Python class `FileHandler` described below.
Class description:
FileHandled encapsulate working with standard input and input files Methods ------- GetLine() Get line from file or call input if input file is not specified Exception --------- Raise EOFError when reading from empty file
Method signatures a... | 64e9d2524b1a0b74be33c1be3d480ad6e17aa2a7 | <|skeleton|>
class FileHandler:
"""FileHandled encapsulate working with standard input and input files Methods ------- GetLine() Get line from file or call input if input file is not specified Exception --------- Raise EOFError when reading from empty file"""
def __init__(self, file):
"""If file is spe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FileHandler:
"""FileHandled encapsulate working with standard input and input files Methods ------- GetLine() Get line from file or call input if input file is not specified Exception --------- Raise EOFError when reading from empty file"""
def __init__(self, file):
"""If file is specified, load ... | the_stack_v2_python_sparse | BIT - Bachelor IT/4.term/IPP - Principles of Programming Languages/Project Interpreter with Parser and Tests/include/interpret/FileHandler.py | sestakp/vut-brno-information-technology | train | 0 |
e03854bf167e891cdae2111754fbedc9f8bea900 | [
"super(ResetPasswordModelForm, self).__init__(*args, **kwargs)\nfor name, field in self.fields.items():\n field.widget.attrs['class'] = 'form-control'",
"password = self.cleaned_data['password']\nr_password = self.cleaned_data['r_password']\nif password != r_password:\n raise ValidationError('两次密码输入不一致')\nr... | <|body_start_0|>
super(ResetPasswordModelForm, self).__init__(*args, **kwargs)
for name, field in self.fields.items():
field.widget.attrs['class'] = 'form-control'
<|end_body_0|>
<|body_start_1|>
password = self.cleaned_data['password']
r_password = self.cleaned_data['r_pass... | 重置密码 | ResetPasswordModelForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResetPasswordModelForm:
"""重置密码"""
def __init__(self, *args, **kwargs):
"""统一给ModelForm字段构建样式 :param args: :param kwargs:"""
<|body_0|>
def clean_r_password(self):
"""钩子函数 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(ResetPassw... | stack_v2_sparse_classes_75kplus_train_004932 | 2,889 | no_license | [
{
"docstring": "统一给ModelForm字段构建样式 :param args: :param kwargs:",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "钩子函数 :return:",
"name": "clean_r_password",
"signature": "def clean_r_password(self)"
}
] | 2 | null | Implement the Python class `ResetPasswordModelForm` described below.
Class description:
重置密码
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): 统一给ModelForm字段构建样式 :param args: :param kwargs:
- def clean_r_password(self): 钩子函数 :return: | Implement the Python class `ResetPasswordModelForm` described below.
Class description:
重置密码
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): 统一给ModelForm字段构建样式 :param args: :param kwargs:
- def clean_r_password(self): 钩子函数 :return:
<|skeleton|>
class ResetPasswordModelForm:
"""重置密码"""
... | 49a95679f028e60e758cf25eaa2469d569a472b2 | <|skeleton|>
class ResetPasswordModelForm:
"""重置密码"""
def __init__(self, *args, **kwargs):
"""统一给ModelForm字段构建样式 :param args: :param kwargs:"""
<|body_0|>
def clean_r_password(self):
"""钩子函数 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResetPasswordModelForm:
"""重置密码"""
def __init__(self, *args, **kwargs):
"""统一给ModelForm字段构建样式 :param args: :param kwargs:"""
super(ResetPasswordModelForm, self).__init__(*args, **kwargs)
for name, field in self.fields.items():
field.widget.attrs['class'] = 'form-contro... | the_stack_v2_python_sparse | rbac/forms/user.py | WuAlin0327/Rbac | train | 1 |
f68e8d93df133ee99060ab7960a68a1e4c1364f4 | [
"matches = []\nfirst_key = keys[0]\nsecond_key = keys[1]\nif isinstance(second_key, (six.string_types, int)):\n if isinstance(map_name, six.string_types):\n mapping = mappings.get(map_name)\n if mapping:\n if isinstance(first_key, (six.string_types, int)):\n if isinstance(... | <|body_start_0|>
matches = []
first_key = keys[0]
second_key = keys[1]
if isinstance(second_key, (six.string_types, int)):
if isinstance(map_name, six.string_types):
mapping = mappings.get(map_name)
if mapping:
if isinstance... | Check if FindInMap values are correct | FindInMapKeys | [
"MIT-0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FindInMapKeys:
"""Check if FindInMap values are correct"""
def check_keys(self, map_name, keys, mappings, tree):
"""Check the validity of the first key"""
<|body_0|>
def match(self, cfn):
"""Check CloudFormation GetAtt"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_75kplus_train_004933 | 3,107 | permissive | [
{
"docstring": "Check the validity of the first key",
"name": "check_keys",
"signature": "def check_keys(self, map_name, keys, mappings, tree)"
},
{
"docstring": "Check CloudFormation GetAtt",
"name": "match",
"signature": "def match(self, cfn)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005890 | Implement the Python class `FindInMapKeys` described below.
Class description:
Check if FindInMap values are correct
Method signatures and docstrings:
- def check_keys(self, map_name, keys, mappings, tree): Check the validity of the first key
- def match(self, cfn): Check CloudFormation GetAtt | Implement the Python class `FindInMapKeys` described below.
Class description:
Check if FindInMap values are correct
Method signatures and docstrings:
- def check_keys(self, map_name, keys, mappings, tree): Check the validity of the first key
- def match(self, cfn): Check CloudFormation GetAtt
<|skeleton|>
class Fin... | 5176573c2f4cb7313998b4bc0bcb0716b58ea380 | <|skeleton|>
class FindInMapKeys:
"""Check if FindInMap values are correct"""
def check_keys(self, map_name, keys, mappings, tree):
"""Check the validity of the first key"""
<|body_0|>
def match(self, cfn):
"""Check CloudFormation GetAtt"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FindInMapKeys:
"""Check if FindInMap values are correct"""
def check_keys(self, map_name, keys, mappings, tree):
"""Check the validity of the first key"""
matches = []
first_key = keys[0]
second_key = keys[1]
if isinstance(second_key, (six.string_types, int)):
... | the_stack_v2_python_sparse | src/cfnlint/rules/functions/FindInMapKeys.py | rene84/cfn-python-lint | train | 1 |
c3b86978378144d924b3b88ca2b7846b87ee74f0 | [
"pk = int_from_request(request.GET, 'project', 1)\nproject = get_object_with_check_and_log(request, Project, pk=pk)\nself.check_object_permissions(request, project)\nparams = {'can_delete_tasks': True, 'can_manage_annotations': True, 'experimental_feature': False}\nreturn Response(get_all_actions(params))",
"pk =... | <|body_start_0|>
pk = int_from_request(request.GET, 'project', 1)
project = get_object_with_check_and_log(request, Project, pk=pk)
self.check_object_permissions(request, project)
params = {'can_delete_tasks': True, 'can_manage_annotations': True, 'experimental_feature': False}
re... | ProjectActionsAPI | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectActionsAPI:
def get(self, request):
"""get: Get actions Retrieve all the registered actions with descriptions that data manager can use."""
<|body_0|>
def post(self, request):
"""post: Post actions Perform an action with the selected items from a specific view... | stack_v2_sparse_classes_75kplus_train_004934 | 12,975 | permissive | [
{
"docstring": "get: Get actions Retrieve all the registered actions with descriptions that data manager can use.",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "post: Post actions Perform an action with the selected items from a specific view.",
"name": "post",
... | 2 | null | Implement the Python class `ProjectActionsAPI` described below.
Class description:
Implement the ProjectActionsAPI class.
Method signatures and docstrings:
- def get(self, request): get: Get actions Retrieve all the registered actions with descriptions that data manager can use.
- def post(self, request): post: Post ... | Implement the Python class `ProjectActionsAPI` described below.
Class description:
Implement the ProjectActionsAPI class.
Method signatures and docstrings:
- def get(self, request): get: Get actions Retrieve all the registered actions with descriptions that data manager can use.
- def post(self, request): post: Post ... | 7c9e5777b7c0fe510b8585ae4c42b74a46929f73 | <|skeleton|>
class ProjectActionsAPI:
def get(self, request):
"""get: Get actions Retrieve all the registered actions with descriptions that data manager can use."""
<|body_0|>
def post(self, request):
"""post: Post actions Perform an action with the selected items from a specific view... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProjectActionsAPI:
def get(self, request):
"""get: Get actions Retrieve all the registered actions with descriptions that data manager can use."""
pk = int_from_request(request.GET, 'project', 1)
project = get_object_with_check_and_log(request, Project, pk=pk)
self.check_object... | the_stack_v2_python_sparse | label_studio/data_manager/api.py | mihirpurwar/label-studio | train | 1 | |
5ebfdeed7b9b9bdaeb5283634e80f3c7442c65b7 | [
"old_password = self.cleaned_data['old_password']\nif not self.user.check_password(old_password):\n raise forms.ValidationError(self.error_messages['password_incorrect'], code='password_incorrect')\nreturn old_password",
"super(CustomPasswordChangeForm, self).__init__(*args, **kwargs)\nself.helper = FormHelper... | <|body_start_0|>
old_password = self.cleaned_data['old_password']
if not self.user.check_password(old_password):
raise forms.ValidationError(self.error_messages['password_incorrect'], code='password_incorrect')
return old_password
<|end_body_0|>
<|body_start_1|>
super(Custom... | A form that lets a user change their password by entering their old password. A slightly modified version of Django's default PasswordChangeForm set up for Crispy Forms | CustomPasswordChangeForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomPasswordChangeForm:
"""A form that lets a user change their password by entering their old password. A slightly modified version of Django's default PasswordChangeForm set up for Crispy Forms"""
def clean_old_password(self):
"""Validates that the old_password field is correct."... | stack_v2_sparse_classes_75kplus_train_004935 | 4,483 | permissive | [
{
"docstring": "Validates that the old_password field is correct.",
"name": "clean_old_password",
"signature": "def clean_old_password(self)"
},
{
"docstring": "Setup the form to work with crispy_forms.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000263 | Implement the Python class `CustomPasswordChangeForm` described below.
Class description:
A form that lets a user change their password by entering their old password. A slightly modified version of Django's default PasswordChangeForm set up for Crispy Forms
Method signatures and docstrings:
- def clean_old_password(... | Implement the Python class `CustomPasswordChangeForm` described below.
Class description:
A form that lets a user change their password by entering their old password. A slightly modified version of Django's default PasswordChangeForm set up for Crispy Forms
Method signatures and docstrings:
- def clean_old_password(... | 1d9edd1959a7d401a76ced29ffbc430017d3dd8b | <|skeleton|>
class CustomPasswordChangeForm:
"""A form that lets a user change their password by entering their old password. A slightly modified version of Django's default PasswordChangeForm set up for Crispy Forms"""
def clean_old_password(self):
"""Validates that the old_password field is correct."... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomPasswordChangeForm:
"""A form that lets a user change their password by entering their old password. A slightly modified version of Django's default PasswordChangeForm set up for Crispy Forms"""
def clean_old_password(self):
"""Validates that the old_password field is correct."""
ol... | the_stack_v2_python_sparse | core/forms/users.py | joshsamara/game-website | train | 3 |
a9d22608bfb1094363b134d8a4321871d713c5ce | [
"super(DIM, self).__init__(model, device)\nself.prob = prob\nself.eps = eps\nself.max_iters = max_iters\nself.flag_target = flag_target\nself.crop_lst = crop_lst\nself.loss = CrossEntropyLoss()",
"xs = xs.to(self.device)\nys = ys.to(self.device)\nxs_ = self.input_transform(xs)\nxs_.requires_grad = True\norigin_xs... | <|body_start_0|>
super(DIM, self).__init__(model, device)
self.prob = prob
self.eps = eps
self.max_iters = max_iters
self.flag_target = flag_target
self.crop_lst = crop_lst
self.loss = CrossEntropyLoss()
<|end_body_0|>
<|body_start_1|>
xs = xs.to(self.dev... | DIM: Diverse Input Method | DIM | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DIM:
"""DIM: Diverse Input Method"""
def __init__(self, model, device, prob=1.0, eps=0.01, max_iters=50, flag_target=False, crop_lst=[0.1, 0.08, 0.06, 0.04, 0.02]):
"""Initialize Diverse Input Method class. Args: model: torch model device: torch.device prob: float, the probability of... | stack_v2_sparse_classes_75kplus_train_004936 | 4,724 | permissive | [
{
"docstring": "Initialize Diverse Input Method class. Args: model: torch model device: torch.device prob: float, the probability of diverse eps: float, epsilon itr_numbers: int, the iteration number flag_target: bool, the target flag crop_lst: list[int], resize list",
"name": "__init__",
"signature": "... | 4 | null | Implement the Python class `DIM` described below.
Class description:
DIM: Diverse Input Method
Method signatures and docstrings:
- def __init__(self, model, device, prob=1.0, eps=0.01, max_iters=50, flag_target=False, crop_lst=[0.1, 0.08, 0.06, 0.04, 0.02]): Initialize Diverse Input Method class. Args: model: torch m... | Implement the Python class `DIM` described below.
Class description:
DIM: Diverse Input Method
Method signatures and docstrings:
- def __init__(self, model, device, prob=1.0, eps=0.01, max_iters=50, flag_target=False, crop_lst=[0.1, 0.08, 0.06, 0.04, 0.02]): Initialize Diverse Input Method class. Args: model: torch m... | 3230044473614d2dd931d96cbd6a3bc974eff926 | <|skeleton|>
class DIM:
"""DIM: Diverse Input Method"""
def __init__(self, model, device, prob=1.0, eps=0.01, max_iters=50, flag_target=False, crop_lst=[0.1, 0.08, 0.06, 0.04, 0.02]):
"""Initialize Diverse Input Method class. Args: model: torch model device: torch.device prob: float, the probability of... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DIM:
"""DIM: Diverse Input Method"""
def __init__(self, model, device, prob=1.0, eps=0.01, max_iters=50, flag_target=False, crop_lst=[0.1, 0.08, 0.06, 0.04, 0.02]):
"""Initialize Diverse Input Method class. Args: model: torch model device: torch.device prob: float, the probability of diverse eps:... | the_stack_v2_python_sparse | advt/attack/dim.py | WindFantasy98/ADVT | train | 0 |
9becb4a634b1e7fabd5aa329cb7572f5456e5b19 | [
"self.filename = filename\nself.sheetname = sheetname\nself.data_list = []\nself.wb = load_workbook(self.filename)\nself.ws = self.wb[sheetname] if sheetname != '' else self.wb.active\nself.max_col = max_col\nself.data_header = tuple(self.ws.iter_rows(max_row=1, max_col=self.max_col, values_only=True))[0]\nself.Cas... | <|body_start_0|>
self.filename = filename
self.sheetname = sheetname
self.data_list = []
self.wb = load_workbook(self.filename)
self.ws = self.wb[sheetname] if sheetname != '' else self.wb.active
self.max_col = max_col
self.data_header = tuple(self.ws.iter_rows(ma... | 封装读写excel的操作 | ExcelHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExcelHandler:
"""封装读写excel的操作"""
def __init__(self, filename, sheetname='', max_col=do_config('excel', 'max_column')):
"""初始化 :param filename: excel文件路径名 :param sheetname: 需要定位的表单名 :param max_col: 读取的最大列数(扣除待写的列)"""
<|body_0|>
def write_excel(self, row, *data_tuple):
... | stack_v2_sparse_classes_75kplus_train_004937 | 3,767 | permissive | [
{
"docstring": "初始化 :param filename: excel文件路径名 :param sheetname: 需要定位的表单名 :param max_col: 读取的最大列数(扣除待写的列)",
"name": "__init__",
"signature": "def __init__(self, filename, sheetname='', max_col=do_config('excel', 'max_column'))"
},
{
"docstring": "写入excel :param row: 单元格的行号 int :param data_tuple... | 3 | stack_v2_sparse_classes_30k_val_000791 | Implement the Python class `ExcelHandler` described below.
Class description:
封装读写excel的操作
Method signatures and docstrings:
- def __init__(self, filename, sheetname='', max_col=do_config('excel', 'max_column')): 初始化 :param filename: excel文件路径名 :param sheetname: 需要定位的表单名 :param max_col: 读取的最大列数(扣除待写的列)
- def write_ex... | Implement the Python class `ExcelHandler` described below.
Class description:
封装读写excel的操作
Method signatures and docstrings:
- def __init__(self, filename, sheetname='', max_col=do_config('excel', 'max_column')): 初始化 :param filename: excel文件路径名 :param sheetname: 需要定位的表单名 :param max_col: 读取的最大列数(扣除待写的列)
- def write_ex... | 8ed884d0e0cb0dac14e26856be19a9a341bef0c0 | <|skeleton|>
class ExcelHandler:
"""封装读写excel的操作"""
def __init__(self, filename, sheetname='', max_col=do_config('excel', 'max_column')):
"""初始化 :param filename: excel文件路径名 :param sheetname: 需要定位的表单名 :param max_col: 读取的最大列数(扣除待写的列)"""
<|body_0|>
def write_excel(self, row, *data_tuple):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExcelHandler:
"""封装读写excel的操作"""
def __init__(self, filename, sheetname='', max_col=do_config('excel', 'max_column')):
"""初始化 :param filename: excel文件路径名 :param sheetname: 需要定位的表单名 :param max_col: 读取的最大列数(扣除待写的列)"""
self.filename = filename
self.sheetname = sheetname
self.... | the_stack_v2_python_sparse | TestMaster/scripts/excelhandler.py | allblue2025/learn_git | train | 0 |
74c45043c8ca7867a70f39bf04aabe86645bfa8f | [
"result = {'code': '1000', 'data': '', 'error': ''}\nif not check_login(token=request.query_params.get('token')):\n result['code'] = '1001'\n result['error'] = 'not valid token!'\n return Response(data=result)\ncabinets = Cabinet.objects.all()\nfor r in cabinets:\n r.machine_num = Client.objects.filter(... | <|body_start_0|>
result = {'code': '1000', 'data': '', 'error': ''}
if not check_login(token=request.query_params.get('token')):
result['code'] = '1001'
result['error'] = 'not valid token!'
return Response(data=result)
cabinets = Cabinet.objects.all()
... | CabinetView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CabinetView:
def get(self, request):
"""获取所有机柜"""
<|body_0|>
def post(self, request):
"""添加机柜"""
<|body_1|>
def put(self, request):
"""修改机柜"""
<|body_2|>
def delete(self, request):
"""删除机房"""
<|body_3|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus_train_004938 | 4,120 | no_license | [
{
"docstring": "获取所有机柜",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "添加机柜",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "修改机柜",
"name": "put",
"signature": "def put(self, request)"
},
{
"docstring": "删除机房",
... | 4 | null | Implement the Python class `CabinetView` described below.
Class description:
Implement the CabinetView class.
Method signatures and docstrings:
- def get(self, request): 获取所有机柜
- def post(self, request): 添加机柜
- def put(self, request): 修改机柜
- def delete(self, request): 删除机房 | Implement the Python class `CabinetView` described below.
Class description:
Implement the CabinetView class.
Method signatures and docstrings:
- def get(self, request): 获取所有机柜
- def post(self, request): 添加机柜
- def put(self, request): 修改机柜
- def delete(self, request): 删除机房
<|skeleton|>
class CabinetView:
def ge... | 75565e674355cb5f8d558e0bb8ef1c2c9b289340 | <|skeleton|>
class CabinetView:
def get(self, request):
"""获取所有机柜"""
<|body_0|>
def post(self, request):
"""添加机柜"""
<|body_1|>
def put(self, request):
"""修改机柜"""
<|body_2|>
def delete(self, request):
"""删除机房"""
<|body_3|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CabinetView:
def get(self, request):
"""获取所有机柜"""
result = {'code': '1000', 'data': '', 'error': ''}
if not check_login(token=request.query_params.get('token')):
result['code'] = '1001'
result['error'] = 'not valid token!'
return Response(data=result... | the_stack_v2_python_sparse | api/views/cabinet_views.py | Sweetbob/om_backend | train | 0 | |
f103224050097ae0ca6e20e4248dac94ae41e41d | [
"self.exname = exname\nself.rbt_server_list = []\namqp_url_list = mdaddr.split(';')\nfor i in amqp_url_list:\n if i:\n self.rbt_server_list.append(i)\nrandom.shuffle(self.rbt_server_list)\nself.current_node_index = 0\nself.mdaddr = mdaddr\nself.connect_rbt_server()",
"for i in range(3):\n res = self.... | <|body_start_0|>
self.exname = exname
self.rbt_server_list = []
amqp_url_list = mdaddr.split(';')
for i in amqp_url_list:
if i:
self.rbt_server_list.append(i)
random.shuffle(self.rbt_server_list)
self.current_node_index = 0
self.mdaddr ... | Rpublish | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rpublish:
def __init__(self, mdaddr, exname='poker_topic'):
"""string mdaddr rabbitmq-serverĵַ Ҫamqpurlʽ amqp://192.168.0.252:5673/ amqp://192.168.0.252:5673/;amqp://192.168.0.252:5674/"""
<|body_0|>
def send(self, topic, args, res, timeout=None):
"""params string to... | stack_v2_sparse_classes_75kplus_train_004939 | 4,289 | no_license | [
{
"docstring": "string mdaddr rabbitmq-serverĵַ Ҫamqpurlʽ amqp://192.168.0.252:5673/ amqp://192.168.0.252:5673/;amqp://192.168.0.252:5674/",
"name": "__init__",
"signature": "def __init__(self, mdaddr, exname='poker_topic')"
},
{
"docstring": "params string topic dict args res args",
"name":... | 6 | null | Implement the Python class `Rpublish` described below.
Class description:
Implement the Rpublish class.
Method signatures and docstrings:
- def __init__(self, mdaddr, exname='poker_topic'): string mdaddr rabbitmq-serverĵַ Ҫamqpurlʽ amqp://192.168.0.252:5673/ amqp://192.168.0.252:5673/;amqp://192.168.0.252:5674/
- def... | Implement the Python class `Rpublish` described below.
Class description:
Implement the Rpublish class.
Method signatures and docstrings:
- def __init__(self, mdaddr, exname='poker_topic'): string mdaddr rabbitmq-serverĵַ Ҫamqpurlʽ amqp://192.168.0.252:5673/ amqp://192.168.0.252:5673/;amqp://192.168.0.252:5674/
- def... | d2e161f3fb957df6502ad49ba5c238fc08bcd4fd | <|skeleton|>
class Rpublish:
def __init__(self, mdaddr, exname='poker_topic'):
"""string mdaddr rabbitmq-serverĵַ Ҫamqpurlʽ amqp://192.168.0.252:5673/ amqp://192.168.0.252:5673/;amqp://192.168.0.252:5674/"""
<|body_0|>
def send(self, topic, args, res, timeout=None):
"""params string to... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Rpublish:
def __init__(self, mdaddr, exname='poker_topic'):
"""string mdaddr rabbitmq-serverĵַ Ҫamqpurlʽ amqp://192.168.0.252:5673/ amqp://192.168.0.252:5673/;amqp://192.168.0.252:5674/"""
self.exname = exname
self.rbt_server_list = []
amqp_url_list = mdaddr.split(';')
... | the_stack_v2_python_sparse | Debao/Match/Rpublish.py | johnwong007/python_framework | train | 0 | |
a8b8280fba60718b8440b4a0db8a88b178dfa5d7 | [
"if comment.ACOrobot:\n user = {'usname': comment.ACOrobot, 'robot': 1}\nelse:\n usid = comment.USid\n from WeiDian.service.SUser import SUser\n from WeiDian.service.SSuperUser import SSuperUser\n if comment.ACOparentid:\n user = SSuperUser().get_one_super_by_suid(usid)\n if user:\n ... | <|body_start_0|>
if comment.ACOrobot:
user = {'usname': comment.ACOrobot, 'robot': 1}
else:
usid = comment.USid
from WeiDian.service.SUser import SUser
from WeiDian.service.SSuperUser import SSuperUser
if comment.ACOparentid:
us... | BaseActivityCommentControl | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseActivityCommentControl:
def fill_user(self, comment):
"""给对象添加一个用户字段"""
<|body_0|>
def fill_comment_apply_for(self, comment):
""""如果既是评论又是回复则添加一个'所回复用户(这里的用户是管理员)'属性"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if comment.ACOrobot:
... | stack_v2_sparse_classes_75kplus_train_004940 | 26,132 | no_license | [
{
"docstring": "给对象添加一个用户字段",
"name": "fill_user",
"signature": "def fill_user(self, comment)"
},
{
"docstring": "\"如果既是评论又是回复则添加一个'所回复用户(这里的用户是管理员)'属性",
"name": "fill_comment_apply_for",
"signature": "def fill_comment_apply_for(self, comment)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000204 | Implement the Python class `BaseActivityCommentControl` described below.
Class description:
Implement the BaseActivityCommentControl class.
Method signatures and docstrings:
- def fill_user(self, comment): 给对象添加一个用户字段
- def fill_comment_apply_for(self, comment): "如果既是评论又是回复则添加一个'所回复用户(这里的用户是管理员)'属性 | Implement the Python class `BaseActivityCommentControl` described below.
Class description:
Implement the BaseActivityCommentControl class.
Method signatures and docstrings:
- def fill_user(self, comment): 给对象添加一个用户字段
- def fill_comment_apply_for(self, comment): "如果既是评论又是回复则添加一个'所回复用户(这里的用户是管理员)'属性
<|skeleton|>
clas... | 50c95b9b8ba10d911e00b521affa4309f5dc20ec | <|skeleton|>
class BaseActivityCommentControl:
def fill_user(self, comment):
"""给对象添加一个用户字段"""
<|body_0|>
def fill_comment_apply_for(self, comment):
""""如果既是评论又是回复则添加一个'所回复用户(这里的用户是管理员)'属性"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseActivityCommentControl:
def fill_user(self, comment):
"""给对象添加一个用户字段"""
if comment.ACOrobot:
user = {'usname': comment.ACOrobot, 'robot': 1}
else:
usid = comment.USid
from WeiDian.service.SUser import SUser
from WeiDian.service.SSuper... | the_stack_v2_python_sparse | WeiDian/control/BaseControl.py | clove2han/Weidian | train | 0 | |
92007de2dbf804ea7f42be3bc6c02559e3186034 | [
"res = physics.model.hfield_nrow[_HEIGHTFIELD_ID]\nassert res == physics.model.hfield_ncol[_HEIGHTFIELD_ID]\nrow_grid, col_grid = np.ogrid[-1:1:res * 1j, -1:1:res * 1j]\nradius = np.clip(np.sqrt(col_grid ** 2 + row_grid ** 2), 0.04, 1)\nbowl_shape = 0.5 - np.cos(2 * np.pi * radius) / 2\nterrain_size = 2 * physics.m... | <|body_start_0|>
res = physics.model.hfield_nrow[_HEIGHTFIELD_ID]
assert res == physics.model.hfield_ncol[_HEIGHTFIELD_ID]
row_grid, col_grid = np.ogrid[-1:1:res * 1j, -1:1:res * 1j]
radius = np.clip(np.sqrt(col_grid ** 2 + row_grid ** 2), 0.04, 1)
bowl_shape = 0.5 - np.cos(2 * n... | A quadruped task solved by escaping a bowl-shaped terrain. | Escape | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Escape:
"""A quadruped task solved by escaping a bowl-shaped terrain."""
def initialize_episode(self, physics):
"""Sets the state of the environment at the start of each episode. Args: physics: An instance of `Physics`."""
<|body_0|>
def get_observation(self, physics):
... | stack_v2_sparse_classes_75kplus_train_004941 | 17,995 | permissive | [
{
"docstring": "Sets the state of the environment at the start of each episode. Args: physics: An instance of `Physics`.",
"name": "initialize_episode",
"signature": "def initialize_episode(self, physics)"
},
{
"docstring": "Returns an observation to the agent.",
"name": "get_observation",
... | 3 | stack_v2_sparse_classes_30k_train_036675 | Implement the Python class `Escape` described below.
Class description:
A quadruped task solved by escaping a bowl-shaped terrain.
Method signatures and docstrings:
- def initialize_episode(self, physics): Sets the state of the environment at the start of each episode. Args: physics: An instance of `Physics`.
- def g... | Implement the Python class `Escape` described below.
Class description:
A quadruped task solved by escaping a bowl-shaped terrain.
Method signatures and docstrings:
- def initialize_episode(self, physics): Sets the state of the environment at the start of each episode. Args: physics: An instance of `Physics`.
- def g... | 33d3ea2682409ee82bf9c5129ceaf06ab01cd48e | <|skeleton|>
class Escape:
"""A quadruped task solved by escaping a bowl-shaped terrain."""
def initialize_episode(self, physics):
"""Sets the state of the environment at the start of each episode. Args: physics: An instance of `Physics`."""
<|body_0|>
def get_observation(self, physics):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Escape:
"""A quadruped task solved by escaping a bowl-shaped terrain."""
def initialize_episode(self, physics):
"""Sets the state of the environment at the start of each episode. Args: physics: An instance of `Physics`."""
res = physics.model.hfield_nrow[_HEIGHTFIELD_ID]
assert re... | the_stack_v2_python_sparse | src/env/dm_control/dm_control/suite/quadruped.py | nicklashansen/svea-vit | train | 16 |
6c9ebf1040fd6dc5d277ff49afaba6c080d7106a | [
"expressed_article = self.get_article(slug)\nresponse, status_ = dislikeReaction.mofidy_reaction(expressed_article, request.user, self.reaction, 'article')\nreturn Response(response, status=status_)",
"try:\n article = Article.objects.get(slug=art)\nexcept Exception as ex:\n print(ex)\n raise exceptions.... | <|body_start_0|>
expressed_article = self.get_article(slug)
response, status_ = dislikeReaction.mofidy_reaction(expressed_article, request.user, self.reaction, 'article')
return Response(response, status=status_)
<|end_body_0|>
<|body_start_1|>
try:
article = Article.objects... | Allows user to post reactions to an article | UserReactionView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserReactionView:
"""Allows user to post reactions to an article"""
def post(self, request, slug):
"""Posts a like or dislike to an article from an autheticated user."""
<|body_0|>
def get_article(self, art):
"""Fetches and returns an article instance given its s... | stack_v2_sparse_classes_75kplus_train_004942 | 2,525 | permissive | [
{
"docstring": "Posts a like or dislike to an article from an autheticated user.",
"name": "post",
"signature": "def post(self, request, slug)"
},
{
"docstring": "Fetches and returns an article instance given its slug field",
"name": "get_article",
"signature": "def get_article(self, art... | 2 | stack_v2_sparse_classes_30k_test_000874 | Implement the Python class `UserReactionView` described below.
Class description:
Allows user to post reactions to an article
Method signatures and docstrings:
- def post(self, request, slug): Posts a like or dislike to an article from an autheticated user.
- def get_article(self, art): Fetches and returns an article... | Implement the Python class `UserReactionView` described below.
Class description:
Allows user to post reactions to an article
Method signatures and docstrings:
- def post(self, request, slug): Posts a like or dislike to an article from an autheticated user.
- def get_article(self, art): Fetches and returns an article... | b80ad485339dbb02b74d9b2093543bf8173d51de | <|skeleton|>
class UserReactionView:
"""Allows user to post reactions to an article"""
def post(self, request, slug):
"""Posts a like or dislike to an article from an autheticated user."""
<|body_0|>
def get_article(self, art):
"""Fetches and returns an article instance given its s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserReactionView:
"""Allows user to post reactions to an article"""
def post(self, request, slug):
"""Posts a like or dislike to an article from an autheticated user."""
expressed_article = self.get_article(slug)
response, status_ = dislikeReaction.mofidy_reaction(expressed_articl... | the_stack_v2_python_sparse | authors/apps/reactions/views.py | deferral/ah-django | train | 1 |
a1db7aadbeb658a757b76d8f33eaf5a3baab6ac2 | [
"self.sequence = sequence\nself.sequence_length = len(sequence)\nself.mutations = mutations",
"if maximum_number_of_mutations > self.sequence_length:\n logger.warning(f'resetting maximum number of mutations ({maximum_number_of_mutations}), since it is higher than sequence length: {self.sequence_length}')\n ... | <|body_start_0|>
self.sequence = sequence
self.sequence_length = len(sequence)
self.mutations = mutations
<|end_body_0|>
<|body_start_1|>
if maximum_number_of_mutations > self.sequence_length:
logger.warning(f'resetting maximum number of mutations ({maximum_number_of_mutatio... | AASequence | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AASequence:
def __init__(self, sequence: str, mutations: Mutations=Mutations(IUPAC_MUTATION_MAPPING)) -> None:
"""Initialize an AA sequence representation. Args: sequence: AA sequence. mutations: mutations definition. Defaults to uniform sampling of IUPAC AAs."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_004943 | 17,866 | permissive | [
{
"docstring": "Initialize an AA sequence representation. Args: sequence: AA sequence. mutations: mutations definition. Defaults to uniform sampling of IUPAC AAs.",
"name": "__init__",
"signature": "def __init__(self, sequence: str, mutations: Mutations=Mutations(IUPAC_MUTATION_MAPPING)) -> None"
},
... | 2 | stack_v2_sparse_classes_30k_train_053904 | Implement the Python class `AASequence` described below.
Class description:
Implement the AASequence class.
Method signatures and docstrings:
- def __init__(self, sequence: str, mutations: Mutations=Mutations(IUPAC_MUTATION_MAPPING)) -> None: Initialize an AA sequence representation. Args: sequence: AA sequence. muta... | Implement the Python class `AASequence` described below.
Class description:
Implement the AASequence class.
Method signatures and docstrings:
- def __init__(self, sequence: str, mutations: Mutations=Mutations(IUPAC_MUTATION_MAPPING)) -> None: Initialize an AA sequence representation. Args: sequence: AA sequence. muta... | 0b69b7d5b261f2f9af3984793c1295b9b80cd01a | <|skeleton|>
class AASequence:
def __init__(self, sequence: str, mutations: Mutations=Mutations(IUPAC_MUTATION_MAPPING)) -> None:
"""Initialize an AA sequence representation. Args: sequence: AA sequence. mutations: mutations definition. Defaults to uniform sampling of IUPAC AAs."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AASequence:
def __init__(self, sequence: str, mutations: Mutations=Mutations(IUPAC_MUTATION_MAPPING)) -> None:
"""Initialize an AA sequence representation. Args: sequence: AA sequence. mutations: mutations definition. Defaults to uniform sampling of IUPAC AAs."""
self.sequence = sequence
... | the_stack_v2_python_sparse | src/gt4sd/frameworks/enzeptional/optimization.py | GT4SD/gt4sd-core | train | 239 | |
ea96fc1c304b5ecc216f370fc60e534002ba147f | [
"if elapsed >= self.dist[node]:\n return\nself.dist[node] = elapsed\nfor dest, w in self.G[node]:\n self.dfs(dest, elapsed + w)\nreturn",
"self.dist = {node: float('inf') for node in range(1, n + 1)}\nself.G = defaultdict(list)\nfor src, dest, w in times:\n self.G[src].append((dest, w))\nself.dfs(k, 0)\n... | <|body_start_0|>
if elapsed >= self.dist[node]:
return
self.dist[node] = elapsed
for dest, w in self.G[node]:
self.dfs(dest, elapsed + w)
return
<|end_body_0|>
<|body_start_1|>
self.dist = {node: float('inf') for node in range(1, n + 1)}
self.G = ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def dfs(self, node, elapsed):
"""node: source elapsed: current time spent from origin"""
<|body_0|>
def networkDelayTime(self, times, n, k):
"""times: weighted graph n: number of nodes k: origin"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_004944 | 1,150 | no_license | [
{
"docstring": "node: source elapsed: current time spent from origin",
"name": "dfs",
"signature": "def dfs(self, node, elapsed)"
},
{
"docstring": "times: weighted graph n: number of nodes k: origin",
"name": "networkDelayTime",
"signature": "def networkDelayTime(self, times, n, k)"
}... | 2 | stack_v2_sparse_classes_30k_train_033616 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dfs(self, node, elapsed): node: source elapsed: current time spent from origin
- def networkDelayTime(self, times, n, k): times: weighted graph n: number of nodes k: origin | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dfs(self, node, elapsed): node: source elapsed: current time spent from origin
- def networkDelayTime(self, times, n, k): times: weighted graph n: number of nodes k: origin
... | 51ddadb0c61fe3dd757fb5227ab577acad13112f | <|skeleton|>
class Solution:
def dfs(self, node, elapsed):
"""node: source elapsed: current time spent from origin"""
<|body_0|>
def networkDelayTime(self, times, n, k):
"""times: weighted graph n: number of nodes k: origin"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def dfs(self, node, elapsed):
"""node: source elapsed: current time spent from origin"""
if elapsed >= self.dist[node]:
return
self.dist[node] = elapsed
for dest, w in self.G[node]:
self.dfs(dest, elapsed + w)
return
def networkDel... | the_stack_v2_python_sparse | 743. Network Delay Time/sol1.py | 5410tiffany/leetcode | train | 0 | |
f06cbc99a8a03f8dff2a9441316ee7736eaa9b6e | [
"u = kwargs.get('u', '')\ngroup = kwargs.get('group', '')\nerror = kwargs.get('error', '')\nsite_name = kwargs.get('site_name', '')\nregistry_url = ''\nbounces: List[Url] = []\nurl = Url(u)\nif url.domain in self.alturl_domains:\n redirect_url = cherrypy.engine.publish('app_url', url.alt).pop()\n raise cherry... | <|body_start_0|>
u = kwargs.get('u', '')
group = kwargs.get('group', '')
error = kwargs.get('error', '')
site_name = kwargs.get('site_name', '')
registry_url = ''
bounces: List[Url] = []
url = Url(u)
if url.domain in self.alturl_domains:
redire... | Controller | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Controller:
def GET(self, **kwargs: str) -> bytes:
"""Display all the URLs in a group."""
<|body_0|>
def POST(url: str, name: str, group: str) -> None:
"""Add a new URL to a group."""
<|body_1|>
def url_to_group(self, host: str='') -> str:
"""Red... | stack_v2_sparse_classes_75kplus_train_004945 | 4,331 | no_license | [
{
"docstring": "Display all the URLs in a group.",
"name": "GET",
"signature": "def GET(self, **kwargs: str) -> bytes"
},
{
"docstring": "Add a new URL to a group.",
"name": "POST",
"signature": "def POST(url: str, name: str, group: str) -> None"
},
{
"docstring": "Reduce a URL t... | 4 | stack_v2_sparse_classes_30k_train_045987 | Implement the Python class `Controller` described below.
Class description:
Implement the Controller class.
Method signatures and docstrings:
- def GET(self, **kwargs: str) -> bytes: Display all the URLs in a group.
- def POST(url: str, name: str, group: str) -> None: Add a new URL to a group.
- def url_to_group(self... | Implement the Python class `Controller` described below.
Class description:
Implement the Controller class.
Method signatures and docstrings:
- def GET(self, **kwargs: str) -> bytes: Display all the URLs in a group.
- def POST(url: str, name: str, group: str) -> None: Add a new URL to a group.
- def url_to_group(self... | 7129415303b94d5d10b2c29ec432f0c7d41cc651 | <|skeleton|>
class Controller:
def GET(self, **kwargs: str) -> bytes:
"""Display all the URLs in a group."""
<|body_0|>
def POST(url: str, name: str, group: str) -> None:
"""Add a new URL to a group."""
<|body_1|>
def url_to_group(self, host: str='') -> str:
"""Red... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Controller:
def GET(self, **kwargs: str) -> bytes:
"""Display all the URLs in a group."""
u = kwargs.get('u', '')
group = kwargs.get('group', '')
error = kwargs.get('error', '')
site_name = kwargs.get('site_name', '')
registry_url = ''
bounces: List[Url]... | the_stack_v2_python_sparse | apps/bounce/main.py | lovett/medley | train | 6 | |
2bc66dc897591aaf23b0c2fdf338663a4c8241ed | [
"def postorder(root, result):\n if root:\n postorder(root.left, result)\n postorder(root.right, result)\n result.append(root.val)\nresult = []\npostorder(root, result)\nreturn result",
"def preorderRightFirst(root):\n result, stack = ([], [root])\n while stack:\n node = stack.... | <|body_start_0|>
def postorder(root, result):
if root:
postorder(root.left, result)
postorder(root.right, result)
result.append(root.val)
result = []
postorder(root, result)
return result
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def postorderTraversal_recursive(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def postorderTraversal_iterative1(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
def postorderTraversal_iterative2(self,... | stack_v2_sparse_classes_75kplus_train_004946 | 2,243 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "postorderTraversal_recursive",
"signature": "def postorderTraversal_recursive(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "postorderTraversal_iterative1",
"signature": "def postorderTra... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def postorderTraversal_recursive(self, root): :type root: TreeNode :rtype: List[int]
- def postorderTraversal_iterative1(self, root): :type root: TreeNode :rtype: List[int]
- def... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def postorderTraversal_recursive(self, root): :type root: TreeNode :rtype: List[int]
- def postorderTraversal_iterative1(self, root): :type root: TreeNode :rtype: List[int]
- def... | 9ac54720f571a4bea09d0cceb0039381a78df9e8 | <|skeleton|>
class Solution:
def postorderTraversal_recursive(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def postorderTraversal_iterative1(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
def postorderTraversal_iterative2(self,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def postorderTraversal_recursive(self, root):
""":type root: TreeNode :rtype: List[int]"""
def postorder(root, result):
if root:
postorder(root.left, result)
postorder(root.right, result)
result.append(root.val)
resu... | the_stack_v2_python_sparse | code/145_binary-tree-postorder-traversal.py | linhdvu14/leetcode-solutions | train | 2 | |
2ca0e3ac9d63fe09a12c9c9bc6c738ed9b81a542 | [
"sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nprint('socket instantiated')\nif server_ip:\n HOST = server_ip\nelse:\n HOST = default_host\nprint('Using Server IP: ' + HOST)\nconnectionSuccessful = False\nwhile True:\n if not connectionSuccessful:\n try:\n sock.connect((HOST, ... | <|body_start_0|>
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('socket instantiated')
if server_ip:
HOST = server_ip
else:
HOST = default_host
print('Using Server IP: ' + HOST)
connectionSuccessful = False
while True:
... | Client | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Client:
def startClient(self, player, server_ip):
"""starts client socket which accepts server messages"""
<|body_0|>
def socket_read_n(self, sock, n):
"""Read exactly n bytes from the socket. Raise RuntimeError if the connection closed before n bytes were read."""
... | stack_v2_sparse_classes_75kplus_train_004947 | 4,093 | no_license | [
{
"docstring": "starts client socket which accepts server messages",
"name": "startClient",
"signature": "def startClient(self, player, server_ip)"
},
{
"docstring": "Read exactly n bytes from the socket. Raise RuntimeError if the connection closed before n bytes were read.",
"name": "socket... | 3 | stack_v2_sparse_classes_30k_test_000424 | Implement the Python class `Client` described below.
Class description:
Implement the Client class.
Method signatures and docstrings:
- def startClient(self, player, server_ip): starts client socket which accepts server messages
- def socket_read_n(self, sock, n): Read exactly n bytes from the socket. Raise RuntimeEr... | Implement the Python class `Client` described below.
Class description:
Implement the Client class.
Method signatures and docstrings:
- def startClient(self, player, server_ip): starts client socket which accepts server messages
- def socket_read_n(self, sock, n): Read exactly n bytes from the socket. Raise RuntimeEr... | bc1e5005467c96ca1f78ef6724fb0c71986747b6 | <|skeleton|>
class Client:
def startClient(self, player, server_ip):
"""starts client socket which accepts server messages"""
<|body_0|>
def socket_read_n(self, sock, n):
"""Read exactly n bytes from the socket. Raise RuntimeError if the connection closed before n bytes were read."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Client:
def startClient(self, player, server_ip):
"""starts client socket which accepts server messages"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('socket instantiated')
if server_ip:
HOST = server_ip
else:
HOST = default_h... | the_stack_v2_python_sparse | football_robots/networking/socketClient.py | clagger/footballrobots | train | 0 | |
ebec1c7b19099ff206c70ca4350ebff1b1651e90 | [
"m = len(grid)\nif m > 0:\n n = len(grid[0])\nelse:\n return 0\ncost = [[0 for _ in range(n)] for _ in range(m)]\ncost[0][0] = grid[0][0]\nfor j in range(1, n):\n cost[0][j] = grid[0][j] = grid[0][j] + cost[0][j - 1]\nfor i in range(1, m):\n cost[i][0] = grid[i][0] + cost[i - 1][0]\nfor i in range(1, m)... | <|body_start_0|>
m = len(grid)
if m > 0:
n = len(grid[0])
else:
return 0
cost = [[0 for _ in range(n)] for _ in range(m)]
cost[0][0] = grid[0][0]
for j in range(1, n):
cost[0][j] = grid[0][j] = grid[0][j] + cost[0][j - 1]
for i ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minPathSum(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_0|>
def minPathSum0(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
m = len(grid)
if m > 0:
... | stack_v2_sparse_classes_75kplus_train_004948 | 1,214 | no_license | [
{
"docstring": ":type grid: List[List[int]] :rtype: int",
"name": "minPathSum",
"signature": "def minPathSum(self, grid)"
},
{
"docstring": ":type grid: List[List[int]] :rtype: int",
"name": "minPathSum0",
"signature": "def minPathSum0(self, grid)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000584 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minPathSum(self, grid): :type grid: List[List[int]] :rtype: int
- def minPathSum0(self, grid): :type grid: List[List[int]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minPathSum(self, grid): :type grid: List[List[int]] :rtype: int
- def minPathSum0(self, grid): :type grid: List[List[int]] :rtype: int
<|skeleton|>
class Solution:
def ... | 9e49b2c6003b957276737005d4aaac276b44d251 | <|skeleton|>
class Solution:
def minPathSum(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_0|>
def minPathSum0(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minPathSum(self, grid):
""":type grid: List[List[int]] :rtype: int"""
m = len(grid)
if m > 0:
n = len(grid[0])
else:
return 0
cost = [[0 for _ in range(n)] for _ in range(m)]
cost[0][0] = grid[0][0]
for j in range(1,... | the_stack_v2_python_sparse | PythonCode/src/0064_Minimum_Path_Sum.py | oneyuan/CodeforFun | train | 0 | |
44bf3002ed9767f038b4a469a2e181268abdd726 | [
"self.cosmology = cosmology\nself.settings_lens = settings_lens or SettingsLens()\nself.positions_likelihood = positions_likelihood",
"if hasattr(instance, 'perturbation'):\n instance.galaxies.subhalo = instance.perturbation\nif hasattr(instance.galaxies, 'subhalo'):\n subhalo_centre = ray_tracing_util.grid... | <|body_start_0|>
self.cosmology = cosmology
self.settings_lens = settings_lens or SettingsLens()
self.positions_likelihood = positions_likelihood
<|end_body_0|>
<|body_start_1|>
if hasattr(instance, 'perturbation'):
instance.galaxies.subhalo = instance.perturbation
i... | AnalysisLensing | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnalysisLensing:
def __init__(self, positions_likelihood: Optional[Union[PositionsLHResample, PositionsLHPenalty]]=None, settings_lens: SettingsLens=SettingsLens(), cosmology: ag.cosmo.LensingCosmology=ag.cosmo.Planck15()):
"""Analysis classes are used by PyAutoFit to fit a model to a da... | stack_v2_sparse_classes_75kplus_train_004949 | 18,150 | permissive | [
{
"docstring": "Analysis classes are used by PyAutoFit to fit a model to a dataset via a non-linear search. This abstract Analysis class has attributes and methods for all model-fits which include lensing calculations, but does not perform a model-fit by itself (and is therefore only inherited from). This class... | 3 | stack_v2_sparse_classes_30k_train_021242 | Implement the Python class `AnalysisLensing` described below.
Class description:
Implement the AnalysisLensing class.
Method signatures and docstrings:
- def __init__(self, positions_likelihood: Optional[Union[PositionsLHResample, PositionsLHPenalty]]=None, settings_lens: SettingsLens=SettingsLens(), cosmology: ag.co... | Implement the Python class `AnalysisLensing` described below.
Class description:
Implement the AnalysisLensing class.
Method signatures and docstrings:
- def __init__(self, positions_likelihood: Optional[Union[PositionsLHResample, PositionsLHPenalty]]=None, settings_lens: SettingsLens=SettingsLens(), cosmology: ag.co... | b31b9d7c8a55d7232695761a41383cb1cc30bd76 | <|skeleton|>
class AnalysisLensing:
def __init__(self, positions_likelihood: Optional[Union[PositionsLHResample, PositionsLHPenalty]]=None, settings_lens: SettingsLens=SettingsLens(), cosmology: ag.cosmo.LensingCosmology=ag.cosmo.Planck15()):
"""Analysis classes are used by PyAutoFit to fit a model to a da... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AnalysisLensing:
def __init__(self, positions_likelihood: Optional[Union[PositionsLHResample, PositionsLHPenalty]]=None, settings_lens: SettingsLens=SettingsLens(), cosmology: ag.cosmo.LensingCosmology=ag.cosmo.Planck15()):
"""Analysis classes are used by PyAutoFit to fit a model to a dataset via a no... | the_stack_v2_python_sparse | autolens/analysis/analysis.py | Jammy2211/PyAutoLens | train | 142 | |
4af42443f391d01315c43a1d592444bedb4c99ae | [
"super().__init__(project, name)\nif project.py_debug:\n uses_limited_api = False\nelif uses_limited_api and (not project.sip_module):\n raise UserException(\"{0} cannot use the limited API without using a shared 'sip' module\".format(name))\nself.target = target\nself.uses_limited_api = uses_limited_api\nsel... | <|body_start_0|>
super().__init__(project, name)
if project.py_debug:
uses_limited_api = False
elif uses_limited_api and (not project.sip_module):
raise UserException("{0} cannot use the limited API without using a shared 'sip' module".format(name))
self.target = ... | Encapsulate the sources used to build an extension module, executable etc. | BuildableFromSources | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BuildableFromSources:
"""Encapsulate the sources used to build an extension module, executable etc."""
def __init__(self, project, name, target, *, uses_limited_api=False):
"""Initialise the buildable."""
<|body_0|>
def make_names_relative(self):
"""Make all file... | stack_v2_sparse_classes_75kplus_train_004950 | 7,122 | permissive | [
{
"docstring": "Initialise the buildable.",
"name": "__init__",
"signature": "def __init__(self, project, name, target, *, uses_limited_api=False)"
},
{
"docstring": "Make all file and directory names relative to the build directory.",
"name": "make_names_relative",
"signature": "def mak... | 3 | null | Implement the Python class `BuildableFromSources` described below.
Class description:
Encapsulate the sources used to build an extension module, executable etc.
Method signatures and docstrings:
- def __init__(self, project, name, target, *, uses_limited_api=False): Initialise the buildable.
- def make_names_relative... | Implement the Python class `BuildableFromSources` described below.
Class description:
Encapsulate the sources used to build an extension module, executable etc.
Method signatures and docstrings:
- def __init__(self, project, name, target, *, uses_limited_api=False): Initialise the buildable.
- def make_names_relative... | 9110cc1e1ba7144f1aeff26ade523445aaa00fa0 | <|skeleton|>
class BuildableFromSources:
"""Encapsulate the sources used to build an extension module, executable etc."""
def __init__(self, project, name, target, *, uses_limited_api=False):
"""Initialise the buildable."""
<|body_0|>
def make_names_relative(self):
"""Make all file... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BuildableFromSources:
"""Encapsulate the sources used to build an extension module, executable etc."""
def __init__(self, project, name, target, *, uses_limited_api=False):
"""Initialise the buildable."""
super().__init__(project, name)
if project.py_debug:
uses_limite... | the_stack_v2_python_sparse | venv/Lib/site-packages/sipbuild/buildable.py | DoesArt-Studios/RamBrowse | train | 1 |
011fd74f7ee1e5058d89451fb37547bc94af2209 | [
"logger.debug('Parsing request object to XML')\ntry:\n xml = xmltodict.unparse(request.normalize_xml())\nexcept Exception as e:\n error_msg = 'Error parsing request to XML'\n logger.error('{}: {}'.format(error_msg, e))\n raise SdkError(error_msg, e)\nreturn xml",
"logger.debug('Parsing XML response to... | <|body_start_0|>
logger.debug('Parsing request object to XML')
try:
xml = xmltodict.unparse(request.normalize_xml())
except Exception as e:
error_msg = 'Error parsing request to XML'
logger.error('{}: {}'.format(error_msg, e))
raise SdkError(error_... | Utils to serialize and deserialize objects to XML | XmlUtils | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XmlUtils:
"""Utils to serialize and deserialize objects to XML"""
def to_xml(request):
"""This method parse request to XML object :return: string"""
<|body_0|>
def from_xml_api_response(xml):
"""Method parse XML to dict. :param xml: string :return: dict"""
... | stack_v2_sparse_classes_75kplus_train_004951 | 1,447 | permissive | [
{
"docstring": "This method parse request to XML object :return: string",
"name": "to_xml",
"signature": "def to_xml(request)"
},
{
"docstring": "Method parse XML to dict. :param xml: string :return: dict",
"name": "from_xml_api_response",
"signature": "def from_xml_api_response(xml)"
... | 2 | stack_v2_sparse_classes_30k_train_002028 | Implement the Python class `XmlUtils` described below.
Class description:
Utils to serialize and deserialize objects to XML
Method signatures and docstrings:
- def to_xml(request): This method parse request to XML object :return: string
- def from_xml_api_response(xml): Method parse XML to dict. :param xml: string :r... | Implement the Python class `XmlUtils` described below.
Class description:
Utils to serialize and deserialize objects to XML
Method signatures and docstrings:
- def to_xml(request): This method parse request to XML object :return: string
- def from_xml_api_response(xml): Method parse XML to dict. :param xml: string :r... | 8fcf2a0e9d6d99d18e313f04b9721ccc4769a83f | <|skeleton|>
class XmlUtils:
"""Utils to serialize and deserialize objects to XML"""
def to_xml(request):
"""This method parse request to XML object :return: string"""
<|body_0|>
def from_xml_api_response(xml):
"""Method parse XML to dict. :param xml: string :return: dict"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class XmlUtils:
"""Utils to serialize and deserialize objects to XML"""
def to_xml(request):
"""This method parse request to XML object :return: string"""
logger.debug('Parsing request object to XML')
try:
xml = xmltodict.unparse(request.normalize_xml())
except Excep... | the_stack_v2_python_sparse | addonpayments/api/utils.py | ComerciaGP/addonpayments-Python-SDK | train | 3 |
dc0c89a6c771ede019ea9c2d7c10adaab23ed8e5 | [
"stk = []\nhead = root\nresult = []\nwhile stk or head:\n if head:\n while head:\n stk.append(head)\n head = head.left\n else:\n head = stk.pop()\n result.append(head.val)\n head = head.right\nreturn result",
"stk = []\nhead = root\nresult = []\nwhile stk or... | <|body_start_0|>
stk = []
head = root
result = []
while stk or head:
if head:
while head:
stk.append(head)
head = head.left
else:
head = stk.pop()
result.append(head.val)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def preorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
stk = []
head = ... | stack_v2_sparse_classes_75kplus_train_004952 | 1,127 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "inorderTraversal",
"signature": "def inorderTraversal(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "preorderTraversal",
"signature": "def preorderTraversal(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_039698 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def inorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def preorderTraversal(self, root): :type root: TreeNode :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def inorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def preorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
<|skeleton|>
class Solution:... | 3bfee704adb1d94efc8e531b732cf06c4f8aef0f | <|skeleton|>
class Solution:
def inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def preorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
stk = []
head = root
result = []
while stk or head:
if head:
while head:
stk.append(head)
head = head.left
... | the_stack_v2_python_sparse | inorder_stack.py | zopepy/leetcode | train | 0 | |
213e8834a47290acfa2e94875c85837707020f55 | [
"new_nodes = list()\nprehead = Node(0)\nindex_map = dict()\np = head\nq = prehead\ni = 0\nwhile p:\n index_map[p] = i\n i += 1\n q.next = q = Node(p.val)\n new_nodes.append(q)\n p = p.next\np = head\nq = prehead.next\nwhile p and q:\n r = p.random\n if r is not None:\n i = index_map[r]\n... | <|body_start_0|>
new_nodes = list()
prehead = Node(0)
index_map = dict()
p = head
q = prehead
i = 0
while p:
index_map[p] = i
i += 1
q.next = q = Node(p.val)
new_nodes.append(q)
p = p.next
p = hea... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def copyRandomList_v1(self, head: 'Node') -> 'Node':
"""Dictionary & Array. Helper data structures: - Dictionary: {original_node: index} - Array: [new_node] Then, origina_node -> original_random_node -> index -> new_random_node Use 3 x O(n) extra space. LeatCode: 36ms, 14.4 MB,... | stack_v2_sparse_classes_75kplus_train_004953 | 4,846 | no_license | [
{
"docstring": "Dictionary & Array. Helper data structures: - Dictionary: {original_node: index} - Array: [new_node] Then, origina_node -> original_random_node -> index -> new_random_node Use 3 x O(n) extra space. LeatCode: 36ms, 14.4 MB, beats 64%.",
"name": "copyRandomList_v1",
"signature": "def copyR... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def copyRandomList_v1(self, head: 'Node') -> 'Node': Dictionary & Array. Helper data structures: - Dictionary: {original_node: index} - Array: [new_node] Then, origina_node -> or... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def copyRandomList_v1(self, head: 'Node') -> 'Node': Dictionary & Array. Helper data structures: - Dictionary: {original_node: index} - Array: [new_node] Then, origina_node -> or... | 97a2386f5e3adbd7138fd123810c3232bdf7f622 | <|skeleton|>
class Solution:
def copyRandomList_v1(self, head: 'Node') -> 'Node':
"""Dictionary & Array. Helper data structures: - Dictionary: {original_node: index} - Array: [new_node] Then, origina_node -> original_random_node -> index -> new_random_node Use 3 x O(n) extra space. LeatCode: 36ms, 14.4 MB,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def copyRandomList_v1(self, head: 'Node') -> 'Node':
"""Dictionary & Array. Helper data structures: - Dictionary: {original_node: index} - Array: [new_node] Then, origina_node -> original_random_node -> index -> new_random_node Use 3 x O(n) extra space. LeatCode: 36ms, 14.4 MB, beats 64%."""... | the_stack_v2_python_sparse | python3/linked_list/copy_list_with_random_pointer.py | victorchu/algorithms | train | 0 | |
6e569729463cb93ed778b9189701d6abb46425bf | [
"self.drive_owner_list = drive_owner_list\nself.restore_to_original_drive = restore_to_original_drive\nself.target_drive_id = target_drive_id\nself.target_folder_path = target_folder_path\nself.target_user = target_user",
"if dictionary is None:\n return None\ndrive_owner_list = None\nif dictionary.get('driveO... | <|body_start_0|>
self.drive_owner_list = drive_owner_list
self.restore_to_original_drive = restore_to_original_drive
self.target_drive_id = target_drive_id
self.target_folder_path = target_folder_path
self.target_user = target_user
<|end_body_0|>
<|body_start_1|>
if dict... | Implementation of the 'OneDriveRestoreParameters' model. Specifies information needed for recovering Drive(s) & Drive items. Attributes: drive_owner_list (list of OneDriveOwner): Specifies the list of Drive owners which are to be restored along with the details of their drives. restore_to_original_drive (bool): Specifi... | OneDriveRestoreParameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OneDriveRestoreParameters:
"""Implementation of the 'OneDriveRestoreParameters' model. Specifies information needed for recovering Drive(s) & Drive items. Attributes: drive_owner_list (list of OneDriveOwner): Specifies the list of Drive owners which are to be restored along with the details of th... | stack_v2_sparse_classes_75kplus_train_004954 | 3,530 | permissive | [
{
"docstring": "Constructor for the OneDriveRestoreParameters class",
"name": "__init__",
"signature": "def __init__(self, drive_owner_list=None, restore_to_original_drive=None, target_drive_id=None, target_folder_path=None, target_user=None)"
},
{
"docstring": "Creates an instance of this model... | 2 | null | Implement the Python class `OneDriveRestoreParameters` described below.
Class description:
Implementation of the 'OneDriveRestoreParameters' model. Specifies information needed for recovering Drive(s) & Drive items. Attributes: drive_owner_list (list of OneDriveOwner): Specifies the list of Drive owners which are to b... | Implement the Python class `OneDriveRestoreParameters` described below.
Class description:
Implementation of the 'OneDriveRestoreParameters' model. Specifies information needed for recovering Drive(s) & Drive items. Attributes: drive_owner_list (list of OneDriveOwner): Specifies the list of Drive owners which are to b... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class OneDriveRestoreParameters:
"""Implementation of the 'OneDriveRestoreParameters' model. Specifies information needed for recovering Drive(s) & Drive items. Attributes: drive_owner_list (list of OneDriveOwner): Specifies the list of Drive owners which are to be restored along with the details of th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OneDriveRestoreParameters:
"""Implementation of the 'OneDriveRestoreParameters' model. Specifies information needed for recovering Drive(s) & Drive items. Attributes: drive_owner_list (list of OneDriveOwner): Specifies the list of Drive owners which are to be restored along with the details of their drives. r... | the_stack_v2_python_sparse | cohesity_management_sdk/models/one_drive_restore_parameters.py | cohesity/management-sdk-python | train | 24 |
af645303b47a64cdd303fd34a197c529cc28f97e | [
"super().__init__(entity_ids, unique_id, group_id, zha_device, **kwargs)\nself._available: bool = False\ngroup = self.zha_device.gateway.get_group(self._group_id)\nself._fan_channel = group.endpoint[hvac.Fan.cluster_id]\n\nasync def async_set_speed(value) -> None:\n \"\"\"Set the speed of the fan.\"\"\"\n try... | <|body_start_0|>
super().__init__(entity_ids, unique_id, group_id, zha_device, **kwargs)
self._available: bool = False
group = self.zha_device.gateway.get_group(self._group_id)
self._fan_channel = group.endpoint[hvac.Fan.cluster_id]
async def async_set_speed(value) -> None:
... | Representation of a fan group. | FanGroup | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FanGroup:
"""Representation of a fan group."""
def __init__(self, entity_ids: List[str], unique_id: str, group_id: int, zha_device, **kwargs) -> None:
"""Initialize a fan group."""
<|body_0|>
async def async_update(self):
"""Attempt to retrieve on off state from ... | stack_v2_sparse_classes_75kplus_train_004955 | 6,291 | permissive | [
{
"docstring": "Initialize a fan group.",
"name": "__init__",
"signature": "def __init__(self, entity_ids: List[str], unique_id: str, group_id: int, zha_device, **kwargs) -> None"
},
{
"docstring": "Attempt to retrieve on off state from the fan.",
"name": "async_update",
"signature": "as... | 2 | stack_v2_sparse_classes_30k_train_004687 | Implement the Python class `FanGroup` described below.
Class description:
Representation of a fan group.
Method signatures and docstrings:
- def __init__(self, entity_ids: List[str], unique_id: str, group_id: int, zha_device, **kwargs) -> None: Initialize a fan group.
- async def async_update(self): Attempt to retrie... | Implement the Python class `FanGroup` described below.
Class description:
Representation of a fan group.
Method signatures and docstrings:
- def __init__(self, entity_ids: List[str], unique_id: str, group_id: int, zha_device, **kwargs) -> None: Initialize a fan group.
- async def async_update(self): Attempt to retrie... | ed4ab403deaed9e8c95e0db728477fcb012bf4fa | <|skeleton|>
class FanGroup:
"""Representation of a fan group."""
def __init__(self, entity_ids: List[str], unique_id: str, group_id: int, zha_device, **kwargs) -> None:
"""Initialize a fan group."""
<|body_0|>
async def async_update(self):
"""Attempt to retrieve on off state from ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FanGroup:
"""Representation of a fan group."""
def __init__(self, entity_ids: List[str], unique_id: str, group_id: int, zha_device, **kwargs) -> None:
"""Initialize a fan group."""
super().__init__(entity_ids, unique_id, group_id, zha_device, **kwargs)
self._available: bool = Fals... | the_stack_v2_python_sparse | homeassistant/components/zha/fan.py | tchellomello/home-assistant | train | 8 |
f6f070f1e5f36adfa535bed4212806218ebceca8 | [
"try:\n if max_last_time is None:\n raise MissingParameter('missing parameter max_last_time')\n url = base64.urlsafe_b64decode(b64url.encode('utf-8'))\n proxy = ProxyPool.instance().get(url, float(max_last_time))\n if proxy is None:\n response = {'success': False, 'error': 'no proxy avaiab... | <|body_start_0|>
try:
if max_last_time is None:
raise MissingParameter('missing parameter max_last_time')
url = base64.urlsafe_b64decode(b64url.encode('utf-8'))
proxy = ProxyPool.instance().get(url, float(max_last_time))
if proxy is None:
... | ProxyHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProxyHandler:
def get(self, b64url, max_last_time):
""":rtype proxy: {'http', 'http://8.8.8.8:8000'}"""
<|body_0|>
def post(self, b64url, useless):
""":param proxy: e.g. 'http://8.8.8.8:8000' :param status: 'success' or 'fail'"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_75kplus_train_004956 | 5,572 | no_license | [
{
"docstring": ":rtype proxy: {'http', 'http://8.8.8.8:8000'}",
"name": "get",
"signature": "def get(self, b64url, max_last_time)"
},
{
"docstring": ":param proxy: e.g. 'http://8.8.8.8:8000' :param status: 'success' or 'fail'",
"name": "post",
"signature": "def post(self, b64url, useless... | 2 | stack_v2_sparse_classes_30k_train_039772 | Implement the Python class `ProxyHandler` described below.
Class description:
Implement the ProxyHandler class.
Method signatures and docstrings:
- def get(self, b64url, max_last_time): :rtype proxy: {'http', 'http://8.8.8.8:8000'}
- def post(self, b64url, useless): :param proxy: e.g. 'http://8.8.8.8:8000' :param sta... | Implement the Python class `ProxyHandler` described below.
Class description:
Implement the ProxyHandler class.
Method signatures and docstrings:
- def get(self, b64url, max_last_time): :rtype proxy: {'http', 'http://8.8.8.8:8000'}
- def post(self, b64url, useless): :param proxy: e.g. 'http://8.8.8.8:8000' :param sta... | 6f7205b00f1a105f4505cf4ee571f2c53762dc3e | <|skeleton|>
class ProxyHandler:
def get(self, b64url, max_last_time):
""":rtype proxy: {'http', 'http://8.8.8.8:8000'}"""
<|body_0|>
def post(self, b64url, useless):
""":param proxy: e.g. 'http://8.8.8.8:8000' :param status: 'success' or 'fail'"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProxyHandler:
def get(self, b64url, max_last_time):
""":rtype proxy: {'http', 'http://8.8.8.8:8000'}"""
try:
if max_last_time is None:
raise MissingParameter('missing parameter max_last_time')
url = base64.urlsafe_b64decode(b64url.encode('utf-8'))
... | the_stack_v2_python_sparse | crawlerservice/handler.py | Justinyj/ruyiwebcrawl | train | 0 | |
6ff0920af5e23e593568f640693e6fff89f864b8 | [
"self.dict = {}\nfor i in range(len(words)):\n w = words[i]\n if w in self.dict:\n self.dict[w].append(i)\n else:\n self.dict[w] = [i]",
"ix1 = self.dict[word1]\nix2 = self.dict[word2]\ni1, i2 = (0, 0)\nret = float('inf')\nwhile i1 < len(ix1) and i2 < len(ix2):\n ret = min(ret, abs(ix2[i... | <|body_start_0|>
self.dict = {}
for i in range(len(words)):
w = words[i]
if w in self.dict:
self.dict[w].append(i)
else:
self.dict[w] = [i]
<|end_body_0|>
<|body_start_1|>
ix1 = self.dict[word1]
ix2 = self.dict[word2]
... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.dict = {}
for i in range... | stack_v2_sparse_classes_75kplus_train_004957 | 950 | no_license | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortest(self, word1, word2)"
}
] | 2 | stack_v2_sparse_classes_30k_train_051660 | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int
<|skeleton|>
class WordDistance:
... | f7cb7cfa6e1f04efd741c2456ad930db48101573 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
self.dict = {}
for i in range(len(words)):
w = words[i]
if w in self.dict:
self.dict[w].append(i)
else:
self.dict[w] = [i]
def shortest(self, w... | the_stack_v2_python_sparse | 244.shortestWordDist2.py | umnstao/leetcodeOJ | train | 0 | |
046ad089503cf0997d47a497883f642cd811841d | [
"super(LFCC, self).__init__()\nself.fl = fl\nself.fs = fs\nself.fn = fn\nself.sr = sr\nself.filter_num = filter_num\nself.num_coef = num_coef\nif min_freq >= 0 and min_freq < max_freq and (max_freq <= 1):\n self.min_freq_bin = int(min_freq * (fn // 2 + 1))\n self.max_freq_bin = int(max_freq * (fn // 2 + 1))\n... | <|body_start_0|>
super(LFCC, self).__init__()
self.fl = fl
self.fs = fs
self.fn = fn
self.sr = sr
self.filter_num = filter_num
self.num_coef = num_coef
if min_freq >= 0 and min_freq < max_freq and (max_freq <= 1):
self.min_freq_bin = int(min_fr... | Based on asvspoof.org baseline Matlab code. Difference: with_energy is added to set the first dimension as energy | LFCC | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LFCC:
"""Based on asvspoof.org baseline Matlab code. Difference: with_energy is added to set the first dimension as energy"""
def __init__(self, fl, fs, fn, sr, filter_num, with_energy=False, with_emphasis=True, with_delta=True, flag_for_LFB=False, num_coef=None, min_freq=0, max_freq=1):
... | stack_v2_sparse_classes_75kplus_train_004958 | 11,719 | permissive | [
{
"docstring": "Initialize LFCC Para: ----- fl: int, frame length, (number of waveform points) fs: int, frame shift, (number of waveform points) fn: int, FFT points sr: int, sampling rate (Hz) filter_num: int, number of filters in filter-bank with_energy: bool, (default False), whether replace 1st dim to energy... | 2 | null | Implement the Python class `LFCC` described below.
Class description:
Based on asvspoof.org baseline Matlab code. Difference: with_energy is added to set the first dimension as energy
Method signatures and docstrings:
- def __init__(self, fl, fs, fn, sr, filter_num, with_energy=False, with_emphasis=True, with_delta=T... | Implement the Python class `LFCC` described below.
Class description:
Based on asvspoof.org baseline Matlab code. Difference: with_energy is added to set the first dimension as energy
Method signatures and docstrings:
- def __init__(self, fl, fs, fn, sr, filter_num, with_energy=False, with_emphasis=True, with_delta=T... | 55da4137149df297ed656ede9c3e4f75a7eaf552 | <|skeleton|>
class LFCC:
"""Based on asvspoof.org baseline Matlab code. Difference: with_energy is added to set the first dimension as energy"""
def __init__(self, fl, fs, fn, sr, filter_num, with_energy=False, with_emphasis=True, with_delta=True, flag_for_LFB=False, num_coef=None, min_freq=0, max_freq=1):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LFCC:
"""Based on asvspoof.org baseline Matlab code. Difference: with_energy is added to set the first dimension as energy"""
def __init__(self, fl, fs, fn, sr, filter_num, with_energy=False, with_emphasis=True, with_delta=True, flag_for_LFB=False, num_coef=None, min_freq=0, max_freq=1):
"""Initi... | the_stack_v2_python_sparse | LA/Baseline-LFCC-LCNN/sandbox/util_frontend.py | Jungjee/2021 | train | 0 |
df489f60de239526387f267b6544f09470395e2b | [
"self.mPos = pos\nself.color = color\nself.angle = 0\nself.xAxis = Vector2.rotate2D(Vector(1, 0), self.angle)\nself.yAxis = self.xAxis.perpendicular\nself.isSelected = False\nself.corners = []",
"self.isSelected = isSelected\npygame.draw.circle(surf, (255, 255, 255), self.mPos.i, 5)\ndrawArrow(surf, self.mPos, se... | <|body_start_0|>
self.mPos = pos
self.color = color
self.angle = 0
self.xAxis = Vector2.rotate2D(Vector(1, 0), self.angle)
self.yAxis = self.xAxis.perpendicular
self.isSelected = False
self.corners = []
<|end_body_0|>
<|body_start_1|>
self.isSelected = is... | generic shape object | Shape | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Shape:
"""generic shape object"""
def __init__(self, color, pos):
"""position of the axis, color of shape, and the rotation info for said axis"""
<|body_0|>
def drawPygame(self, surf, isSelected, isCollide):
"""draws the axis and position of the shape"""
... | stack_v2_sparse_classes_75kplus_train_004959 | 10,232 | no_license | [
{
"docstring": "position of the axis, color of shape, and the rotation info for said axis",
"name": "__init__",
"signature": "def __init__(self, color, pos)"
},
{
"docstring": "draws the axis and position of the shape",
"name": "drawPygame",
"signature": "def drawPygame(self, surf, isSel... | 3 | null | Implement the Python class `Shape` described below.
Class description:
generic shape object
Method signatures and docstrings:
- def __init__(self, color, pos): position of the axis, color of shape, and the rotation info for said axis
- def drawPygame(self, surf, isSelected, isCollide): draws the axis and position of ... | Implement the Python class `Shape` described below.
Class description:
generic shape object
Method signatures and docstrings:
- def __init__(self, color, pos): position of the axis, color of shape, and the rotation info for said axis
- def drawPygame(self, surf, isSelected, isCollide): draws the axis and position of ... | 658589a01740da5ba76d09d770b198e21c478479 | <|skeleton|>
class Shape:
"""generic shape object"""
def __init__(self, color, pos):
"""position of the axis, color of shape, and the rotation info for said axis"""
<|body_0|>
def drawPygame(self, surf, isSelected, isCollide):
"""draws the axis and position of the shape"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Shape:
"""generic shape object"""
def __init__(self, color, pos):
"""position of the axis, color of shape, and the rotation info for said axis"""
self.mPos = pos
self.color = color
self.angle = 0
self.xAxis = Vector2.rotate2D(Vector(1, 0), self.angle)
self.... | the_stack_v2_python_sparse | Code/SplitAxisCollision.py | dragonsarebest/Portfolio | train | 1 |
2ddd68b4ed5804d1b05b930e3a77c81c89acf22b | [
"logg = logging.getLogger(f'c.{__name__}.__init__')\nlogg.debug(f'Start __init__')\nsuper().__init__(data_x, data_y, th_bin_num_fp, r_stride_fp, th_bin_num_sp, r_stride_sp, r_num_sp, corridor_width)",
"logg = logging.getLogger(f'c.{__name__}.visual_test_all_dist_sp_th')\nlogg.debug(f'Start visual_test_all_dist_sp... | <|body_start_0|>
logg = logging.getLogger(f'c.{__name__}.__init__')
logg.debug(f'Start __init__')
super().__init__(data_x, data_y, th_bin_num_fp, r_stride_fp, th_bin_num_sp, r_stride_sp, r_num_sp, corridor_width)
<|end_body_0|>
<|body_start_1|>
logg = logging.getLogger(f'c.{__name__}.vi... | VisualDoubleHough | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VisualDoubleHough:
def __init__(self, data_x: np.ndarray, data_y: np.ndarray, th_bin_num_fp: int, r_stride_fp: float, th_bin_num_sp: int, r_stride_sp: float, r_num_sp: int, corridor_width: float):
"""Setup the analyzer"""
<|body_0|>
def visual_test_all_dist_sp_th(self, ax=No... | stack_v2_sparse_classes_75kplus_train_004960 | 12,447 | no_license | [
{
"docstring": "Setup the analyzer",
"name": "__init__",
"signature": "def __init__(self, data_x: np.ndarray, data_y: np.ndarray, th_bin_num_fp: int, r_stride_fp: float, th_bin_num_sp: int, r_stride_sp: float, r_num_sp: int, corridor_width: float)"
},
{
"docstring": "TODO: what is visual_test_al... | 3 | null | Implement the Python class `VisualDoubleHough` described below.
Class description:
Implement the VisualDoubleHough class.
Method signatures and docstrings:
- def __init__(self, data_x: np.ndarray, data_y: np.ndarray, th_bin_num_fp: int, r_stride_fp: float, th_bin_num_sp: int, r_stride_sp: float, r_num_sp: int, corrid... | Implement the Python class `VisualDoubleHough` described below.
Class description:
Implement the VisualDoubleHough class.
Method signatures and docstrings:
- def __init__(self, data_x: np.ndarray, data_y: np.ndarray, th_bin_num_fp: int, r_stride_fp: float, th_bin_num_sp: int, r_stride_sp: float, r_num_sp: int, corrid... | 1d7e5657014b00612cde87b78d5506a9e8b6adfc | <|skeleton|>
class VisualDoubleHough:
def __init__(self, data_x: np.ndarray, data_y: np.ndarray, th_bin_num_fp: int, r_stride_fp: float, th_bin_num_sp: int, r_stride_sp: float, r_num_sp: int, corridor_width: float):
"""Setup the analyzer"""
<|body_0|>
def visual_test_all_dist_sp_th(self, ax=No... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VisualDoubleHough:
def __init__(self, data_x: np.ndarray, data_y: np.ndarray, th_bin_num_fp: int, r_stride_fp: float, th_bin_num_sp: int, r_stride_sp: float, r_num_sp: int, corridor_width: float):
"""Setup the analyzer"""
logg = logging.getLogger(f'c.{__name__}.__init__')
logg.debug(f'... | the_stack_v2_python_sparse | python/hough-parallel-lines/double_hough.py | Pitrified/snippet | train | 2 | |
724afb99271330df506e4cde457a5dab69b636cd | [
"self.tt_annotator = Truth_teller_factuality_annotator(Truth_teller_wrapper(tt_path))\nself.props_hostname = props_hostname\nself.props_port = props_port\nself.spacy_hostname = spacy_hostname\nself.spacy_port = spacy_port",
"logging.debug('factcheck args: {}'.format(kwargs))\nsent = kwargs['text']\noutput = conll... | <|body_start_0|>
self.tt_annotator = Truth_teller_factuality_annotator(Truth_teller_wrapper(tt_path))
self.props_hostname = props_hostname
self.props_port = props_port
self.spacy_hostname = spacy_hostname
self.spacy_port = spacy_port
<|end_body_0|>
<|body_start_1|>
loggi... | Factuality server instance | Factuality_server | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Factuality_server:
"""Factuality server instance"""
def __init__(self, tt_path, props_hostname, props_port, spacy_hostname, spacy_port):
"""Init spacy engine and clear cache tt_path - the path to the root of truthteller"""
<|body_0|>
def factcheck(self, **kwargs):
... | stack_v2_sparse_classes_75kplus_train_004961 | 3,022 | permissive | [
{
"docstring": "Init spacy engine and clear cache tt_path - the path to the root of truthteller",
"name": "__init__",
"signature": "def __init__(self, tt_path, props_hostname, props_port, spacy_hostname, spacy_port)"
},
{
"docstring": "Run factuality annotation on a single sentence, returns brat... | 2 | stack_v2_sparse_classes_30k_train_051617 | Implement the Python class `Factuality_server` described below.
Class description:
Factuality server instance
Method signatures and docstrings:
- def __init__(self, tt_path, props_hostname, props_port, spacy_hostname, spacy_port): Init spacy engine and clear cache tt_path - the path to the root of truthteller
- def f... | Implement the Python class `Factuality_server` described below.
Class description:
Factuality server instance
Method signatures and docstrings:
- def __init__(self, tt_path, props_hostname, props_port, spacy_hostname, spacy_port): Init spacy engine and clear cache tt_path - the path to the root of truthteller
- def f... | 869fd23ec8fe71ab2b9f30389018615932d27cde | <|skeleton|>
class Factuality_server:
"""Factuality server instance"""
def __init__(self, tt_path, props_hostname, props_port, spacy_hostname, spacy_port):
"""Init spacy engine and clear cache tt_path - the path to the root of truthteller"""
<|body_0|>
def factcheck(self, **kwargs):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Factuality_server:
"""Factuality server instance"""
def __init__(self, tt_path, props_hostname, props_port, spacy_hostname, spacy_port):
"""Init spacy engine and clear cache tt_path - the path to the root of truthteller"""
self.tt_annotator = Truth_teller_factuality_annotator(Truth_teller... | the_stack_v2_python_sparse | src/webserver/webserver.py | gabrielStanovsky/unified-factuality | train | 8 |
948f2ded80f4282bfba8f48950cb3c7b6a5f623f | [
"grid_indexing = stencil_factory.grid_indexing\nself._n_halo = grid_indexing.n_halo\nself._dx = grid_data.dx\nself._dy = grid_data.dy\nself._a11 = grid_data.a11\nself._a12 = grid_data.a12\nself._a21 = grid_data.a21\nself._a22 = grid_data.a22\nif order == 2:\n self._do_ord4 = False\n halos = (1, 1)\n func =... | <|body_start_0|>
grid_indexing = stencil_factory.grid_indexing
self._n_halo = grid_indexing.n_halo
self._dx = grid_data.dx
self._dy = grid_data.dy
self._a11 = grid_data.a11
self._a12 = grid_data.a12
self._a21 = grid_data.a21
self._a22 = grid_data.a22
... | Fortan name is c2l_ord2 | CubedToLatLon | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CubedToLatLon:
"""Fortan name is c2l_ord2"""
def __init__(self, state: fv3core.DycoreState, stencil_factory: StencilFactory, quantity_factory: pace.util.QuantityFactory, grid_data: GridData, order: int, comm: pace.util.CubedSphereCommunicator):
"""Initializes stencils to use either 2... | stack_v2_sparse_classes_75kplus_train_004962 | 5,666 | permissive | [
{
"docstring": "Initializes stencils to use either 2nd or 4th order of interpolation based on namelist setting Args: stencil_factory: creates stencils grid_data: object with metric terms order: Order of interpolation, must be 2 or 4",
"name": "__init__",
"signature": "def __init__(self, state: fv3core.D... | 2 | stack_v2_sparse_classes_30k_train_043773 | Implement the Python class `CubedToLatLon` described below.
Class description:
Fortan name is c2l_ord2
Method signatures and docstrings:
- def __init__(self, state: fv3core.DycoreState, stencil_factory: StencilFactory, quantity_factory: pace.util.QuantityFactory, grid_data: GridData, order: int, comm: pace.util.Cubed... | Implement the Python class `CubedToLatLon` described below.
Class description:
Fortan name is c2l_ord2
Method signatures and docstrings:
- def __init__(self, state: fv3core.DycoreState, stencil_factory: StencilFactory, quantity_factory: pace.util.QuantityFactory, grid_data: GridData, order: int, comm: pace.util.Cubed... | c543e8ec478d46d88b48cdd3beaaa1717a95b935 | <|skeleton|>
class CubedToLatLon:
"""Fortan name is c2l_ord2"""
def __init__(self, state: fv3core.DycoreState, stencil_factory: StencilFactory, quantity_factory: pace.util.QuantityFactory, grid_data: GridData, order: int, comm: pace.util.CubedSphereCommunicator):
"""Initializes stencils to use either 2... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CubedToLatLon:
"""Fortan name is c2l_ord2"""
def __init__(self, state: fv3core.DycoreState, stencil_factory: StencilFactory, quantity_factory: pace.util.QuantityFactory, grid_data: GridData, order: int, comm: pace.util.CubedSphereCommunicator):
"""Initializes stencils to use either 2nd or 4th ord... | the_stack_v2_python_sparse | stencils/pace/stencils/c2l_ord.py | ai2cm/pace | train | 27 |
eceab50f4fa819db09cee07519146553b34d4ff2 | [
"super().__init__()\nself.n_words = params.src_vocab_size\nself.eos_index = params.eos_index\nself.pad_index = params.pad_index\nself.dim = params.model_dim\nself.emb_dim = params.model_dim // 4\nself.hidden_dim = params.hidden_dim\nself.num_heads = params.num_heads\nassert self.dim % self.num_heads == 0, 'transfor... | <|body_start_0|>
super().__init__()
self.n_words = params.src_vocab_size
self.eos_index = params.eos_index
self.pad_index = params.pad_index
self.dim = params.model_dim
self.emb_dim = params.model_dim // 4
self.hidden_dim = params.hidden_dim
self.num_heads... | TableEncoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TableEncoder:
def __init__(self, params):
"""Table2Text Transformer model (encoder)."""
<|body_0|>
def forward(self, x1, x2, x3, x4, lengths):
"""Inputs: `src_seq` LongTensor(bs, slen), containing word indices"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_75kplus_train_004963 | 21,450 | no_license | [
{
"docstring": "Table2Text Transformer model (encoder).",
"name": "__init__",
"signature": "def __init__(self, params)"
},
{
"docstring": "Inputs: `src_seq` LongTensor(bs, slen), containing word indices",
"name": "forward",
"signature": "def forward(self, x1, x2, x3, x4, lengths)"
}
] | 2 | stack_v2_sparse_classes_30k_train_046021 | Implement the Python class `TableEncoder` described below.
Class description:
Implement the TableEncoder class.
Method signatures and docstrings:
- def __init__(self, params): Table2Text Transformer model (encoder).
- def forward(self, x1, x2, x3, x4, lengths): Inputs: `src_seq` LongTensor(bs, slen), containing word ... | Implement the Python class `TableEncoder` described below.
Class description:
Implement the TableEncoder class.
Method signatures and docstrings:
- def __init__(self, params): Table2Text Transformer model (encoder).
- def forward(self, x1, x2, x3, x4, lengths): Inputs: `src_seq` LongTensor(bs, slen), containing word ... | 72079bd70f3252a9f9334099de047236e3b0a476 | <|skeleton|>
class TableEncoder:
def __init__(self, params):
"""Table2Text Transformer model (encoder)."""
<|body_0|>
def forward(self, x1, x2, x3, x4, lengths):
"""Inputs: `src_seq` LongTensor(bs, slen), containing word indices"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TableEncoder:
def __init__(self, params):
"""Table2Text Transformer model (encoder)."""
super().__init__()
self.n_words = params.src_vocab_size
self.eos_index = params.eos_index
self.pad_index = params.pad_index
self.dim = params.model_dim
self.emb_dim =... | the_stack_v2_python_sparse | src/model/table2text_transformer.py | gongliym/table2text-transformer | train | 0 | |
3630e1d4935221b7a211f876330c73a3eba414bf | [
"try:\n params = request._serialize()\n body = self.call('CreateCredential', params)\n response = json.loads(body)\n if 'Error' not in response['Response']:\n model = models.CreateCredentialResponse()\n model._deserialize(response['Response'])\n return model\n else:\n code... | <|body_start_0|>
try:
params = request._serialize()
body = self.call('CreateCredential', params)
response = json.loads(body)
if 'Error' not in response['Response']:
model = models.CreateCredentialResponse()
model._deserialize(respon... | TdidClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TdidClient:
def CreateCredential(self, request):
"""创建凭证 :param request: Request instance for CreateCredential. :type request: :class:`tencentcloud.tdid.v20210519.models.CreateCredentialRequest` :rtype: :class:`tencentcloud.tdid.v20210519.models.CreateCredentialResponse`"""
<|bod... | stack_v2_sparse_classes_75kplus_train_004964 | 5,585 | permissive | [
{
"docstring": "创建凭证 :param request: Request instance for CreateCredential. :type request: :class:`tencentcloud.tdid.v20210519.models.CreateCredentialRequest` :rtype: :class:`tencentcloud.tdid.v20210519.models.CreateCredentialResponse`",
"name": "CreateCredential",
"signature": "def CreateCredential(sel... | 4 | stack_v2_sparse_classes_30k_train_009765 | Implement the Python class `TdidClient` described below.
Class description:
Implement the TdidClient class.
Method signatures and docstrings:
- def CreateCredential(self, request): 创建凭证 :param request: Request instance for CreateCredential. :type request: :class:`tencentcloud.tdid.v20210519.models.CreateCredentialReq... | Implement the Python class `TdidClient` described below.
Class description:
Implement the TdidClient class.
Method signatures and docstrings:
- def CreateCredential(self, request): 创建凭证 :param request: Request instance for CreateCredential. :type request: :class:`tencentcloud.tdid.v20210519.models.CreateCredentialReq... | baed8b8e84ed0e8dd19600225796a75405cb922c | <|skeleton|>
class TdidClient:
def CreateCredential(self, request):
"""创建凭证 :param request: Request instance for CreateCredential. :type request: :class:`tencentcloud.tdid.v20210519.models.CreateCredentialRequest` :rtype: :class:`tencentcloud.tdid.v20210519.models.CreateCredentialResponse`"""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TdidClient:
def CreateCredential(self, request):
"""创建凭证 :param request: Request instance for CreateCredential. :type request: :class:`tencentcloud.tdid.v20210519.models.CreateCredentialRequest` :rtype: :class:`tencentcloud.tdid.v20210519.models.CreateCredentialResponse`"""
try:
pa... | the_stack_v2_python_sparse | tencentcloud/tdid/v20210519/tdid_client.py | WANGMUXIAN/tencentcloud-sdk-python | train | 0 | |
e1bde543363f5544ccc545e126c8333c5e345da2 | [
"super().setUp()\nself.client = Client()\nself.reference = Product.objects.get(name='Chocolat bio')\nself.substitute = Product.objects.get(name='Chocolat noir sans sucres')",
"self.client.force_login(self.user)\nresponse = self.client.get('/favorites/')\nself.assertEqual(response.status_code, 200)",
"self.clien... | <|body_start_0|>
super().setUp()
self.client = Client()
self.reference = Product.objects.get(name='Chocolat bio')
self.substitute = Product.objects.get(name='Chocolat noir sans sucres')
<|end_body_0|>
<|body_start_1|>
self.client.force_login(self.user)
response = self.cl... | FavorisTestCase class. | FavoritesTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FavoritesTestCase:
"""FavorisTestCase class."""
def setUp(self):
"""Make Setup."""
<|body_0|>
def test_favorites_status_code_200(self):
"""Test favoris status_code 200."""
<|body_1|>
def test_favorites_per_user(self):
"""Test favoris per user... | stack_v2_sparse_classes_75kplus_train_004965 | 14,928 | no_license | [
{
"docstring": "Make Setup.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test favoris status_code 200.",
"name": "test_favorites_status_code_200",
"signature": "def test_favorites_status_code_200(self)"
},
{
"docstring": "Test favoris per user.",
"name... | 5 | stack_v2_sparse_classes_30k_train_050960 | Implement the Python class `FavoritesTestCase` described below.
Class description:
FavorisTestCase class.
Method signatures and docstrings:
- def setUp(self): Make Setup.
- def test_favorites_status_code_200(self): Test favoris status_code 200.
- def test_favorites_per_user(self): Test favoris per user.
- def test_fa... | Implement the Python class `FavoritesTestCase` described below.
Class description:
FavorisTestCase class.
Method signatures and docstrings:
- def setUp(self): Make Setup.
- def test_favorites_status_code_200(self): Test favoris status_code 200.
- def test_favorites_per_user(self): Test favoris per user.
- def test_fa... | e260066e84e0f5ec69af566dec37af46edf027b4 | <|skeleton|>
class FavoritesTestCase:
"""FavorisTestCase class."""
def setUp(self):
"""Make Setup."""
<|body_0|>
def test_favorites_status_code_200(self):
"""Test favoris status_code 200."""
<|body_1|>
def test_favorites_per_user(self):
"""Test favoris per user... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FavoritesTestCase:
"""FavorisTestCase class."""
def setUp(self):
"""Make Setup."""
super().setUp()
self.client = Client()
self.reference = Product.objects.get(name='Chocolat bio')
self.substitute = Product.objects.get(name='Chocolat noir sans sucres')
def test... | the_stack_v2_python_sparse | purapps/purbeurre/tests.py | Jerome-LorD/p11_pur_beurre | train | 0 |
4e4d351f64702f06e7c165d910a518098a47c400 | [
"if self._async_current_entries():\n return self.async_abort(reason='single_instance_allowed')\nif user_input is None:\n return self.async_show_form(step_id='user')\ntry:\n webhook_id, webhook_url, cloudhook = await self._get_webhook_id()\nexcept cloud.CloudNotConnected:\n return self.async_abort(reason... | <|body_start_0|>
if self._async_current_entries():
return self.async_abort(reason='single_instance_allowed')
if user_input is None:
return self.async_show_form(step_id='user')
try:
webhook_id, webhook_url, cloudhook = await self._get_webhook_id()
excep... | Set up OwnTracks. | OwnTracksFlow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OwnTracksFlow:
"""Set up OwnTracks."""
async def async_step_user(self, user_input=None):
"""Handle a user initiated set up flow to create OwnTracks webhook."""
<|body_0|>
async def _get_webhook_id(self):
"""Generate webhook ID."""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_75kplus_train_004966 | 2,396 | permissive | [
{
"docstring": "Handle a user initiated set up flow to create OwnTracks webhook.",
"name": "async_step_user",
"signature": "async def async_step_user(self, user_input=None)"
},
{
"docstring": "Generate webhook ID.",
"name": "_get_webhook_id",
"signature": "async def _get_webhook_id(self)... | 2 | stack_v2_sparse_classes_30k_train_022658 | Implement the Python class `OwnTracksFlow` described below.
Class description:
Set up OwnTracks.
Method signatures and docstrings:
- async def async_step_user(self, user_input=None): Handle a user initiated set up flow to create OwnTracks webhook.
- async def _get_webhook_id(self): Generate webhook ID. | Implement the Python class `OwnTracksFlow` described below.
Class description:
Set up OwnTracks.
Method signatures and docstrings:
- async def async_step_user(self, user_input=None): Handle a user initiated set up flow to create OwnTracks webhook.
- async def _get_webhook_id(self): Generate webhook ID.
<|skeleton|>
... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class OwnTracksFlow:
"""Set up OwnTracks."""
async def async_step_user(self, user_input=None):
"""Handle a user initiated set up flow to create OwnTracks webhook."""
<|body_0|>
async def _get_webhook_id(self):
"""Generate webhook ID."""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OwnTracksFlow:
"""Set up OwnTracks."""
async def async_step_user(self, user_input=None):
"""Handle a user initiated set up flow to create OwnTracks webhook."""
if self._async_current_entries():
return self.async_abort(reason='single_instance_allowed')
if user_input is ... | the_stack_v2_python_sparse | homeassistant/components/owntracks/config_flow.py | home-assistant/core | train | 35,501 |
285e9d9e73a651c309357195e14324298f44a702 | [
"super().__init__()\nself.username = username\nself.nodes = []",
"if name == 'node':\n if attributes.getValue('user') == self.username:\n self.nodes.append((float(attributes.getValue('lat')), float(attributes.getValue('lon'))))"
] | <|body_start_0|>
super().__init__()
self.username = username
self.nodes = []
<|end_body_0|>
<|body_start_1|>
if name == 'node':
if attributes.getValue('user') == self.username:
self.nodes.append((float(attributes.getValue('lat')), float(attributes.getValue('l... | SAX Parser to retrieve nodes from an OSM XML document. | OsmNodeParser | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OsmNodeParser:
"""SAX Parser to retrieve nodes from an OSM XML document."""
def __init__(self, username):
"""Constructor. :param username: The name of the user for whom nodes should be retrieved. :type username: str :returns: An OsmNodeParser instance. :rtype: OsmNodeParser"""
... | stack_v2_sparse_classes_75kplus_train_004967 | 1,277 | permissive | [
{
"docstring": "Constructor. :param username: The name of the user for whom nodes should be retrieved. :type username: str :returns: An OsmNodeParser instance. :rtype: OsmNodeParser",
"name": "__init__",
"signature": "def __init__(self, username)"
},
{
"docstring": "Callback for when an element ... | 2 | stack_v2_sparse_classes_30k_train_051709 | Implement the Python class `OsmNodeParser` described below.
Class description:
SAX Parser to retrieve nodes from an OSM XML document.
Method signatures and docstrings:
- def __init__(self, username): Constructor. :param username: The name of the user for whom nodes should be retrieved. :type username: str :returns: A... | Implement the Python class `OsmNodeParser` described below.
Class description:
SAX Parser to retrieve nodes from an OSM XML document.
Method signatures and docstrings:
- def __init__(self, username): Constructor. :param username: The name of the user for whom nodes should be retrieved. :type username: str :returns: A... | 53d448b8d558e88df5710a672a76ef1f9c983e57 | <|skeleton|>
class OsmNodeParser:
"""SAX Parser to retrieve nodes from an OSM XML document."""
def __init__(self, username):
"""Constructor. :param username: The name of the user for whom nodes should be retrieved. :type username: str :returns: An OsmNodeParser instance. :rtype: OsmNodeParser"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OsmNodeParser:
"""SAX Parser to retrieve nodes from an OSM XML document."""
def __init__(self, username):
"""Constructor. :param username: The name of the user for whom nodes should be retrieved. :type username: str :returns: An OsmNodeParser instance. :rtype: OsmNodeParser"""
super().__i... | the_stack_v2_python_sparse | flask_project/reporter/osm_node_parser.py | russbiggs/MapCampaigner | train | 0 |
7cef8b3f2136f30c92d06386ce47da095a92993d | [
"l = 0\nr = len(nums) - 1\nwhile l < r:\n m = l + (r - l) / 2\n if nums[m] > nums[r]:\n l = m + 1\n elif nums[m] < nums[r]:\n r = m\n else:\n r -= 1\nreturn nums[r]",
"l = 0\nr = len(nums)\nwhile l < r:\n m = l + (r - l) / 2\n if nums[m] > nums[r - 1]:\n l = m\n el... | <|body_start_0|>
l = 0
r = len(nums) - 1
while l < r:
m = l + (r - l) / 2
if nums[m] > nums[r]:
l = m + 1
elif nums[m] < nums[r]:
r = m
else:
r -= 1
return nums[r]
<|end_body_0|>
<|body_start... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMin(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findMin(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
l = 0
r = len(nums) - 1
while l < r:
... | stack_v2_sparse_classes_75kplus_train_004968 | 2,200 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findMin",
"signature": "def findMin(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findMin",
"signature": "def findMin(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_test_002482 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMin(self, nums): :type nums: List[int] :rtype: int
- def findMin(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMin(self, nums): :type nums: List[int] :rtype: int
- def findMin(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def findMin(self, nums)... | 860590239da0618c52967a55eda8d6bbe00bfa96 | <|skeleton|>
class Solution:
def findMin(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findMin(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findMin(self, nums):
""":type nums: List[int] :rtype: int"""
l = 0
r = len(nums) - 1
while l < r:
m = l + (r - l) / 2
if nums[m] > nums[r]:
l = m + 1
elif nums[m] < nums[r]:
r = m
else... | the_stack_v2_python_sparse | LeetCode/p0154/II/find-minimum-in-rotated-sorted-array-ii.py | Ynjxsjmh/PracticeMakesPerfect | train | 0 | |
89066286f11ac5633b5be45d5ed9835a356b0898 | [
"endpoint = 'videos/{}'.format(video_id)\nparams = {'text_format': text_format or self.response_format}\nreturn self._make_request(path=endpoint, params_=params, public_api=True)",
"msg = 'Pass only one of `album_id`, `article_id`, `song_id` and `video_id`., not more than one.'\ncondition = sum([bool(album_id), b... | <|body_start_0|>
endpoint = 'videos/{}'.format(video_id)
params = {'text_format': text_format or self.response_format}
return self._make_request(path=endpoint, params_=params, public_api=True)
<|end_body_0|>
<|body_start_1|>
msg = 'Pass only one of `album_id`, `article_id`, `song_id` an... | Video methods of the public API. | VideoMethods | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VideoMethods:
"""Video methods of the public API."""
def video(self, video_id, text_format=None):
"""Gets data for a specific video. Args: video_id (:obj:`int`): Genius video ID text_format (:obj:`str`, optional): Text format of the results ('dom', 'html', 'markdown' or 'plain'). Ret... | stack_v2_sparse_classes_75kplus_train_004969 | 2,796 | permissive | [
{
"docstring": "Gets data for a specific video. Args: video_id (:obj:`int`): Genius video ID text_format (:obj:`str`, optional): Text format of the results ('dom', 'html', 'markdown' or 'plain'). Returns: :obj:`dict`",
"name": "video",
"signature": "def video(self, video_id, text_format=None)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_000092 | Implement the Python class `VideoMethods` described below.
Class description:
Video methods of the public API.
Method signatures and docstrings:
- def video(self, video_id, text_format=None): Gets data for a specific video. Args: video_id (:obj:`int`): Genius video ID text_format (:obj:`str`, optional): Text format o... | Implement the Python class `VideoMethods` described below.
Class description:
Video methods of the public API.
Method signatures and docstrings:
- def video(self, video_id, text_format=None): Gets data for a specific video. Args: video_id (:obj:`int`): Genius video ID text_format (:obj:`str`, optional): Text format o... | a702f5f0161bfcb28dd52dbfa96ab3192c36ed93 | <|skeleton|>
class VideoMethods:
"""Video methods of the public API."""
def video(self, video_id, text_format=None):
"""Gets data for a specific video. Args: video_id (:obj:`int`): Genius video ID text_format (:obj:`str`, optional): Text format of the results ('dom', 'html', 'markdown' or 'plain'). Ret... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VideoMethods:
"""Video methods of the public API."""
def video(self, video_id, text_format=None):
"""Gets data for a specific video. Args: video_id (:obj:`int`): Genius video ID text_format (:obj:`str`, optional): Text format of the results ('dom', 'html', 'markdown' or 'plain'). Returns: :obj:`d... | the_stack_v2_python_sparse | lyricsgenius/api/public_methods/video.py | johnwmillr/LyricsGenius | train | 849 |
fda00fd4f413da4a8981cad9804374bab7e1727b | [
"self.data.seek(0)\ndata = pickle.loads(self.data.read())\nif sample and sample < data.shape[0]:\n idx = np.random.randint(0, data.shape[0], size=sample)\n return data[idx, :]\nreturn data",
"if self.data:\n self.data.replace(Binary(pickle.dumps(data, protocol=2)))\nelse:\n self.data.new_file()\n s... | <|body_start_0|>
self.data.seek(0)
data = pickle.loads(self.data.read())
if sample and sample < data.shape[0]:
idx = np.random.randint(0, data.shape[0], size=sample)
return data[idx, :]
return data
<|end_body_0|>
<|body_start_1|>
if self.data:
... | Document representation of a single FCS file. Parameters ----------- file_id: str, required Unique identifier for fcs file file_type: str, required, (default='complete') One of either 'complete' or 'control'; signifies the type of data stored data: FileField Numpy array of fcs events data compensated: bool, required, (... | File | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class File:
"""Document representation of a single FCS file. Parameters ----------- file_id: str, required Unique identifier for fcs file file_type: str, required, (default='complete') One of either 'complete' or 'control'; signifies the type of data stored data: FileField Numpy array of fcs events dat... | stack_v2_sparse_classes_75kplus_train_004970 | 22,785 | permissive | [
{
"docstring": "Retrieve single cell data from database Parameters ---------- sample: int, optional If an integer value is given, a random sample of this size is returned Returns ------- Numpy.array Array of single cell data",
"name": "pull",
"signature": "def pull(self, sample: int or None=None) -> np.... | 2 | stack_v2_sparse_classes_30k_train_021986 | Implement the Python class `File` described below.
Class description:
Document representation of a single FCS file. Parameters ----------- file_id: str, required Unique identifier for fcs file file_type: str, required, (default='complete') One of either 'complete' or 'control'; signifies the type of data stored data: ... | Implement the Python class `File` described below.
Class description:
Document representation of a single FCS file. Parameters ----------- file_id: str, required Unique identifier for fcs file file_type: str, required, (default='complete') One of either 'complete' or 'control'; signifies the type of data stored data: ... | 74baea59cfe9e9f664b6b1bf7abf9847f34893eb | <|skeleton|>
class File:
"""Document representation of a single FCS file. Parameters ----------- file_id: str, required Unique identifier for fcs file file_type: str, required, (default='complete') One of either 'complete' or 'control'; signifies the type of data stored data: FileField Numpy array of fcs events dat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class File:
"""Document representation of a single FCS file. Parameters ----------- file_id: str, required Unique identifier for fcs file file_type: str, required, (default='complete') One of either 'complete' or 'control'; signifies the type of data stored data: FileField Numpy array of fcs events data compensated... | the_stack_v2_python_sparse | CytoPy/data/fcs.py | fabbondanza/CytoPy | train | 0 |
20aedacc18cc7f0f03310d3cbe740c73290aea06 | [
"TextProduct.__init__(self, text, utcnow, ugc_provider, nwsli_provider)\nself.data = parse_product(self)\nself.afos = f'CWA{self.source[1:]}'",
"data = self.data\nif data is None:\n return\nif data.is_corrected:\n txn.execute('DELETE from cwas where issue = %s and num = %s and center = %s', (data.issue, dat... | <|body_start_0|>
TextProduct.__init__(self, text, utcnow, ugc_provider, nwsli_provider)
self.data = parse_product(self)
self.afos = f'CWA{self.source[1:]}'
<|end_body_0|>
<|body_start_1|>
data = self.data
if data is None:
return
if data.is_corrected:
... | Represents a Center Weather Advsiory (CWA) product. | CWAProduct | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CWAProduct:
"""Represents a Center Weather Advsiory (CWA) product."""
def __init__(self, text, utcnow=None, ugc_provider=None, nwsli_provider=None):
"""constructor"""
<|body_0|>
def sql(self, txn):
"""Do SQL related stuff that is required"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_004971 | 9,359 | permissive | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self, text, utcnow=None, ugc_provider=None, nwsli_provider=None)"
},
{
"docstring": "Do SQL related stuff that is required",
"name": "sql",
"signature": "def sql(self, txn)"
},
{
"docstring": "Return the... | 3 | stack_v2_sparse_classes_30k_train_053582 | Implement the Python class `CWAProduct` described below.
Class description:
Represents a Center Weather Advsiory (CWA) product.
Method signatures and docstrings:
- def __init__(self, text, utcnow=None, ugc_provider=None, nwsli_provider=None): constructor
- def sql(self, txn): Do SQL related stuff that is required
- d... | Implement the Python class `CWAProduct` described below.
Class description:
Represents a Center Weather Advsiory (CWA) product.
Method signatures and docstrings:
- def __init__(self, text, utcnow=None, ugc_provider=None, nwsli_provider=None): constructor
- def sql(self, txn): Do SQL related stuff that is required
- d... | 460f44394be05e1b655111595a3d7de3f7e47757 | <|skeleton|>
class CWAProduct:
"""Represents a Center Weather Advsiory (CWA) product."""
def __init__(self, text, utcnow=None, ugc_provider=None, nwsli_provider=None):
"""constructor"""
<|body_0|>
def sql(self, txn):
"""Do SQL related stuff that is required"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CWAProduct:
"""Represents a Center Weather Advsiory (CWA) product."""
def __init__(self, text, utcnow=None, ugc_provider=None, nwsli_provider=None):
"""constructor"""
TextProduct.__init__(self, text, utcnow, ugc_provider, nwsli_provider)
self.data = parse_product(self)
sel... | the_stack_v2_python_sparse | src/pyiem/nws/products/cwa.py | akrherz/pyIEM | train | 38 |
f8b9acfc4f5541e964330df331eb979f41f5d8d1 | [
"insurance_requirement = get_object_or_404(InsuranceRequirement, pk=pk)\nself.check_object_permissions(request, insurance_requirement)\nserializer = InsuranceRequirementRetrieveUpdateDestroySerializer(insurance_requirement, many=False)\nreturn Response(data=serializer.data, status=status.HTTP_200_OK)",
"insurance... | <|body_start_0|>
insurance_requirement = get_object_or_404(InsuranceRequirement, pk=pk)
self.check_object_permissions(request, insurance_requirement)
serializer = InsuranceRequirementRetrieveUpdateDestroySerializer(insurance_requirement, many=False)
return Response(data=serializer.data, ... | InsuranceRequirementRetrieveUpdateDestroyAPIView | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InsuranceRequirementRetrieveUpdateDestroyAPIView:
def get(self, request, pk=None):
"""Retrieve"""
<|body_0|>
def put(self, request, pk=None):
"""Update"""
<|body_1|>
def delete(self, request, pk=None):
"""Delete"""
<|body_2|>
<|end_skele... | stack_v2_sparse_classes_75kplus_train_004972 | 3,452 | permissive | [
{
"docstring": "Retrieve",
"name": "get",
"signature": "def get(self, request, pk=None)"
},
{
"docstring": "Update",
"name": "put",
"signature": "def put(self, request, pk=None)"
},
{
"docstring": "Delete",
"name": "delete",
"signature": "def delete(self, request, pk=None... | 3 | stack_v2_sparse_classes_30k_train_029749 | Implement the Python class `InsuranceRequirementRetrieveUpdateDestroyAPIView` described below.
Class description:
Implement the InsuranceRequirementRetrieveUpdateDestroyAPIView class.
Method signatures and docstrings:
- def get(self, request, pk=None): Retrieve
- def put(self, request, pk=None): Update
- def delete(s... | Implement the Python class `InsuranceRequirementRetrieveUpdateDestroyAPIView` described below.
Class description:
Implement the InsuranceRequirementRetrieveUpdateDestroyAPIView class.
Method signatures and docstrings:
- def get(self, request, pk=None): Retrieve
- def put(self, request, pk=None): Update
- def delete(s... | 289318b0333d830c089f4492716c38d409c365ed | <|skeleton|>
class InsuranceRequirementRetrieveUpdateDestroyAPIView:
def get(self, request, pk=None):
"""Retrieve"""
<|body_0|>
def put(self, request, pk=None):
"""Update"""
<|body_1|>
def delete(self, request, pk=None):
"""Delete"""
<|body_2|>
<|end_skele... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InsuranceRequirementRetrieveUpdateDestroyAPIView:
def get(self, request, pk=None):
"""Retrieve"""
insurance_requirement = get_object_or_404(InsuranceRequirement, pk=pk)
self.check_object_permissions(request, insurance_requirement)
serializer = InsuranceRequirementRetrieveUpdate... | the_stack_v2_python_sparse | workery/tenant_api/views/insurance_requirement.py | wahello/workery-django | train | 0 | |
507133abeab3dde2d0a8fad0b20fb6d7cef979fc | [
"from scitbx.simplex import simplex_opt\nself.center_of_mass = center_of_mass\nself.pdb_object = pdb_object\nself.rb_type = rb_type\nself.l = l\nl.process_message('Simplex minimizing rms difference B-factor profile input and ensemble')\nn = 2\nstart_simplex = []\nif self.rb_type == 'rot':\n for ii in range(n + 1... | <|body_start_0|>
from scitbx.simplex import simplex_opt
self.center_of_mass = center_of_mass
self.pdb_object = pdb_object
self.rb_type = rb_type
self.l = l
l.process_message('Simplex minimizing rms difference B-factor profile input and ensemble')
n = 2
sta... | Simplex optimiser class. Calls scitbx simplex and optimizes target function for rotation and translation | CA_Optimiser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CA_Optimiser:
"""Simplex optimiser class. Calls scitbx simplex and optimizes target function for rotation and translation"""
def __init__(self, trans_sigma=None, rot_sigma=None, pdb_object=None, center_of_mass=None, rb_type=None, l=None):
"""Initialize class and start simplex method"... | stack_v2_sparse_classes_75kplus_train_004973 | 24,369 | no_license | [
{
"docstring": "Initialize class and start simplex method",
"name": "__init__",
"signature": "def __init__(self, trans_sigma=None, rot_sigma=None, pdb_object=None, center_of_mass=None, rb_type=None, l=None)"
},
{
"docstring": "Target function simplex has to be called target",
"name": "target... | 2 | stack_v2_sparse_classes_30k_train_016543 | Implement the Python class `CA_Optimiser` described below.
Class description:
Simplex optimiser class. Calls scitbx simplex and optimizes target function for rotation and translation
Method signatures and docstrings:
- def __init__(self, trans_sigma=None, rot_sigma=None, pdb_object=None, center_of_mass=None, rb_type=... | Implement the Python class `CA_Optimiser` described below.
Class description:
Simplex optimiser class. Calls scitbx simplex and optimizes target function for rotation and translation
Method signatures and docstrings:
- def __init__(self, trans_sigma=None, rot_sigma=None, pdb_object=None, center_of_mass=None, rb_type=... | b55423edb4b0e33110cf96fbd3828f86166924c9 | <|skeleton|>
class CA_Optimiser:
"""Simplex optimiser class. Calls scitbx simplex and optimizes target function for rotation and translation"""
def __init__(self, trans_sigma=None, rot_sigma=None, pdb_object=None, center_of_mass=None, rb_type=None, l=None):
"""Initialize class and start simplex method"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CA_Optimiser:
"""Simplex optimiser class. Calls scitbx simplex and optimizes target function for rotation and translation"""
def __init__(self, trans_sigma=None, rot_sigma=None, pdb_object=None, center_of_mass=None, rb_type=None, l=None):
"""Initialize class and start simplex method"""
fr... | the_stack_v2_python_sparse | scud/pdb/PDB.py | kroon-lab/scud | train | 0 |
784853d4e7f89f3f808949c56bb430cdb7f79c39 | [
"if self.request.version == 'v6' or self.request.version == 'v7':\n return self.get_v6(request, dsm_id=dsm_id)\nelse:\n raise Http404",
"try:\n dsm = DataSetMember.objects.get_details_v6(dsm_id)\nexcept DataSet.DoesNotExist:\n raise Http404\nserializer = self.get_serializer(dsm)\nreturn Response(seria... | <|body_start_0|>
if self.request.version == 'v6' or self.request.version == 'v7':
return self.get_v6(request, dsm_id=dsm_id)
else:
raise Http404
<|end_body_0|>
<|body_start_1|>
try:
dsm = DataSetMember.objects.get_details_v6(dsm_id)
except DataSet.Doe... | This view is the endpoint for retrieving details of a specific dataset member | DataSetMemberDetailsView | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataSetMemberDetailsView:
"""This view is the endpoint for retrieving details of a specific dataset member"""
def get(self, request, dsm_id):
"""Retrieves the details for a data set and return them in JSON form :param request: the HTTP GET request :type request: :class:`rest_framewor... | stack_v2_sparse_classes_75kplus_train_004974 | 24,544 | permissive | [
{
"docstring": "Retrieves the details for a data set and return them in JSON form :param request: the HTTP GET request :type request: :class:`rest_framework.request.Request` :param dsm_id: The dataset member id :type dsm_id: int encoded as a str :rtype: :class:`rest_framework.response.Response` :returns: the HT... | 2 | stack_v2_sparse_classes_30k_train_016596 | Implement the Python class `DataSetMemberDetailsView` described below.
Class description:
This view is the endpoint for retrieving details of a specific dataset member
Method signatures and docstrings:
- def get(self, request, dsm_id): Retrieves the details for a data set and return them in JSON form :param request: ... | Implement the Python class `DataSetMemberDetailsView` described below.
Class description:
This view is the endpoint for retrieving details of a specific dataset member
Method signatures and docstrings:
- def get(self, request, dsm_id): Retrieves the details for a data set and return them in JSON form :param request: ... | 28618aee07ceed9e4a6eb7b8d0e6f05b31d8fd6b | <|skeleton|>
class DataSetMemberDetailsView:
"""This view is the endpoint for retrieving details of a specific dataset member"""
def get(self, request, dsm_id):
"""Retrieves the details for a data set and return them in JSON form :param request: the HTTP GET request :type request: :class:`rest_framewor... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataSetMemberDetailsView:
"""This view is the endpoint for retrieving details of a specific dataset member"""
def get(self, request, dsm_id):
"""Retrieves the details for a data set and return them in JSON form :param request: the HTTP GET request :type request: :class:`rest_framework.request.Req... | the_stack_v2_python_sparse | scale/data/views.py | kfconsultant/scale | train | 0 |
3de78b84a8fe8dedfeb021f99996643bad8b60b0 | [
"n = len(s)\ndp = [[0 for _ in range(n)] for _ in range(n)]\nmax_length = 1\nmax_str = s[0]\nfor i in range(n):\n dp[i][i] = 1\nfor i in range(n - 1):\n if s[i] == s[i + 1]:\n dp[i][i + 1] = 1\n max_str = s[i:i + 2]\n max_length = 2\nfor k in range(3, n + 1):\n for i in range(n - k + 1... | <|body_start_0|>
n = len(s)
dp = [[0 for _ in range(n)] for _ in range(n)]
max_length = 1
max_str = s[0]
for i in range(n):
dp[i][i] = 1
for i in range(n - 1):
if s[i] == s[i + 1]:
dp[i][i + 1] = 1
max_str = s[i:i + ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome(self, s: str) -> str:
"""DP 视频:https://www.youtube.com/watch?v=UflHuQj6MVA&t=441s 代码:https://www.geeksforgeeks.org/longest-palindrome-substring-set-1/ 思想: 先判断最长的子串是否为 1,2,及大于 3 max_length = 1, max_str = s[0], dp[i][i] = 1 max_length = 2, max_str = s[i:i+2]... | stack_v2_sparse_classes_75kplus_train_004975 | 4,264 | no_license | [
{
"docstring": "DP 视频:https://www.youtube.com/watch?v=UflHuQj6MVA&t=441s 代码:https://www.geeksforgeeks.org/longest-palindrome-substring-set-1/ 思想: 先判断最长的子串是否为 1,2,及大于 3 max_length = 1, max_str = s[0], dp[i][i] = 1 max_length = 2, max_str = s[i:i+2], dp[i][i+1] = 1 max_length >= 3, max_str = s[i:i+k], k is the le... | 2 | stack_v2_sparse_classes_30k_train_012529 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s: str) -> str: DP 视频:https://www.youtube.com/watch?v=UflHuQj6MVA&t=441s 代码:https://www.geeksforgeeks.org/longest-palindrome-substring-set-1/ 思想: 先判断最... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s: str) -> str: DP 视频:https://www.youtube.com/watch?v=UflHuQj6MVA&t=441s 代码:https://www.geeksforgeeks.org/longest-palindrome-substring-set-1/ 思想: 先判断最... | 3a5649357e0f21cbbc5e238351300cd706d533b3 | <|skeleton|>
class Solution:
def longestPalindrome(self, s: str) -> str:
"""DP 视频:https://www.youtube.com/watch?v=UflHuQj6MVA&t=441s 代码:https://www.geeksforgeeks.org/longest-palindrome-substring-set-1/ 思想: 先判断最长的子串是否为 1,2,及大于 3 max_length = 1, max_str = s[0], dp[i][i] = 1 max_length = 2, max_str = s[i:i+2]... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def longestPalindrome(self, s: str) -> str:
"""DP 视频:https://www.youtube.com/watch?v=UflHuQj6MVA&t=441s 代码:https://www.geeksforgeeks.org/longest-palindrome-substring-set-1/ 思想: 先判断最长的子串是否为 1,2,及大于 3 max_length = 1, max_str = s[0], dp[i][i] = 1 max_length = 2, max_str = s[i:i+2], dp[i][i+1] =... | the_stack_v2_python_sparse | leetcode-py/leetcode5.py | cicihou/LearningProject | train | 0 | |
62f96a6d2ff09586914263ebfbdb2827d8ad5e38 | [
"view = cls.as_view('periodic_expenses')\napp.add_url_rule('/api/budgets/<int:budget_id>/periodic-expenses', defaults={'expense_id': None}, view_func=view, methods=['GET'])\napp.add_url_rule('/api/budgets/<int:budget_id>/periodic-expenses', view_func=view, methods=['POST'])\napp.add_url_rule('/api/budget-periodic-e... | <|body_start_0|>
view = cls.as_view('periodic_expenses')
app.add_url_rule('/api/budgets/<int:budget_id>/periodic-expenses', defaults={'expense_id': None}, view_func=view, methods=['GET'])
app.add_url_rule('/api/budgets/<int:budget_id>/periodic-expenses', view_func=view, methods=['POST'])
... | Periodic expense REST resource view | PeriodicExpensesView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PeriodicExpensesView:
"""Periodic expense REST resource view"""
def register(cls, app: Flask):
"""Registers routes for this view"""
<|body_0|>
def get(budget_id: Optional[int], expense_id: Optional[int]):
"""Gets a specific periodic expense or all expenses in the... | stack_v2_sparse_classes_75kplus_train_004976 | 17,779 | permissive | [
{
"docstring": "Registers routes for this view",
"name": "register",
"signature": "def register(cls, app: Flask)"
},
{
"docstring": "Gets a specific periodic expense or all expenses in the specified budget",
"name": "get",
"signature": "def get(budget_id: Optional[int], expense_id: Optio... | 5 | stack_v2_sparse_classes_30k_train_008356 | Implement the Python class `PeriodicExpensesView` described below.
Class description:
Periodic expense REST resource view
Method signatures and docstrings:
- def register(cls, app: Flask): Registers routes for this view
- def get(budget_id: Optional[int], expense_id: Optional[int]): Gets a specific periodic expense o... | Implement the Python class `PeriodicExpensesView` described below.
Class description:
Periodic expense REST resource view
Method signatures and docstrings:
- def register(cls, app: Flask): Registers routes for this view
- def get(budget_id: Optional[int], expense_id: Optional[int]): Gets a specific periodic expense o... | 20d992356952542fd79aab69849a04129fa22de2 | <|skeleton|>
class PeriodicExpensesView:
"""Periodic expense REST resource view"""
def register(cls, app: Flask):
"""Registers routes for this view"""
<|body_0|>
def get(budget_id: Optional[int], expense_id: Optional[int]):
"""Gets a specific periodic expense or all expenses in the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PeriodicExpensesView:
"""Periodic expense REST resource view"""
def register(cls, app: Flask):
"""Registers routes for this view"""
view = cls.as_view('periodic_expenses')
app.add_url_rule('/api/budgets/<int:budget_id>/periodic-expenses', defaults={'expense_id': None}, view_func=v... | the_stack_v2_python_sparse | backend/underbudget/views/budgets.py | vimofthevine/underbudget4 | train | 0 |
611c8f7d9d6e07e95cdf20f0ccea9c25816f83a1 | [
"if record.__dict__.get('request_id', None):\n self._fmt = FLAGS.logging_context_format_string\nelse:\n self._fmt = FLAGS.logging_default_format_string\nif record.levelno == logging.DEBUG and FLAGS.logging_debug_format_suffix:\n self._fmt += ' ' + FLAGS.logging_debug_format_suffix\nif record.exc_info:\n ... | <|body_start_0|>
if record.__dict__.get('request_id', None):
self._fmt = FLAGS.logging_context_format_string
else:
self._fmt = FLAGS.logging_default_format_string
if record.levelno == logging.DEBUG and FLAGS.logging_debug_format_suffix:
self._fmt += ' ' + FLAG... | A nova.context.RequestContext aware formatter configured through flags. The flags used to set format strings are: logging_context_foramt_string and logging_default_format_string. You can also specify logging_debug_format_suffix to append extra formatting if the log level is debug. For information about what variables a... | NovaFormatter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NovaFormatter:
"""A nova.context.RequestContext aware formatter configured through flags. The flags used to set format strings are: logging_context_foramt_string and logging_default_format_string. You can also specify logging_debug_format_suffix to append extra formatting if the log level is debu... | stack_v2_sparse_classes_75kplus_train_004977 | 11,477 | permissive | [
{
"docstring": "Uses contextstring if request_id is set, otherwise default.",
"name": "format",
"signature": "def format(self, record)"
},
{
"docstring": "Format exception output with FLAGS.logging_exception_prefix.",
"name": "formatException",
"signature": "def formatException(self, exc... | 2 | stack_v2_sparse_classes_30k_train_010283 | Implement the Python class `NovaFormatter` described below.
Class description:
A nova.context.RequestContext aware formatter configured through flags. The flags used to set format strings are: logging_context_foramt_string and logging_default_format_string. You can also specify logging_debug_format_suffix to append ex... | Implement the Python class `NovaFormatter` described below.
Class description:
A nova.context.RequestContext aware formatter configured through flags. The flags used to set format strings are: logging_context_foramt_string and logging_default_format_string. You can also specify logging_debug_format_suffix to append ex... | 1a3d7575d4b341f64fa1764ed47e47a7504a9bcc | <|skeleton|>
class NovaFormatter:
"""A nova.context.RequestContext aware formatter configured through flags. The flags used to set format strings are: logging_context_foramt_string and logging_default_format_string. You can also specify logging_debug_format_suffix to append extra formatting if the log level is debu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NovaFormatter:
"""A nova.context.RequestContext aware formatter configured through flags. The flags used to set format strings are: logging_context_foramt_string and logging_default_format_string. You can also specify logging_debug_format_suffix to append extra formatting if the log level is debug. For inform... | the_stack_v2_python_sparse | stack/nova/nova/log.py | ashokcse/openstack-bill | train | 5 |
6f510f3d164dc8a38820e8365f07d0bdd3db2009 | [
"start_time = self.start_time\nend_time = self.end_time\nself.data = {'offset': '0', 'limit': '20', 'searchname': None, 'SCHEDULENAME': None, 'qdi': self.apiqdi, 'starttime': start_time, 'endtime': end_time, 'datetype': self.apidatatype, 'token': self.token, 'channelcode': None, 'code': getattr(self, 'request_code'... | <|body_start_0|>
start_time = self.start_time
end_time = self.end_time
self.data = {'offset': '0', 'limit': '20', 'searchname': None, 'SCHEDULENAME': None, 'qdi': self.apiqdi, 'starttime': start_time, 'endtime': end_time, 'datetype': self.apidatatype, 'token': self.token, 'channelcode': None, 'c... | ChannelBase2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChannelBase2:
def request_data_home(self):
"""构造首页请求数据"""
<|body_0|>
def f_search(self, **kwargs):
"""查询流程 :param kwargs: :return"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
start_time = self.start_time
end_time = self.end_time
s... | stack_v2_sparse_classes_75kplus_train_004978 | 21,435 | no_license | [
{
"docstring": "构造首页请求数据",
"name": "request_data_home",
"signature": "def request_data_home(self)"
},
{
"docstring": "查询流程 :param kwargs: :return",
"name": "f_search",
"signature": "def f_search(self, **kwargs)"
}
] | 2 | null | Implement the Python class `ChannelBase2` described below.
Class description:
Implement the ChannelBase2 class.
Method signatures and docstrings:
- def request_data_home(self): 构造首页请求数据
- def f_search(self, **kwargs): 查询流程 :param kwargs: :return | Implement the Python class `ChannelBase2` described below.
Class description:
Implement the ChannelBase2 class.
Method signatures and docstrings:
- def request_data_home(self): 构造首页请求数据
- def f_search(self, **kwargs): 查询流程 :param kwargs: :return
<|skeleton|>
class ChannelBase2:
def request_data_home(self):
... | 8c3a2447e53f1fcf7d418e171a01c8e94fc4c8ae | <|skeleton|>
class ChannelBase2:
def request_data_home(self):
"""构造首页请求数据"""
<|body_0|>
def f_search(self, **kwargs):
"""查询流程 :param kwargs: :return"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChannelBase2:
def request_data_home(self):
"""构造首页请求数据"""
start_time = self.start_time
end_time = self.end_time
self.data = {'offset': '0', 'limit': '20', 'searchname': None, 'SCHEDULENAME': None, 'qdi': self.apiqdi, 'starttime': start_time, 'endtime': end_time, 'datetype': sel... | the_stack_v2_python_sparse | BI_6.0.7_WebUI_AUTOTOOLS_003/BI_6.0.7_WebUI_AUTOTOOLS_03/BI_6.0.7_WebUI_AUTOTOOLS_03/flow/biportal/channelbase.py | demi52/mandy | train | 0 | |
c87919dc93fafaa2d8e584a99a9487bedd084d4f | [
"if velocity is not None:\n numvel = len(velocity)\n myvel = velocity\n if numvel > dim:\n dim = numvel\n elif numvel < dim:\n myvel = np.zeros(shape=(dim,))\n for i in range(numvel):\n myvel[i] = velocity[i]\n self._velocity = myvel\nelse:\n self._velocity = np.zer... | <|body_start_0|>
if velocity is not None:
numvel = len(velocity)
myvel = velocity
if numvel > dim:
dim = numvel
elif numvel < dim:
myvel = np.zeros(shape=(dim,))
for i in range(numvel):
myvel[i] =... | Solution initializer for a uniform flow. A uniform flow is the same everywhere and should have a zero RHS. .. automethod:: __init__ .. automethod:: __call__ .. automethod:: exact_rhs | Uniform | [
"X11",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Uniform:
"""Solution initializer for a uniform flow. A uniform flow is the same everywhere and should have a zero RHS. .. automethod:: __init__ .. automethod:: __call__ .. automethod:: exact_rhs"""
def __init__(self, *, dim=1, nspecies=0, rho=1.0, p=1.0, e=2.5, velocity=None, mass_fracs=None... | stack_v2_sparse_classes_75kplus_train_004979 | 32,800 | permissive | [
{
"docstring": "Initialize uniform flow parameters. Parameters ---------- dim: int specify the number of dimensions for the flow nspecies: int specify the number of species in the flow rho: float specifies the density p: float specifies the pressure e: float specifies the internal energy velocity: numpy.ndarray... | 3 | stack_v2_sparse_classes_30k_train_052324 | Implement the Python class `Uniform` described below.
Class description:
Solution initializer for a uniform flow. A uniform flow is the same everywhere and should have a zero RHS. .. automethod:: __init__ .. automethod:: __call__ .. automethod:: exact_rhs
Method signatures and docstrings:
- def __init__(self, *, dim=... | Implement the Python class `Uniform` described below.
Class description:
Solution initializer for a uniform flow. A uniform flow is the same everywhere and should have a zero RHS. .. automethod:: __init__ .. automethod:: __call__ .. automethod:: exact_rhs
Method signatures and docstrings:
- def __init__(self, *, dim=... | 47f144782258eae2b1fb39520e96f414ae176ff4 | <|skeleton|>
class Uniform:
"""Solution initializer for a uniform flow. A uniform flow is the same everywhere and should have a zero RHS. .. automethod:: __init__ .. automethod:: __call__ .. automethod:: exact_rhs"""
def __init__(self, *, dim=1, nspecies=0, rho=1.0, p=1.0, e=2.5, velocity=None, mass_fracs=None... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Uniform:
"""Solution initializer for a uniform flow. A uniform flow is the same everywhere and should have a zero RHS. .. automethod:: __init__ .. automethod:: __call__ .. automethod:: exact_rhs"""
def __init__(self, *, dim=1, nspecies=0, rho=1.0, p=1.0, e=2.5, velocity=None, mass_fracs=None):
""... | the_stack_v2_python_sparse | mirgecom/initializers.py | kaushikcfd/mirgecom | train | 0 |
45b8714287765098e1b2c8ce6734369aba64d6ad | [
"gateway = JavaGateway(gateway_parameters=GatewayParameters(auto_convert=True))\nself.java_image_stacker = gateway.entry_point.getImageStacker()\nself.config_parse = config_file",
"image_path = self.java_image_stacker.stackImageFromPaths(paths, self.config_parse['GENERAL']['fitsimagepaths'], int(self.config_parse... | <|body_start_0|>
gateway = JavaGateway(gateway_parameters=GatewayParameters(auto_convert=True))
self.java_image_stacker = gateway.entry_point.getImageStacker()
self.config_parse = config_file
<|end_body_0|>
<|body_start_1|>
image_path = self.java_image_stacker.stackImageFromPaths(paths,... | 'Bridge' between python and java image stacker | ImageStacker | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageStacker:
"""'Bridge' between python and java image stacker"""
def __init__(self, config_file):
"""initialise the gateway to the java image stacker"""
<|body_0|>
def convert_from_paths(self, paths):
"""Take paths of fits images and send them to the java image... | stack_v2_sparse_classes_75kplus_train_004980 | 1,246 | permissive | [
{
"docstring": "initialise the gateway to the java image stacker",
"name": "__init__",
"signature": "def __init__(self, config_file)"
},
{
"docstring": "Take paths of fits images and send them to the java image stacker to process into one image",
"name": "convert_from_paths",
"signature"... | 2 | null | Implement the Python class `ImageStacker` described below.
Class description:
'Bridge' between python and java image stacker
Method signatures and docstrings:
- def __init__(self, config_file): initialise the gateway to the java image stacker
- def convert_from_paths(self, paths): Take paths of fits images and send t... | Implement the Python class `ImageStacker` described below.
Class description:
'Bridge' between python and java image stacker
Method signatures and docstrings:
- def __init__(self, config_file): initialise the gateway to the java image stacker
- def convert_from_paths(self, paths): Take paths of fits images and send t... | 5e5946eb7198c6d83aafdbae49e4780c9fd15467 | <|skeleton|>
class ImageStacker:
"""'Bridge' between python and java image stacker"""
def __init__(self, config_file):
"""initialise the gateway to the java image stacker"""
<|body_0|>
def convert_from_paths(self, paths):
"""Take paths of fits images and send them to the java image... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImageStacker:
"""'Bridge' between python and java image stacker"""
def __init__(self, config_file):
"""initialise the gateway to the java image stacker"""
gateway = JavaGateway(gateway_parameters=GatewayParameters(auto_convert=True))
self.java_image_stacker = gateway.entry_point.g... | the_stack_v2_python_sparse | meteoreala/image_stacking.py | HmirceaD/Meteoreala-Project | train | 0 |
97d68ea6d8f1a442b9dfcad0f46cf6af6f3d71da | [
"self.links = []\nself.feed(html)\nreturn self.links",
"if tag == 'a':\n for name, value in attrs:\n if name == 'href':\n self.links.append(value)"
] | <|body_start_0|>
self.links = []
self.feed(html)
return self.links
<|end_body_0|>
<|body_start_1|>
if tag == 'a':
for name, value in attrs:
if name == 'href':
self.links.append(value)
<|end_body_1|>
| Link parser. | LinkParser | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinkParser:
"""Link parser."""
def parse(self, html: str) -> list:
"""Parse links in html string. Args: html: html document Returns: List of the found links list"""
<|body_0|>
def handle_starttag(self, tag, attrs):
"""Handle starttag. Called by parse method Args:... | stack_v2_sparse_classes_75kplus_train_004981 | 2,157 | permissive | [
{
"docstring": "Parse links in html string. Args: html: html document Returns: List of the found links list",
"name": "parse",
"signature": "def parse(self, html: str) -> list"
},
{
"docstring": "Handle starttag. Called by parse method Args: tag: element tag attrs: element attributes",
"name... | 2 | stack_v2_sparse_classes_30k_train_025712 | Implement the Python class `LinkParser` described below.
Class description:
Link parser.
Method signatures and docstrings:
- def parse(self, html: str) -> list: Parse links in html string. Args: html: html document Returns: List of the found links list
- def handle_starttag(self, tag, attrs): Handle starttag. Called ... | Implement the Python class `LinkParser` described below.
Class description:
Link parser.
Method signatures and docstrings:
- def parse(self, html: str) -> list: Parse links in html string. Args: html: html document Returns: List of the found links list
- def handle_starttag(self, tag, attrs): Handle starttag. Called ... | 766b538ac90daa8f8eadce8a1fd43f83413610de | <|skeleton|>
class LinkParser:
"""Link parser."""
def parse(self, html: str) -> list:
"""Parse links in html string. Args: html: html document Returns: List of the found links list"""
<|body_0|>
def handle_starttag(self, tag, attrs):
"""Handle starttag. Called by parse method Args:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LinkParser:
"""Link parser."""
def parse(self, html: str) -> list:
"""Parse links in html string. Args: html: html document Returns: List of the found links list"""
self.links = []
self.feed(html)
return self.links
def handle_starttag(self, tag, attrs):
"""Han... | the_stack_v2_python_sparse | saas/web/browser.py | nattvara/saas | train | 2 |
c55ab635fba84566b3d6d2039b5abe279b11d470 | [
"if len(data):\n formatted_data = ujson.loads(data)\n if isinstance(formatted_data, dict):\n return formatted_data.get(ResponseDataConst.DATA, formatted_data)\n else:\n return formatted_data\nelse:\n return {}",
"if len(data):\n formatted_data = ujson.loads(data)\n if isinstance(fo... | <|body_start_0|>
if len(data):
formatted_data = ujson.loads(data)
if isinstance(formatted_data, dict):
return formatted_data.get(ResponseDataConst.DATA, formatted_data)
else:
return formatted_data
else:
return {}
<|end_body_... | JSON data formatter class. | Json | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Json:
"""JSON data formatter class."""
def _format(self, data: AnyStr) -> Dict:
"""Transform raw data from server into python native type."""
<|body_0|>
def _format_meta(self, data: AnyStr) -> Dict:
"""Transform raw data from server into python native type."""
... | stack_v2_sparse_classes_75kplus_train_004982 | 9,312 | permissive | [
{
"docstring": "Transform raw data from server into python native type.",
"name": "_format",
"signature": "def _format(self, data: AnyStr) -> Dict"
},
{
"docstring": "Transform raw data from server into python native type.",
"name": "_format_meta",
"signature": "def _format_meta(self, da... | 2 | stack_v2_sparse_classes_30k_train_023864 | Implement the Python class `Json` described below.
Class description:
JSON data formatter class.
Method signatures and docstrings:
- def _format(self, data: AnyStr) -> Dict: Transform raw data from server into python native type.
- def _format_meta(self, data: AnyStr) -> Dict: Transform raw data from server into pyth... | Implement the Python class `Json` described below.
Class description:
JSON data formatter class.
Method signatures and docstrings:
- def _format(self, data: AnyStr) -> Dict: Transform raw data from server into python native type.
- def _format_meta(self, data: AnyStr) -> Dict: Transform raw data from server into pyth... | 464fe34d089fc04a97944e58e22f3b486e086c90 | <|skeleton|>
class Json:
"""JSON data formatter class."""
def _format(self, data: AnyStr) -> Dict:
"""Transform raw data from server into python native type."""
<|body_0|>
def _format_meta(self, data: AnyStr) -> Dict:
"""Transform raw data from server into python native type."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Json:
"""JSON data formatter class."""
def _format(self, data: AnyStr) -> Dict:
"""Transform raw data from server into python native type."""
if len(data):
formatted_data = ujson.loads(data)
if isinstance(formatted_data, dict):
return formatted_data... | the_stack_v2_python_sparse | marinetrafficapi/formatter.py | amphinicy/marine-traffic-client-api | train | 22 |
a00ef0e759b4072870e87fba2e093578e0c3e770 | [
"self.k_min = k_min\nself.k_max = k_max\nself.s0 = canonical_scale\nself.lvl0 = canonical_level\nself.eps = eps",
"s = torch.sqrt(boxes_area(rois))\ntarget_lvls = torch.floor(self.lvl0 + torch.log2(s / self.s0 + 1e-06))\ntarget_lvls = torch.clamp(target_lvls, min=self.k_min, max=self.k_max)\nreturn target_lvls"
] | <|body_start_0|>
self.k_min = k_min
self.k_max = k_max
self.s0 = canonical_scale
self.lvl0 = canonical_level
self.eps = eps
<|end_body_0|>
<|body_start_1|>
s = torch.sqrt(boxes_area(rois))
target_lvls = torch.floor(self.lvl0 + torch.log2(s / self.s0 + 1e-06))
... | Determine which FPN level each RoI in a set of RoIs should map to based on the heuristic in the FPN paper. | ROI2FPNLevelsMapper | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ROI2FPNLevelsMapper:
"""Determine which FPN level each RoI in a set of RoIs should map to based on the heuristic in the FPN paper."""
def __init__(self, k_min, k_max, canonical_scale=224, canonical_level=4, eps=1e-06):
"""Arguments: k_min (int) k_max (int) canonical_scale (int) canon... | stack_v2_sparse_classes_75kplus_train_004983 | 16,133 | permissive | [
{
"docstring": "Arguments: k_min (int) k_max (int) canonical_scale (int) canonical_level (int) eps (float)",
"name": "__init__",
"signature": "def __init__(self, k_min, k_max, canonical_scale=224, canonical_level=4, eps=1e-06)"
},
{
"docstring": "Arguments: rois: tensor",
"name": "__call__",... | 2 | null | Implement the Python class `ROI2FPNLevelsMapper` described below.
Class description:
Determine which FPN level each RoI in a set of RoIs should map to based on the heuristic in the FPN paper.
Method signatures and docstrings:
- def __init__(self, k_min, k_max, canonical_scale=224, canonical_level=4, eps=1e-06): Argum... | Implement the Python class `ROI2FPNLevelsMapper` described below.
Class description:
Determine which FPN level each RoI in a set of RoIs should map to based on the heuristic in the FPN paper.
Method signatures and docstrings:
- def __init__(self, k_min, k_max, canonical_scale=224, canonical_level=4, eps=1e-06): Argum... | 11c38436a158c453e3011f8684570f7a55c03330 | <|skeleton|>
class ROI2FPNLevelsMapper:
"""Determine which FPN level each RoI in a set of RoIs should map to based on the heuristic in the FPN paper."""
def __init__(self, k_min, k_max, canonical_scale=224, canonical_level=4, eps=1e-06):
"""Arguments: k_min (int) k_max (int) canonical_scale (int) canon... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ROI2FPNLevelsMapper:
"""Determine which FPN level each RoI in a set of RoIs should map to based on the heuristic in the FPN paper."""
def __init__(self, k_min, k_max, canonical_scale=224, canonical_level=4, eps=1e-06):
"""Arguments: k_min (int) k_max (int) canonical_scale (int) canonical_level (i... | the_stack_v2_python_sparse | v0.5.0/nvidia/submission/code/object_detection/pytorch/maskrcnn_benchmark/modeling/post_processors/rpn.py | myelintek/results | train | 0 |
cae282367358cb6be140aaba695fde2476101d30 | [
"self._vm = vm\nself._ops_by_line = collections.defaultdict(list)\nfor op, symbol, type_defs in vm.opcode_traces:\n trace_entry = Trace(op, symbol, type_defs)\n self._ops_by_line[trace_entry.op.line].append(trace_entry)",
"op_types = tuple(op_types)\nentries = self._ops_by_line[line_num]\nops = []\nfor entr... | <|body_start_0|>
self._vm = vm
self._ops_by_line = collections.defaultdict(list)
for op, symbol, type_defs in vm.opcode_traces:
trace_entry = Trace(op, symbol, type_defs)
self._ops_by_line[trace_entry.op.line].append(trace_entry)
<|end_body_0|>
<|body_start_1|>
o... | Collection of Pytype's type inference info. | Traces | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Traces:
"""Collection of Pytype's type inference info."""
def __init__(self, vm):
"""Creates an instance. Args: vm: analyze.CallTracer, VM with all the information gathered by Pytype."""
<|body_0|>
def find_unassociated_traces(self, line_num, op_types, symbol):
"... | stack_v2_sparse_classes_75kplus_train_004984 | 6,965 | permissive | [
{
"docstring": "Creates an instance. Args: vm: analyze.CallTracer, VM with all the information gathered by Pytype.",
"name": "__init__",
"signature": "def __init__(self, vm)"
},
{
"docstring": "Finds `Trace` objects that haven't been associated to an AST node. Args: line_num: int, the line numbe... | 2 | null | Implement the Python class `Traces` described below.
Class description:
Collection of Pytype's type inference info.
Method signatures and docstrings:
- def __init__(self, vm): Creates an instance. Args: vm: analyze.CallTracer, VM with all the information gathered by Pytype.
- def find_unassociated_traces(self, line_n... | Implement the Python class `Traces` described below.
Class description:
Collection of Pytype's type inference info.
Method signatures and docstrings:
- def __init__(self, vm): Creates an instance. Args: vm: analyze.CallTracer, VM with all the information gathered by Pytype.
- def find_unassociated_traces(self, line_n... | 44b1f6f7cddccb326abac4c21b4f26688369764e | <|skeleton|>
class Traces:
"""Collection of Pytype's type inference info."""
def __init__(self, vm):
"""Creates an instance. Args: vm: analyze.CallTracer, VM with all the information gathered by Pytype."""
<|body_0|>
def find_unassociated_traces(self, line_num, op_types, symbol):
"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Traces:
"""Collection of Pytype's type inference info."""
def __init__(self, vm):
"""Creates an instance. Args: vm: analyze.CallTracer, VM with all the information gathered by Pytype."""
self._vm = vm
self._ops_by_line = collections.defaultdict(list)
for op, symbol, type_d... | the_stack_v2_python_sparse | pytype/tools/annotate_ast/annotate_ast.py | priyansh19/pytype | train | 2 |
3003d117cdd59865341ac5acd5fe11872bc08d0c | [
"result, exinfo = check_return_value(retval, exinfo)\nallowed_to_fail: Optional[bool] = None\nif result is FAIL or result is EXCEPTION:\n extra_args = {}\n if isinstance(retval, FAIL):\n if retval.allowed_to_fail is not None:\n extra_args['allowed_to_fail'] = retval.allowed_to_fail\n ... | <|body_start_0|>
result, exinfo = check_return_value(retval, exinfo)
allowed_to_fail: Optional[bool] = None
if result is FAIL or result is EXCEPTION:
extra_args = {}
if isinstance(retval, FAIL):
if retval.allowed_to_fail is not None:
ex... | ResultHandlerMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResultHandlerMixin:
def handle_return_value(valinfo: ValidatorInfo, obj: models.Model, retval: Any, exinfo: Optional[ExceptionInfo]) -> Tuple[Type[Result], Optional[ExceptionInfo], Optional[bool]]:
"""handle the value returned by an instance-method validator :returns: a tuple (result, ex... | stack_v2_sparse_classes_75kplus_train_004985 | 20,738 | permissive | [
{
"docstring": "handle the value returned by an instance-method validator :returns: a tuple (result, exception_info, allowed_to_fail) result: return value of the method cast to Type[Result], exception_info: if there was an exception allowed_to_fail: set if result is FAIL and the object is marked allowed to fail... | 3 | stack_v2_sparse_classes_30k_train_006794 | Implement the Python class `ResultHandlerMixin` described below.
Class description:
Implement the ResultHandlerMixin class.
Method signatures and docstrings:
- def handle_return_value(valinfo: ValidatorInfo, obj: models.Model, retval: Any, exinfo: Optional[ExceptionInfo]) -> Tuple[Type[Result], Optional[ExceptionInfo... | Implement the Python class `ResultHandlerMixin` described below.
Class description:
Implement the ResultHandlerMixin class.
Method signatures and docstrings:
- def handle_return_value(valinfo: ValidatorInfo, obj: models.Model, retval: Any, exinfo: Optional[ExceptionInfo]) -> Tuple[Type[Result], Optional[ExceptionInfo... | 9d3aacb525f4a658504aa24edd50bed54aa5be6e | <|skeleton|>
class ResultHandlerMixin:
def handle_return_value(valinfo: ValidatorInfo, obj: models.Model, retval: Any, exinfo: Optional[ExceptionInfo]) -> Tuple[Type[Result], Optional[ExceptionInfo], Optional[bool]]:
"""handle the value returned by an instance-method validator :returns: a tuple (result, ex... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResultHandlerMixin:
def handle_return_value(valinfo: ValidatorInfo, obj: models.Model, retval: Any, exinfo: Optional[ExceptionInfo]) -> Tuple[Type[Result], Optional[ExceptionInfo], Optional[bool]]:
"""handle the value returned by an instance-method validator :returns: a tuple (result, exception_info, ... | the_stack_v2_python_sparse | datavalidation/runners.py | VersBersh/django-data-validation | train | 1 | |
fb2f8c3d67676e981d18d4e9a510382f81c1b022 | [
"for i in range(len(nums) - 1):\n subarray_sum = nums[i]\n for j in range(i + 1, len(nums)):\n subarray_sum += nums[j]\n if k == 0:\n if subarray_sum == 0:\n return True\n elif subarray_sum % k == 0:\n return True\nreturn False",
"sum = 0\nlookup = {... | <|body_start_0|>
for i in range(len(nums) - 1):
subarray_sum = nums[i]
for j in range(i + 1, len(nums)):
subarray_sum += nums[j]
if k == 0:
if subarray_sum == 0:
return True
elif subarray_sum % k ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def checkSubarraySum_1(self, nums: List[int], k: int) -> bool:
"""1. 暴力遍历"""
<|body_0|>
def checkSubarraySum(self, nums: List[int], k: int) -> bool:
"""2. 哈希表"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for i in range(len(nums) - 1):
... | stack_v2_sparse_classes_75kplus_train_004986 | 1,942 | no_license | [
{
"docstring": "1. 暴力遍历",
"name": "checkSubarraySum_1",
"signature": "def checkSubarraySum_1(self, nums: List[int], k: int) -> bool"
},
{
"docstring": "2. 哈希表",
"name": "checkSubarraySum",
"signature": "def checkSubarraySum(self, nums: List[int], k: int) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_train_033379 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def checkSubarraySum_1(self, nums: List[int], k: int) -> bool: 1. 暴力遍历
- def checkSubarraySum(self, nums: List[int], k: int) -> bool: 2. 哈希表 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def checkSubarraySum_1(self, nums: List[int], k: int) -> bool: 1. 暴力遍历
- def checkSubarraySum(self, nums: List[int], k: int) -> bool: 2. 哈希表
<|skeleton|>
class Solution:
de... | 4732fb80710a08a715c3e7080c394f5298b8326d | <|skeleton|>
class Solution:
def checkSubarraySum_1(self, nums: List[int], k: int) -> bool:
"""1. 暴力遍历"""
<|body_0|>
def checkSubarraySum(self, nums: List[int], k: int) -> bool:
"""2. 哈希表"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def checkSubarraySum_1(self, nums: List[int], k: int) -> bool:
"""1. 暴力遍历"""
for i in range(len(nums) - 1):
subarray_sum = nums[i]
for j in range(i + 1, len(nums)):
subarray_sum += nums[j]
if k == 0:
if subar... | the_stack_v2_python_sparse | .leetcode/523.连续的子数组和.py | xiaoruijiang/algorithm | train | 0 | |
5b34943f12616c4e842d6d59b9e7e9df16cabda5 | [
"self.scale = scale\nself.footprint = footprint\nself.bbox = bounds_to_bbox(footprint.bounds)\nself.peaks = {scale: footprint.peaks}\nself._all_peaks = None",
"if scale not in self.peaks:\n self.peaks[scale] = []\nself.peaks[scale] += footprint.peaks\nself._all_peaks = None",
"for box in tree.query(self.bbox... | <|body_start_0|>
self.scale = scale
self.footprint = footprint
self.bbox = bounds_to_bbox(footprint.bounds)
self.peaks = {scale: footprint.peaks}
self._all_peaks = None
<|end_body_0|>
<|body_start_1|>
if scale not in self.peaks:
self.peaks[scale] = []
... | A structure at a single scale with quadtrees to lookup child boxes at different scales. Using the terminology from Starck et al. 2011 we refere to a connected set of pixels with a common set of peaks at a single scale as a structure. Attributes ---------- scale: `int` The wavelet scale of this structure. footprint: `sc... | SingleScaleStructure | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingleScaleStructure:
"""A structure at a single scale with quadtrees to lookup child boxes at different scales. Using the terminology from Starck et al. 2011 we refere to a connected set of pixels with a common set of peaks at a single scale as a structure. Attributes ---------- scale: `int` The... | stack_v2_sparse_classes_75kplus_train_004987 | 19,114 | permissive | [
{
"docstring": "Initialize the SingleScaleStructure Parameters ---------- scale: `int` The wavelet scale of this structure footprint: `scarlet.detect_pybind11.Footprint` The footprint of this structure at its given scale.",
"name": "__init__",
"signature": "def __init__(self, scale, footprint)"
},
{... | 4 | null | Implement the Python class `SingleScaleStructure` described below.
Class description:
A structure at a single scale with quadtrees to lookup child boxes at different scales. Using the terminology from Starck et al. 2011 we refere to a connected set of pixels with a common set of peaks at a single scale as a structure.... | Implement the Python class `SingleScaleStructure` described below.
Class description:
A structure at a single scale with quadtrees to lookup child boxes at different scales. Using the terminology from Starck et al. 2011 we refere to a connected set of pixels with a common set of peaks at a single scale as a structure.... | 45187fdccbe8b8c8d7551a84572d7243b24bc8cb | <|skeleton|>
class SingleScaleStructure:
"""A structure at a single scale with quadtrees to lookup child boxes at different scales. Using the terminology from Starck et al. 2011 we refere to a connected set of pixels with a common set of peaks at a single scale as a structure. Attributes ---------- scale: `int` The... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SingleScaleStructure:
"""A structure at a single scale with quadtrees to lookup child boxes at different scales. Using the terminology from Starck et al. 2011 we refere to a connected set of pixels with a common set of peaks at a single scale as a structure. Attributes ---------- scale: `int` The wavelet scal... | the_stack_v2_python_sparse | scarlet/detect.py | pmelchior/scarlet | train | 36 |
6b0ae6a2c0d5038e1869254754db0b11075686da | [
"query = self.session.query(SessionModel)\nnow = time.time()\nquery = query.filter(SessionModel.expire_time > now)\nSession_Jar = {session.auth_code: (session.expire_time, session.user_name) for session in query.all()}\nreturn Session_Jar",
"new_session = SessionModel.from_dict(session)\nself.session.add(new_sess... | <|body_start_0|>
query = self.session.query(SessionModel)
now = time.time()
query = query.filter(SessionModel.expire_time > now)
Session_Jar = {session.auth_code: (session.expire_time, session.user_name) for session in query.all()}
return Session_Jar
<|end_body_0|>
<|body_start_... | SessionDao | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SessionDao:
def get_session_jar(self):
"""将数据库持久化保存的session auth code缓存在内存中"""
<|body_0|>
def add_session(self, session):
"""将session数据存入 :param session: :return:"""
<|body_1|>
def delete_session(self, auth_code):
"""删除过期的auth_code,用户需要重新登录 :para... | stack_v2_sparse_classes_75kplus_train_004988 | 10,198 | permissive | [
{
"docstring": "将数据库持久化保存的session auth code缓存在内存中",
"name": "get_session_jar",
"signature": "def get_session_jar(self)"
},
{
"docstring": "将session数据存入 :param session: :return:",
"name": "add_session",
"signature": "def add_session(self, session)"
},
{
"docstring": "删除过期的auth_cod... | 5 | stack_v2_sparse_classes_30k_train_016692 | Implement the Python class `SessionDao` described below.
Class description:
Implement the SessionDao class.
Method signatures and docstrings:
- def get_session_jar(self): 将数据库持久化保存的session auth code缓存在内存中
- def add_session(self, session): 将session数据存入 :param session: :return:
- def delete_session(self, auth_code): 删除... | Implement the Python class `SessionDao` described below.
Class description:
Implement the SessionDao class.
Method signatures and docstrings:
- def get_session_jar(self): 将数据库持久化保存的session auth code缓存在内存中
- def add_session(self, session): 将session数据存入 :param session: :return:
- def delete_session(self, auth_code): 删除... | 2e32e6e7b225e0bd87ee8c847c22862f12c51bb1 | <|skeleton|>
class SessionDao:
def get_session_jar(self):
"""将数据库持久化保存的session auth code缓存在内存中"""
<|body_0|>
def add_session(self, session):
"""将session数据存入 :param session: :return:"""
<|body_1|>
def delete_session(self, auth_code):
"""删除过期的auth_code,用户需要重新登录 :para... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SessionDao:
def get_session_jar(self):
"""将数据库持久化保存的session auth code缓存在内存中"""
query = self.session.query(SessionModel)
now = time.time()
query = query.filter(SessionModel.expire_time > now)
Session_Jar = {session.auth_code: (session.expire_time, session.user_name) for ... | the_stack_v2_python_sparse | nebula/dao/user_dao.py | threathunterX/nebula_web | train | 2 | |
85cf03543052069c7936fb1466192326a33c8f90 | [
"self.errors = JsonBackend(fname='errors', initialize=False)\nself._cork = cork_obj\nassert error_name in self.errors, 'Unknown error'\nself.error_name = error_name\nerror = self._cork.errors[error_name]\nself.time = error['time']\nself.counted = error['counted']\nif session is not None:\n try:\n self.ses... | <|body_start_0|>
self.errors = JsonBackend(fname='errors', initialize=False)
self._cork = cork_obj
assert error_name in self.errors, 'Unknown error'
self.error_name = error_name
error = self._cork.errors[error_name]
self.time = error['time']
self.counted = error['... | Errors | [
"X11-distribute-modifications-variant"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Errors:
def __init__(self, error_name, cork_obj, session=None):
"""Represent an authenticated user, exposing useful attributes: email_addr, role, level, description, email_addr, session_creation_time, session_accessed_time, session_id. The session-related attributes are available for the... | stack_v2_sparse_classes_75kplus_train_004989 | 6,513 | permissive | [
{
"docstring": "Represent an authenticated user, exposing useful attributes: email_addr, role, level, description, email_addr, session_creation_time, session_accessed_time, session_id. The session-related attributes are available for the current user only. :param email_addr: email_addr :type email_addr: str. :p... | 3 | stack_v2_sparse_classes_30k_train_035025 | Implement the Python class `Errors` described below.
Class description:
Implement the Errors class.
Method signatures and docstrings:
- def __init__(self, error_name, cork_obj, session=None): Represent an authenticated user, exposing useful attributes: email_addr, role, level, description, email_addr, session_creatio... | Implement the Python class `Errors` described below.
Class description:
Implement the Errors class.
Method signatures and docstrings:
- def __init__(self, error_name, cork_obj, session=None): Represent an authenticated user, exposing useful attributes: email_addr, role, level, description, email_addr, session_creatio... | 4559b9053a5af83b0bf6d267bb65cbd2faa3b7d3 | <|skeleton|>
class Errors:
def __init__(self, error_name, cork_obj, session=None):
"""Represent an authenticated user, exposing useful attributes: email_addr, role, level, description, email_addr, session_creation_time, session_accessed_time, session_id. The session-related attributes are available for the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Errors:
def __init__(self, error_name, cork_obj, session=None):
"""Represent an authenticated user, exposing useful attributes: email_addr, role, level, description, email_addr, session_creation_time, session_accessed_time, session_id. The session-related attributes are available for the current user ... | the_stack_v2_python_sparse | munin/json_backend.py | namndev/python-munin | train | 1 | |
08b463d8d16a3f31c24c226dbc218f1910de4085 | [
"super(SequenceThumbnailTask, self).__init__(*args, **kwargs)\nself.setOption('width', self.__defaultWidth)\nself.setOption('height', self.__defaultHeight)",
"targetThumbnails = OrderedDict()\nfor crawler in self.crawlers():\n targetFilePath = self.target(crawler)\n if targetFilePath not in targetThumbnails... | <|body_start_0|>
super(SequenceThumbnailTask, self).__init__(*args, **kwargs)
self.setOption('width', self.__defaultWidth)
self.setOption('height', self.__defaultHeight)
<|end_body_0|>
<|body_start_1|>
targetThumbnails = OrderedDict()
for crawler in self.crawlers():
... | Creates a thumbnail for the image sequence. | SequenceThumbnailTask | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequenceThumbnailTask:
"""Creates a thumbnail for the image sequence."""
def __init__(self, *args, **kwargs):
"""Create a sequence thumbnail object."""
<|body_0|>
def _perform(self):
"""Perform the task."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_004990 | 1,609 | permissive | [
{
"docstring": "Create a sequence thumbnail object.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Perform the task.",
"name": "_perform",
"signature": "def _perform(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002919 | Implement the Python class `SequenceThumbnailTask` described below.
Class description:
Creates a thumbnail for the image sequence.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create a sequence thumbnail object.
- def _perform(self): Perform the task. | Implement the Python class `SequenceThumbnailTask` described below.
Class description:
Creates a thumbnail for the image sequence.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create a sequence thumbnail object.
- def _perform(self): Perform the task.
<|skeleton|>
class SequenceThumbnailT... | 046dbb0c1b4ff20ea5f2e1679f8d89f3089b6aa4 | <|skeleton|>
class SequenceThumbnailTask:
"""Creates a thumbnail for the image sequence."""
def __init__(self, *args, **kwargs):
"""Create a sequence thumbnail object."""
<|body_0|>
def _perform(self):
"""Perform the task."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SequenceThumbnailTask:
"""Creates a thumbnail for the image sequence."""
def __init__(self, *args, **kwargs):
"""Create a sequence thumbnail object."""
super(SequenceThumbnailTask, self).__init__(*args, **kwargs)
self.setOption('width', self.__defaultWidth)
self.setOption(... | the_stack_v2_python_sparse | src/lib/kombi/Task/ImageSequence/SequenceThumbnailTask.py | kombiHQ/kombi | train | 2 |
930d424ded6f0aa0b028987689428d781d1a81a6 | [
"self.forumName = ''\nself.lms = ''\nself.introduction = ''\nself._nameInstruc = x_(u'Type a forum name here')\nself.lms = Lms()\nself.lms.idevice = self\nself.subjectInstruc = ''\nself.messageInstruc = ''\nself.discussions = []\nself._lmsInstruc = x_('Choose a LMS')\nself.refCount = 1",
"if discussion in self.di... | <|body_start_0|>
self.forumName = ''
self.lms = ''
self.introduction = ''
self._nameInstruc = x_(u'Type a forum name here')
self.lms = Lms()
self.lms.idevice = self
self.subjectInstruc = ''
self.messageInstruc = ''
self.discussions = []
sel... | Forum | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Forum:
def __init__(self):
"""Initialize"""
<|body_0|>
def addDiscussion(self, discussion):
"""adds a new topic. If the topic already exists increments a reference count"""
<|body_1|>
def deleteDiscussion(self, discussion):
"""decrements the refe... | stack_v2_sparse_classes_75kplus_train_004991 | 4,530 | no_license | [
{
"docstring": "Initialize",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "adds a new topic. If the topic already exists increments a reference count",
"name": "addDiscussion",
"signature": "def addDiscussion(self, discussion)"
},
{
"docstring": "decrem... | 3 | null | Implement the Python class `Forum` described below.
Class description:
Implement the Forum class.
Method signatures and docstrings:
- def __init__(self): Initialize
- def addDiscussion(self, discussion): adds a new topic. If the topic already exists increments a reference count
- def deleteDiscussion(self, discussion... | Implement the Python class `Forum` described below.
Class description:
Implement the Forum class.
Method signatures and docstrings:
- def __init__(self): Initialize
- def addDiscussion(self, discussion): adds a new topic. If the topic already exists increments a reference count
- def deleteDiscussion(self, discussion... | 1a99c1788f0eb9f1e5d8c2ced3892d00cd9449ad | <|skeleton|>
class Forum:
def __init__(self):
"""Initialize"""
<|body_0|>
def addDiscussion(self, discussion):
"""adds a new topic. If the topic already exists increments a reference count"""
<|body_1|>
def deleteDiscussion(self, discussion):
"""decrements the refe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Forum:
def __init__(self):
"""Initialize"""
self.forumName = ''
self.lms = ''
self.introduction = ''
self._nameInstruc = x_(u'Type a forum name here')
self.lms = Lms()
self.lms.idevice = self
self.subjectInstruc = ''
self.messageInstruc =... | the_stack_v2_python_sparse | eXe/rev1889-1952/base-trunk-1889/exe/idevices/forumidevice.py | joliebig/featurehouse_fstmerge_examples | train | 3 | |
ddf04b008cb356ba984b8ba435a6ac09680f89a0 | [
"rv, ref = self.execute_rv('--git-dir=' + git_dir, 'show-ref', '--head')\nif rv != 0:\n err('failed to extract a submodule revision')\n return None\nrevision = ref.split(None, 2)[1]\nif revision.startswith('refs/heads/'):\n revision = revision[len('refs/heads/'):]\nelif revision.startswith('refs/remotes/or... | <|body_start_0|>
rv, ref = self.execute_rv('--git-dir=' + git_dir, 'show-ref', '--head')
if rv != 0:
err('failed to extract a submodule revision')
return None
revision = ref.split(None, 2)[1]
if revision.startswith('refs/heads/'):
revision = revision[l... | git host tool Provides addition helper methods for git-based tool interaction. | GitTool | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GitTool:
"""git host tool Provides addition helper methods for git-based tool interaction."""
def extract_submodule_revision(self, git_dir):
"""extract a submodule revision Attempts to extract the HEAD reference of a submodule based off a provided git Git repository. This is to help ... | stack_v2_sparse_classes_75kplus_train_004992 | 4,129 | permissive | [
{
"docstring": "extract a submodule revision Attempts to extract the HEAD reference of a submodule based off a provided git Git repository. This is to help support processing Git submodules which do not have a branch/version explicitly set for module, which is required for (at least) recursive submodule process... | 3 | stack_v2_sparse_classes_30k_train_019259 | Implement the Python class `GitTool` described below.
Class description:
git host tool Provides addition helper methods for git-based tool interaction.
Method signatures and docstrings:
- def extract_submodule_revision(self, git_dir): extract a submodule revision Attempts to extract the HEAD reference of a submodule ... | Implement the Python class `GitTool` described below.
Class description:
git host tool Provides addition helper methods for git-based tool interaction.
Method signatures and docstrings:
- def extract_submodule_revision(self, git_dir): extract a submodule revision Attempts to extract the HEAD reference of a submodule ... | d05eb2153c72e9bd82c5fdddd5eb41d5316592d6 | <|skeleton|>
class GitTool:
"""git host tool Provides addition helper methods for git-based tool interaction."""
def extract_submodule_revision(self, git_dir):
"""extract a submodule revision Attempts to extract the HEAD reference of a submodule based off a provided git Git repository. This is to help ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GitTool:
"""git host tool Provides addition helper methods for git-based tool interaction."""
def extract_submodule_revision(self, git_dir):
"""extract a submodule revision Attempts to extract the HEAD reference of a submodule based off a provided git Git repository. This is to help support proce... | the_stack_v2_python_sparse | releng_tool/tool/git.py | releng-tool/releng-tool | train | 12 |
5d07a0dd38dc97d564b1800c73d3993db704d2bd | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | The JobController provides methods to manage jobs. | JobControllerServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JobControllerServicer:
"""The JobController provides methods to manage jobs."""
def SubmitJob(self, request, context):
"""Submits a job to a cluster."""
<|body_0|>
def GetJob(self, request, context):
"""Gets the resource representation for a job in a project."""
... | stack_v2_sparse_classes_75kplus_train_004993 | 7,103 | permissive | [
{
"docstring": "Submits a job to a cluster.",
"name": "SubmitJob",
"signature": "def SubmitJob(self, request, context)"
},
{
"docstring": "Gets the resource representation for a job in a project.",
"name": "GetJob",
"signature": "def GetJob(self, request, context)"
},
{
"docstrin... | 6 | stack_v2_sparse_classes_30k_train_029226 | Implement the Python class `JobControllerServicer` described below.
Class description:
The JobController provides methods to manage jobs.
Method signatures and docstrings:
- def SubmitJob(self, request, context): Submits a job to a cluster.
- def GetJob(self, request, context): Gets the resource representation for a ... | Implement the Python class `JobControllerServicer` described below.
Class description:
The JobController provides methods to manage jobs.
Method signatures and docstrings:
- def SubmitJob(self, request, context): Submits a job to a cluster.
- def GetJob(self, request, context): Gets the resource representation for a ... | d897d56bce03d1fda98b79afb08264e51d46c421 | <|skeleton|>
class JobControllerServicer:
"""The JobController provides methods to manage jobs."""
def SubmitJob(self, request, context):
"""Submits a job to a cluster."""
<|body_0|>
def GetJob(self, request, context):
"""Gets the resource representation for a job in a project."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JobControllerServicer:
"""The JobController provides methods to manage jobs."""
def SubmitJob(self, request, context):
"""Submits a job to a cluster."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError... | the_stack_v2_python_sparse | dataproc/google/cloud/dataproc_v1beta2/proto/jobs_pb2_grpc.py | tswast/google-cloud-python | train | 1 |
11af807d4c795e1dc52c10bc098ecc1c3c2b8c65 | [
"if delta_r is None:\n delta_r = 0\nif offset is None:\n offset = Point(0, 0, 0)\nif angle is None:\n angle = 0\nif weld_params is None:\n weld_params = WeldingState()\nself.offset = offset\nself.delta_r = delta_r\nself.angle = angle\nself.welding_parameters = weld_params",
"if not mod.offset.is_zero(... | <|body_start_0|>
if delta_r is None:
delta_r = 0
if offset is None:
offset = Point(0, 0, 0)
if angle is None:
angle = 0
if weld_params is None:
weld_params = WeldingState()
self.offset = offset
self.delta_r = delta_r
... | Modification | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Modification:
def __init__(self, offset=None, delta_r=None, angle=None, weld_params=None):
"""Initalize a Modification object Arguments: object {Modification} -- self Keyword Arguments: offset {Point} -- offset (x,y,z) in meters (default: Point(0,0,0)) delta_r {float} -- delta r angle (d... | stack_v2_sparse_classes_75kplus_train_004994 | 2,560 | permissive | [
{
"docstring": "Initalize a Modification object Arguments: object {Modification} -- self Keyword Arguments: offset {Point} -- offset (x,y,z) in meters (default: Point(0,0,0)) delta_r {float} -- delta r angle (default: 0) angle {float} -- torch angle (default: 0) weld_params {WeldingState} -- welding parameters ... | 2 | stack_v2_sparse_classes_30k_train_010628 | Implement the Python class `Modification` described below.
Class description:
Implement the Modification class.
Method signatures and docstrings:
- def __init__(self, offset=None, delta_r=None, angle=None, weld_params=None): Initalize a Modification object Arguments: object {Modification} -- self Keyword Arguments: o... | Implement the Python class `Modification` described below.
Class description:
Implement the Modification class.
Method signatures and docstrings:
- def __init__(self, offset=None, delta_r=None, angle=None, weld_params=None): Initalize a Modification object Arguments: object {Modification} -- self Keyword Arguments: o... | 7c39e1e5a6e98fc6c8dfcae6abf033f5d961b16c | <|skeleton|>
class Modification:
def __init__(self, offset=None, delta_r=None, angle=None, weld_params=None):
"""Initalize a Modification object Arguments: object {Modification} -- self Keyword Arguments: offset {Point} -- offset (x,y,z) in meters (default: Point(0,0,0)) delta_r {float} -- delta r angle (d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Modification:
def __init__(self, offset=None, delta_r=None, angle=None, weld_params=None):
"""Initalize a Modification object Arguments: object {Modification} -- self Keyword Arguments: offset {Point} -- offset (x,y,z) in meters (default: Point(0,0,0)) delta_r {float} -- delta r angle (default: 0) ang... | the_stack_v2_python_sparse | src/rosweld/modification.py | HuaiLeiTang/rosweld_tools | train | 0 | |
8f6c2d8a59afa834a66068f3128d81e0cf35ab82 | [
"print(f'get_context_data {kwargs}')\nprint(f'get_context_data {self.kwargs}')\ncontext = super().get_context_data(**kwargs)\ndetail = kwargs['object']\nimage = base64.b64encode(detail.avatar.read()).decode('ascii')\ncontext['author'] = detail\ncontext['image'] = image\nprint(f'{context}')\nreturn context",
"prin... | <|body_start_0|>
print(f'get_context_data {kwargs}')
print(f'get_context_data {self.kwargs}')
context = super().get_context_data(**kwargs)
detail = kwargs['object']
image = base64.b64encode(detail.avatar.read()).decode('ascii')
context['author'] = detail
context['... | AuthorView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthorView:
def get_context_data(self, **kwargs):
"""get the binary image from the database and add it to the context for streaming directly into the browser"""
<|body_0|>
def get_object(self, queryset=None):
"""Return the Author for the specific slug"""
<|bo... | stack_v2_sparse_classes_75kplus_train_004995 | 2,595 | no_license | [
{
"docstring": "get the binary image from the database and add it to the context for streaming directly into the browser",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
},
{
"docstring": "Return the Author for the specific slug",
"name": "get_object",
"s... | 2 | stack_v2_sparse_classes_30k_train_016842 | Implement the Python class `AuthorView` described below.
Class description:
Implement the AuthorView class.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): get the binary image from the database and add it to the context for streaming directly into the browser
- def get_object(self, queryset... | Implement the Python class `AuthorView` described below.
Class description:
Implement the AuthorView class.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): get the binary image from the database and add it to the context for streaming directly into the browser
- def get_object(self, queryset... | 1704f1796cb3f25cac260c6120becd70e9f1c33f | <|skeleton|>
class AuthorView:
def get_context_data(self, **kwargs):
"""get the binary image from the database and add it to the context for streaming directly into the browser"""
<|body_0|>
def get_object(self, queryset=None):
"""Return the Author for the specific slug"""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AuthorView:
def get_context_data(self, **kwargs):
"""get the binary image from the database and add it to the context for streaming directly into the browser"""
print(f'get_context_data {kwargs}')
print(f'get_context_data {self.kwargs}')
context = super().get_context_data(**kwa... | the_stack_v2_python_sparse | django-djongo/venv-djongo/SRC/djongo-gridfs/blog/views.py | sdugaro/django | train | 0 | |
c4e6b127330682d4c5d6bf997bf9f0c9ed616928 | [
"super().__init__()\nself.generator = Generator()\nself.master = Master()",
"logger.info('SpNasPipeStep started')\nwhile not self.generator.is_completed:\n id, spnas_sample = self.generator.search_alg.search()\n cls_trainer = ClassFactory.get_cls('trainer')\n trainer = cls_trainer(spnas_sample=spnas_samp... | <|body_start_0|>
super().__init__()
self.generator = Generator()
self.master = Master()
<|end_body_0|>
<|body_start_1|>
logger.info('SpNasPipeStep started')
while not self.generator.is_completed:
id, spnas_sample = self.generator.search_alg.search()
cls_t... | PipeStep is the base components class that can be added in Pipeline. | SpNasPipeStep | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpNasPipeStep:
"""PipeStep is the base components class that can be added in Pipeline."""
def __init__(self):
"""Initialize SpNasPipeStep."""
<|body_0|>
def do(self):
"""Do the main task in this pipe step."""
<|body_1|>
def update_generator(self, gen... | stack_v2_sparse_classes_75kplus_train_004996 | 3,119 | permissive | [
{
"docstring": "Initialize SpNasPipeStep.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Do the main task in this pipe step.",
"name": "do",
"signature": "def do(self)"
},
{
"docstring": "Get finished worker's info, and use it to update target `generat... | 3 | stack_v2_sparse_classes_30k_train_008910 | Implement the Python class `SpNasPipeStep` described below.
Class description:
PipeStep is the base components class that can be added in Pipeline.
Method signatures and docstrings:
- def __init__(self): Initialize SpNasPipeStep.
- def do(self): Do the main task in this pipe step.
- def update_generator(self, generat... | Implement the Python class `SpNasPipeStep` described below.
Class description:
PipeStep is the base components class that can be added in Pipeline.
Method signatures and docstrings:
- def __init__(self): Initialize SpNasPipeStep.
- def do(self): Do the main task in this pipe step.
- def update_generator(self, generat... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class SpNasPipeStep:
"""PipeStep is the base components class that can be added in Pipeline."""
def __init__(self):
"""Initialize SpNasPipeStep."""
<|body_0|>
def do(self):
"""Do the main task in this pipe step."""
<|body_1|>
def update_generator(self, gen... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpNasPipeStep:
"""PipeStep is the base components class that can be added in Pipeline."""
def __init__(self):
"""Initialize SpNasPipeStep."""
super().__init__()
self.generator = Generator()
self.master = Master()
def do(self):
"""Do the main task in this pipe ... | the_stack_v2_python_sparse | built-in/TensorFlow/Official/cv/image_classification/ResnetVariant_for_TensorFlow/automl/vega/algorithms/nas/sp_nas/spnas_pipe_step.py | Huawei-Ascend/modelzoo | train | 1 |
20a83660be9dfcb9d1b836f1ec063792508ee003 | [
"super(TemporalConvNet, self).__init__()\nself.C = C\nself.mask_nonlinear = mask_nonlinear\nlayer_norm = ChannelwiseLayerNorm(N)\nbottleneck_conv1x1 = nn.Conv1d(N, B, 1, bias=False)\nrepeats = []\nfor r in range(R):\n blocks = []\n for x in range(X):\n dilation = 2 ** x\n padding = (P - 1) * dil... | <|body_start_0|>
super(TemporalConvNet, self).__init__()
self.C = C
self.mask_nonlinear = mask_nonlinear
layer_norm = ChannelwiseLayerNorm(N)
bottleneck_conv1x1 = nn.Conv1d(N, B, 1, bias=False)
repeats = []
for r in range(R):
blocks = []
fo... | TemporalConvNet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TemporalConvNet:
def __init__(self, N, B, H, P, X, R, C, norm_type='gLN', causal=False, mask_nonlinear='relu'):
"""Basic Module of tasnet. Args: N: Number of filters in autoencoder B: Number of channels in bottleneck 1 * 1-conv block H: Number of channels in convolutional blocks P: Kerne... | stack_v2_sparse_classes_75kplus_train_004997 | 18,713 | permissive | [
{
"docstring": "Basic Module of tasnet. Args: N: Number of filters in autoencoder B: Number of channels in bottleneck 1 * 1-conv block H: Number of channels in convolutional blocks P: Kernel size in convolutional blocks X: Number of convolutional blocks in each repeat R: Number of repeats C: Number of speakers ... | 2 | stack_v2_sparse_classes_30k_train_015209 | Implement the Python class `TemporalConvNet` described below.
Class description:
Implement the TemporalConvNet class.
Method signatures and docstrings:
- def __init__(self, N, B, H, P, X, R, C, norm_type='gLN', causal=False, mask_nonlinear='relu'): Basic Module of tasnet. Args: N: Number of filters in autoencoder B: ... | Implement the Python class `TemporalConvNet` described below.
Class description:
Implement the TemporalConvNet class.
Method signatures and docstrings:
- def __init__(self, N, B, H, P, X, R, C, norm_type='gLN', causal=False, mask_nonlinear='relu'): Basic Module of tasnet. Args: N: Number of filters in autoencoder B: ... | 6ecde88045e1b706b2390f98eb1950ce4075a07d | <|skeleton|>
class TemporalConvNet:
def __init__(self, N, B, H, P, X, R, C, norm_type='gLN', causal=False, mask_nonlinear='relu'):
"""Basic Module of tasnet. Args: N: Number of filters in autoencoder B: Number of channels in bottleneck 1 * 1-conv block H: Number of channels in convolutional blocks P: Kerne... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TemporalConvNet:
def __init__(self, N, B, H, P, X, R, C, norm_type='gLN', causal=False, mask_nonlinear='relu'):
"""Basic Module of tasnet. Args: N: Number of filters in autoencoder B: Number of channels in bottleneck 1 * 1-conv block H: Number of channels in convolutional blocks P: Kernel size in conv... | the_stack_v2_python_sparse | espnet2/enh/nets/tasnet.py | sw005320/espnet-1 | train | 4 | |
d9555f4bd70ead15d60260307fb670644513ce1c | [
"super(QMixer, self).__init__()\nself.device = device\nself.n_agents = args.n_agents\nself.cent_obs_dim = args.cent_obs_dim\nself.use_orthogonal = args.use_orthogonal\nself.hidden_layer_dim = args.mixer_hidden_dim\nself.hypernet_hidden_dim = args.hypernet_hidden_dim\nif multidiscrete_list:\n self.num_mixer_q_inp... | <|body_start_0|>
super(QMixer, self).__init__()
self.device = device
self.n_agents = args.n_agents
self.cent_obs_dim = args.cent_obs_dim
self.use_orthogonal = args.use_orthogonal
self.hidden_layer_dim = args.mixer_hidden_dim
self.hypernet_hidden_dim = args.hyperne... | computes Q_tot from individual Q_a values and the state | QMixer | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QMixer:
"""computes Q_tot from individual Q_a values and the state"""
def __init__(self, args, device, multidiscrete_list=None):
"""init mixer class"""
<|body_0|>
def forward(self, agent_q_inps, states):
"""outputs Q_tot, using the individual agent Q values and t... | stack_v2_sparse_classes_75kplus_train_004998 | 4,926 | permissive | [
{
"docstring": "init mixer class",
"name": "__init__",
"signature": "def __init__(self, args, device, multidiscrete_list=None)"
},
{
"docstring": "outputs Q_tot, using the individual agent Q values and the centralized env state as inputs",
"name": "forward",
"signature": "def forward(sel... | 2 | stack_v2_sparse_classes_30k_test_002532 | Implement the Python class `QMixer` described below.
Class description:
computes Q_tot from individual Q_a values and the state
Method signatures and docstrings:
- def __init__(self, args, device, multidiscrete_list=None): init mixer class
- def forward(self, agent_q_inps, states): outputs Q_tot, using the individual... | Implement the Python class `QMixer` described below.
Class description:
computes Q_tot from individual Q_a values and the state
Method signatures and docstrings:
- def __init__(self, args, device, multidiscrete_list=None): init mixer class
- def forward(self, agent_q_inps, states): outputs Q_tot, using the individual... | 44411fddac496c7ee63abbce2cf277ebcf4c28e8 | <|skeleton|>
class QMixer:
"""computes Q_tot from individual Q_a values and the state"""
def __init__(self, args, device, multidiscrete_list=None):
"""init mixer class"""
<|body_0|>
def forward(self, agent_q_inps, states):
"""outputs Q_tot, using the individual agent Q values and t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QMixer:
"""computes Q_tot from individual Q_a values and the state"""
def __init__(self, args, device, multidiscrete_list=None):
"""init mixer class"""
super(QMixer, self).__init__()
self.device = device
self.n_agents = args.n_agents
self.cent_obs_dim = args.cent_o... | the_stack_v2_python_sparse | OFF-POLICY/algorithms/qmix/algorithm/q_mixer.py | umersheikh846/benchmarkmarl_repo | train | 1 |
4e66e839bf127ab8e9fe55efcde6ed9a332fc640 | [
"import mmdeploy.codebase.mmdet.models\nimport mmdeploy.codebase.mmdet.ops\nimport mmdeploy.codebase.mmdet.structures\nimport mmdeploy.codebase.mmpose.models",
"from mmpose.utils.setup_env import register_all_modules\ncls.register_deploy_modules()\nregister_all_modules(True)"
] | <|body_start_0|>
import mmdeploy.codebase.mmdet.models
import mmdeploy.codebase.mmdet.ops
import mmdeploy.codebase.mmdet.structures
import mmdeploy.codebase.mmpose.models
<|end_body_0|>
<|body_start_1|>
from mmpose.utils.setup_env import register_all_modules
cls.register... | mmpose codebase class. | MMPose | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MMPose:
"""mmpose codebase class."""
def register_deploy_modules(cls):
"""register rewritings."""
<|body_0|>
def register_all_modules(cls):
"""register all modules from mmpose."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
import mmdeploy.code... | stack_v2_sparse_classes_75kplus_train_004999 | 14,265 | permissive | [
{
"docstring": "register rewritings.",
"name": "register_deploy_modules",
"signature": "def register_deploy_modules(cls)"
},
{
"docstring": "register all modules from mmpose.",
"name": "register_all_modules",
"signature": "def register_all_modules(cls)"
}
] | 2 | null | Implement the Python class `MMPose` described below.
Class description:
mmpose codebase class.
Method signatures and docstrings:
- def register_deploy_modules(cls): register rewritings.
- def register_all_modules(cls): register all modules from mmpose. | Implement the Python class `MMPose` described below.
Class description:
mmpose codebase class.
Method signatures and docstrings:
- def register_deploy_modules(cls): register rewritings.
- def register_all_modules(cls): register all modules from mmpose.
<|skeleton|>
class MMPose:
"""mmpose codebase class."""
... | 5479c8774f5b88d7ed9d399d4e305cb42cc2e73a | <|skeleton|>
class MMPose:
"""mmpose codebase class."""
def register_deploy_modules(cls):
"""register rewritings."""
<|body_0|>
def register_all_modules(cls):
"""register all modules from mmpose."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MMPose:
"""mmpose codebase class."""
def register_deploy_modules(cls):
"""register rewritings."""
import mmdeploy.codebase.mmdet.models
import mmdeploy.codebase.mmdet.ops
import mmdeploy.codebase.mmdet.structures
import mmdeploy.codebase.mmpose.models
def regi... | the_stack_v2_python_sparse | mmdeploy/codebase/mmpose/deploy/pose_detection.py | open-mmlab/mmdeploy | train | 2,164 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.