blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1d5dab32240219910780f6f2191cea3a9ebe07f3 | [
"filepath = pathlib.Path(filepath)\nif zipfile.is_zipfile(str(filepath)):\n return (str(filepath), None, False)\nfor zipfilepath in filepath.parents:\n if zipfile.is_zipfile(str(zipfilepath)):\n break\nelse:\n return False\nfilename = filepath.relative_to(zipfilepath)\nzipfilepath = str(zipfilepath)... | <|body_start_0|>
filepath = pathlib.Path(filepath)
if zipfile.is_zipfile(str(filepath)):
return (str(filepath), None, False)
for zipfilepath in filepath.parents:
if zipfile.is_zipfile(str(zipfilepath)):
break
else:
return False
... | FMZipFileManagement | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FMZipFileManagement:
def splitZipfilepath(cls, filepath):
"""Deals with path with the name ./foo.zip/foo1.txt Returns: ⋅ If no zipfile can be found, returns False ⋅ Otherwise, returns the tuple (zipfilepath,filename,inzip) with - zipfilepath : returns the zip filepath. - filename : the n... | stack_v2_sparse_classes_36k_train_033100 | 10,302 | no_license | [
{
"docstring": "Deals with path with the name ./foo.zip/foo1.txt Returns: ⋅ If no zipfile can be found, returns False ⋅ Otherwise, returns the tuple (zipfilepath,filename,inzip) with - zipfilepath : returns the zip filepath. - filename : the name of the file in the archive - inzip : True if the file is in the z... | 4 | stack_v2_sparse_classes_30k_train_007115 | Implement the Python class `FMZipFileManagement` described below.
Class description:
Implement the FMZipFileManagement class.
Method signatures and docstrings:
- def splitZipfilepath(cls, filepath): Deals with path with the name ./foo.zip/foo1.txt Returns: ⋅ If no zipfile can be found, returns False ⋅ Otherwise, retu... | Implement the Python class `FMZipFileManagement` described below.
Class description:
Implement the FMZipFileManagement class.
Method signatures and docstrings:
- def splitZipfilepath(cls, filepath): Deals with path with the name ./foo.zip/foo1.txt Returns: ⋅ If no zipfile can be found, returns False ⋅ Otherwise, retu... | 14c9e51fa31fd3ff4113f33e26619d07c9f1dc7c | <|skeleton|>
class FMZipFileManagement:
def splitZipfilepath(cls, filepath):
"""Deals with path with the name ./foo.zip/foo1.txt Returns: ⋅ If no zipfile can be found, returns False ⋅ Otherwise, returns the tuple (zipfilepath,filename,inzip) with - zipfilepath : returns the zip filepath. - filename : the n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FMZipFileManagement:
def splitZipfilepath(cls, filepath):
"""Deals with path with the name ./foo.zip/foo1.txt Returns: ⋅ If no zipfile can be found, returns False ⋅ Otherwise, returns the tuple (zipfilepath,filename,inzip) with - zipfilepath : returns the zip filepath. - filename : the name of the fil... | the_stack_v2_python_sparse | FileManagement/FileManagement.py | grumpfou/AthenaWriter | train | 0 | |
9d500b8e6ea3ec3fbaebfe26afbcb254cf1c2917 | [
"if isinstance(dateval, str):\n return datetime.strptime(dateval, '%Y-%m-%d').strftime('%Y-%m-%d')\nreturn dateval",
"for key in ['perFemales', 'perMales', 'perUnknowns']:\n if isnan(values[key]):\n values[key] = 0.0\nreturn values"
] | <|body_start_0|>
if isinstance(dateval, str):
return datetime.strptime(dateval, '%Y-%m-%d').strftime('%Y-%m-%d')
return dateval
<|end_body_0|>
<|body_start_1|>
for key in ['perFemales', 'perMales', 'perUnknowns']:
if isnan(values[key]):
values[key] = 0.0
... | OutletStatsByWeek | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OutletStatsByWeek:
def valid_date(dateval):
"""Validate a date string to be of the format yyyy-mm-dd"""
<|body_0|>
def _valid_percentage(cls, values):
"""Avoid NaNs by setting them to 0.0"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if isinstance... | stack_v2_sparse_classes_36k_train_033101 | 2,517 | permissive | [
{
"docstring": "Validate a date string to be of the format yyyy-mm-dd",
"name": "valid_date",
"signature": "def valid_date(dateval)"
},
{
"docstring": "Avoid NaNs by setting them to 0.0",
"name": "_valid_percentage",
"signature": "def _valid_percentage(cls, values)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008664 | Implement the Python class `OutletStatsByWeek` described below.
Class description:
Implement the OutletStatsByWeek class.
Method signatures and docstrings:
- def valid_date(dateval): Validate a date string to be of the format yyyy-mm-dd
- def _valid_percentage(cls, values): Avoid NaNs by setting them to 0.0 | Implement the Python class `OutletStatsByWeek` described below.
Class description:
Implement the OutletStatsByWeek class.
Method signatures and docstrings:
- def valid_date(dateval): Validate a date string to be of the format yyyy-mm-dd
- def _valid_percentage(cls, values): Avoid NaNs by setting them to 0.0
<|skelet... | 30d09b51206894a78b33faf98f367cb3878ba663 | <|skeleton|>
class OutletStatsByWeek:
def valid_date(dateval):
"""Validate a date string to be of the format yyyy-mm-dd"""
<|body_0|>
def _valid_percentage(cls, values):
"""Avoid NaNs by setting them to 0.0"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OutletStatsByWeek:
def valid_date(dateval):
"""Validate a date string to be of the format yyyy-mm-dd"""
if isinstance(dateval, str):
return datetime.strptime(dateval, '%Y-%m-%d').strftime('%Y-%m-%d')
return dateval
def _valid_percentage(cls, values):
"""Avoid N... | the_stack_v2_python_sparse | api/french/schemas/stats_weekly.py | sfu-discourse-lab/GenderGapTracker | train | 37 | |
58a63830862cc02da542b6a3a8cb90712b939f0c | [
"n = len(nums)\nif n * k == 0:\n return []\nif k == 1:\n return nums\nq = deque()\n\ndef clean_queue(index: int):\n if q and q[0] == index - k:\n q.popleft()\n while q and nums[q[-1]] < nums[index]:\n q.pop()\nmax_index = 0\nfor index in range(k):\n clean_queue(index)\n q.append(inde... | <|body_start_0|>
n = len(nums)
if n * k == 0:
return []
if k == 1:
return nums
q = deque()
def clean_queue(index: int):
if q and q[0] == index - k:
q.popleft()
while q and nums[q[-1]] < nums[index]:
... | Window | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Window:
def max_in_sliding(self, nums: List[int], k: int) -> List[int]:
"""Approach: Deque Time Complexity: O(N) Space Complexity: O(N) :param nums: :param k: :return:"""
<|body_0|>
def max_while_sliding(self, nums: List[int], k: int) -> List[int]:
"""Approach: DP Ti... | stack_v2_sparse_classes_36k_train_033102 | 2,181 | no_license | [
{
"docstring": "Approach: Deque Time Complexity: O(N) Space Complexity: O(N) :param nums: :param k: :return:",
"name": "max_in_sliding",
"signature": "def max_in_sliding(self, nums: List[int], k: int) -> List[int]"
},
{
"docstring": "Approach: DP Time Complexity: O(N) Space Complexity: O(N) :par... | 2 | null | Implement the Python class `Window` described below.
Class description:
Implement the Window class.
Method signatures and docstrings:
- def max_in_sliding(self, nums: List[int], k: int) -> List[int]: Approach: Deque Time Complexity: O(N) Space Complexity: O(N) :param nums: :param k: :return:
- def max_while_sliding(s... | Implement the Python class `Window` described below.
Class description:
Implement the Window class.
Method signatures and docstrings:
- def max_in_sliding(self, nums: List[int], k: int) -> List[int]: Approach: Deque Time Complexity: O(N) Space Complexity: O(N) :param nums: :param k: :return:
- def max_while_sliding(s... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Window:
def max_in_sliding(self, nums: List[int], k: int) -> List[int]:
"""Approach: Deque Time Complexity: O(N) Space Complexity: O(N) :param nums: :param k: :return:"""
<|body_0|>
def max_while_sliding(self, nums: List[int], k: int) -> List[int]:
"""Approach: DP Ti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Window:
def max_in_sliding(self, nums: List[int], k: int) -> List[int]:
"""Approach: Deque Time Complexity: O(N) Space Complexity: O(N) :param nums: :param k: :return:"""
n = len(nums)
if n * k == 0:
return []
if k == 1:
return nums
q = deque()
... | the_stack_v2_python_sparse | expedia/sliding_window_maximum.py | Shiv2157k/leet_code | train | 1 | |
34df6bae770f18d7f38b3bbc53514008d139426f | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ApprovalSettings()",
"from .unified_approval_stage import UnifiedApprovalStage\nfrom .unified_approval_stage import UnifiedApprovalStage\nfields: Dict[str, Callable[[Any], None]] = {'approvalMode': lambda n: setattr(self, 'approval_mod... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ApprovalSettings()
<|end_body_0|>
<|body_start_1|>
from .unified_approval_stage import UnifiedApprovalStage
from .unified_approval_stage import UnifiedApprovalStage
fields: Dict[... | ApprovalSettings | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApprovalSettings:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ApprovalSettings:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object R... | stack_v2_sparse_classes_36k_train_033103 | 4,301 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ApprovalSettings",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_va... | 3 | null | Implement the Python class `ApprovalSettings` described below.
Class description:
Implement the ApprovalSettings class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ApprovalSettings: Creates a new instance of the appropriate class based on discrimina... | Implement the Python class `ApprovalSettings` described below.
Class description:
Implement the ApprovalSettings class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ApprovalSettings: Creates a new instance of the appropriate class based on discrimina... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ApprovalSettings:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ApprovalSettings:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object R... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ApprovalSettings:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ApprovalSettings:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Approv... | the_stack_v2_python_sparse | msgraph/generated/models/approval_settings.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
2b5ae912190d192c9800f906ef4ce1e338138b5b | [
"if value is self.field.missing_value:\n return []\nwidget = self.widget\nif widget.terms is None:\n widget.updateTerms()\nvalues = []\nfor entry in value:\n try:\n values.append(widget.terms.getTerm(entry).token)\n except LookupError:\n pass\nreturn values",
"widget = self.widget\nif wi... | <|body_start_0|>
if value is self.field.missing_value:
return []
widget = self.widget
if widget.terms is None:
widget.updateTerms()
values = []
for entry in value:
try:
values.append(widget.terms.getTerm(entry).token)
... | A special converter between collections and sequence widgets. | CollectionSequenceDataConverter | [
"ZPL-2.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CollectionSequenceDataConverter:
"""A special converter between collections and sequence widgets."""
def toWidgetValue(self, value):
"""Convert from Python bool to HTML representation."""
<|body_0|>
def toFieldValue(self, value):
"""See interfaces.IDataConverter"... | stack_v2_sparse_classes_36k_train_033104 | 15,934 | permissive | [
{
"docstring": "Convert from Python bool to HTML representation.",
"name": "toWidgetValue",
"signature": "def toWidgetValue(self, value)"
},
{
"docstring": "See interfaces.IDataConverter",
"name": "toFieldValue",
"signature": "def toFieldValue(self, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015061 | Implement the Python class `CollectionSequenceDataConverter` described below.
Class description:
A special converter between collections and sequence widgets.
Method signatures and docstrings:
- def toWidgetValue(self, value): Convert from Python bool to HTML representation.
- def toFieldValue(self, value): See inter... | Implement the Python class `CollectionSequenceDataConverter` described below.
Class description:
A special converter between collections and sequence widgets.
Method signatures and docstrings:
- def toWidgetValue(self, value): Convert from Python bool to HTML representation.
- def toFieldValue(self, value): See inter... | aa47e9b109ad2d7de600fc1d4ea7359d8144f356 | <|skeleton|>
class CollectionSequenceDataConverter:
"""A special converter between collections and sequence widgets."""
def toWidgetValue(self, value):
"""Convert from Python bool to HTML representation."""
<|body_0|>
def toFieldValue(self, value):
"""See interfaces.IDataConverter"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CollectionSequenceDataConverter:
"""A special converter between collections and sequence widgets."""
def toWidgetValue(self, value):
"""Convert from Python bool to HTML representation."""
if value is self.field.missing_value:
return []
widget = self.widget
if w... | the_stack_v2_python_sparse | src/z3c/form/converter.py | zopefoundation/z3c.form | train | 6 |
34c5bee622a1c40e85bac4b9b1b1a66683e7e881 | [
"result = []\nitem = ''\nfor char in s:\n if char.isspace():\n if item != '':\n result.append(int(item))\n item = ''\n if char in ['(', ')', '+', '-']:\n if item != '':\n result.append(int(item))\n item = ''\n result.append(char)\n if char.is... | <|body_start_0|>
result = []
item = ''
for char in s:
if char.isspace():
if item != '':
result.append(int(item))
item = ''
if char in ['(', ')', '+', '-']:
if item != '':
result.ap... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def segregate(self, s: str) -> list:
"""Separetes elements of the equation from string to list. >>>segregate("(1+(4+5+2)-3)+(6+8)") ['(', '(', 1, '+', '(', 4, '+', 5, '+', 2, ')', '-', 3, ')', '+', '(', 6, '+', 8, ')', ')'] >>>segregate("( 11 + ( 41 + 51 + 21 ) - 31 ) + ( 16 + ... | stack_v2_sparse_classes_36k_train_033105 | 4,081 | permissive | [
{
"docstring": "Separetes elements of the equation from string to list. >>>segregate(\"(1+(4+5+2)-3)+(6+8)\") ['(', '(', 1, '+', '(', 4, '+', 5, '+', 2, ')', '-', 3, ')', '+', '(', 6, '+', 8, ')', ')'] >>>segregate(\"( 11 + ( 41 + 51 + 21 ) - 31 ) + ( 16 + 18 )\") ['(', '(', 11, '+', '(', 41, '+', 51, '+', 21, ... | 2 | stack_v2_sparse_classes_30k_train_004511 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def segregate(self, s: str) -> list: Separetes elements of the equation from string to list. >>>segregate("(1+(4+5+2)-3)+(6+8)") ['(', '(', 1, '+', '(', 4, '+', 5, '+', 2, ')', '... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def segregate(self, s: str) -> list: Separetes elements of the equation from string to list. >>>segregate("(1+(4+5+2)-3)+(6+8)") ['(', '(', 1, '+', '(', 4, '+', 5, '+', 2, ')', '... | a0df2bff78e64bd2371abb700b06a4e85cd960e4 | <|skeleton|>
class Solution:
def segregate(self, s: str) -> list:
"""Separetes elements of the equation from string to list. >>>segregate("(1+(4+5+2)-3)+(6+8)") ['(', '(', 1, '+', '(', 4, '+', 5, '+', 2, ')', '-', 3, ')', '+', '(', 6, '+', 8, ')', ')'] >>>segregate("( 11 + ( 41 + 51 + 21 ) - 31 ) + ( 16 + ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def segregate(self, s: str) -> list:
"""Separetes elements of the equation from string to list. >>>segregate("(1+(4+5+2)-3)+(6+8)") ['(', '(', 1, '+', '(', 4, '+', 5, '+', 2, ')', '-', 3, ')', '+', '(', 6, '+', 8, ')', ')'] >>>segregate("( 11 + ( 41 + 51 + 21 ) - 31 ) + ( 16 + 18 )") ['(', '... | the_stack_v2_python_sparse | Python/224. BasicCalculator.py | uniyalabhishek/LeetCode-Solutions | train | 1 | |
cc14ee3aae6d52e2fb5beea2eaa6cad27856dcb8 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn DelegatedAdminServiceManagementDetail()",
"from .entity import Entity\nfrom .entity import Entity\nfields: Dict[str, Callable[[Any], None]] = {'serviceManagementUrl': lambda n: setattr(self, 'service_management_url', n.get_str_value())... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return DelegatedAdminServiceManagementDetail()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .entity import Entity
fields: Dict[str, Callable[[Any], None]] = {'service... | DelegatedAdminServiceManagementDetail | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DelegatedAdminServiceManagementDetail:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DelegatedAdminServiceManagementDetail:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the d... | stack_v2_sparse_classes_36k_train_033106 | 2,388 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: DelegatedAdminServiceManagementDetail",
"name": "create_from_discriminator_value",
"signature": "def create_... | 3 | null | Implement the Python class `DelegatedAdminServiceManagementDetail` described below.
Class description:
Implement the DelegatedAdminServiceManagementDetail class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DelegatedAdminServiceManagementDetail: Crea... | Implement the Python class `DelegatedAdminServiceManagementDetail` described below.
Class description:
Implement the DelegatedAdminServiceManagementDetail class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DelegatedAdminServiceManagementDetail: Crea... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class DelegatedAdminServiceManagementDetail:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DelegatedAdminServiceManagementDetail:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DelegatedAdminServiceManagementDetail:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DelegatedAdminServiceManagementDetail:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator v... | the_stack_v2_python_sparse | msgraph/generated/models/delegated_admin_service_management_detail.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
1a676a8b67563b048015cac710bb075cc46ee16d | [
"if cls.OUTPUT_SHARDING_PARAM in mapper_spec.params:\n raise errors.BadWriterParamsError('output_sharding should not be specified for %s' % cls.__name__)\nmapper_spec.params[cls.OUTPUT_SHARDING_PARAM] = cls.OUTPUT_SHARDING_INPUT_SHARDS\nsuper(BlobstoreRecordsOutputWriter, cls).validate(mapper_spec)",
"if ctx.g... | <|body_start_0|>
if cls.OUTPUT_SHARDING_PARAM in mapper_spec.params:
raise errors.BadWriterParamsError('output_sharding should not be specified for %s' % cls.__name__)
mapper_spec.params[cls.OUTPUT_SHARDING_PARAM] = cls.OUTPUT_SHARDING_INPUT_SHARDS
super(BlobstoreRecordsOutputWriter,... | An OutputWriter which outputs data into records format. | BlobstoreRecordsOutputWriter | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlobstoreRecordsOutputWriter:
"""An OutputWriter which outputs data into records format."""
def validate(cls, mapper_spec):
"""Validates mapper specification. Args: mapper_spec: an instance of model.MapperSpec to validate."""
<|body_0|>
def write(self, data, ctx):
... | stack_v2_sparse_classes_36k_train_033107 | 18,136 | permissive | [
{
"docstring": "Validates mapper specification. Args: mapper_spec: an instance of model.MapperSpec to validate.",
"name": "validate",
"signature": "def validate(cls, mapper_spec)"
},
{
"docstring": "Write data. Args: data: actual data yielded from handler. Type is writer-specific. ctx: an instan... | 2 | null | Implement the Python class `BlobstoreRecordsOutputWriter` described below.
Class description:
An OutputWriter which outputs data into records format.
Method signatures and docstrings:
- def validate(cls, mapper_spec): Validates mapper specification. Args: mapper_spec: an instance of model.MapperSpec to validate.
- de... | Implement the Python class `BlobstoreRecordsOutputWriter` described below.
Class description:
An OutputWriter which outputs data into records format.
Method signatures and docstrings:
- def validate(cls, mapper_spec): Validates mapper specification. Args: mapper_spec: an instance of model.MapperSpec to validate.
- de... | e3c50ee4ec8364c61cfff3ea68ece1098674f4d6 | <|skeleton|>
class BlobstoreRecordsOutputWriter:
"""An OutputWriter which outputs data into records format."""
def validate(cls, mapper_spec):
"""Validates mapper specification. Args: mapper_spec: an instance of model.MapperSpec to validate."""
<|body_0|>
def write(self, data, ctx):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BlobstoreRecordsOutputWriter:
"""An OutputWriter which outputs data into records format."""
def validate(cls, mapper_spec):
"""Validates mapper specification. Args: mapper_spec: an instance of model.MapperSpec to validate."""
if cls.OUTPUT_SHARDING_PARAM in mapper_spec.params:
... | the_stack_v2_python_sparse | app/mapreduce/output_writers.py | MapofLife/MOL | train | 19 |
383e364e2b922a047fdc0958e0790935b29716f8 | [
"self.mfd_model = 'Characteristic'\nself.mfd_weight = mfd_conf['Model_Weight']\nself.bin_width = mfd_conf['MFD_spacing']\nself.mmin = None\nself.mmax = None\nself.mmax_sigma = None\nself.lower_bound = mfd_conf['Lower_Bound']\nself.upper_bound = mfd_conf['Upper_Bound']\nself.sigma = mfd_conf['Sigma']\nself.occurrenc... | <|body_start_0|>
self.mfd_model = 'Characteristic'
self.mfd_weight = mfd_conf['Model_Weight']
self.bin_width = mfd_conf['MFD_spacing']
self.mmin = None
self.mmax = None
self.mmax_sigma = None
self.lower_bound = mfd_conf['Lower_Bound']
self.upper_bound = mf... | Class to implement the characteristic earthquake model assuming a truncated Gaussian distribution :param str mfd_model: Type of magnitude frequency distribution :param float mfd_weight: Weight of the mfd distribution (for subsequent logic tree processing) :param float bin_width: Width of the magnitude bin (rates are gi... | Characteristic | [
"AGPL-3.0-only",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Characteristic:
"""Class to implement the characteristic earthquake model assuming a truncated Gaussian distribution :param str mfd_model: Type of magnitude frequency distribution :param float mfd_weight: Weight of the mfd distribution (for subsequent logic tree processing) :param float bin_width... | stack_v2_sparse_classes_36k_train_033108 | 7,443 | permissive | [
{
"docstring": "Input core configuration parameters as specified in the configuration file :param dict mfd_conf: Configuration file containing the following attributes: * 'Model_Weight' - Logic tree weight of model type (float) * 'MFD_spacing' - Width of MFD bin (float) * 'Minimum_Magnitude' - Minimum magnitude... | 3 | stack_v2_sparse_classes_30k_train_010991 | Implement the Python class `Characteristic` described below.
Class description:
Class to implement the characteristic earthquake model assuming a truncated Gaussian distribution :param str mfd_model: Type of magnitude frequency distribution :param float mfd_weight: Weight of the mfd distribution (for subsequent logic ... | Implement the Python class `Characteristic` described below.
Class description:
Class to implement the characteristic earthquake model assuming a truncated Gaussian distribution :param str mfd_model: Type of magnitude frequency distribution :param float mfd_weight: Weight of the mfd distribution (for subsequent logic ... | 0da9ba5a575360081715e8b90c71d4b16c6687c8 | <|skeleton|>
class Characteristic:
"""Class to implement the characteristic earthquake model assuming a truncated Gaussian distribution :param str mfd_model: Type of magnitude frequency distribution :param float mfd_weight: Weight of the mfd distribution (for subsequent logic tree processing) :param float bin_width... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Characteristic:
"""Class to implement the characteristic earthquake model assuming a truncated Gaussian distribution :param str mfd_model: Type of magnitude frequency distribution :param float mfd_weight: Weight of the mfd distribution (for subsequent logic tree processing) :param float bin_width: Width of th... | the_stack_v2_python_sparse | openquake/hmtk/faults/mfd/characteristic.py | GFZ-Centre-for-Early-Warning/shakyground | train | 1 |
2ea96482745dcc4cfd6c3417777055c6044370f7 | [
"self.host = host\nself.port = port\nself.verbose = verbose\nself.opts = opts\nself.flags = flags\nself.connect()",
"context = zmq.Context()\npuller = context.socket(zmq.PULL)\nfor opt in self.opts:\n puller.setsockopt(opt, 1)\npuller.connect('tcp://{0}:{1}'.format(self.host, self.port))\nself.puller = puller\... | <|body_start_0|>
self.host = host
self.port = port
self.verbose = verbose
self.opts = opts
self.flags = flags
self.connect()
<|end_body_0|>
<|body_start_1|>
context = zmq.Context()
puller = context.socket(zmq.PULL)
for opt in self.opts:
... | ZMQPull | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZMQPull:
def __init__(self, host, port, opts=[], flags=0, verbose=False):
"""create a Default ZMQ Pull socket"""
<|body_0|>
def connect(self):
"""open ZMQ pull socket return receiver object"""
<|body_1|>
def receive(self):
"""receive and return z... | stack_v2_sparse_classes_36k_train_033109 | 12,974 | no_license | [
{
"docstring": "create a Default ZMQ Pull socket",
"name": "__init__",
"signature": "def __init__(self, host, port, opts=[], flags=0, verbose=False)"
},
{
"docstring": "open ZMQ pull socket return receiver object",
"name": "connect",
"signature": "def connect(self)"
},
{
"docstri... | 4 | null | Implement the Python class `ZMQPull` described below.
Class description:
Implement the ZMQPull class.
Method signatures and docstrings:
- def __init__(self, host, port, opts=[], flags=0, verbose=False): create a Default ZMQ Pull socket
- def connect(self): open ZMQ pull socket return receiver object
- def receive(sel... | Implement the Python class `ZMQPull` described below.
Class description:
Implement the ZMQPull class.
Method signatures and docstrings:
- def __init__(self, host, port, opts=[], flags=0, verbose=False): create a Default ZMQ Pull socket
- def connect(self): open ZMQ pull socket return receiver object
- def receive(sel... | 55041e6947b888242ff01cb18bd5f1ee4c4c8f28 | <|skeleton|>
class ZMQPull:
def __init__(self, host, port, opts=[], flags=0, verbose=False):
"""create a Default ZMQ Pull socket"""
<|body_0|>
def connect(self):
"""open ZMQ pull socket return receiver object"""
<|body_1|>
def receive(self):
"""receive and return z... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZMQPull:
def __init__(self, host, port, opts=[], flags=0, verbose=False):
"""create a Default ZMQ Pull socket"""
self.host = host
self.port = port
self.verbose = verbose
self.opts = opts
self.flags = flags
self.connect()
def connect(self):
"... | the_stack_v2_python_sparse | NPC/gui/ZmqSockets.py | coquellen/NanoPeakCell | train | 6 | |
55e10c0109b6299d648126ae16c8f30485d7968b | [
"self.nsamp = nsamp\nself.mingap = mingap\nif lookback_samples == None:\n lookback_samples = nsamp * 4\nself.lookback_samples = lookback_samples\nself.reset(nseen=nseen, **kwargs)",
"self.nseen = nseen\nself.active = []\nself.lookback = None\nself.onreset(**kwargs)",
"full = []\nif self.lookback == None:\n ... | <|body_start_0|>
self.nsamp = nsamp
self.mingap = mingap
if lookback_samples == None:
lookback_samples = nsamp * 4
self.lookback_samples = lookback_samples
self.reset(nseen=nseen, **kwargs)
<|end_body_0|>
<|body_start_1|>
self.nseen = nseen
self.activ... | TriggerlessTrapSequence | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TriggerlessTrapSequence:
def __init__(self, nsamp, mingap=0, nseen=0, lookback_samples=None, **kwargs):
"""Like a TrapSequence, but for use in situations where there is no trigger channel. Instead, each epoch is triggered when a particular "event offset" is supplied while processing a si... | stack_v2_sparse_classes_36k_train_033110 | 19,507 | no_license | [
{
"docstring": "Like a TrapSequence, but for use in situations where there is no trigger channel. Instead, each epoch is triggered when a particular \"event offset\" is supplied while processing a signal packet. The event offset dictates when, in samples relative to the start of the packet being processed, a ne... | 3 | stack_v2_sparse_classes_30k_train_011919 | Implement the Python class `TriggerlessTrapSequence` described below.
Class description:
Implement the TriggerlessTrapSequence class.
Method signatures and docstrings:
- def __init__(self, nsamp, mingap=0, nseen=0, lookback_samples=None, **kwargs): Like a TrapSequence, but for use in situations where there is no trig... | Implement the Python class `TriggerlessTrapSequence` described below.
Class description:
Implement the TriggerlessTrapSequence class.
Method signatures and docstrings:
- def __init__(self, nsamp, mingap=0, nseen=0, lookback_samples=None, **kwargs): Like a TrapSequence, but for use in situations where there is no trig... | 9db5556f204516467515defd6a6b93991df4ffe7 | <|skeleton|>
class TriggerlessTrapSequence:
def __init__(self, nsamp, mingap=0, nseen=0, lookback_samples=None, **kwargs):
"""Like a TrapSequence, but for use in situations where there is no trigger channel. Instead, each epoch is triggered when a particular "event offset" is supplied while processing a si... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TriggerlessTrapSequence:
def __init__(self, nsamp, mingap=0, nseen=0, lookback_samples=None, **kwargs):
"""Like a TrapSequence, but for use in situations where there is no trigger channel. Instead, each epoch is triggered when a particular "event offset" is supplied while processing a signal packet. T... | the_stack_v2_python_sparse | SigTools/Buffering4417.py | neurotechcenter/BCpy2000 | train | 9 | |
55154b36dba31bea2dc471c885789711c43ab30c | [
"super().__init__(healthy_data, broken_data, data_labels, dataset_name, windows_size)\nself.model_name = FORWARD_NETWORK\nself.reshape_data()\nself.model = self.define_model()",
"log.info('Defining FeedForward Autoencoder neural network architecture...')\nmodel = Sequential()\nmodel.add(Dense(PRIMARY_UNITS_SIZE, ... | <|body_start_0|>
super().__init__(healthy_data, broken_data, data_labels, dataset_name, windows_size)
self.model_name = FORWARD_NETWORK
self.reshape_data()
self.model = self.define_model()
<|end_body_0|>
<|body_start_1|>
log.info('Defining FeedForward Autoencoder neural network ... | FFModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FFModel:
def __init__(self, healthy_data: ndarray, broken_data: ndarray, data_labels: array, dataset_name: str, windows_size: int) -> None:
"""Initialize the FFModel class. Args: healthy_data (ndarray): Healthy data for training. broken_data (ndarray): Data with anomalies to detect. data... | stack_v2_sparse_classes_36k_train_033111 | 2,399 | no_license | [
{
"docstring": "Initialize the FFModel class. Args: healthy_data (ndarray): Healthy data for training. broken_data (ndarray): Data with anomalies to detect. data_labels (array): Data labels. dataset_name (str): Name of the dataset. windows_size (int): Step in time per example.",
"name": "__init__",
"sig... | 2 | stack_v2_sparse_classes_30k_train_009352 | Implement the Python class `FFModel` described below.
Class description:
Implement the FFModel class.
Method signatures and docstrings:
- def __init__(self, healthy_data: ndarray, broken_data: ndarray, data_labels: array, dataset_name: str, windows_size: int) -> None: Initialize the FFModel class. Args: healthy_data ... | Implement the Python class `FFModel` described below.
Class description:
Implement the FFModel class.
Method signatures and docstrings:
- def __init__(self, healthy_data: ndarray, broken_data: ndarray, data_labels: array, dataset_name: str, windows_size: int) -> None: Initialize the FFModel class. Args: healthy_data ... | 322a27511eb5a270ad88b4e83e30c44bc8943369 | <|skeleton|>
class FFModel:
def __init__(self, healthy_data: ndarray, broken_data: ndarray, data_labels: array, dataset_name: str, windows_size: int) -> None:
"""Initialize the FFModel class. Args: healthy_data (ndarray): Healthy data for training. broken_data (ndarray): Data with anomalies to detect. data... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FFModel:
def __init__(self, healthy_data: ndarray, broken_data: ndarray, data_labels: array, dataset_name: str, windows_size: int) -> None:
"""Initialize the FFModel class. Args: healthy_data (ndarray): Healthy data for training. broken_data (ndarray): Data with anomalies to detect. data_labels (array... | the_stack_v2_python_sparse | PYTHON/AnomalyDetection/Models/DeepLearningModels/Forward.py | dwisniewski1993/Machine-Learning | train | 4 | |
2af66b547d2acbf5533e9439ab3f93cad5380ce3 | [
"p = profile(self.driver)\np.open_profile()\nself.assertEqual(p.verify(), True)\np.clear()\np.profile_save()\nself.assertEqual(p.error_name(), '不能为空哦')\nfunction.screenshot(self.driver, 'profile_name_blank.jpg')",
"p = profile(self.driver)\np.open_profile()\nself.assertEqual(p.verify(), True)\np.profile_modify()\... | <|body_start_0|>
p = profile(self.driver)
p.open_profile()
self.assertEqual(p.verify(), True)
p.clear()
p.profile_save()
self.assertEqual(p.error_name(), '不能为空哦')
function.screenshot(self.driver, 'profile_name_blank.jpg')
<|end_body_0|>
<|body_start_1|>
p... | Test008_Profile_Error | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test008_Profile_Error:
def test_modify_name_error(self):
"""用户姓名为空"""
<|body_0|>
def test_modify_password_error1(self):
"""输入为空"""
<|body_1|>
def test_modify_password_error2(self):
"""确认密码不一致"""
<|body_2|>
def test_modify_password_er... | stack_v2_sparse_classes_36k_train_033112 | 2,454 | no_license | [
{
"docstring": "用户姓名为空",
"name": "test_modify_name_error",
"signature": "def test_modify_name_error(self)"
},
{
"docstring": "输入为空",
"name": "test_modify_password_error1",
"signature": "def test_modify_password_error1(self)"
},
{
"docstring": "确认密码不一致",
"name": "test_modify_p... | 5 | null | Implement the Python class `Test008_Profile_Error` described below.
Class description:
Implement the Test008_Profile_Error class.
Method signatures and docstrings:
- def test_modify_name_error(self): 用户姓名为空
- def test_modify_password_error1(self): 输入为空
- def test_modify_password_error2(self): 确认密码不一致
- def test_modif... | Implement the Python class `Test008_Profile_Error` described below.
Class description:
Implement the Test008_Profile_Error class.
Method signatures and docstrings:
- def test_modify_name_error(self): 用户姓名为空
- def test_modify_password_error1(self): 输入为空
- def test_modify_password_error2(self): 确认密码不一致
- def test_modif... | 6f42c25249fc642cecc270578a180820988d45b5 | <|skeleton|>
class Test008_Profile_Error:
def test_modify_name_error(self):
"""用户姓名为空"""
<|body_0|>
def test_modify_password_error1(self):
"""输入为空"""
<|body_1|>
def test_modify_password_error2(self):
"""确认密码不一致"""
<|body_2|>
def test_modify_password_er... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test008_Profile_Error:
def test_modify_name_error(self):
"""用户姓名为空"""
p = profile(self.driver)
p.open_profile()
self.assertEqual(p.verify(), True)
p.clear()
p.profile_save()
self.assertEqual(p.error_name(), '不能为空哦')
function.screenshot(self.drive... | the_stack_v2_python_sparse | GlxssLive_web/TestCase/User/Test008_profile_error.py | rrmiracle/GlxssLive | train | 0 | |
ce8d377e7063adb8d27b9ce01ed53af503428bf3 | [
"if initial_guess is None:\n initial_guess = np.zeros(opt_size)\nself.props = [initial_guess]\nself.res = []\nself.max_hist = max_hist\nself.max_iter = max_iter\nself.opt_size = opt_size\nself.return_object = collections.namedtuple('NewtonResult', ['x', 'nfev'])",
"try:\n increment = -np.dot(np.linalg.pinv(... | <|body_start_0|>
if initial_guess is None:
initial_guess = np.zeros(opt_size)
self.props = [initial_guess]
self.res = []
self.max_hist = max_hist
self.max_iter = max_iter
self.opt_size = opt_size
self.return_object = collections.namedtuple('NewtonResul... | Newton root finding. | NewtonOptimizer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewtonOptimizer:
"""Newton root finding."""
def __init__(self, opt_size, max_hist=1, max_iter=20000, initial_guess=None):
""":param opt_size: number of variables (integer) :param max_hist: maximal history for mixing (integer) :param max_iter: maximum number of iterations for root fin... | stack_v2_sparse_classes_36k_train_033113 | 47,924 | permissive | [
{
"docstring": ":param opt_size: number of variables (integer) :param max_hist: maximal history for mixing (integer) :param max_iter: maximum number of iterations for root finding :param initial_guess: initial guess for the root finding.",
"name": "__init__",
"signature": "def __init__(self, opt_size, m... | 4 | stack_v2_sparse_classes_30k_train_014376 | Implement the Python class `NewtonOptimizer` described below.
Class description:
Newton root finding.
Method signatures and docstrings:
- def __init__(self, opt_size, max_hist=1, max_iter=20000, initial_guess=None): :param opt_size: number of variables (integer) :param max_hist: maximal history for mixing (integer) :... | Implement the Python class `NewtonOptimizer` described below.
Class description:
Newton root finding.
Method signatures and docstrings:
- def __init__(self, opt_size, max_hist=1, max_iter=20000, initial_guess=None): :param opt_size: number of variables (integer) :param max_hist: maximal history for mixing (integer) :... | 84d864b75b90805b5b1688dfbf4a2387dfa20e3d | <|skeleton|>
class NewtonOptimizer:
"""Newton root finding."""
def __init__(self, opt_size, max_hist=1, max_iter=20000, initial_guess=None):
""":param opt_size: number of variables (integer) :param max_hist: maximal history for mixing (integer) :param max_iter: maximum number of iterations for root fin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NewtonOptimizer:
"""Newton root finding."""
def __init__(self, opt_size, max_hist=1, max_iter=20000, initial_guess=None):
""":param opt_size: number of variables (integer) :param max_hist: maximal history for mixing (integer) :param max_iter: maximum number of iterations for root finding :param i... | the_stack_v2_python_sparse | ana_cont/solvers.py | josefkaufmann/ana_cont | train | 39 |
e9551ea6a5198dafc8a49a4d8dc17dd983bbf9fb | [
"t, dat = dat\nif len(dat) > 3:\n print('wrong meta', dat, len(dat))\n return None\nr = (t, dat['value'], dat['time'], dat['temp'])\nreturn np.array([r], dtype=cls.fields)",
"if len(dat) == 1:\n dat = dat[0]\nif len(dat) != len(cls.fields):\n return None\nreturn [dat[0], {'value': dat[1], 'time': dat[... | <|body_start_0|>
t, dat = dat
if len(dat) > 3:
print('wrong meta', dat, len(dat))
return None
r = (t, dat['value'], dat['time'], dat['temp'])
return np.array([r], dtype=cls.fields)
<|end_body_0|>
<|body_start_1|>
if len(dat) == 1:
dat = dat[0]... | An Array reference with 4 columns, one for the time, 3 for value,time,temp keys of a Meta option type | Meta | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Meta:
"""An Array reference with 4 columns, one for the time, 3 for value,time,temp keys of a Meta option type"""
def encode(cls, dat):
"""Flatten the Meta dictionary into a float list of t,value,time,temp"""
<|body_0|>
def decode(cls, dat):
"""Rebuild the Meta d... | stack_v2_sparse_classes_36k_train_033114 | 6,398 | permissive | [
{
"docstring": "Flatten the Meta dictionary into a float list of t,value,time,temp",
"name": "encode",
"signature": "def encode(cls, dat)"
},
{
"docstring": "Rebuild the Meta dictionary",
"name": "decode",
"signature": "def decode(cls, dat)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011178 | Implement the Python class `Meta` described below.
Class description:
An Array reference with 4 columns, one for the time, 3 for value,time,temp keys of a Meta option type
Method signatures and docstrings:
- def encode(cls, dat): Flatten the Meta dictionary into a float list of t,value,time,temp
- def decode(cls, dat... | Implement the Python class `Meta` described below.
Class description:
An Array reference with 4 columns, one for the time, 3 for value,time,temp keys of a Meta option type
Method signatures and docstrings:
- def encode(cls, dat): Flatten the Meta dictionary into a float list of t,value,time,temp
- def decode(cls, dat... | 726cd8eb6f28070dad3332b8708fc17261de8f94 | <|skeleton|>
class Meta:
"""An Array reference with 4 columns, one for the time, 3 for value,time,temp keys of a Meta option type"""
def encode(cls, dat):
"""Flatten the Meta dictionary into a float list of t,value,time,temp"""
<|body_0|>
def decode(cls, dat):
"""Rebuild the Meta d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Meta:
"""An Array reference with 4 columns, one for the time, 3 for value,time,temp keys of a Meta option type"""
def encode(cls, dat):
"""Flatten the Meta dictionary into a float list of t,value,time,temp"""
t, dat = dat
if len(dat) > 3:
print('wrong meta', dat, len(d... | the_stack_v2_python_sparse | misura/canon/reference/array.py | tainstr/misura.canon | train | 1 |
2ed28c58d3ade348839a51576b13e9b8abbb936f | [
"try:\n int(period)\n if int(period) > 0:\n return True\n else:\n return False\nexcept ValueError:\n return False",
"_validate_window(window_days_size)\naverage_ratings_df = pd.DataFrame(reviews_df[['date', ratings_column_name]])\nif not sorted_date:\n average_ratings_df.sort_values('... | <|body_start_0|>
try:
int(period)
if int(period) > 0:
return True
else:
return False
except ValueError:
return False
<|end_body_0|>
<|body_start_1|>
_validate_window(window_days_size)
average_ratings_df = pd... | AverageRating | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AverageRating:
def check_valid_period(period):
"""Checks whether period is a positive integer. :param period"""
<|body_0|>
def calculate_average_ratings(reviews_df, window_days_size=30, ratings_column_name='stars', sorted_date=False):
"""Calculates the average rating... | stack_v2_sparse_classes_36k_train_033115 | 2,357 | permissive | [
{
"docstring": "Checks whether period is a positive integer. :param period",
"name": "check_valid_period",
"signature": "def check_valid_period(period)"
},
{
"docstring": "Calculates the average rating for windows of length window_days_size. :param reviews_df: reviews dataframe, it should contai... | 2 | null | Implement the Python class `AverageRating` described below.
Class description:
Implement the AverageRating class.
Method signatures and docstrings:
- def check_valid_period(period): Checks whether period is a positive integer. :param period
- def calculate_average_ratings(reviews_df, window_days_size=30, ratings_colu... | Implement the Python class `AverageRating` described below.
Class description:
Implement the AverageRating class.
Method signatures and docstrings:
- def check_valid_period(period): Checks whether period is a positive integer. :param period
- def calculate_average_ratings(reviews_df, window_days_size=30, ratings_colu... | dc9185cbc5e65650d985ebecf877a157c8c19a13 | <|skeleton|>
class AverageRating:
def check_valid_period(period):
"""Checks whether period is a positive integer. :param period"""
<|body_0|>
def calculate_average_ratings(reviews_df, window_days_size=30, ratings_column_name='stars', sorted_date=False):
"""Calculates the average rating... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AverageRating:
def check_valid_period(period):
"""Checks whether period is a positive integer. :param period"""
try:
int(period)
if int(period) > 0:
return True
else:
return False
except ValueError:
return ... | the_stack_v2_python_sparse | ak6179/src/average_rating/average_rating.py | ds-ga-1007/final_project | train | 0 | |
de23e308fcda789b8250cc9e3bae34f6b678013d | [
"self.s3_resource = s3_resource\nself.iam_resource = iam_resource\nself.bucket = None\nself.data_access_role = None",
"try:\n self.bucket = self.s3_resource.create_bucket(Bucket=f'doc-example-bucket-{uuid.uuid4()}', CreateBucketConfiguration={'LocationConstraint': self.s3_resource.meta.client.meta.region_name}... | <|body_start_0|>
self.s3_resource = s3_resource
self.iam_resource = iam_resource
self.bucket = None
self.data_access_role = None
<|end_body_0|>
<|body_start_1|>
try:
self.bucket = self.s3_resource.create_bucket(Bucket=f'doc-example-bucket-{uuid.uuid4()}', CreateBucke... | Encapsulates resources used for demonstrations. | ComprehendDemoResources | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComprehendDemoResources:
"""Encapsulates resources used for demonstrations."""
def __init__(self, s3_resource, iam_resource):
""":param s3_resource: A Boto3 Amazon S3 resource. :param iam_resource: A Boto3 AWS Identity and Access Management (IAM) resource."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_033116 | 7,087 | permissive | [
{
"docstring": ":param s3_resource: A Boto3 Amazon S3 resource. :param iam_resource: A Boto3 AWS Identity and Access Management (IAM) resource.",
"name": "__init__",
"signature": "def __init__(self, s3_resource, iam_resource)"
},
{
"docstring": "Creates an Amazon S3 bucket to be used for a demon... | 4 | null | Implement the Python class `ComprehendDemoResources` described below.
Class description:
Encapsulates resources used for demonstrations.
Method signatures and docstrings:
- def __init__(self, s3_resource, iam_resource): :param s3_resource: A Boto3 Amazon S3 resource. :param iam_resource: A Boto3 AWS Identity and Acce... | Implement the Python class `ComprehendDemoResources` described below.
Class description:
Encapsulates resources used for demonstrations.
Method signatures and docstrings:
- def __init__(self, s3_resource, iam_resource): :param s3_resource: A Boto3 Amazon S3 resource. :param iam_resource: A Boto3 AWS Identity and Acce... | dec41fb589043ac9d8667aac36fb88a53c3abe50 | <|skeleton|>
class ComprehendDemoResources:
"""Encapsulates resources used for demonstrations."""
def __init__(self, s3_resource, iam_resource):
""":param s3_resource: A Boto3 Amazon S3 resource. :param iam_resource: A Boto3 AWS Identity and Access Management (IAM) resource."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ComprehendDemoResources:
"""Encapsulates resources used for demonstrations."""
def __init__(self, s3_resource, iam_resource):
""":param s3_resource: A Boto3 Amazon S3 resource. :param iam_resource: A Boto3 AWS Identity and Access Management (IAM) resource."""
self.s3_resource = s3_resourc... | the_stack_v2_python_sparse | python/example_code/comprehend/comprehend_demo_resources.py | awsdocs/aws-doc-sdk-examples | train | 8,240 |
2b7abfa80c343c73e821a04c3a2d009acc3e809a | [
"self.delivery_target_vec = delivery_target_vec\nself.emails = emails\nself.policy = policy\nself.raise_object_level_failure_alert = raise_object_level_failure_alert",
"if dictionary is None:\n return None\ndelivery_target_vec = None\nif dictionary.get('deliveryTargetVec') != None:\n delivery_target_vec = l... | <|body_start_0|>
self.delivery_target_vec = delivery_target_vec
self.emails = emails
self.policy = policy
self.raise_object_level_failure_alert = raise_object_level_failure_alert
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
delivery_targ... | Implementation of the 'AlertingPolicyProto' model. TODO: type description here. Attributes: delivery_target_vec (list of DeliveryRuleProto_DeliveryTarget): The delivery targets to be alerted. emails (list of string): The email addresses to send alerts to. This field has been deprecated in favor of the field delivery_ta... | AlertingPolicyProto | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlertingPolicyProto:
"""Implementation of the 'AlertingPolicyProto' model. TODO: type description here. Attributes: delivery_target_vec (list of DeliveryRuleProto_DeliveryTarget): The delivery targets to be alerted. emails (list of string): The email addresses to send alerts to. This field has be... | stack_v2_sparse_classes_36k_train_033117 | 3,177 | permissive | [
{
"docstring": "Constructor for the AlertingPolicyProto class",
"name": "__init__",
"signature": "def __init__(self, delivery_target_vec=None, emails=None, policy=None, raise_object_level_failure_alert=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary... | 2 | null | Implement the Python class `AlertingPolicyProto` described below.
Class description:
Implementation of the 'AlertingPolicyProto' model. TODO: type description here. Attributes: delivery_target_vec (list of DeliveryRuleProto_DeliveryTarget): The delivery targets to be alerted. emails (list of string): The email address... | Implement the Python class `AlertingPolicyProto` described below.
Class description:
Implementation of the 'AlertingPolicyProto' model. TODO: type description here. Attributes: delivery_target_vec (list of DeliveryRuleProto_DeliveryTarget): The delivery targets to be alerted. emails (list of string): The email address... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class AlertingPolicyProto:
"""Implementation of the 'AlertingPolicyProto' model. TODO: type description here. Attributes: delivery_target_vec (list of DeliveryRuleProto_DeliveryTarget): The delivery targets to be alerted. emails (list of string): The email addresses to send alerts to. This field has be... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlertingPolicyProto:
"""Implementation of the 'AlertingPolicyProto' model. TODO: type description here. Attributes: delivery_target_vec (list of DeliveryRuleProto_DeliveryTarget): The delivery targets to be alerted. emails (list of string): The email addresses to send alerts to. This field has been deprecated... | the_stack_v2_python_sparse | cohesity_management_sdk/models/alerting_policy_proto.py | cohesity/management-sdk-python | train | 24 |
32782efa9947842511be3bc886cf221e7372ca55 | [
"json_dict = json.loads(request.body.decode())\nsku_id = json_dict.get('sku_id')\ntry:\n SKU.objects.get(id=sku_id)\nexcept SKU.DoesNotExist:\n return http.HttpResponseForbidden('sku不存在')\nredis_conn = get_redis_connection('history')\npl = redis_conn.pipeline()\nuser_id = request.user.id\npl.lrem('history_{}'... | <|body_start_0|>
json_dict = json.loads(request.body.decode())
sku_id = json_dict.get('sku_id')
try:
SKU.objects.get(id=sku_id)
except SKU.DoesNotExist:
return http.HttpResponseForbidden('sku不存在')
redis_conn = get_redis_connection('history')
pl = r... | 用户浏览记录 | UserBrowseHistory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserBrowseHistory:
"""用户浏览记录"""
def post(self, request):
"""保存用户浏览记录"""
<|body_0|>
def get(self, request):
"""获取用户浏览记录"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
json_dict = json.loads(request.body.decode())
sku_id = json_dict.get('... | stack_v2_sparse_classes_36k_train_033118 | 26,474 | no_license | [
{
"docstring": "保存用户浏览记录",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "获取用户浏览记录",
"name": "get",
"signature": "def get(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014194 | Implement the Python class `UserBrowseHistory` described below.
Class description:
用户浏览记录
Method signatures and docstrings:
- def post(self, request): 保存用户浏览记录
- def get(self, request): 获取用户浏览记录 | Implement the Python class `UserBrowseHistory` described below.
Class description:
用户浏览记录
Method signatures and docstrings:
- def post(self, request): 保存用户浏览记录
- def get(self, request): 获取用户浏览记录
<|skeleton|>
class UserBrowseHistory:
"""用户浏览记录"""
def post(self, request):
"""保存用户浏览记录"""
<|body... | e3976cbb9e96a1558f4e00abed1c61d887f915b1 | <|skeleton|>
class UserBrowseHistory:
"""用户浏览记录"""
def post(self, request):
"""保存用户浏览记录"""
<|body_0|>
def get(self, request):
"""获取用户浏览记录"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserBrowseHistory:
"""用户浏览记录"""
def post(self, request):
"""保存用户浏览记录"""
json_dict = json.loads(request.body.decode())
sku_id = json_dict.get('sku_id')
try:
SKU.objects.get(id=sku_id)
except SKU.DoesNotExist:
return http.HttpResponseForbidden... | the_stack_v2_python_sparse | meiduo_mall/meiduo_mall/apps/users/views.py | yi0506/meiduo | train | 0 |
62773eb73917c27b01cb5ee11edba17b531017cc | [
"super(littlePoolingConv, self).__init__()\nself.main = nn.Sequential(nn.Conv2d(num_channels, 64, 3, 1, 1, bias=True), nn.ReLU(True), nn.MaxPool2d(2), nn.BatchNorm2d(64), nn.Dropout2d(p=dropoutP), nn.Conv2d(64, 128, 3, 1, 1, bias=False), nn.ReLU(True), nn.MaxPool2d(2), nn.BatchNorm2d(128), nn.Dropout2d(p=dropoutP),... | <|body_start_0|>
super(littlePoolingConv, self).__init__()
self.main = nn.Sequential(nn.Conv2d(num_channels, 64, 3, 1, 1, bias=True), nn.ReLU(True), nn.MaxPool2d(2), nn.BatchNorm2d(64), nn.Dropout2d(p=dropoutP), nn.Conv2d(64, 128, 3, 1, 1, bias=False), nn.ReLU(True), nn.MaxPool2d(2), nn.BatchNorm2d(128)... | Class encoder | littlePoolingConv | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class littlePoolingConv:
"""Class encoder"""
def __init__(self, c_dim, z_dim=200, num_channels=1, dropoutP=0.2, std=0.02):
"""Initialization conv -> ReLU x 4 -> (mu, sigma)"""
<|body_0|>
def init_weights(self):
"""Weight Initialization"""
<|body_1|>
def fo... | stack_v2_sparse_classes_36k_train_033119 | 3,780 | no_license | [
{
"docstring": "Initialization conv -> ReLU x 4 -> (mu, sigma)",
"name": "__init__",
"signature": "def __init__(self, c_dim, z_dim=200, num_channels=1, dropoutP=0.2, std=0.02)"
},
{
"docstring": "Weight Initialization",
"name": "init_weights",
"signature": "def init_weights(self)"
},
... | 3 | stack_v2_sparse_classes_30k_train_005619 | Implement the Python class `littlePoolingConv` described below.
Class description:
Class encoder
Method signatures and docstrings:
- def __init__(self, c_dim, z_dim=200, num_channels=1, dropoutP=0.2, std=0.02): Initialization conv -> ReLU x 4 -> (mu, sigma)
- def init_weights(self): Weight Initialization
- def forwar... | Implement the Python class `littlePoolingConv` described below.
Class description:
Class encoder
Method signatures and docstrings:
- def __init__(self, c_dim, z_dim=200, num_channels=1, dropoutP=0.2, std=0.02): Initialization conv -> ReLU x 4 -> (mu, sigma)
- def init_weights(self): Weight Initialization
- def forwar... | 21c0bf459388bd616a64afc1a34441123b1f41fe | <|skeleton|>
class littlePoolingConv:
"""Class encoder"""
def __init__(self, c_dim, z_dim=200, num_channels=1, dropoutP=0.2, std=0.02):
"""Initialization conv -> ReLU x 4 -> (mu, sigma)"""
<|body_0|>
def init_weights(self):
"""Weight Initialization"""
<|body_1|>
def fo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class littlePoolingConv:
"""Class encoder"""
def __init__(self, c_dim, z_dim=200, num_channels=1, dropoutP=0.2, std=0.02):
"""Initialization conv -> ReLU x 4 -> (mu, sigma)"""
super(littlePoolingConv, self).__init__()
self.main = nn.Sequential(nn.Conv2d(num_channels, 64, 3, 1, 1, bias=T... | the_stack_v2_python_sparse | classification/models/littleConv.py | CHOcho-quan/CS385ML | train | 1 |
8f0c376281c5bed18dddfdae8843e3b5c2d04845 | [
"result = []\nself.helper(nums, target, '', 0, 0, 0, result)\nprint(result)\nreturn result",
"if pos == len(num):\n if current == target:\n result.append(temp)\n pass\n return\nfor i in range(pos, len(num)):\n if num[pos] == '0' and i != pos:\n break\n pass\n m: str = num[p... | <|body_start_0|>
result = []
self.helper(nums, target, '', 0, 0, 0, result)
print(result)
return result
<|end_body_0|>
<|body_start_1|>
if pos == len(num):
if current == target:
result.append(temp)
pass
return
for i... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lucky_numbers(self, nums: str, target: int) -> List[str]:
""":param nums: the input phone number string :param target: the number we want to get with :return: a list of results that conform to this rule"""
<|body_0|>
def helper(self, num: str, target: int, temp... | stack_v2_sparse_classes_36k_train_033120 | 1,986 | permissive | [
{
"docstring": ":param nums: the input phone number string :param target: the number we want to get with :return: a list of results that conform to this rule",
"name": "lucky_numbers",
"signature": "def lucky_numbers(self, nums: str, target: int) -> List[str]"
},
{
"docstring": ":param num: the ... | 2 | stack_v2_sparse_classes_30k_train_018576 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lucky_numbers(self, nums: str, target: int) -> List[str]: :param nums: the input phone number string :param target: the number we want to get with :return: a list of results ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lucky_numbers(self, nums: str, target: int) -> List[str]: :param nums: the input phone number string :param target: the number we want to get with :return: a list of results ... | 55c6488e39f51875107b0eefd2a91e2cc251d3c8 | <|skeleton|>
class Solution:
def lucky_numbers(self, nums: str, target: int) -> List[str]:
""":param nums: the input phone number string :param target: the number we want to get with :return: a list of results that conform to this rule"""
<|body_0|>
def helper(self, num: str, target: int, temp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lucky_numbers(self, nums: str, target: int) -> List[str]:
""":param nums: the input phone number string :param target: the number we want to get with :return: a list of results that conform to this rule"""
result = []
self.helper(nums, target, '', 0, 0, 0, result)
... | the_stack_v2_python_sparse | 190524_lucky_numbers_888/lucky-number.py | yo1995/Daily_agorithm_practices | train | 0 | |
4ff4657cb55dae61232be7f18410429f469ad00b | [
"self.q = q\nself.baseline = baseline\nself.rep = rep\nself.theta_source = theta_source\nself.nu_source = nu_source\nself.frame = frame\nself.interp = interp",
"if self.q.config != 'TD':\n raise ValueError('Maynooth simulations are for the TD only.')\nxONAFP, yONAFP, fringes_fullreso = get_power_Maynooth(self.... | <|body_start_0|>
self.q = q
self.baseline = baseline
self.rep = rep
self.theta_source = theta_source
self.nu_source = nu_source
self.frame = frame
self.interp = interp
<|end_body_0|>
<|body_start_1|>
if self.q.config != 'TD':
raise ValueError(... | Model_Fringes_Maynooth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Model_Fringes_Maynooth:
def __init__(self, q, baseline, rep, theta_source=0.0, nu_source=150000000000.0, frame='ONAFP', interp=False):
"""Parameters ---------- q: QubicInstrument baseline: list Baseline formed with 2 horns, index between 1 and 64 as on the instrument. rep: str Repository... | stack_v2_sparse_classes_36k_train_033121 | 45,734 | no_license | [
{
"docstring": "Parameters ---------- q: QubicInstrument baseline: list Baseline formed with 2 horns, index between 1 and 64 as on the instrument. rep: str Repository with the simulation files. theta: float The source zenith angle [rad]. nu: float Frequency of the calibration source [Hz] frame: str 'GRF' or 'ON... | 3 | null | Implement the Python class `Model_Fringes_Maynooth` described below.
Class description:
Implement the Model_Fringes_Maynooth class.
Method signatures and docstrings:
- def __init__(self, q, baseline, rep, theta_source=0.0, nu_source=150000000000.0, frame='ONAFP', interp=False): Parameters ---------- q: QubicInstrumen... | Implement the Python class `Model_Fringes_Maynooth` described below.
Class description:
Implement the Model_Fringes_Maynooth class.
Method signatures and docstrings:
- def __init__(self, q, baseline, rep, theta_source=0.0, nu_source=150000000000.0, frame='ONAFP', interp=False): Parameters ---------- q: QubicInstrumen... | cb9bb4493da5ce5427f33583025bc0e32291177e | <|skeleton|>
class Model_Fringes_Maynooth:
def __init__(self, q, baseline, rep, theta_source=0.0, nu_source=150000000000.0, frame='ONAFP', interp=False):
"""Parameters ---------- q: QubicInstrument baseline: list Baseline formed with 2 horns, index between 1 and 64 as on the instrument. rep: str Repository... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Model_Fringes_Maynooth:
def __init__(self, q, baseline, rep, theta_source=0.0, nu_source=150000000000.0, frame='ONAFP', interp=False):
"""Parameters ---------- q: QubicInstrument baseline: list Baseline formed with 2 horns, index between 1 and 64 as on the instrument. rep: str Repository with the simu... | the_stack_v2_python_sparse | qubic/selfcal_lib.py | qubicsoft/qubic | train | 14 | |
d33db5ddebbf8a442af846aba937a0ee92fb99c1 | [
"issues = issue_tracker_utils.get_similar_issues(issue_tracker, testcase, only_open=only_open)\nitems = []\nfor entry in issues:\n items.append({'owner': entry.assignee, 'reporter': entry.reporter, 'status': entry.status, 'title': entry.title, 'id': entry.id})\nitems = sorted(items, key=lambda k: k['id'])\nretur... | <|body_start_0|>
issues = issue_tracker_utils.get_similar_issues(issue_tracker, testcase, only_open=only_open)
items = []
for entry in issues:
items.append({'owner': entry.assignee, 'reporter': entry.reporter, 'status': entry.status, 'title': entry.title, 'id': entry.id})
ite... | Handler that finds similar issues. | Handler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Handler:
"""Handler that finds similar issues."""
def get_issues(issue_tracker, testcase, only_open):
"""Get similar issues. It is used by self.process() and handler.testcase_detail.FindSimilarIssuesHandler.get()"""
<|body_0|>
def get(self, testcase):
"""Find sim... | stack_v2_sparse_classes_36k_train_033122 | 2,304 | permissive | [
{
"docstring": "Get similar issues. It is used by self.process() and handler.testcase_detail.FindSimilarIssuesHandler.get()",
"name": "get_issues",
"signature": "def get_issues(issue_tracker, testcase, only_open)"
},
{
"docstring": "Find similar issues.",
"name": "get",
"signature": "def... | 2 | null | Implement the Python class `Handler` described below.
Class description:
Handler that finds similar issues.
Method signatures and docstrings:
- def get_issues(issue_tracker, testcase, only_open): Get similar issues. It is used by self.process() and handler.testcase_detail.FindSimilarIssuesHandler.get()
- def get(self... | Implement the Python class `Handler` described below.
Class description:
Handler that finds similar issues.
Method signatures and docstrings:
- def get_issues(issue_tracker, testcase, only_open): Get similar issues. It is used by self.process() and handler.testcase_detail.FindSimilarIssuesHandler.get()
- def get(self... | 6501a839b27a264500244f32bace8bee4d5cb9a2 | <|skeleton|>
class Handler:
"""Handler that finds similar issues."""
def get_issues(issue_tracker, testcase, only_open):
"""Get similar issues. It is used by self.process() and handler.testcase_detail.FindSimilarIssuesHandler.get()"""
<|body_0|>
def get(self, testcase):
"""Find sim... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Handler:
"""Handler that finds similar issues."""
def get_issues(issue_tracker, testcase, only_open):
"""Get similar issues. It is used by self.process() and handler.testcase_detail.FindSimilarIssuesHandler.get()"""
issues = issue_tracker_utils.get_similar_issues(issue_tracker, testcase, ... | the_stack_v2_python_sparse | src/appengine/handlers/testcase_detail/find_similar_issues.py | google/clusterfuzz | train | 5,420 |
39756ced8ef6140c7f8351aff4d2c3a8df6e0f72 | [
"df = None\ntry:\n if filename.endswith('.csv'):\n df = pd.read_csv(filename)\n if filename.endswith('.json'):\n df = pd.read_json(filename)\nexcept FileNotFoundError:\n print(f'File {filename} not found.')\n raise FileNotFoundError\nrows, columns = df.shape\nprint(f'Loading dataset of dim... | <|body_start_0|>
df = None
try:
if filename.endswith('.csv'):
df = pd.read_csv(filename)
if filename.endswith('.json'):
df = pd.read_json(filename)
except FileNotFoundError:
print(f'File {filename} not found.')
raise... | FileLoader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileLoader:
def load(filename):
""":param string filename: :return: pd.DataFrame"""
<|body_0|>
def display(dataframe, n):
""":param pd.DataFrame dataframe: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
df = None
try:
i... | stack_v2_sparse_classes_36k_train_033123 | 1,031 | no_license | [
{
"docstring": ":param string filename: :return: pd.DataFrame",
"name": "load",
"signature": "def load(filename)"
},
{
"docstring": ":param pd.DataFrame dataframe: :return:",
"name": "display",
"signature": "def display(dataframe, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011798 | Implement the Python class `FileLoader` described below.
Class description:
Implement the FileLoader class.
Method signatures and docstrings:
- def load(filename): :param string filename: :return: pd.DataFrame
- def display(dataframe, n): :param pd.DataFrame dataframe: :return: | Implement the Python class `FileLoader` described below.
Class description:
Implement the FileLoader class.
Method signatures and docstrings:
- def load(filename): :param string filename: :return: pd.DataFrame
- def display(dataframe, n): :param pd.DataFrame dataframe: :return:
<|skeleton|>
class FileLoader:
de... | fcf8b4a4b74d552d775bc7dbb8e83c05aa31f80f | <|skeleton|>
class FileLoader:
def load(filename):
""":param string filename: :return: pd.DataFrame"""
<|body_0|>
def display(dataframe, n):
""":param pd.DataFrame dataframe: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileLoader:
def load(filename):
""":param string filename: :return: pd.DataFrame"""
df = None
try:
if filename.endswith('.csv'):
df = pd.read_csv(filename)
if filename.endswith('.json'):
df = pd.read_json(filename)
except ... | the_stack_v2_python_sparse | day04/ex04/FileLoader.py | edramir18/42_python_bootcamp | train | 0 | |
41ec649af4c99f83e1c92288a0d671c9bf7cdfb3 | [
"PISM.IP_SSATaucTaoTikhonovProblemListener.__init__(self)\nself.owner = owner\nself.listener = listener",
"data = Bunch(tikhonov_penalty=eta, JDesign=objVal, JState=penaltyVal, zeta=d, zeta_step=diff_d, grad_JDesign=grad_d, u=u, residual=diff_u, grad_JState=grad_u, grad_JTikhonov=grad)\ntry:\n self.listener(se... | <|body_start_0|>
PISM.IP_SSATaucTaoTikhonovProblemListener.__init__(self)
self.owner = owner
self.listener = listener
<|end_body_0|>
<|body_start_1|>
data = Bunch(tikhonov_penalty=eta, JDesign=objVal, JState=penaltyVal, zeta=d, zeta_step=diff_d, grad_JDesign=grad_d, u=u, residual=diff_u... | Adaptor converting calls to a C++ :cpp:class:`IP_SSATaucTaoTikhonovProblemListener` on to a standard python-based listener. Used internally by :class:`InvSSATaucSolver_Tikhonov`. I.e. don't make one of these for yourself. | TaucIterationListenerAdaptor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaucIterationListenerAdaptor:
"""Adaptor converting calls to a C++ :cpp:class:`IP_SSATaucTaoTikhonovProblemListener` on to a standard python-based listener. Used internally by :class:`InvSSATaucSolver_Tikhonov`. I.e. don't make one of these for yourself."""
def __init__(self, owner, listener... | stack_v2_sparse_classes_36k_train_033124 | 10,589 | no_license | [
{
"docstring": ":param owner: The :class:`InvSSATaucSolver_Tikhonov` that constructed us :param listener: The python-based listener.",
"name": "__init__",
"signature": "def __init__(self, owner, listener)"
},
{
"docstring": "Called during IP_SSATaucTaoTikhonovProblem iterations. Gathers together... | 2 | stack_v2_sparse_classes_30k_train_016925 | Implement the Python class `TaucIterationListenerAdaptor` described below.
Class description:
Adaptor converting calls to a C++ :cpp:class:`IP_SSATaucTaoTikhonovProblemListener` on to a standard python-based listener. Used internally by :class:`InvSSATaucSolver_Tikhonov`. I.e. don't make one of these for yourself.
Me... | Implement the Python class `TaucIterationListenerAdaptor` described below.
Class description:
Adaptor converting calls to a C++ :cpp:class:`IP_SSATaucTaoTikhonovProblemListener` on to a standard python-based listener. Used internally by :class:`InvSSATaucSolver_Tikhonov`. I.e. don't make one of these for yourself.
Me... | 88664f50a2f7075b6e96a06a5976986aac0302ed | <|skeleton|>
class TaucIterationListenerAdaptor:
"""Adaptor converting calls to a C++ :cpp:class:`IP_SSATaucTaoTikhonovProblemListener` on to a standard python-based listener. Used internally by :class:`InvSSATaucSolver_Tikhonov`. I.e. don't make one of these for yourself."""
def __init__(self, owner, listener... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TaucIterationListenerAdaptor:
"""Adaptor converting calls to a C++ :cpp:class:`IP_SSATaucTaoTikhonovProblemListener` on to a standard python-based listener. Used internally by :class:`InvSSATaucSolver_Tikhonov`. I.e. don't make one of these for yourself."""
def __init__(self, owner, listener):
""... | the_stack_v2_python_sparse | site-packages/PISM/invert/ssa_tao.py | flapo099/test | train | 0 |
6408899d30de966e78d134f240e4fec246db8d46 | [
"formset_form_attrs = kwargs.pop('formset_form_attrs', {})\nsuper(FormSetFormMixin, self).__init__(*args, **kwargs)\nif formset_form_attrs is not None:\n for key, value in formset_form_attrs.items():\n self.fields[key].form_attrs = value",
"instance = super(FormSetFormMixin, self).save(commit)\nif commi... | <|body_start_0|>
formset_form_attrs = kwargs.pop('formset_form_attrs', {})
super(FormSetFormMixin, self).__init__(*args, **kwargs)
if formset_form_attrs is not None:
for key, value in formset_form_attrs.items():
self.fields[key].form_attrs = value
<|end_body_0|>
<|bo... | Custom form mixin to allow easier use of formset fields. With the setup of the formset fields the formset_form_attrs kwargs is translated to form_attrs on the specific fields. Also there is custom save logic for each of the formset fields. | FormSetFormMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FormSetFormMixin:
"""Custom form mixin to allow easier use of formset fields. With the setup of the formset fields the formset_form_attrs kwargs is translated to form_attrs on the specific fields. Also there is custom save logic for each of the formset fields."""
def __init__(self, *args, **... | stack_v2_sparse_classes_36k_train_033125 | 2,534 | no_license | [
{
"docstring": "Custom init function to set the form_attrs on each formset field specified in formset_form_attrs. Args: formset_form_attrs (dict, optional): Dict specifying the fields and value for the form_attr of that field. *args: Variable length argument list. **kwargs: Arbitrary keyword arguments. The form... | 2 | null | Implement the Python class `FormSetFormMixin` described below.
Class description:
Custom form mixin to allow easier use of formset fields. With the setup of the formset fields the formset_form_attrs kwargs is translated to form_attrs on the specific fields. Also there is custom save logic for each of the formset field... | Implement the Python class `FormSetFormMixin` described below.
Class description:
Custom form mixin to allow easier use of formset fields. With the setup of the formset fields the formset_form_attrs kwargs is translated to form_attrs on the specific fields. Also there is custom save logic for each of the formset field... | ddb25fa16280d1ca5fba32f71d65c90815648f0a | <|skeleton|>
class FormSetFormMixin:
"""Custom form mixin to allow easier use of formset fields. With the setup of the formset fields the formset_form_attrs kwargs is translated to form_attrs on the specific fields. Also there is custom save logic for each of the formset fields."""
def __init__(self, *args, **... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FormSetFormMixin:
"""Custom form mixin to allow easier use of formset fields. With the setup of the formset fields the formset_form_attrs kwargs is translated to form_attrs on the specific fields. Also there is custom save logic for each of the formset fields."""
def __init__(self, *args, **kwargs):
... | the_stack_v2_python_sparse | lily/utils/forms/mixins.py | Vegulla/hellolily | train | 0 |
c6dbded20186ca84aab72e84e012e705bf73e6dc | [
"assert isinstance(pot, NFWPotential), 'pot= must be potential.NFWPotential'\n_osipkovmerrittdf.__init__(self, pot=pot, ra=ra, rmax=rmax, ro=ro, vo=vo)\nself._Qtildemax = pot._amp / pot.a\nself._Qtildemin = -pot(self._rmax, 0, use_physical=False) / self._Qtildemax\nself._a2overra2 = self._pot.a ** 2.0 / self._ra2\n... | <|body_start_0|>
assert isinstance(pot, NFWPotential), 'pot= must be potential.NFWPotential'
_osipkovmerrittdf.__init__(self, pot=pot, ra=ra, rmax=rmax, ro=ro, vo=vo)
self._Qtildemax = pot._amp / pot.a
self._Qtildemin = -pot(self._rmax, 0, use_physical=False) / self._Qtildemax
se... | Class that implements the anisotropic spherical NFW DF with radially varying anisotropy of the Osipkov-Merritt type .. math:: \\beta(r) = \\frac{1}{1+r_a^2/r^2} with :math:`r_a` the anistropy radius. | osipkovmerrittNFWdf | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class osipkovmerrittNFWdf:
"""Class that implements the anisotropic spherical NFW DF with radially varying anisotropy of the Osipkov-Merritt type .. math:: \\beta(r) = \\frac{1}{1+r_a^2/r^2} with :math:`r_a` the anistropy radius."""
def __init__(self, pot=None, ra=1.4, rmax=10000.0, ro=None, vo=No... | stack_v2_sparse_classes_36k_train_033126 | 3,022 | permissive | [
{
"docstring": "NAME: __init__ PURPOSE: Initialize a NFW DF with Osipkov-Merritt anisotropy INPUT: pot - NFW potential which determines the DF ra - anisotropy radius (can be a Quantity) rmax= (1e4) maximum radius to consider (can be Quantity); set to numpy.inf to evaluate NFW w/o cut-off ro=, vo= galpy unit par... | 2 | null | Implement the Python class `osipkovmerrittNFWdf` described below.
Class description:
Class that implements the anisotropic spherical NFW DF with radially varying anisotropy of the Osipkov-Merritt type .. math:: \\beta(r) = \\frac{1}{1+r_a^2/r^2} with :math:`r_a` the anistropy radius.
Method signatures and docstrings:... | Implement the Python class `osipkovmerrittNFWdf` described below.
Class description:
Class that implements the anisotropic spherical NFW DF with radially varying anisotropy of the Osipkov-Merritt type .. math:: \\beta(r) = \\frac{1}{1+r_a^2/r^2} with :math:`r_a` the anistropy radius.
Method signatures and docstrings:... | a46619fd4f5979acfccad23f4d57503033f440c5 | <|skeleton|>
class osipkovmerrittNFWdf:
"""Class that implements the anisotropic spherical NFW DF with radially varying anisotropy of the Osipkov-Merritt type .. math:: \\beta(r) = \\frac{1}{1+r_a^2/r^2} with :math:`r_a` the anistropy radius."""
def __init__(self, pot=None, ra=1.4, rmax=10000.0, ro=None, vo=No... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class osipkovmerrittNFWdf:
"""Class that implements the anisotropic spherical NFW DF with radially varying anisotropy of the Osipkov-Merritt type .. math:: \\beta(r) = \\frac{1}{1+r_a^2/r^2} with :math:`r_a` the anistropy radius."""
def __init__(self, pot=None, ra=1.4, rmax=10000.0, ro=None, vo=None):
... | the_stack_v2_python_sparse | galpy/df/osipkovmerrittNFWdf.py | jobovy/galpy | train | 182 |
999f962d439a3451dbef7ee65c390eac1b6f067e | [
"if root is None:\n return 0\nreturn self.path(root, sum) + self.pathSum(root.left, sum) + self.pathSum(root.right, sum)",
"if root is None:\n return 0\npath = 1 if root.val == sum else 0\nreturn path + self.path(root.left, sum - root.val) + self.path(root.right, sum - root.val)"
] | <|body_start_0|>
if root is None:
return 0
return self.path(root, sum) + self.pathSum(root.left, sum) + self.pathSum(root.right, sum)
<|end_body_0|>
<|body_start_1|>
if root is None:
return 0
path = 1 if root.val == sum else 0
return path + self.path(root... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def pathSum(self, root, sum):
""":type root: TreeNode :type sum: int :rtype: int"""
<|body_0|>
def path(self, root, sum):
""":type root: TreeNode :type sum: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if root is None:
... | stack_v2_sparse_classes_36k_train_033127 | 1,252 | no_license | [
{
"docstring": ":type root: TreeNode :type sum: int :rtype: int",
"name": "pathSum",
"signature": "def pathSum(self, root, sum)"
},
{
"docstring": ":type root: TreeNode :type sum: int :rtype: int",
"name": "path",
"signature": "def path(self, root, sum)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009624 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum(self, root, sum): :type root: TreeNode :type sum: int :rtype: int
- def path(self, root, sum): :type root: TreeNode :type sum: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum(self, root, sum): :type root: TreeNode :type sum: int :rtype: int
- def path(self, root, sum): :type root: TreeNode :type sum: int :rtype: int
<|skeleton|>
class Sol... | 028cd7c187fade013cb6f8c78c2929617019abbb | <|skeleton|>
class Solution:
def pathSum(self, root, sum):
""":type root: TreeNode :type sum: int :rtype: int"""
<|body_0|>
def path(self, root, sum):
""":type root: TreeNode :type sum: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def pathSum(self, root, sum):
""":type root: TreeNode :type sum: int :rtype: int"""
if root is None:
return 0
return self.path(root, sum) + self.pathSum(root.left, sum) + self.pathSum(root.right, sum)
def path(self, root, sum):
""":type root: TreeNode... | the_stack_v2_python_sparse | LeetCode437.py | ilumer/leetcode-python | train | 0 | |
6ecefef4be9ec72d8569b4f0d2fd511383ad9d97 | [
"updated = queryset.update(start_date=timezone.now())\nif updated == 1:\n message = _(' Discount was Successfully Beginning.')\nelse:\n message = _(' Discounts were Successfully Beginning.')\nself.message_user(request, str(updated) + message)",
"updated = queryset.update(end_date=timezone.now())\nif updated... | <|body_start_0|>
updated = queryset.update(start_date=timezone.now())
if updated == 1:
message = _(' Discount was Successfully Beginning.')
else:
message = _(' Discounts were Successfully Beginning.')
self.message_user(request, str(updated) + message)
<|end_body_0... | Manage Discount Class Model and Show Fields in Panel Admin | DiscountAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiscountAdmin:
"""Manage Discount Class Model and Show Fields in Panel Admin"""
def beginning(self, request, queryset):
"""Action for Change Start Date of Selected Discounts to Now"""
<|body_0|>
def finishing(self, request, queryset):
"""Action for Change End Dat... | stack_v2_sparse_classes_36k_train_033128 | 4,927 | no_license | [
{
"docstring": "Action for Change Start Date of Selected Discounts to Now",
"name": "beginning",
"signature": "def beginning(self, request, queryset)"
},
{
"docstring": "Action for Change End Date of Selected Discounts to Now",
"name": "finishing",
"signature": "def finishing(self, reque... | 2 | stack_v2_sparse_classes_30k_train_002568 | Implement the Python class `DiscountAdmin` described below.
Class description:
Manage Discount Class Model and Show Fields in Panel Admin
Method signatures and docstrings:
- def beginning(self, request, queryset): Action for Change Start Date of Selected Discounts to Now
- def finishing(self, request, queryset): Acti... | Implement the Python class `DiscountAdmin` described below.
Class description:
Manage Discount Class Model and Show Fields in Panel Admin
Method signatures and docstrings:
- def beginning(self, request, queryset): Action for Change Start Date of Selected Discounts to Now
- def finishing(self, request, queryset): Acti... | 4e694f99c896a7ef78676711e5ef8458a14bd902 | <|skeleton|>
class DiscountAdmin:
"""Manage Discount Class Model and Show Fields in Panel Admin"""
def beginning(self, request, queryset):
"""Action for Change Start Date of Selected Discounts to Now"""
<|body_0|>
def finishing(self, request, queryset):
"""Action for Change End Dat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DiscountAdmin:
"""Manage Discount Class Model and Show Fields in Panel Admin"""
def beginning(self, request, queryset):
"""Action for Change Start Date of Selected Discounts to Now"""
updated = queryset.update(start_date=timezone.now())
if updated == 1:
message = _(' D... | the_stack_v2_python_sparse | product/admin.py | SepehrBazyar/Shopping | train | 9 |
761d059bc51ee29c9b235411e3002479972c7202 | [
"adm = ProjectAdministration()\nsem = adm.get_semester_by_id(semester_id)\nif sem is not None:\n return (sem, 200)\nelse:\n return ('Semester nicht vorhanden', 500)",
"adm = ProjectAdministration()\nsem = adm.get_semester_by_id(semester_id)\nif sem is not None:\n adm.delete_semester(sem)\n return ('ge... | <|body_start_0|>
adm = ProjectAdministration()
sem = adm.get_semester_by_id(semester_id)
if sem is not None:
return (sem, 200)
else:
return ('Semester nicht vorhanden', 500)
<|end_body_0|>
<|body_start_1|>
adm = ProjectAdministration()
sem = adm.g... | SemesterOperations | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SemesterOperations:
def get(self, semester_id):
"""Auslesen eines bestimmten Semester-Objektes, welches durch die semester_id in dem URI bestimmt wird."""
<|body_0|>
def delete(self, semester_id):
"""Löschen eines bestimmten Semester-Objektes, welches durch die semes... | stack_v2_sparse_classes_36k_train_033129 | 44,493 | no_license | [
{
"docstring": "Auslesen eines bestimmten Semester-Objektes, welches durch die semester_id in dem URI bestimmt wird.",
"name": "get",
"signature": "def get(self, semester_id)"
},
{
"docstring": "Löschen eines bestimmten Semester-Objektes, welches durch die semester_id in dem URI bestimmt wird.",... | 2 | stack_v2_sparse_classes_30k_train_008829 | Implement the Python class `SemesterOperations` described below.
Class description:
Implement the SemesterOperations class.
Method signatures and docstrings:
- def get(self, semester_id): Auslesen eines bestimmten Semester-Objektes, welches durch die semester_id in dem URI bestimmt wird.
- def delete(self, semester_i... | Implement the Python class `SemesterOperations` described below.
Class description:
Implement the SemesterOperations class.
Method signatures and docstrings:
- def get(self, semester_id): Auslesen eines bestimmten Semester-Objektes, welches durch die semester_id in dem URI bestimmt wird.
- def delete(self, semester_i... | 4b2826225525ae855e15e1174f5cf90466097021 | <|skeleton|>
class SemesterOperations:
def get(self, semester_id):
"""Auslesen eines bestimmten Semester-Objektes, welches durch die semester_id in dem URI bestimmt wird."""
<|body_0|>
def delete(self, semester_id):
"""Löschen eines bestimmten Semester-Objektes, welches durch die semes... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SemesterOperations:
def get(self, semester_id):
"""Auslesen eines bestimmten Semester-Objektes, welches durch die semester_id in dem URI bestimmt wird."""
adm = ProjectAdministration()
sem = adm.get_semester_by_id(semester_id)
if sem is not None:
return (sem, 200)
... | the_stack_v2_python_sparse | src/main.py | KieserChristian/SW_Praktikum_Gruppe1 | train | 0 | |
d375a4b5f23acad3288c689c2dbcd76499ddbd72 | [
"self.account_id = account_id\nself.call_id = call_id\nself.application_id = application_id\nself.to = to\nself.mfrom = mfrom\nself.enqueued_time = (APIHelper.RFC3339DateTime(enqueued_time) if enqueued_time else None,)\nself.enqueued_time = enqueued_time\nself.call_url = call_url\nself.call_timeout = call_timeout\n... | <|body_start_0|>
self.account_id = account_id
self.call_id = call_id
self.application_id = application_id
self.to = to
self.mfrom = mfrom
self.enqueued_time = (APIHelper.RFC3339DateTime(enqueued_time) if enqueued_time else None,)
self.enqueued_time = enqueued_time... | Implementation of the 'CreateCallResponse' model. TODO: type model description here. Attributes: account_id (string): TODO: type description here. call_id (string): TODO: type description here. application_id (string): TODO: type description here. to (string): TODO: type description here. mfrom (string): TODO: type des... | CreateCallResponse | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateCallResponse:
"""Implementation of the 'CreateCallResponse' model. TODO: type model description here. Attributes: account_id (string): TODO: type description here. call_id (string): TODO: type description here. application_id (string): TODO: type description here. to (string): TODO: type de... | stack_v2_sparse_classes_36k_train_033130 | 7,154 | permissive | [
{
"docstring": "Constructor for the CreateCallResponse class",
"name": "__init__",
"signature": "def __init__(self, account_id=None, call_id=None, application_id=None, to=None, mfrom=None, call_url=None, answer_url=None, answer_method=None, disconnect_method=None, enqueued_time=None, call_timeout=None, ... | 2 | stack_v2_sparse_classes_30k_train_010559 | Implement the Python class `CreateCallResponse` described below.
Class description:
Implementation of the 'CreateCallResponse' model. TODO: type model description here. Attributes: account_id (string): TODO: type description here. call_id (string): TODO: type description here. application_id (string): TODO: type descr... | Implement the Python class `CreateCallResponse` described below.
Class description:
Implementation of the 'CreateCallResponse' model. TODO: type model description here. Attributes: account_id (string): TODO: type description here. call_id (string): TODO: type description here. application_id (string): TODO: type descr... | 447df3cc8cb7acaf3361d842630c432a9c31ce6e | <|skeleton|>
class CreateCallResponse:
"""Implementation of the 'CreateCallResponse' model. TODO: type model description here. Attributes: account_id (string): TODO: type description here. call_id (string): TODO: type description here. application_id (string): TODO: type description here. to (string): TODO: type de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateCallResponse:
"""Implementation of the 'CreateCallResponse' model. TODO: type model description here. Attributes: account_id (string): TODO: type description here. call_id (string): TODO: type description here. application_id (string): TODO: type description here. to (string): TODO: type description her... | the_stack_v2_python_sparse | bandwidth/voice/models/create_call_response.py | Bandwidth/python-sdk | train | 10 |
4dcac7c8e6539a65aca63901807903f1c823858b | [
"ctx = self.server.context\nres = {}\nres['method'] = self.command\nres['path'] = self.path\nres['headers'] = self.headers.items()\nres['request_version'] = self.request_version\nif self.headers.get('Content-Length') is not None:\n body_length = int(self.headers.get('Content-Length'))\n res['request_body'] = ... | <|body_start_0|>
ctx = self.server.context
res = {}
res['method'] = self.command
res['path'] = self.path
res['headers'] = self.headers.items()
res['request_version'] = self.request_version
if self.headers.get('Content-Length') is not None:
body_length ... | A request hander class implementing recording all the requests&request data made to given endpoint. This class will most likely be inherited from and extended with some extra code that actually processes the requests because on itself it just returns some sample text. | RecordingHTTPRequestHandler | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-oracle-bcl-javase-javafx-2012",
"ErlPL-1.1",
"MPL-2.0",
"ISC",
"BSL-1.0",
"Python-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecordingHTTPRequestHandler:
"""A request hander class implementing recording all the requests&request data made to given endpoint. This class will most likely be inherited from and extended with some extra code that actually processes the requests because on itself it just returns some sample te... | stack_v2_sparse_classes_36k_train_033131 | 4,611 | permissive | [
{
"docstring": "Store all the relevant data of the request into the endpoint context.",
"name": "_record_request",
"signature": "def _record_request(self)"
},
{
"docstring": "Process all the endpoint configuration and execute things that user requested. Please refer to the description of the Bas... | 2 | stack_v2_sparse_classes_30k_train_008381 | Implement the Python class `RecordingHTTPRequestHandler` described below.
Class description:
A request hander class implementing recording all the requests&request data made to given endpoint. This class will most likely be inherited from and extended with some extra code that actually processes the requests because o... | Implement the Python class `RecordingHTTPRequestHandler` described below.
Class description:
A request hander class implementing recording all the requests&request data made to given endpoint. This class will most likely be inherited from and extended with some extra code that actually processes the requests because o... | 79b9a39b4e639dc2c9435a869918399b50bfaf24 | <|skeleton|>
class RecordingHTTPRequestHandler:
"""A request hander class implementing recording all the requests&request data made to given endpoint. This class will most likely be inherited from and extended with some extra code that actually processes the requests because on itself it just returns some sample te... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RecordingHTTPRequestHandler:
"""A request hander class implementing recording all the requests&request data made to given endpoint. This class will most likely be inherited from and extended with some extra code that actually processes the requests because on itself it just returns some sample text."""
d... | the_stack_v2_python_sparse | packages/adminrouter/extra/src/test-harness/modules/mocker/endpoints/recording.py | dcos/dcos | train | 2,613 |
0dfc3a4702e2207ac0a1ba45cdae5f24f468f287 | [
"try:\n admin = self.app.admin_api.getAdminById(cherrypy.request.db, admin_id)\n response = {'admin': admin.getCleanDict()}\nexcept Exception as ex:\n self._logger.error(str(ex))\n self.handleException(ex)\n response = self.errorResponse(str(ex))\nreturn self.formatResponse(response)",
"try:\n a... | <|body_start_0|>
try:
admin = self.app.admin_api.getAdminById(cherrypy.request.db, admin_id)
response = {'admin': admin.getCleanDict()}
except Exception as ex:
self._logger.error(str(ex))
self.handleException(ex)
response = self.errorResponse(s... | Update controller class. | AdminController | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdminController:
"""Update controller class."""
def getAdmin(self, admin_id):
"""Get an admin by name"""
<|body_0|>
def getAdminList(self):
"""Return list of admin users"""
<|body_1|>
def addAdmin(self):
"""Add a new admin to the system"""
... | stack_v2_sparse_classes_36k_train_033132 | 6,222 | permissive | [
{
"docstring": "Get an admin by name",
"name": "getAdmin",
"signature": "def getAdmin(self, admin_id)"
},
{
"docstring": "Return list of admin users",
"name": "getAdminList",
"signature": "def getAdminList(self)"
},
{
"docstring": "Add a new admin to the system",
"name": "add... | 6 | stack_v2_sparse_classes_30k_train_002827 | Implement the Python class `AdminController` described below.
Class description:
Update controller class.
Method signatures and docstrings:
- def getAdmin(self, admin_id): Get an admin by name
- def getAdminList(self): Return list of admin users
- def addAdmin(self): Add a new admin to the system
- def deleteAdmin(se... | Implement the Python class `AdminController` described below.
Class description:
Update controller class.
Method signatures and docstrings:
- def getAdmin(self, admin_id): Get an admin by name
- def getAdminList(self): Return list of admin users
- def addAdmin(self): Add a new admin to the system
- def deleteAdmin(se... | 56d808d7836cd15d6c6748cbf704cdea4407fef6 | <|skeleton|>
class AdminController:
"""Update controller class."""
def getAdmin(self, admin_id):
"""Get an admin by name"""
<|body_0|>
def getAdminList(self):
"""Return list of admin users"""
<|body_1|>
def addAdmin(self):
"""Add a new admin to the system"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdminController:
"""Update controller class."""
def getAdmin(self, admin_id):
"""Get an admin by name"""
try:
admin = self.app.admin_api.getAdminById(cherrypy.request.db, admin_id)
response = {'admin': admin.getCleanDict()}
except Exception as ex:
... | the_stack_v2_python_sparse | src/installer/src/tortuga/web_service/controllers/adminController.py | UnivaCorporation/tortuga | train | 33 |
15470ff195ba368570c85d6f308b628cc3725e19 | [
"super(Meme_classifier2, self).__init__()\nself.backbone = backbone\nself.hidden_size = hidden_size\nself.batch_size = batch_size\nself.hidden_size2 = hidden_size2\nself.input_size = weight_matrix.shape[1]\nself.embedding = nn.Embedding.from_pretrained(weight_matrix)\nself.embedding.weight.requires_grad = True\nsel... | <|body_start_0|>
super(Meme_classifier2, self).__init__()
self.backbone = backbone
self.hidden_size = hidden_size
self.batch_size = batch_size
self.hidden_size2 = hidden_size2
self.input_size = weight_matrix.shape[1]
self.embedding = nn.Embedding.from_pretrained(w... | Meme_classifier2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Meme_classifier2:
def __init__(self, backbone, weight_matrix, hidden_size2, hidden_size, batch_size):
"""Input: backbone: This the image feature extractor, we used pretrained model for this. weight_matrix: (Tensor) This is matrix for initilize the word embedding layer hidden_size2: size ... | stack_v2_sparse_classes_36k_train_033133 | 4,920 | no_license | [
{
"docstring": "Input: backbone: This the image feature extractor, we used pretrained model for this. weight_matrix: (Tensor) This is matrix for initilize the word embedding layer hidden_size2: size for first image fc output hidden_size: this is size for LSTM hidden layer and this is the feature size for superi... | 2 | stack_v2_sparse_classes_30k_train_015969 | Implement the Python class `Meme_classifier2` described below.
Class description:
Implement the Meme_classifier2 class.
Method signatures and docstrings:
- def __init__(self, backbone, weight_matrix, hidden_size2, hidden_size, batch_size): Input: backbone: This the image feature extractor, we used pretrained model fo... | Implement the Python class `Meme_classifier2` described below.
Class description:
Implement the Meme_classifier2 class.
Method signatures and docstrings:
- def __init__(self, backbone, weight_matrix, hidden_size2, hidden_size, batch_size): Input: backbone: This the image feature extractor, we used pretrained model fo... | a3ae712f54d9a32d0272dd5636874aef4550bbff | <|skeleton|>
class Meme_classifier2:
def __init__(self, backbone, weight_matrix, hidden_size2, hidden_size, batch_size):
"""Input: backbone: This the image feature extractor, we used pretrained model for this. weight_matrix: (Tensor) This is matrix for initilize the word embedding layer hidden_size2: size ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Meme_classifier2:
def __init__(self, backbone, weight_matrix, hidden_size2, hidden_size, batch_size):
"""Input: backbone: This the image feature extractor, we used pretrained model for this. weight_matrix: (Tensor) This is matrix for initilize the word embedding layer hidden_size2: size for first imag... | the_stack_v2_python_sparse | step2_MemeClassifier/MemeModel.py | yuhaodu/TwitterMeme | train | 5 | |
d70e88bce02d3642024077d5865fd3e72a2a3c1b | [
"if n == 1:\n return [0]\nout = [[] for i in range(n)]\nfor edge in edges:\n out[edge[0]].append(edge[1])\n out[edge[1]].append(edge[0])\ncurrent = []\nfor i in range(n):\n if len(out[i]) == 1:\n current.append(i)\nwhile current:\n next = []\n for node in current:\n for i in range(le... | <|body_start_0|>
if n == 1:
return [0]
out = [[] for i in range(n)]
for edge in edges:
out[edge[0]].append(edge[1])
out[edge[1]].append(edge[0])
current = []
for i in range(n):
if len(out[i]) == 1:
current.append(i)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
"""从树的叶子节点bfs遍历整棵树 1.枚举所有的边 2.找到入度为0的边 3.以这些点为基础枚举他们的出度,然后减去相对应入度 4.找到当前入度为1的点,进入队列(入度为1相当于当前的最外层),找到最后入度为1的点 :param n: :param edges: :return:"""
<|body_0|>
def _findMinHeightTrees(self, n: ... | stack_v2_sparse_classes_36k_train_033134 | 2,371 | no_license | [
{
"docstring": "从树的叶子节点bfs遍历整棵树 1.枚举所有的边 2.找到入度为0的边 3.以这些点为基础枚举他们的出度,然后减去相对应入度 4.找到当前入度为1的点,进入队列(入度为1相当于当前的最外层),找到最后入度为1的点 :param n: :param edges: :return:",
"name": "findMinHeightTrees",
"signature": "def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]"
},
{
"docstring": "... | 2 | stack_v2_sparse_classes_30k_train_001471 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: 从树的叶子节点bfs遍历整棵树 1.枚举所有的边 2.找到入度为0的边 3.以这些点为基础枚举他们的出度,然后减去相对应入度 4.找到当前入度为1的点,进入队列(入度为1相当于当前的最外层),找到最后入度为... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: 从树的叶子节点bfs遍历整棵树 1.枚举所有的边 2.找到入度为0的边 3.以这些点为基础枚举他们的出度,然后减去相对应入度 4.找到当前入度为1的点,进入队列(入度为1相当于当前的最外层),找到最后入度为... | 9ab35dbffed7865e41b437b026f2268d133357be | <|skeleton|>
class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
"""从树的叶子节点bfs遍历整棵树 1.枚举所有的边 2.找到入度为0的边 3.以这些点为基础枚举他们的出度,然后减去相对应入度 4.找到当前入度为1的点,进入队列(入度为1相当于当前的最外层),找到最后入度为1的点 :param n: :param edges: :return:"""
<|body_0|>
def _findMinHeightTrees(self, n: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
"""从树的叶子节点bfs遍历整棵树 1.枚举所有的边 2.找到入度为0的边 3.以这些点为基础枚举他们的出度,然后减去相对应入度 4.找到当前入度为1的点,进入队列(入度为1相当于当前的最外层),找到最后入度为1的点 :param n: :param edges: :return:"""
if n == 1:
return [0]
out = [[] for i in ra... | the_stack_v2_python_sparse | leetcode/310. 最小高度树.py | Cjz-Y/shuati | train | 0 | |
bb893e534230218159d8be3d43c4d33273f2f60f | [
"ret = await self.db.jobs.find_one({'job_id': job_id}, projection={'_id': False})\nif not ret:\n self.send_error(404, reason='Job not found')\nelse:\n self.write(ret)\n self.finish()",
"data = json.loads(self.request.body)\nif not data:\n raise tornado.web.HTTPError(400, reason='Missing update data')\... | <|body_start_0|>
ret = await self.db.jobs.find_one({'job_id': job_id}, projection={'_id': False})
if not ret:
self.send_error(404, reason='Job not found')
else:
self.write(ret)
self.finish()
<|end_body_0|>
<|body_start_1|>
data = json.loads(self.reque... | Handle single job requests. | JobsHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JobsHandler:
"""Handle single job requests."""
async def get(self, job_id):
"""Get a job entry. Args: job_id (str): the job id Returns: dict: job entry"""
<|body_0|>
async def patch(self, job_id):
"""Update a job entry. Body should contain the job data to update.... | stack_v2_sparse_classes_36k_train_033135 | 10,884 | permissive | [
{
"docstring": "Get a job entry. Args: job_id (str): the job id Returns: dict: job entry",
"name": "get",
"signature": "async def get(self, job_id)"
},
{
"docstring": "Update a job entry. Body should contain the job data to update. Note that this will perform a merge (not replace). Args: job_id ... | 2 | null | Implement the Python class `JobsHandler` described below.
Class description:
Handle single job requests.
Method signatures and docstrings:
- async def get(self, job_id): Get a job entry. Args: job_id (str): the job id Returns: dict: job entry
- async def patch(self, job_id): Update a job entry. Body should contain th... | Implement the Python class `JobsHandler` described below.
Class description:
Handle single job requests.
Method signatures and docstrings:
- async def get(self, job_id): Get a job entry. Args: job_id (str): the job id Returns: dict: job entry
- async def patch(self, job_id): Update a job entry. Body should contain th... | b66c35bb1072f835bc84ea01fce169989323c4b9 | <|skeleton|>
class JobsHandler:
"""Handle single job requests."""
async def get(self, job_id):
"""Get a job entry. Args: job_id (str): the job id Returns: dict: job entry"""
<|body_0|>
async def patch(self, job_id):
"""Update a job entry. Body should contain the job data to update.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JobsHandler:
"""Handle single job requests."""
async def get(self, job_id):
"""Get a job entry. Args: job_id (str): the job id Returns: dict: job entry"""
ret = await self.db.jobs.find_one({'job_id': job_id}, projection={'_id': False})
if not ret:
self.send_error(404, ... | the_stack_v2_python_sparse | iceprod/rest/handlers/jobs.py | WIPACrepo/iceprod | train | 5 |
c6aab7383eda527197d4e6c1d2a62ade5a3de4b1 | [
"self.k = k\nself.kLargest = heapq.nlargest(k, nums)\nheapq.heapify(self.kLargest)",
"if len(self.kLargest) < self.k:\n heapq.heappush(self.kLargest, val)\nelif val > self.kLargest[0]:\n heapq.heappushpop(self.kLargest, val)\nelse:\n pass\nreturn self.kLargest[0]"
] | <|body_start_0|>
self.k = k
self.kLargest = heapq.nlargest(k, nums)
heapq.heapify(self.kLargest)
<|end_body_0|>
<|body_start_1|>
if len(self.kLargest) < self.k:
heapq.heappush(self.kLargest, val)
elif val > self.kLargest[0]:
heapq.heappushpop(self.kLarges... | KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.k = k
self.kLargest = heapq.nlargest(k, nums)... | stack_v2_sparse_classes_36k_train_033136 | 1,042 | no_license | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010567 | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def __init__(self, k, nu... | d3e8669f932fc2e22711e8b7590d3365d020e189 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
self.k = k
self.kLargest = heapq.nlargest(k, nums)
heapq.heapify(self.kLargest)
def add(self, val):
""":type val: int :rtype: int"""
if len(self.kLargest) < self.k:
... | the_stack_v2_python_sparse | leetcode/703.py | liuweilin17/algorithm | train | 3 | |
96664f379fab6ae669ffe821e65a697665046e53 | [
"self.from_start, self.from_end = _known_bands[from_script]\nself.to_start, self.to_end = _known_bands[to_script]\nself.ord_diff = ord(self.to_start) - ord(self.from_start)\nassert ord(self.from_end) - ord(self.from_start) <= ord(self.to_end) - ord(self.to_start)",
"result = []\nfor char in j_string:\n if self... | <|body_start_0|>
self.from_start, self.from_end = _known_bands[from_script]
self.to_start, self.to_end = _known_bands[to_script]
self.ord_diff = ord(self.to_start) - ord(self.from_start)
assert ord(self.from_end) - ord(self.from_start) <= ord(self.to_end) - ord(self.to_start)
<|end_body_... | A mapping function between two scripts. We assume that the given scripts are different versions of the same characters, and further that they are aligned at the start and end points stored. | ScriptMapping | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScriptMapping:
"""A mapping function between two scripts. We assume that the given scripts are different versions of the same characters, and further that they are aligned at the start and end points stored."""
def __init__(self, from_script, to_script):
"""Constructor, initializes s... | stack_v2_sparse_classes_36k_train_033137 | 7,948 | permissive | [
{
"docstring": "Constructor, initializes script conversion. @param from_script: The script to convert from. @type from_script: Script @param to_script: The script to convert to. @type to_script: Script",
"name": "__init__",
"signature": "def __init__(self, from_script, to_script)"
},
{
"docstrin... | 2 | stack_v2_sparse_classes_30k_train_013808 | Implement the Python class `ScriptMapping` described below.
Class description:
A mapping function between two scripts. We assume that the given scripts are different versions of the same characters, and further that they are aligned at the start and end points stored.
Method signatures and docstrings:
- def __init__(... | Implement the Python class `ScriptMapping` described below.
Class description:
A mapping function between two scripts. We assume that the given scripts are different versions of the same characters, and further that they are aligned at the start and end points stored.
Method signatures and docstrings:
- def __init__(... | 352f5230cb52f07aaabd2bbc76d583f585deffb7 | <|skeleton|>
class ScriptMapping:
"""A mapping function between two scripts. We assume that the given scripts are different versions of the same characters, and further that they are aligned at the start and end points stored."""
def __init__(self, from_script, to_script):
"""Constructor, initializes s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScriptMapping:
"""A mapping function between two scripts. We assume that the given scripts are different versions of the same characters, and further that they are aligned at the start and end points stored."""
def __init__(self, from_script, to_script):
"""Constructor, initializes script convers... | the_stack_v2_python_sparse | kdsg_sac/cjktools/scripts.py | fenildf/anki_addons-1 | train | 0 |
082da737cb9ddb907e8017e9040733e8498da03f | [
"self.comp_stars = comp_stars\nself.days_per_bin = days_per_bin\nself.alphabet_size = alphabet_size\nself.slide = slide\nself.meth = meth",
"word_size = compute_bins(star.lightCurve.time, self.days_per_bin)\nlogging.debug('Curve Shape Descr word size: {}'.format(word_size))\nreturn self._getWord(star.lightCurve.m... | <|body_start_0|>
self.comp_stars = comp_stars
self.days_per_bin = days_per_bin
self.alphabet_size = alphabet_size
self.slide = slide
self.meth = meth
<|end_body_0|>
<|body_start_1|>
word_size = compute_bins(star.lightCurve.time, self.days_per_bin)
logging.debug('... | This descriptor which compares light curves of inspected star with the template in symbolic representation Attributes ----------- comp_stars : list Template stars days_per_bin : float Ratio which decides about length of the word alphabet_size : int Range of of used letters slide : bool If True, words with different len... | CurvesShapeDescr | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CurvesShapeDescr:
"""This descriptor which compares light curves of inspected star with the template in symbolic representation Attributes ----------- comp_stars : list Template stars days_per_bin : float Ratio which decides about length of the word alphabet_size : int Range of of used letters sl... | stack_v2_sparse_classes_36k_train_033138 | 4,880 | permissive | [
{
"docstring": "Parameters ----------- comp_stars : list Template stars days_per_bin : float Ratio which decides about length of the word alphabet_size : int Range of of used letters slide : NoneType, float If a float, words with different lengths are dynamically compared by sliding shorter word thru longer and... | 3 | null | Implement the Python class `CurvesShapeDescr` described below.
Class description:
This descriptor which compares light curves of inspected star with the template in symbolic representation Attributes ----------- comp_stars : list Template stars days_per_bin : float Ratio which decides about length of the word alphabet... | Implement the Python class `CurvesShapeDescr` described below.
Class description:
This descriptor which compares light curves of inspected star with the template in symbolic representation Attributes ----------- comp_stars : list Template stars days_per_bin : float Ratio which decides about length of the word alphabet... | a0a51f033cb8adf45296913f0de0aa2568e0530c | <|skeleton|>
class CurvesShapeDescr:
"""This descriptor which compares light curves of inspected star with the template in symbolic representation Attributes ----------- comp_stars : list Template stars days_per_bin : float Ratio which decides about length of the word alphabet_size : int Range of of used letters sl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CurvesShapeDescr:
"""This descriptor which compares light curves of inspected star with the template in symbolic representation Attributes ----------- comp_stars : list Template stars days_per_bin : float Ratio which decides about length of the word alphabet_size : int Range of of used letters slide : bool If... | the_stack_v2_python_sparse | lcc/stars_processing/descriptors/curves_shape_descr.py | pierfra-rocci/LightCurvesClassifier | train | 0 |
05aeeacedf29184406bee077e06ddd43215b6ff4 | [
"self._device_queue = device_queue\nself._device_cache = device_cache\nself._entity_cache = entity_cache\nself._plugins = plugins\nself._exclude_known_noisy_beacons = exclude_known_noisy_beacons\nself._blacklist = blacklist",
"new_entity = device_to_entity(device, data)\nif self._exclude_known_noisy_beacons and s... | <|body_start_0|>
self._device_queue = device_queue
self._device_cache = device_cache
self._entity_cache = entity_cache
self._plugins = plugins
self._exclude_known_noisy_beacons = exclude_known_noisy_beacons
self._blacklist = blacklist
<|end_body_0|>
<|body_start_1|>
... | Event handler for BLE devices. | EventHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventHandler:
"""Event handler for BLE devices."""
def __init__(self, device_queue: Queue, device_cache: DeviceCache, entity_cache: EntityCache, plugins: Collection[BaseBluetoothPlugin], exclude_known_noisy_beacons: bool, blacklist: DevicesBlacklist):
""":param device_queue: Queue us... | stack_v2_sparse_classes_36k_train_033139 | 7,916 | permissive | [
{
"docstring": ":param device_queue: Queue used to publish updated devices upstream. :param device_cache: Device cache. :param entity_cache: Entity cache. :param exclude_known_noisy_beacons: Exclude known noisy beacons. :param blacklist: Blacklist rules.",
"name": "__init__",
"signature": "def __init__(... | 3 | null | Implement the Python class `EventHandler` described below.
Class description:
Event handler for BLE devices.
Method signatures and docstrings:
- def __init__(self, device_queue: Queue, device_cache: DeviceCache, entity_cache: EntityCache, plugins: Collection[BaseBluetoothPlugin], exclude_known_noisy_beacons: bool, bl... | Implement the Python class `EventHandler` described below.
Class description:
Event handler for BLE devices.
Method signatures and docstrings:
- def __init__(self, device_queue: Queue, device_cache: DeviceCache, entity_cache: EntityCache, plugins: Collection[BaseBluetoothPlugin], exclude_known_noisy_beacons: bool, bl... | 446bc2f67493d3554c5422242ff91d5b5c76d78a | <|skeleton|>
class EventHandler:
"""Event handler for BLE devices."""
def __init__(self, device_queue: Queue, device_cache: DeviceCache, entity_cache: EntityCache, plugins: Collection[BaseBluetoothPlugin], exclude_known_noisy_beacons: bool, blacklist: DevicesBlacklist):
""":param device_queue: Queue us... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EventHandler:
"""Event handler for BLE devices."""
def __init__(self, device_queue: Queue, device_cache: DeviceCache, entity_cache: EntityCache, plugins: Collection[BaseBluetoothPlugin], exclude_known_noisy_beacons: bool, blacklist: DevicesBlacklist):
""":param device_queue: Queue used to publish... | the_stack_v2_python_sparse | platypush/plugins/bluetooth/_ble/_event_handler.py | BlackLight/platypush | train | 265 |
35250b03fd03b5af65a8271754432215dc0e2995 | [
"freq = [0] * 26\nn = len(p)\nm = len(s)\nres = []\nfor k in p:\n freq[ord(k) - ord('a')] += 1\nl = 0\nwhile l < m - n + 1:\n i = l\n freq_copy = copy(freq)\n while i < m and freq_copy[ord(s[i]) - ord('a')] != 0:\n freq_copy[ord(s[i]) - ord('a')] -= 1\n i += 1\n if i - l == n:\n ... | <|body_start_0|>
freq = [0] * 26
n = len(p)
m = len(s)
res = []
for k in p:
freq[ord(k) - ord('a')] += 1
l = 0
while l < m - n + 1:
i = l
freq_copy = copy(freq)
while i < m and freq_copy[ord(s[i]) - ord('a')] != 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findAnagrams(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
<|body_0|>
def findAnagrams1(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
<|body_1|>
def findAnagrams2(self, s, p):
""":type s: str :type ... | stack_v2_sparse_classes_36k_train_033140 | 3,116 | no_license | [
{
"docstring": ":type s: str :type p: str :rtype: List[int]",
"name": "findAnagrams",
"signature": "def findAnagrams(self, s, p)"
},
{
"docstring": ":type s: str :type p: str :rtype: List[int]",
"name": "findAnagrams1",
"signature": "def findAnagrams1(self, s, p)"
},
{
"docstring... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findAnagrams(self, s, p): :type s: str :type p: str :rtype: List[int]
- def findAnagrams1(self, s, p): :type s: str :type p: str :rtype: List[int]
- def findAnagrams2(self, s... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findAnagrams(self, s, p): :type s: str :type p: str :rtype: List[int]
- def findAnagrams1(self, s, p): :type s: str :type p: str :rtype: List[int]
- def findAnagrams2(self, s... | c55b0cfd2967a2221c27ed738e8de15034775945 | <|skeleton|>
class Solution:
def findAnagrams(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
<|body_0|>
def findAnagrams1(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
<|body_1|>
def findAnagrams2(self, s, p):
""":type s: str :type ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findAnagrams(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
freq = [0] * 26
n = len(p)
m = len(s)
res = []
for k in p:
freq[ord(k) - ord('a')] += 1
l = 0
while l < m - n + 1:
i = l
... | the_stack_v2_python_sparse | PycharmProjects/leetcode/UsingArray/FindAllAnagramsInaString438.py | crystal30/DataStructure | train | 0 | |
16735da1a755908f562d3d59cf5ed009f837f213 | [
"rqcz = int(rqcz)\ndqrq = get_strftime2()[:8]\nclwjm = (datetime.datetime.strptime(dqrq, '%Y%m%d') + datetime.timedelta(days=rqcz)).strftime(self.dxbm)\nresult = self.findfiles(wjml, clwjm)\nresult = pickle_dumps(result) if result else ''\nwith sjapi.connection() as db:\n csxx = {'id': get_uuid(), 'ssdxid': self... | <|body_start_0|>
rqcz = int(rqcz)
dqrq = get_strftime2()[:8]
clwjm = (datetime.datetime.strptime(dqrq, '%Y%m%d') + datetime.timedelta(days=rqcz)).strftime(self.dxbm)
result = self.findfiles(wjml, clwjm)
result = pickle_dumps(result) if result else ''
with sjapi.connection... | File | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class File:
def ind_filedir_exist(self, wjml, rqcz):
"""文件是否在指定目录存在"""
<|body_0|>
def ind_filedb_exist(self, zt, rqcz, ywlx):
"""文件是否在文件处理登记表中存在"""
<|body_1|>
def findfiles(self, dirname, pattern):
"""获取指定目录下的文件信息"""
<|body_2|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_033141 | 16,132 | no_license | [
{
"docstring": "文件是否在指定目录存在",
"name": "ind_filedir_exist",
"signature": "def ind_filedir_exist(self, wjml, rqcz)"
},
{
"docstring": "文件是否在文件处理登记表中存在",
"name": "ind_filedb_exist",
"signature": "def ind_filedb_exist(self, zt, rqcz, ywlx)"
},
{
"docstring": "获取指定目录下的文件信息",
"name... | 3 | stack_v2_sparse_classes_30k_train_007427 | Implement the Python class `File` described below.
Class description:
Implement the File class.
Method signatures and docstrings:
- def ind_filedir_exist(self, wjml, rqcz): 文件是否在指定目录存在
- def ind_filedb_exist(self, zt, rqcz, ywlx): 文件是否在文件处理登记表中存在
- def findfiles(self, dirname, pattern): 获取指定目录下的文件信息 | Implement the Python class `File` described below.
Class description:
Implement the File class.
Method signatures and docstrings:
- def ind_filedir_exist(self, wjml, rqcz): 文件是否在指定目录存在
- def ind_filedb_exist(self, zt, rqcz, ywlx): 文件是否在文件处理登记表中存在
- def findfiles(self, dirname, pattern): 获取指定目录下的文件信息
<|skeleton|>
cla... | 68ddf3df6d2cd731e6634b09d27aff4c22debd8e | <|skeleton|>
class File:
def ind_filedir_exist(self, wjml, rqcz):
"""文件是否在指定目录存在"""
<|body_0|>
def ind_filedb_exist(self, zt, rqcz, ywlx):
"""文件是否在文件处理登记表中存在"""
<|body_1|>
def findfiles(self, dirname, pattern):
"""获取指定目录下的文件信息"""
<|body_2|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class File:
def ind_filedir_exist(self, wjml, rqcz):
"""文件是否在指定目录存在"""
rqcz = int(rqcz)
dqrq = get_strftime2()[:8]
clwjm = (datetime.datetime.strptime(dqrq, '%Y%m%d') + datetime.timedelta(days=rqcz)).strftime(self.dxbm)
result = self.findfiles(wjml, clwjm)
result = pi... | the_stack_v2_python_sparse | zh_manage/apps/_init/oa/yw_jkgl/yw_jkgl_001/yw_jkgl_001.py | yizhong120110/CPOS | train | 0 | |
451111fde2bd7863fdc343a99a8c576fc3342117 | [
"self.insurance_policy_type_velue = insurance_policy_type_velue\nself.fire_insurance_policy_extend_view = fire_insurance_policy_extend_view\nself.fire_insurance_policy_filter = fire_insurance_policy_filter\nself.id = id\nself.selected_insurance_policy_has_been_changed = selected_insurance_policy_has_been_changed\ns... | <|body_start_0|>
self.insurance_policy_type_velue = insurance_policy_type_velue
self.fire_insurance_policy_extend_view = fire_insurance_policy_extend_view
self.fire_insurance_policy_filter = fire_insurance_policy_filter
self.id = id
self.selected_insurance_policy_has_been_changed... | Implementation of the 'InsuranceData FireInsurance' model. TODO: type model description here. Attributes: insurance_policy_type_velue (int): TODO: type description here. fire_insurance_policy_extend_view (FireInsurancePolicyExtendView): TODO: type description here. fire_insurance_policy_filter (FireInsurancePolicyFilte... | InsuranceDataFireInsurance | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InsuranceDataFireInsurance:
"""Implementation of the 'InsuranceData FireInsurance' model. TODO: type model description here. Attributes: insurance_policy_type_velue (int): TODO: type description here. fire_insurance_policy_extend_view (FireInsurancePolicyExtendView): TODO: type description here. ... | stack_v2_sparse_classes_36k_train_033142 | 9,068 | permissive | [
{
"docstring": "Constructor for the InsuranceDataFireInsurance class",
"name": "__init__",
"signature": "def __init__(self, insurance_policy_type_velue=None, fire_insurance_policy_extend_view=None, fire_insurance_policy_filter=None, id=None, selected_insurance_policy_has_been_changed=None, is_paymented=... | 2 | stack_v2_sparse_classes_30k_train_021641 | Implement the Python class `InsuranceDataFireInsurance` described below.
Class description:
Implementation of the 'InsuranceData FireInsurance' model. TODO: type model description here. Attributes: insurance_policy_type_velue (int): TODO: type description here. fire_insurance_policy_extend_view (FireInsurancePolicyExt... | Implement the Python class `InsuranceDataFireInsurance` described below.
Class description:
Implementation of the 'InsuranceData FireInsurance' model. TODO: type model description here. Attributes: insurance_policy_type_velue (int): TODO: type description here. fire_insurance_policy_extend_view (FireInsurancePolicyExt... | b574a76a8805b306a423229b572c36dae0159def | <|skeleton|>
class InsuranceDataFireInsurance:
"""Implementation of the 'InsuranceData FireInsurance' model. TODO: type model description here. Attributes: insurance_policy_type_velue (int): TODO: type description here. fire_insurance_policy_extend_view (FireInsurancePolicyExtendView): TODO: type description here. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InsuranceDataFireInsurance:
"""Implementation of the 'InsuranceData FireInsurance' model. TODO: type model description here. Attributes: insurance_policy_type_velue (int): TODO: type description here. fire_insurance_policy_extend_view (FireInsurancePolicyExtendView): TODO: type description here. fire_insuranc... | the_stack_v2_python_sparse | easybimehlanding/models/insurance_data_fire_insurance.py | kmelodi/EasyBimehLanding_Python | train | 0 |
1e354c99cfaae71fe77fed7d25d407945e3d5a19 | [
"rest_utils.validate_inputs({'tenant_name': tenant_name})\nif request.content_length:\n request_dict = rest_utils.get_json_and_verify_params({'rabbitmq_password': {'type': str, 'optional': True}})\nelse:\n request_dict = {}\nif tenant_name in ('users', 'user-groups'):\n raise BadParametersError(\"{0!r} is ... | <|body_start_0|>
rest_utils.validate_inputs({'tenant_name': tenant_name})
if request.content_length:
request_dict = rest_utils.get_json_and_verify_params({'rabbitmq_password': {'type': str, 'optional': True}})
else:
request_dict = {}
if tenant_name in ('users', 'u... | TenantsId | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TenantsId:
def post(self, tenant_name, multi_tenancy):
"""Create a tenant"""
<|body_0|>
def get(self, tenant_name, multi_tenancy=None):
"""Get details for a single tenant On community, only getting the default tenant is allowed."""
<|body_1|>
def delete(... | stack_v2_sparse_classes_36k_train_033143 | 10,735 | permissive | [
{
"docstring": "Create a tenant",
"name": "post",
"signature": "def post(self, tenant_name, multi_tenancy)"
},
{
"docstring": "Get details for a single tenant On community, only getting the default tenant is allowed.",
"name": "get",
"signature": "def get(self, tenant_name, multi_tenancy... | 3 | null | Implement the Python class `TenantsId` described below.
Class description:
Implement the TenantsId class.
Method signatures and docstrings:
- def post(self, tenant_name, multi_tenancy): Create a tenant
- def get(self, tenant_name, multi_tenancy=None): Get details for a single tenant On community, only getting the def... | Implement the Python class `TenantsId` described below.
Class description:
Implement the TenantsId class.
Method signatures and docstrings:
- def post(self, tenant_name, multi_tenancy): Create a tenant
- def get(self, tenant_name, multi_tenancy=None): Get details for a single tenant On community, only getting the def... | c0de6442e1d7653fad824d75e571802a74eee605 | <|skeleton|>
class TenantsId:
def post(self, tenant_name, multi_tenancy):
"""Create a tenant"""
<|body_0|>
def get(self, tenant_name, multi_tenancy=None):
"""Get details for a single tenant On community, only getting the default tenant is allowed."""
<|body_1|>
def delete(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TenantsId:
def post(self, tenant_name, multi_tenancy):
"""Create a tenant"""
rest_utils.validate_inputs({'tenant_name': tenant_name})
if request.content_length:
request_dict = rest_utils.get_json_and_verify_params({'rabbitmq_password': {'type': str, 'optional': True}})
... | the_stack_v2_python_sparse | rest-service/manager_rest/rest/resources_v3/tenants.py | cloudify-cosmo/cloudify-manager | train | 146 | |
67ea1d23d9617ff2372b9eb893607f43f0542c93 | [
"instrument_list = super(ActiveInstrumentManager, self).get_queryset().filter(instrument_id=instrument_id)\nif len(instrument_list) > 0:\n return instrument_list[0].is_alive\nelse:\n return True",
"instrument_list = super(ActiveInstrumentManager, self).get_queryset().filter(instrument_id=instrument_id)\nif ... | <|body_start_0|>
instrument_list = super(ActiveInstrumentManager, self).get_queryset().filter(instrument_id=instrument_id)
if len(instrument_list) > 0:
return instrument_list[0].is_alive
else:
return True
<|end_body_0|>
<|body_start_1|>
instrument_list = super(Ac... | Table of options for instruments | ActiveInstrumentManager | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActiveInstrumentManager:
"""Table of options for instruments"""
def is_alive(self, instrument_id):
"""Returns True if the instrument should be presented as part of the suite of instruments"""
<|body_0|>
def is_adara(self, instrument_id):
"""Returns True if the in... | stack_v2_sparse_classes_36k_train_033144 | 4,318 | permissive | [
{
"docstring": "Returns True if the instrument should be presented as part of the suite of instruments",
"name": "is_alive",
"signature": "def is_alive(self, instrument_id)"
},
{
"docstring": "Returns True if the instrument is running ADARA",
"name": "is_adara",
"signature": "def is_adar... | 4 | stack_v2_sparse_classes_30k_train_015095 | Implement the Python class `ActiveInstrumentManager` described below.
Class description:
Table of options for instruments
Method signatures and docstrings:
- def is_alive(self, instrument_id): Returns True if the instrument should be presented as part of the suite of instruments
- def is_adara(self, instrument_id): R... | Implement the Python class `ActiveInstrumentManager` described below.
Class description:
Table of options for instruments
Method signatures and docstrings:
- def is_alive(self, instrument_id): Returns True if the instrument should be presented as part of the suite of instruments
- def is_adara(self, instrument_id): R... | ff55e4e1a0203a6966fc9dab6b49e0d6dd03d18d | <|skeleton|>
class ActiveInstrumentManager:
"""Table of options for instruments"""
def is_alive(self, instrument_id):
"""Returns True if the instrument should be presented as part of the suite of instruments"""
<|body_0|>
def is_adara(self, instrument_id):
"""Returns True if the in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ActiveInstrumentManager:
"""Table of options for instruments"""
def is_alive(self, instrument_id):
"""Returns True if the instrument should be presented as part of the suite of instruments"""
instrument_list = super(ActiveInstrumentManager, self).get_queryset().filter(instrument_id=instru... | the_stack_v2_python_sparse | src/webmon_app/reporting/dasmon/models.py | neutrons/data_workflow | train | 4 |
fecce9bcfcc5d0f9fea50cc8877178f1a5698e8a | [
"ids = self.cur_devs.ids\nrail_cache = {dev.id: dev.cur_rail.id for dev in self.cur_devs}\nold_dev_ids = self.plan_infos.mapped('cur_train_id.id')\nitems = []\nfor tmp_id in ids:\n if tmp_id not in old_dev_ids:\n items.append((0, 0, {'cur_train_id': tmp_id, 'rail': rail_cache[tmp_id], 'exchange_rail_time'... | <|body_start_0|>
ids = self.cur_devs.ids
rail_cache = {dev.id: dev.cur_rail.id for dev in self.cur_devs}
old_dev_ids = self.plan_infos.mapped('cur_train_id.id')
items = []
for tmp_id in ids:
if tmp_id not in old_dev_ids:
items.append((0, 0, {'cur_train... | 添加新的收车计划 | AddNewBackPlan | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddNewBackPlan:
"""添加新的收车计划"""
def on_change_cur_devs(self):
"""加开只能是 :return:"""
<|body_0|>
def on_ok(self):
"""点击确定 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ids = self.cur_devs.ids
rail_cache = {dev.id: dev.cur_rail.id ... | stack_v2_sparse_classes_36k_train_033145 | 4,155 | no_license | [
{
"docstring": "加开只能是 :return:",
"name": "on_change_cur_devs",
"signature": "def on_change_cur_devs(self)"
},
{
"docstring": "点击确定 :return:",
"name": "on_ok",
"signature": "def on_ok(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007754 | Implement the Python class `AddNewBackPlan` described below.
Class description:
添加新的收车计划
Method signatures and docstrings:
- def on_change_cur_devs(self): 加开只能是 :return:
- def on_ok(self): 点击确定 :return: | Implement the Python class `AddNewBackPlan` described below.
Class description:
添加新的收车计划
Method signatures and docstrings:
- def on_change_cur_devs(self): 加开只能是 :return:
- def on_ok(self): 点击确定 :return:
<|skeleton|>
class AddNewBackPlan:
"""添加新的收车计划"""
def on_change_cur_devs(self):
"""加开只能是 :return:... | 13b428a5c4ade6278e3e5e996ef10d9fb0fea4b9 | <|skeleton|>
class AddNewBackPlan:
"""添加新的收车计划"""
def on_change_cur_devs(self):
"""加开只能是 :return:"""
<|body_0|>
def on_ok(self):
"""点击确定 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddNewBackPlan:
"""添加新的收车计划"""
def on_change_cur_devs(self):
"""加开只能是 :return:"""
ids = self.cur_devs.ids
rail_cache = {dev.id: dev.cur_rail.id for dev in self.cur_devs}
old_dev_ids = self.plan_infos.mapped('cur_train_id.id')
items = []
for tmp_id in ids:
... | the_stack_v2_python_sparse | mdias_addons/metro_park_dispatch/models/add_new_back_plan.py | rezaghanimi/main_mdias | train | 0 |
26248d8cfa9c6560e0d2d720c690751411c8fe8d | [
"if obj == cls.IGNORE:\n return dataset_options_pb2.ExternalStatePolicy.POLICY_IGNORE\nif obj == cls.FAIL:\n return dataset_options_pb2.ExternalStatePolicy.POLICY_FAIL\nif obj == cls.WARN:\n return dataset_options_pb2.ExternalStatePolicy.POLICY_WARN\nraise ValueError('%s._to_proto() is called with undefine... | <|body_start_0|>
if obj == cls.IGNORE:
return dataset_options_pb2.ExternalStatePolicy.POLICY_IGNORE
if obj == cls.FAIL:
return dataset_options_pb2.ExternalStatePolicy.POLICY_FAIL
if obj == cls.WARN:
return dataset_options_pb2.ExternalStatePolicy.POLICY_WARN
... | Represents how to handle external state during serialization. See the `tf.data.Options.experimental_external_state_policy` documentation for more information. | ExternalStatePolicy | [
"MIT",
"Apache-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExternalStatePolicy:
"""Represents how to handle external state during serialization. See the `tf.data.Options.experimental_external_state_policy` documentation for more information."""
def _to_proto(cls, obj):
"""Convert enum to proto."""
<|body_0|>
def _from_proto(cls,... | stack_v2_sparse_classes_36k_train_033146 | 6,002 | permissive | [
{
"docstring": "Convert enum to proto.",
"name": "_to_proto",
"signature": "def _to_proto(cls, obj)"
},
{
"docstring": "Convert proto to enum.",
"name": "_from_proto",
"signature": "def _from_proto(cls, pb)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000844 | Implement the Python class `ExternalStatePolicy` described below.
Class description:
Represents how to handle external state during serialization. See the `tf.data.Options.experimental_external_state_policy` documentation for more information.
Method signatures and docstrings:
- def _to_proto(cls, obj): Convert enum ... | Implement the Python class `ExternalStatePolicy` described below.
Class description:
Represents how to handle external state during serialization. See the `tf.data.Options.experimental_external_state_policy` documentation for more information.
Method signatures and docstrings:
- def _to_proto(cls, obj): Convert enum ... | 085b20a4b6287eff8c0b792425d52422ab8cbab3 | <|skeleton|>
class ExternalStatePolicy:
"""Represents how to handle external state during serialization. See the `tf.data.Options.experimental_external_state_policy` documentation for more information."""
def _to_proto(cls, obj):
"""Convert enum to proto."""
<|body_0|>
def _from_proto(cls,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExternalStatePolicy:
"""Represents how to handle external state during serialization. See the `tf.data.Options.experimental_external_state_policy` documentation for more information."""
def _to_proto(cls, obj):
"""Convert enum to proto."""
if obj == cls.IGNORE:
return dataset_... | the_stack_v2_python_sparse | tensorflow/python/data/experimental/ops/distribute_options.py | graphcore/tensorflow | train | 84 |
7c1ca75a4f218e02e1c9b99c1c60a43e56d3f8f6 | [
"super().__init__(game, mode_label_ui)\nself.mode_label_ui = mode_label_ui\nself.stage_1_ui, self.stage_2_ui = (stage_1_ui, stage_2_ui)",
"logger.info(f'{self.mode_name}: {self.stages} stages available.')\nif self.stages > 0:\n self.game.select_mode(self.mode_name)\n stage_1_num, stage_2_num = self.separate... | <|body_start_0|>
super().__init__(game, mode_label_ui)
self.mode_label_ui = mode_label_ui
self.stage_1_ui, self.stage_2_ui = (stage_1_ui, stage_2_ui)
<|end_body_0|>
<|body_start_1|>
logger.info(f'{self.mode_name}: {self.stages} stages available.')
if self.stages > 0:
... | Class for working with Epic Quests with two separate stages. | TwoStageEpicQuest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwoStageEpicQuest:
"""Class for working with Epic Quests with two separate stages."""
def __init__(self, game, mode_label_ui, stage_1_ui, stage_2_ui):
"""Class initialization. :param lib.game.game.Game game: instance of the game. :param ui.UIElement mode_label_ui: mission's game mode... | stack_v2_sparse_classes_36k_train_033147 | 26,035 | permissive | [
{
"docstring": "Class initialization. :param lib.game.game.Game game: instance of the game. :param ui.UIElement mode_label_ui: mission's game mode label UI element.",
"name": "__init__",
"signature": "def __init__(self, game, mode_label_ui, stage_1_ui, stage_2_ui)"
},
{
"docstring": "Starts two ... | 3 | stack_v2_sparse_classes_30k_train_010312 | Implement the Python class `TwoStageEpicQuest` described below.
Class description:
Class for working with Epic Quests with two separate stages.
Method signatures and docstrings:
- def __init__(self, game, mode_label_ui, stage_1_ui, stage_2_ui): Class initialization. :param lib.game.game.Game game: instance of the gam... | Implement the Python class `TwoStageEpicQuest` described below.
Class description:
Class for working with Epic Quests with two separate stages.
Method signatures and docstrings:
- def __init__(self, game, mode_label_ui, stage_1_ui, stage_2_ui): Class initialization. :param lib.game.game.Game game: instance of the gam... | fd3f0bd45aea45e2e8ad8e8fc73a8953c96d350a | <|skeleton|>
class TwoStageEpicQuest:
"""Class for working with Epic Quests with two separate stages."""
def __init__(self, game, mode_label_ui, stage_1_ui, stage_2_ui):
"""Class initialization. :param lib.game.game.Game game: instance of the game. :param ui.UIElement mode_label_ui: mission's game mode... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TwoStageEpicQuest:
"""Class for working with Epic Quests with two separate stages."""
def __init__(self, game, mode_label_ui, stage_1_ui, stage_2_ui):
"""Class initialization. :param lib.game.game.Game game: instance of the game. :param ui.UIElement mode_label_ui: mission's game mode label UI ele... | the_stack_v2_python_sparse | lib/game/missions/epic_quest.py | th3f1v3/mff_auto | train | 0 |
9788f13284e58b468d12fd133c8028ffc2ca2dce | [
"tempdir = tempfile.mkdtemp()\nmodel_path = os.path.join(tempdir, cls.MODEL_FILENAME)\nstripped_state_dict = consume_prefix_in_state_dict_if_present_not_in_place(state_dict, 'module.')\ntorch.save(stripped_state_dict, model_path)\ncheckpoint = cls.from_directory(tempdir)\nif preprocessor:\n checkpoint.set_prepro... | <|body_start_0|>
tempdir = tempfile.mkdtemp()
model_path = os.path.join(tempdir, cls.MODEL_FILENAME)
stripped_state_dict = consume_prefix_in_state_dict_if_present_not_in_place(state_dict, 'module.')
torch.save(stripped_state_dict, model_path)
checkpoint = cls.from_directory(tempd... | A :class:`~ray.train.Checkpoint` with Torch-specific functionality. | TorchCheckpoint | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TorchCheckpoint:
"""A :class:`~ray.train.Checkpoint` with Torch-specific functionality."""
def from_state_dict(cls, state_dict: Dict[str, Any], *, preprocessor: Optional['Preprocessor']=None) -> 'TorchCheckpoint':
"""Create a :class:`~ray.train.Checkpoint` that stores a model state d... | stack_v2_sparse_classes_36k_train_033148 | 15,178 | permissive | [
{
"docstring": "Create a :class:`~ray.train.Checkpoint` that stores a model state dictionary. .. tip:: This is the recommended method for creating :class:`TorchCheckpoints<TorchCheckpoint>`. Args: state_dict: The model state dictionary to store in the checkpoint. preprocessor: A fitted preprocessor to be applie... | 3 | stack_v2_sparse_classes_30k_train_012249 | Implement the Python class `TorchCheckpoint` described below.
Class description:
A :class:`~ray.train.Checkpoint` with Torch-specific functionality.
Method signatures and docstrings:
- def from_state_dict(cls, state_dict: Dict[str, Any], *, preprocessor: Optional['Preprocessor']=None) -> 'TorchCheckpoint': Create a :... | Implement the Python class `TorchCheckpoint` described below.
Class description:
A :class:`~ray.train.Checkpoint` with Torch-specific functionality.
Method signatures and docstrings:
- def from_state_dict(cls, state_dict: Dict[str, Any], *, preprocessor: Optional['Preprocessor']=None) -> 'TorchCheckpoint': Create a :... | edba68c3e7cf255d1d6479329f305adb7fa4c3ed | <|skeleton|>
class TorchCheckpoint:
"""A :class:`~ray.train.Checkpoint` with Torch-specific functionality."""
def from_state_dict(cls, state_dict: Dict[str, Any], *, preprocessor: Optional['Preprocessor']=None) -> 'TorchCheckpoint':
"""Create a :class:`~ray.train.Checkpoint` that stores a model state d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TorchCheckpoint:
"""A :class:`~ray.train.Checkpoint` with Torch-specific functionality."""
def from_state_dict(cls, state_dict: Dict[str, Any], *, preprocessor: Optional['Preprocessor']=None) -> 'TorchCheckpoint':
"""Create a :class:`~ray.train.Checkpoint` that stores a model state dictionary. ..... | the_stack_v2_python_sparse | python/ray/train/torch/torch_checkpoint.py | ray-project/ray | train | 29,482 |
f558089dbfdb9f6230ea66462c6465259cf6ff9e | [
"print('FooTest:setUp_:begin')\ntestname = self.shortDescription()\nif testname == 'Test routine A':\n print('setting up for test A')\nelif testname == 'Test routine B':\n print('setting up for test B')\nelse:\n print('Unknown Test Routine')\nprint('FooTest:setUp_:end')",
"print('FooTest:tearDown_:begin'... | <|body_start_0|>
print('FooTest:setUp_:begin')
testname = self.shortDescription()
if testname == 'Test routine A':
print('setting up for test A')
elif testname == 'Test routine B':
print('setting up for test B')
else:
print('Unknown Test Routin... | Sample test case | FooTestSetupTearDown | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FooTestSetupTearDown:
"""Sample test case"""
def setUp(self):
"""Setting up for the test"""
<|body_0|>
def tearDown(self):
"""Cleaning up after the test"""
<|body_1|>
def testLogic(self):
"""Test routine A"""
<|body_2|>
def testC... | stack_v2_sparse_classes_36k_train_033149 | 3,969 | no_license | [
{
"docstring": "Setting up for the test",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Cleaning up after the test",
"name": "tearDown",
"signature": "def tearDown(self)"
},
{
"docstring": "Test routine A",
"name": "testLogic",
"signature": "def testL... | 4 | stack_v2_sparse_classes_30k_train_009846 | Implement the Python class `FooTestSetupTearDown` described below.
Class description:
Sample test case
Method signatures and docstrings:
- def setUp(self): Setting up for the test
- def tearDown(self): Cleaning up after the test
- def testLogic(self): Test routine A
- def testCollections(self): Test routine B | Implement the Python class `FooTestSetupTearDown` described below.
Class description:
Sample test case
Method signatures and docstrings:
- def setUp(self): Setting up for the test
- def tearDown(self): Cleaning up after the test
- def testLogic(self): Test routine A
- def testCollections(self): Test routine B
<|skel... | 6968983514e696472d13ef62ebae59828a8da44b | <|skeleton|>
class FooTestSetupTearDown:
"""Sample test case"""
def setUp(self):
"""Setting up for the test"""
<|body_0|>
def tearDown(self):
"""Cleaning up after the test"""
<|body_1|>
def testLogic(self):
"""Test routine A"""
<|body_2|>
def testC... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FooTestSetupTearDown:
"""Sample test case"""
def setUp(self):
"""Setting up for the test"""
print('FooTest:setUp_:begin')
testname = self.shortDescription()
if testname == 'Test routine A':
print('setting up for test A')
elif testname == 'Test routine B... | the_stack_v2_python_sparse | dev_tools/test_unittest_basics.py | InCodeLearning/InCodeLearning-Python3 | train | 8 |
4c423dd8d29685f1f48ab7c9bbf263c25c054ef8 | [
"ans = []\nif not intervals:\n return ans\nit = iter(sorted(intervals))\ncurr = next(it)\nfor x in it:\n if x[0] <= curr[1]:\n if x[1] > curr[1]:\n curr[1] = x[1]\n else:\n ans.append(curr)\n curr = x\nans.append(curr)\nreturn ans",
"visited = set()\nans = []\nfor i, x in ... | <|body_start_0|>
ans = []
if not intervals:
return ans
it = iter(sorted(intervals))
curr = next(it)
for x in it:
if x[0] <= curr[1]:
if x[1] > curr[1]:
curr[1] = x[1]
else:
ans.append(curr)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def merge_v1(self, intervals: List[List[int]]) -> List[List[int]]:
"""Sort. A simple method will take O(N^2), comparing each element with the other. If we sort the intervals first, it will be O(N log(N)) + O(N). Here we use the built-in sort method. Alternatively, we may write ... | stack_v2_sparse_classes_36k_train_033150 | 2,640 | no_license | [
{
"docstring": "Sort. A simple method will take O(N^2), comparing each element with the other. If we sort the intervals first, it will be O(N log(N)) + O(N). Here we use the built-in sort method. Alternatively, we may write our own sort method (like merge sort) and make some modifications.",
"name": "merge_... | 2 | stack_v2_sparse_classes_30k_train_013861 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge_v1(self, intervals: List[List[int]]) -> List[List[int]]: Sort. A simple method will take O(N^2), comparing each element with the other. If we sort the intervals first, ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge_v1(self, intervals: List[List[int]]) -> List[List[int]]: Sort. A simple method will take O(N^2), comparing each element with the other. If we sort the intervals first, ... | 97a2386f5e3adbd7138fd123810c3232bdf7f622 | <|skeleton|>
class Solution:
def merge_v1(self, intervals: List[List[int]]) -> List[List[int]]:
"""Sort. A simple method will take O(N^2), comparing each element with the other. If we sort the intervals first, it will be O(N log(N)) + O(N). Here we use the built-in sort method. Alternatively, we may write ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def merge_v1(self, intervals: List[List[int]]) -> List[List[int]]:
"""Sort. A simple method will take O(N^2), comparing each element with the other. If we sort the intervals first, it will be O(N log(N)) + O(N). Here we use the built-in sort method. Alternatively, we may write our own sort m... | the_stack_v2_python_sparse | python3/sorting_and_search/merge_intervals.py | victorchu/algorithms | train | 0 | |
f9d3c7f1e9ffe1e3c38cee5eeafd17c93abe2304 | [
"self.num_generations = 0\nself.num_schemas = num_schemas\nself.min_generations = min_generations",
"self.num_generations += 1\nif self.num_generations >= self.min_generations:\n all_seqs = []\n for org in organisms:\n if org.fitness > 0:\n if org.genome not in all_seqs:\n a... | <|body_start_0|>
self.num_generations = 0
self.num_schemas = num_schemas
self.min_generations = min_generations
<|end_body_0|>
<|body_start_1|>
self.num_generations += 1
if self.num_generations >= self.min_generations:
all_seqs = []
for org in organisms:
... | Determine when we are done evolving motifs. This takes the very simple approach of halting evolution when the GA has proceeded for a specified number of generations and has a given number of unique schema with positive fitness. | SimpleFinisher | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleFinisher:
"""Determine when we are done evolving motifs. This takes the very simple approach of halting evolution when the GA has proceeded for a specified number of generations and has a given number of unique schema with positive fitness."""
def __init__(self, num_schemas, min_genera... | stack_v2_sparse_classes_36k_train_033151 | 26,199 | permissive | [
{
"docstring": "Initialize the finisher with its parameters. Arguments: o num_schemas -- the number of useful (positive fitness) schemas we want to generation o min_generations -- The minimum number of generations to allow the GA to proceed.",
"name": "__init__",
"signature": "def __init__(self, num_sch... | 2 | stack_v2_sparse_classes_30k_train_018403 | Implement the Python class `SimpleFinisher` described below.
Class description:
Determine when we are done evolving motifs. This takes the very simple approach of halting evolution when the GA has proceeded for a specified number of generations and has a given number of unique schema with positive fitness.
Method sig... | Implement the Python class `SimpleFinisher` described below.
Class description:
Determine when we are done evolving motifs. This takes the very simple approach of halting evolution when the GA has proceeded for a specified number of generations and has a given number of unique schema with positive fitness.
Method sig... | 1d9a8e84a8572809ee3260ede44290e14de3bdd1 | <|skeleton|>
class SimpleFinisher:
"""Determine when we are done evolving motifs. This takes the very simple approach of halting evolution when the GA has proceeded for a specified number of generations and has a given number of unique schema with positive fitness."""
def __init__(self, num_schemas, min_genera... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimpleFinisher:
"""Determine when we are done evolving motifs. This takes the very simple approach of halting evolution when the GA has proceeded for a specified number of generations and has a given number of unique schema with positive fitness."""
def __init__(self, num_schemas, min_generations=100):
... | the_stack_v2_python_sparse | bin/last_wrapper/Bio/NeuralNetwork/Gene/Schema.py | LyonsLab/coge | train | 41 |
61929cb9652b6dedc88baeb58838ac8b580e44ae | [
"for order in self.browse(cr, uid, ids, context=context):\n if order.ttype == 'other':\n if order.stock_journal_id.need_visit:\n return True\n for line in order.order_line:\n if line.product_id.need_visit:\n return True\nreturn super(exchange_order, self).has_ca... | <|body_start_0|>
for order in self.browse(cr, uid, ids, context=context):
if order.ttype == 'other':
if order.stock_journal_id.need_visit:
return True
for line in order.order_line:
if line.product_id.need_visit:
... | exchange_order | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class exchange_order:
def has_category_manager(self, cr, uid, ids, context=None):
"""Condition Workflow function. @return: boolean"""
<|body_0|>
def action_approve_order(self, cr, uid, ids, context=None):
"""Workflow function Changes order state to approve. @return: True""... | stack_v2_sparse_classes_36k_train_033152 | 6,031 | no_license | [
{
"docstring": "Condition Workflow function. @return: boolean",
"name": "has_category_manager",
"signature": "def has_category_manager(self, cr, uid, ids, context=None)"
},
{
"docstring": "Workflow function Changes order state to approve. @return: True",
"name": "action_approve_order",
"... | 3 | stack_v2_sparse_classes_30k_train_005052 | Implement the Python class `exchange_order` described below.
Class description:
Implement the exchange_order class.
Method signatures and docstrings:
- def has_category_manager(self, cr, uid, ids, context=None): Condition Workflow function. @return: boolean
- def action_approve_order(self, cr, uid, ids, context=None)... | Implement the Python class `exchange_order` described below.
Class description:
Implement the exchange_order class.
Method signatures and docstrings:
- def has_category_manager(self, cr, uid, ids, context=None): Condition Workflow function. @return: boolean
- def action_approve_order(self, cr, uid, ids, context=None)... | 0b997095c260d58b026440967fea3a202bef7efb | <|skeleton|>
class exchange_order:
def has_category_manager(self, cr, uid, ids, context=None):
"""Condition Workflow function. @return: boolean"""
<|body_0|>
def action_approve_order(self, cr, uid, ids, context=None):
"""Workflow function Changes order state to approve. @return: True""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class exchange_order:
def has_category_manager(self, cr, uid, ids, context=None):
"""Condition Workflow function. @return: boolean"""
for order in self.browse(cr, uid, ids, context=context):
if order.ttype == 'other':
if order.stock_journal_id.need_visit:
... | the_stack_v2_python_sparse | v_7/GDS/shamil_v3/stock_exchange_NISS/stock_exchange.py | musabahmed/baba | train | 0 | |
a1fcc8013a75275391941c9fe096a5aebfb7c985 | [
"self.iterations = iterations\nself.depth = depth\nself.learning_rate = learning_rate\nself.logging_level = logging_level\nself.l2_leaf_reg = l2_leaf_reg\nself.thread_count = thread_count\nself.kwargs = kwargs\nsuper(CatBoostModelMultiSegment, self).__init__()\nself._base_model = _CatBoostModel(iterations=iteration... | <|body_start_0|>
self.iterations = iterations
self.depth = depth
self.learning_rate = learning_rate
self.logging_level = logging_level
self.l2_leaf_reg = l2_leaf_reg
self.thread_count = thread_count
self.kwargs = kwargs
super(CatBoostModelMultiSegment, sel... | Class for holding Catboost model for all segments. Examples -------- >>> from etna.datasets import generate_periodic_df >>> from etna.datasets import TSDataset >>> from etna.models import CatBoostModelMultiSegment >>> from etna.transforms import LagTransform >>> classic_df = generate_periodic_df( ... periods=100, ... s... | CatBoostModelMultiSegment | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CatBoostModelMultiSegment:
"""Class for holding Catboost model for all segments. Examples -------- >>> from etna.datasets import generate_periodic_df >>> from etna.datasets import TSDataset >>> from etna.models import CatBoostModelMultiSegment >>> from etna.transforms import LagTransform >>> clas... | stack_v2_sparse_classes_36k_train_033153 | 12,080 | permissive | [
{
"docstring": "Create instance of CatBoostModelMultiSegment with given parameters. Parameters ---------- iterations: The maximum number of trees that can be built when solving machine learning problems. When using other parameters that limit the number of iterations, the final number of trees may be less than ... | 3 | stack_v2_sparse_classes_30k_train_015072 | Implement the Python class `CatBoostModelMultiSegment` described below.
Class description:
Class for holding Catboost model for all segments. Examples -------- >>> from etna.datasets import generate_periodic_df >>> from etna.datasets import TSDataset >>> from etna.models import CatBoostModelMultiSegment >>> from etna.... | Implement the Python class `CatBoostModelMultiSegment` described below.
Class description:
Class for holding Catboost model for all segments. Examples -------- >>> from etna.datasets import generate_periodic_df >>> from etna.datasets import TSDataset >>> from etna.models import CatBoostModelMultiSegment >>> from etna.... | b2453671b00affe2af23c4b10f556f6fb5d7d602 | <|skeleton|>
class CatBoostModelMultiSegment:
"""Class for holding Catboost model for all segments. Examples -------- >>> from etna.datasets import generate_periodic_df >>> from etna.datasets import TSDataset >>> from etna.models import CatBoostModelMultiSegment >>> from etna.transforms import LagTransform >>> clas... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CatBoostModelMultiSegment:
"""Class for holding Catboost model for all segments. Examples -------- >>> from etna.datasets import generate_periodic_df >>> from etna.datasets import TSDataset >>> from etna.models import CatBoostModelMultiSegment >>> from etna.transforms import LagTransform >>> classic_df = gene... | the_stack_v2_python_sparse | etna/models/catboost.py | jingmouren/etna-ts | train | 0 |
00f3b73a17f249a6cb3ac196ce9111290f2d5d1a | [
"try:\n igdb = request.GET['igdb']\n game = Game.objects.get(igdb=igdb)\n user = CustomUser.objects.get(id=request.user.id)\n r = Ratings.objects.get(game=game, user=user)\nexcept ObjectDoesNotExist:\n return Response({})\nserializer = RatingSerializer(r)\nreturn Response(serializer.data)",
"rating... | <|body_start_0|>
try:
igdb = request.GET['igdb']
game = Game.objects.get(igdb=igdb)
user = CustomUser.objects.get(id=request.user.id)
r = Ratings.objects.get(game=game, user=user)
except ObjectDoesNotExist:
return Response({})
serialize... | Endpoint related to rating a game. Users can rate a game in a scale of 1 to 10. This value is saved in the Ratigs model, which takes the IDs of a user and a game as foreign keys. This endpoint accepts both GET and POST methods. Users must be authenticated to interact with this endpoint. | Rate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rate:
"""Endpoint related to rating a game. Users can rate a game in a scale of 1 to 10. This value is saved in the Ratigs model, which takes the IDs of a user and a game as foreign keys. This endpoint accepts both GET and POST methods. Users must be authenticated to interact with this endpoint."... | stack_v2_sparse_classes_36k_train_033154 | 15,728 | no_license | [
{
"docstring": "Get rating for a specific game by the logged-in user. If the game or rating don't exist in the database, no rating exists, so we return nothing. Args: game: the game ID. Returns: response: a RatingSerializer indicating the user, game and rating.",
"name": "get",
"signature": "def get(sel... | 2 | stack_v2_sparse_classes_30k_train_010853 | Implement the Python class `Rate` described below.
Class description:
Endpoint related to rating a game. Users can rate a game in a scale of 1 to 10. This value is saved in the Ratigs model, which takes the IDs of a user and a game as foreign keys. This endpoint accepts both GET and POST methods. Users must be authent... | Implement the Python class `Rate` described below.
Class description:
Endpoint related to rating a game. Users can rate a game in a scale of 1 to 10. This value is saved in the Ratigs model, which takes the IDs of a user and a game as foreign keys. This endpoint accepts both GET and POST methods. Users must be authent... | 7f7e44ca0dae3525394458c16b7093f90612524b | <|skeleton|>
class Rate:
"""Endpoint related to rating a game. Users can rate a game in a scale of 1 to 10. This value is saved in the Ratigs model, which takes the IDs of a user and a game as foreign keys. This endpoint accepts both GET and POST methods. Users must be authenticated to interact with this endpoint."... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Rate:
"""Endpoint related to rating a game. Users can rate a game in a scale of 1 to 10. This value is saved in the Ratigs model, which takes the IDs of a user and a game as foreign keys. This endpoint accepts both GET and POST methods. Users must be authenticated to interact with this endpoint."""
def g... | the_stack_v2_python_sparse | backend/actions/views.py | RMalmberg/overworld | train | 3 |
4a622fe91a923ad9ee0b5b1b69226941ca9026f2 | [
"logger.logic_log('LOSI00001', 'None')\nself.last_update_user = User.objects.get(user_id=DB_OASE_USER).user_name\nself.hostname = gethostname()\nlogger.logic_log('LOSI00002', 'None')",
"logger.logic_log('LOSI00001', 'aryPCB: %s, zabbix_adapter_id: %s' % (aryPCB, zabbix_adapter_id))\ntry:\n file_path = os.path.... | <|body_start_0|>
logger.logic_log('LOSI00001', 'None')
self.last_update_user = User.objects.get(user_id=DB_OASE_USER).user_name
self.hostname = gethostname()
logger.logic_log('LOSI00002', 'None')
<|end_body_0|>
<|body_start_1|>
logger.logic_log('LOSI00001', 'aryPCB: %s, zabbix_a... | [クラス概要] ZABBIXアダプタメイン処理クラス | ZabbixAdapterMainModules | [
"Apache-2.0",
"BSD-3-Clause",
"LGPL-3.0-only",
"MIT",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZabbixAdapterMainModules:
"""[クラス概要] ZABBIXアダプタメイン処理クラス"""
def __init__(self):
"""[概要] コンストラクタ"""
<|body_0|>
def execute_subprocess(self, aryPCB, zabbix_adapter_id):
"""[概要] Zabbix情報を取得する子プロセスを起動するメソッド"""
<|body_1|>
def do_normal(self, aryPCB):
... | stack_v2_sparse_classes_36k_train_033155 | 7,891 | permissive | [
{
"docstring": "[概要] コンストラクタ",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "[概要] Zabbix情報を取得する子プロセスを起動するメソッド",
"name": "execute_subprocess",
"signature": "def execute_subprocess(self, aryPCB, zabbix_adapter_id)"
},
{
"docstring": "ZABBIXアダプタ通常実行",
... | 5 | null | Implement the Python class `ZabbixAdapterMainModules` described below.
Class description:
[クラス概要] ZABBIXアダプタメイン処理クラス
Method signatures and docstrings:
- def __init__(self): [概要] コンストラクタ
- def execute_subprocess(self, aryPCB, zabbix_adapter_id): [概要] Zabbix情報を取得する子プロセスを起動するメソッド
- def do_normal(self, aryPCB): ZABBIXアダプ... | Implement the Python class `ZabbixAdapterMainModules` described below.
Class description:
[クラス概要] ZABBIXアダプタメイン処理クラス
Method signatures and docstrings:
- def __init__(self): [概要] コンストラクタ
- def execute_subprocess(self, aryPCB, zabbix_adapter_id): [概要] Zabbix情報を取得する子プロセスを起動するメソッド
- def do_normal(self, aryPCB): ZABBIXアダプ... | c00ea4fe1bf4b4a18d545aabeaaf1d95c7664b94 | <|skeleton|>
class ZabbixAdapterMainModules:
"""[クラス概要] ZABBIXアダプタメイン処理クラス"""
def __init__(self):
"""[概要] コンストラクタ"""
<|body_0|>
def execute_subprocess(self, aryPCB, zabbix_adapter_id):
"""[概要] Zabbix情報を取得する子プロセスを起動するメソッド"""
<|body_1|>
def do_normal(self, aryPCB):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZabbixAdapterMainModules:
"""[クラス概要] ZABBIXアダプタメイン処理クラス"""
def __init__(self):
"""[概要] コンストラクタ"""
logger.logic_log('LOSI00001', 'None')
self.last_update_user = User.objects.get(user_id=DB_OASE_USER).user_name
self.hostname = gethostname()
logger.logic_log('LOSI0000... | the_stack_v2_python_sparse | oase-root/backyards/monitoring_adapter/ZABBIX_monitoring.py | exastro-suite/oase | train | 10 |
565c42408320e7de368e2e1ebdb25709255f99c0 | [
"self.user32 = user32\nself.kernel32 = kernel32\nself.is_hooked = None",
"self.is_hooked = self.user32.SetWindowsHookExA(WH_KEYBOARD_LL, ptr, kernel32.GetModuleHandleW(None), 0)\nif not self.is_hooked:\n return False\nreturn True",
"if self.is_hooked is None:\n return\nself.user32.UnhookWindowsHookEx(self... | <|body_start_0|>
self.user32 = user32
self.kernel32 = kernel32
self.is_hooked = None
<|end_body_0|>
<|body_start_1|>
self.is_hooked = self.user32.SetWindowsHookExA(WH_KEYBOARD_LL, ptr, kernel32.GetModuleHandleW(None), 0)
if not self.is_hooked:
return False
re... | Class for installing/uninstalling a hook | hook | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class hook:
"""Class for installing/uninstalling a hook"""
def __init__(self):
"""Constructor for the hook class. Responsible for allowing methods to call functions from user32.dll and kernel32.dll."""
<|body_0|>
def install_hook(self, ptr):
"""Method for installing ho... | stack_v2_sparse_classes_36k_train_033156 | 2,947 | no_license | [
{
"docstring": "Constructor for the hook class. Responsible for allowing methods to call functions from user32.dll and kernel32.dll.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Method for installing hook. Arguments ptr: pointer to the HOOKPROC callback function",
... | 3 | stack_v2_sparse_classes_30k_train_009107 | Implement the Python class `hook` described below.
Class description:
Class for installing/uninstalling a hook
Method signatures and docstrings:
- def __init__(self): Constructor for the hook class. Responsible for allowing methods to call functions from user32.dll and kernel32.dll.
- def install_hook(self, ptr): Met... | Implement the Python class `hook` described below.
Class description:
Class for installing/uninstalling a hook
Method signatures and docstrings:
- def __init__(self): Constructor for the hook class. Responsible for allowing methods to call functions from user32.dll and kernel32.dll.
- def install_hook(self, ptr): Met... | 0e965cdc4a23c1d02f7052bc8da473b7f57ffa04 | <|skeleton|>
class hook:
"""Class for installing/uninstalling a hook"""
def __init__(self):
"""Constructor for the hook class. Responsible for allowing methods to call functions from user32.dll and kernel32.dll."""
<|body_0|>
def install_hook(self, ptr):
"""Method for installing ho... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class hook:
"""Class for installing/uninstalling a hook"""
def __init__(self):
"""Constructor for the hook class. Responsible for allowing methods to call functions from user32.dll and kernel32.dll."""
self.user32 = user32
self.kernel32 = kernel32
self.is_hooked = None
def ... | the_stack_v2_python_sparse | misc/keylogger_test.py | minhkhoi1026/remote-monitor | train | 0 |
998aa5fe9780f216e148c5645631e8ef7373c076 | [
"if not is_exe(exe_path):\n msg = '{0} is not an executable'.format(exe_path)\n raise NotExecutableError(msg)\nself._exe_path = exe_path",
"self.__build_cmd(reads, indexstem, outfilename, threads, fasta)\nprint(self._cmd)\nif dry_run:\n results = Results(self._cmd, self._outfname, None, None)\nelse:\n ... | <|body_start_0|>
if not is_exe(exe_path):
msg = '{0} is not an executable'.format(exe_path)
raise NotExecutableError(msg)
self._exe_path = exe_path
<|end_body_0|>
<|body_start_1|>
self.__build_cmd(reads, indexstem, outfilename, threads, fasta)
print(self._cmd)
... | Class for working with Bowtie2_Map | Bowtie2_Map | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bowtie2_Map:
"""Class for working with Bowtie2_Map"""
def __init__(self, exe_path):
"""Instantiate with location of executable"""
<|body_0|>
def run(self, reads, indexstem, outfilename, threads, fasta=False, dry_run=False):
"""Construct and execute a bowtie2 comm... | stack_v2_sparse_classes_36k_train_033157 | 3,930 | permissive | [
{
"docstring": "Instantiate with location of executable",
"name": "__init__",
"signature": "def __init__(self, exe_path)"
},
{
"docstring": "Construct and execute a bowtie2 command-line reads - can be a fasta file or a string of left and right reads. infnames - the fasta to index indexstem - the... | 3 | null | Implement the Python class `Bowtie2_Map` described below.
Class description:
Class for working with Bowtie2_Map
Method signatures and docstrings:
- def __init__(self, exe_path): Instantiate with location of executable
- def run(self, reads, indexstem, outfilename, threads, fasta=False, dry_run=False): Construct and e... | Implement the Python class `Bowtie2_Map` described below.
Class description:
Class for working with Bowtie2_Map
Method signatures and docstrings:
- def __init__(self, exe_path): Instantiate with location of executable
- def run(self, reads, indexstem, outfilename, threads, fasta=False, dry_run=False): Construct and e... | a3c64198aad3709a5c4d969f48ae0af11fdc25db | <|skeleton|>
class Bowtie2_Map:
"""Class for working with Bowtie2_Map"""
def __init__(self, exe_path):
"""Instantiate with location of executable"""
<|body_0|>
def run(self, reads, indexstem, outfilename, threads, fasta=False, dry_run=False):
"""Construct and execute a bowtie2 comm... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Bowtie2_Map:
"""Class for working with Bowtie2_Map"""
def __init__(self, exe_path):
"""Instantiate with location of executable"""
if not is_exe(exe_path):
msg = '{0} is not an executable'.format(exe_path)
raise NotExecutableError(msg)
self._exe_path = exe_p... | the_stack_v2_python_sparse | metapy/pycits/bowtie_map.py | peterthorpe5/public_scripts | train | 35 |
965eefb8f909f05b9904da4f143b4d22f035c005 | [
"self.model = model\nself.model.eval()\nself.selected_layer = selected_layer\nself.selected_filter = selected_filter\nself.conv_output = 0\nif not os.path.exists('../generated'):\n os.makedirs('../generated')",
"random_seq = np.uint8(np.random.uniform(0, 4, (100, 4)))\nvar_seq = np.ndarray.astype(np.array([np.... | <|body_start_0|>
self.model = model
self.model.eval()
self.selected_layer = selected_layer
self.selected_filter = selected_filter
self.conv_output = 0
if not os.path.exists('../generated'):
os.makedirs('../generated')
<|end_body_0|>
<|body_start_1|>
r... | Produce an image that minimizes the loss of a filter on a conv layer. | CNNLayerVisualization | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CNNLayerVisualization:
"""Produce an image that minimizes the loss of a filter on a conv layer."""
def __init__(self, model, selected_layer, selected_filter):
"""Init with a torch neural network `model`."""
<|body_0|>
def visualise_layer1D(self, save=True):
"""Pl... | stack_v2_sparse_classes_36k_train_033158 | 4,696 | no_license | [
{
"docstring": "Init with a torch neural network `model`.",
"name": "__init__",
"signature": "def __init__(self, model, selected_layer, selected_filter)"
},
{
"docstring": "Plot activations but just for one dimension (four pixels/lettes).",
"name": "visualise_layer1D",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_000432 | Implement the Python class `CNNLayerVisualization` described below.
Class description:
Produce an image that minimizes the loss of a filter on a conv layer.
Method signatures and docstrings:
- def __init__(self, model, selected_layer, selected_filter): Init with a torch neural network `model`.
- def visualise_layer1D... | Implement the Python class `CNNLayerVisualization` described below.
Class description:
Produce an image that minimizes the loss of a filter on a conv layer.
Method signatures and docstrings:
- def __init__(self, model, selected_layer, selected_filter): Init with a torch neural network `model`.
- def visualise_layer1D... | f438ee61d8a1e01b9abb959ec056631e6bf48463 | <|skeleton|>
class CNNLayerVisualization:
"""Produce an image that minimizes the loss of a filter on a conv layer."""
def __init__(self, model, selected_layer, selected_filter):
"""Init with a torch neural network `model`."""
<|body_0|>
def visualise_layer1D(self, save=True):
"""Pl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CNNLayerVisualization:
"""Produce an image that minimizes the loss of a filter on a conv layer."""
def __init__(self, model, selected_layer, selected_filter):
"""Init with a torch neural network `model`."""
self.model = model
self.model.eval()
self.selected_layer = selecte... | the_stack_v2_python_sparse | src/post-processing/plot_conv.py | carrascomj/drastic | train | 1 |
60c13a34616c0cec74a1fc963ab431056b44bbe8 | [
"if scheduler != 'PNDM':\n raise ValueError(f'Inpainting only supports PNDM scheduler')\nsuper(InpaintPipeline, self).__init__(*args, **kwargs, inpaint=True, scheduler=scheduler, stages=['vae_encoder', 'clip', 'unet', 'vae'])",
"batch_size = len(prompt)\nassert len(prompt) == len(negative_prompt)\nlatent_heigh... | <|body_start_0|>
if scheduler != 'PNDM':
raise ValueError(f'Inpainting only supports PNDM scheduler')
super(InpaintPipeline, self).__init__(*args, **kwargs, inpaint=True, scheduler=scheduler, stages=['vae_encoder', 'clip', 'unet', 'vae'])
<|end_body_0|>
<|body_start_1|>
batch_size =... | Application showcasing the acceleration of Stable Diffusion Inpainting v1.5, v2.0 pipeline using NVidia TensorRT w/ Plugins. | InpaintPipeline | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"ISC",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InpaintPipeline:
"""Application showcasing the acceleration of Stable Diffusion Inpainting v1.5, v2.0 pipeline using NVidia TensorRT w/ Plugins."""
def __init__(self, scheduler='PNDM', *args, **kwargs):
"""Initializes the Inpainting Diffusion pipeline. Args: scheduler (str): The sche... | stack_v2_sparse_classes_36k_train_033159 | 4,835 | permissive | [
{
"docstring": "Initializes the Inpainting Diffusion pipeline. Args: scheduler (str): The scheduler to guide the denoising process. Must be one of the [PNDM].",
"name": "__init__",
"signature": "def __init__(self, scheduler='PNDM', *args, **kwargs)"
},
{
"docstring": "Run the diffusion pipeline.... | 2 | null | Implement the Python class `InpaintPipeline` described below.
Class description:
Application showcasing the acceleration of Stable Diffusion Inpainting v1.5, v2.0 pipeline using NVidia TensorRT w/ Plugins.
Method signatures and docstrings:
- def __init__(self, scheduler='PNDM', *args, **kwargs): Initializes the Inpai... | Implement the Python class `InpaintPipeline` described below.
Class description:
Application showcasing the acceleration of Stable Diffusion Inpainting v1.5, v2.0 pipeline using NVidia TensorRT w/ Plugins.
Method signatures and docstrings:
- def __init__(self, scheduler='PNDM', *args, **kwargs): Initializes the Inpai... | a167852705d74bcc619d8fad0af4b9e4d84472fc | <|skeleton|>
class InpaintPipeline:
"""Application showcasing the acceleration of Stable Diffusion Inpainting v1.5, v2.0 pipeline using NVidia TensorRT w/ Plugins."""
def __init__(self, scheduler='PNDM', *args, **kwargs):
"""Initializes the Inpainting Diffusion pipeline. Args: scheduler (str): The sche... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InpaintPipeline:
"""Application showcasing the acceleration of Stable Diffusion Inpainting v1.5, v2.0 pipeline using NVidia TensorRT w/ Plugins."""
def __init__(self, scheduler='PNDM', *args, **kwargs):
"""Initializes the Inpainting Diffusion pipeline. Args: scheduler (str): The scheduler to guid... | the_stack_v2_python_sparse | demo/Diffusion/inpaint_pipeline.py | NVIDIA/TensorRT | train | 8,026 |
e2f4210419d1559e9f11fed7a68d5f5430bc35cf | [
"self.num_idx = collections.defaultdict(list)\nfor i, v in enumerate(nums):\n self.num_idx[v].append(i)",
"indicies = self.num_idx[target]\nres = indicies[0]\nfor i in range(1, len(indicies)):\n if random.choice(range(i + 1)) == 0:\n res = indicies[i]\nreturn res"
] | <|body_start_0|>
self.num_idx = collections.defaultdict(list)
for i, v in enumerate(nums):
self.num_idx[v].append(i)
<|end_body_0|>
<|body_start_1|>
indicies = self.num_idx[target]
res = indicies[0]
for i in range(1, len(indicies)):
if random.choice(range... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def pick(self, target):
""":type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.num_idx = collections.defaultdict(list)
for i, v in enum... | stack_v2_sparse_classes_36k_train_033160 | 652 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type target: int :rtype: int",
"name": "pick",
"signature": "def pick(self, target)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def pick(self, target): :type target: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def pick(self, target): :type target: int :rtype: int
<|skeleton|>
class Solution:
def __init__(self, nums):
""":t... | 692bf0e5aab402d55463274e99ab4d0ed56ce64c | <|skeleton|>
class Solution:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def pick(self, target):
""":type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, nums):
""":type nums: List[int]"""
self.num_idx = collections.defaultdict(list)
for i, v in enumerate(nums):
self.num_idx[v].append(i)
def pick(self, target):
""":type target: int :rtype: int"""
indicies = self.num_idx[targe... | the_stack_v2_python_sparse | 398-random_pick_idx.py | WweiL/LeetCode | train | 0 | |
e55b506b0835cf5404a2af9787973bdbfd6b4ec6 | [
"if layer:\n self.layer = layer\nif x:\n self.x = x\nif y:\n self.y = y\nself.manager.driftwood.area.changed = True",
"if not x or not x in [-1, 0, 1]:\n x = 0\nif not y or not y in [-1, 0, 1]:\n y = 0\nif self.collision:\n for ent in self.manager.entities:\n if ent.eid == self.eid:\n ... | <|body_start_0|>
if layer:
self.layer = layer
if x:
self.x = x
if y:
self.y = y
self.manager.driftwood.area.changed = True
<|end_body_0|>
<|body_start_1|>
if not x or not x in [-1, 0, 1]:
x = 0
if not y or not y in [-1, 0, ... | This Entity subclass represents an Entity configured for movement in by-pixel mode. | PixelModeEntity | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PixelModeEntity:
"""This Entity subclass represents an Entity configured for movement in by-pixel mode."""
def teleport(self, layer, x, y):
"""Teleport the entity to a new pixel position. Args: layer: New layer, or None to skip. x: New x-coordinate, or None to skip. y: New y-coordina... | stack_v2_sparse_classes_36k_train_033161 | 18,827 | permissive | [
{
"docstring": "Teleport the entity to a new pixel position. Args: layer: New layer, or None to skip. x: New x-coordinate, or None to skip. y: New y-coordinate, or None to skip.",
"name": "teleport",
"signature": "def teleport(self, layer, x, y)"
},
{
"docstring": "Move the entity by one pixel t... | 2 | stack_v2_sparse_classes_30k_val_000923 | Implement the Python class `PixelModeEntity` described below.
Class description:
This Entity subclass represents an Entity configured for movement in by-pixel mode.
Method signatures and docstrings:
- def teleport(self, layer, x, y): Teleport the entity to a new pixel position. Args: layer: New layer, or None to skip... | Implement the Python class `PixelModeEntity` described below.
Class description:
This Entity subclass represents an Entity configured for movement in by-pixel mode.
Method signatures and docstrings:
- def teleport(self, layer, x, y): Teleport the entity to a new pixel position. Args: layer: New layer, or None to skip... | 95fd4497c268ef10fa950a91ca9cc26f6dff557d | <|skeleton|>
class PixelModeEntity:
"""This Entity subclass represents an Entity configured for movement in by-pixel mode."""
def teleport(self, layer, x, y):
"""Teleport the entity to a new pixel position. Args: layer: New layer, or None to skip. x: New x-coordinate, or None to skip. y: New y-coordina... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PixelModeEntity:
"""This Entity subclass represents an Entity configured for movement in by-pixel mode."""
def teleport(self, layer, x, y):
"""Teleport the entity to a new pixel position. Args: layer: New layer, or None to skip. x: New x-coordinate, or None to skip. y: New y-coordinate, or None t... | the_stack_v2_python_sparse | src/entity.py | pmer/Driftwood | train | 0 |
abf103845299e7eb8edd6df81b7b2244f466e5d9 | [
"tf.reset_default_graph()\noptim = tf.train.GradientDescentOptimizer(0.1)\nsparse_optim = sparse_optimizers.SparseMomentumOptimizer(optim, start_iter, end_iter, freq_iter, drop_fraction=drop_frac, momentum=momentum)\nx = tf.ones((1, n_inp))\ny = layers.masked_fully_connected(x, n_out, activation_fn=None)\ny = y * t... | <|body_start_0|>
tf.reset_default_graph()
optim = tf.train.GradientDescentOptimizer(0.1)
sparse_optim = sparse_optimizers.SparseMomentumOptimizer(optim, start_iter, end_iter, freq_iter, drop_fraction=drop_frac, momentum=momentum)
x = tf.ones((1, n_inp))
y = layers.masked_fully_co... | SparseMomentumOptimizerTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparseMomentumOptimizerTest:
def _setup_graph(self, n_inp, n_out, drop_frac, start_iter=1, end_iter=4, freq_iter=2, momentum=0.5):
"""Setups a trivial training procedure for sparse training."""
<|body_0|>
def testMomentumUpdate(self, n_inp, n_out, momentum):
"""Check... | stack_v2_sparse_classes_36k_train_033162 | 25,606 | permissive | [
{
"docstring": "Setups a trivial training procedure for sparse training.",
"name": "_setup_graph",
"signature": "def _setup_graph(self, n_inp, n_out, drop_frac, start_iter=1, end_iter=4, freq_iter=2, momentum=0.5)"
},
{
"docstring": "Checking whether momentum applied correctly.",
"name": "te... | 2 | null | Implement the Python class `SparseMomentumOptimizerTest` described below.
Class description:
Implement the SparseMomentumOptimizerTest class.
Method signatures and docstrings:
- def _setup_graph(self, n_inp, n_out, drop_frac, start_iter=1, end_iter=4, freq_iter=2, momentum=0.5): Setups a trivial training procedure fo... | Implement the Python class `SparseMomentumOptimizerTest` described below.
Class description:
Implement the SparseMomentumOptimizerTest class.
Method signatures and docstrings:
- def _setup_graph(self, n_inp, n_out, drop_frac, start_iter=1, end_iter=4, freq_iter=2, momentum=0.5): Setups a trivial training procedure fo... | d39fc7d46505cb3196cb1edeb32ed0b6dd44c0f9 | <|skeleton|>
class SparseMomentumOptimizerTest:
def _setup_graph(self, n_inp, n_out, drop_frac, start_iter=1, end_iter=4, freq_iter=2, momentum=0.5):
"""Setups a trivial training procedure for sparse training."""
<|body_0|>
def testMomentumUpdate(self, n_inp, n_out, momentum):
"""Check... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SparseMomentumOptimizerTest:
def _setup_graph(self, n_inp, n_out, drop_frac, start_iter=1, end_iter=4, freq_iter=2, momentum=0.5):
"""Setups a trivial training procedure for sparse training."""
tf.reset_default_graph()
optim = tf.train.GradientDescentOptimizer(0.1)
sparse_optim... | the_stack_v2_python_sparse | rigl/sparse_optimizers_test.py | google-research/rigl | train | 324 | |
7c152fe9eadd0621b19d794e990159d8195b25f9 | [
"datastore_hooks.SetPrivilegedRequest()\nrevision = int(self.request.get('revision'))\nnum_around = int(self.request.get('num_around'), 10)\ntest_key = ndb.Key(urlsafe=self.request.get('test_key'))\ncontainer_key = ndb.Key(urlsafe=self.request.get('parent_key'))\nbefore_revs = graph_data.Row.query(graph_data.Row.pa... | <|body_start_0|>
datastore_hooks.SetPrivilegedRequest()
revision = int(self.request.get('revision'))
num_around = int(self.request.get('num_around'), 10)
test_key = ndb.Key(urlsafe=self.request.get('test_key'))
container_key = ndb.Key(urlsafe=self.request.get('parent_key'))
... | URL endpoint for tasks which generate stats before/after a revision. | StatsAroundRevisionHandler | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StatsAroundRevisionHandler:
"""URL endpoint for tasks which generate stats before/after a revision."""
def post(self):
"""Task queue task to get stats before/after a revision of a single Test. Request parameters: revision: A central revision to look around. num_around: The number of ... | stack_v2_sparse_classes_36k_train_033163 | 17,003 | permissive | [
{
"docstring": "Task queue task to get stats before/after a revision of a single Test. Request parameters: revision: A central revision to look around. num_around: The number of points before and after the given revision. test_key: The urlsafe string of a Test key. parent_key: The urlsafe string of a StatContai... | 3 | null | Implement the Python class `StatsAroundRevisionHandler` described below.
Class description:
URL endpoint for tasks which generate stats before/after a revision.
Method signatures and docstrings:
- def post(self): Task queue task to get stats before/after a revision of a single Test. Request parameters: revision: A ce... | Implement the Python class `StatsAroundRevisionHandler` described below.
Class description:
URL endpoint for tasks which generate stats before/after a revision.
Method signatures and docstrings:
- def post(self): Task queue task to get stats before/after a revision of a single Test. Request parameters: revision: A ce... | e71f21b9b4b9b839f5093301974a45545dad2691 | <|skeleton|>
class StatsAroundRevisionHandler:
"""URL endpoint for tasks which generate stats before/after a revision."""
def post(self):
"""Task queue task to get stats before/after a revision of a single Test. Request parameters: revision: A central revision to look around. num_around: The number of ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StatsAroundRevisionHandler:
"""URL endpoint for tasks which generate stats before/after a revision."""
def post(self):
"""Task queue task to get stats before/after a revision of a single Test. Request parameters: revision: A central revision to look around. num_around: The number of points before... | the_stack_v2_python_sparse | third_party/catapult/dashboard/dashboard/stats.py | zenoalbisser/chromium | train | 0 |
63986f0297d48db3861456e49677712f25618874 | [
"self._august_gateway = None\nself.user_auth_details = {}\nself._needs_reset = False\nsuper().__init__()",
"if self._august_gateway is None:\n self._august_gateway = AugustGateway(self.hass)\nerrors = {}\nif user_input is not None:\n combined_inputs = {**self.user_auth_details, **user_input}\n await self... | <|body_start_0|>
self._august_gateway = None
self.user_auth_details = {}
self._needs_reset = False
super().__init__()
<|end_body_0|>
<|body_start_1|>
if self._august_gateway is None:
self._august_gateway = AugustGateway(self.hass)
errors = {}
if user_... | Handle a config flow for August. | AugustConfigFlow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AugustConfigFlow:
"""Handle a config flow for August."""
def __init__(self):
"""Store an AugustGateway()."""
<|body_0|>
async def async_step_user(self, user_input=None):
"""Handle the initial step."""
<|body_1|>
async def async_step_validation(self, ... | stack_v2_sparse_classes_36k_train_033164 | 5,668 | permissive | [
{
"docstring": "Store an AugustGateway().",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Handle the initial step.",
"name": "async_step_user",
"signature": "async def async_step_user(self, user_input=None)"
},
{
"docstring": "Handle validation (2fa) st... | 6 | stack_v2_sparse_classes_30k_train_014607 | Implement the Python class `AugustConfigFlow` described below.
Class description:
Handle a config flow for August.
Method signatures and docstrings:
- def __init__(self): Store an AugustGateway().
- async def async_step_user(self, user_input=None): Handle the initial step.
- async def async_step_validation(self, user... | Implement the Python class `AugustConfigFlow` described below.
Class description:
Handle a config flow for August.
Method signatures and docstrings:
- def __init__(self): Store an AugustGateway().
- async def async_step_user(self, user_input=None): Handle the initial step.
- async def async_step_validation(self, user... | ed4ab403deaed9e8c95e0db728477fcb012bf4fa | <|skeleton|>
class AugustConfigFlow:
"""Handle a config flow for August."""
def __init__(self):
"""Store an AugustGateway()."""
<|body_0|>
async def async_step_user(self, user_input=None):
"""Handle the initial step."""
<|body_1|>
async def async_step_validation(self, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AugustConfigFlow:
"""Handle a config flow for August."""
def __init__(self):
"""Store an AugustGateway()."""
self._august_gateway = None
self.user_auth_details = {}
self._needs_reset = False
super().__init__()
async def async_step_user(self, user_input=None):
... | the_stack_v2_python_sparse | homeassistant/components/august/config_flow.py | tchellomello/home-assistant | train | 8 |
8e4e24a1c0fc91f6121c5fd6e4dfc68fdeab120a | [
"super().__init__()\nself.trans = Transform(dim_in, k)\nself.convK1 = nn.Conv1d(k, 1, 1)",
"transformed_feats = self.trans(region_feats)\npooled_feats = self.convK1(transformed_feats)\npooled_feats = pooled_feats.squeeze(1)\nreturn pooled_feats"
] | <|body_start_0|>
super().__init__()
self.trans = Transform(dim_in, k)
self.convK1 = nn.Conv1d(k, 1, 1)
<|end_body_0|>
<|body_start_1|>
transformed_feats = self.trans(region_feats)
pooled_feats = self.convK1(transformed_feats)
pooled_feats = pooled_feats.squeeze(1)
... | A Vertex Convolution layer Transform (N, k, d) feature to (N, d) feature by transform matrix and 1-D convolution | VertexConv | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VertexConv:
"""A Vertex Convolution layer Transform (N, k, d) feature to (N, d) feature by transform matrix and 1-D convolution"""
def __init__(self, dim_in, k):
""":param dim_in: input feature dimension :param k: k neighbors"""
<|body_0|>
def forward(self, region_feats)... | stack_v2_sparse_classes_36k_train_033165 | 15,047 | no_license | [
{
"docstring": ":param dim_in: input feature dimension :param k: k neighbors",
"name": "__init__",
"signature": "def __init__(self, dim_in, k)"
},
{
"docstring": ":param region_feats: (N, k, d) :return: (N, d)",
"name": "forward",
"signature": "def forward(self, region_feats)"
}
] | 2 | null | Implement the Python class `VertexConv` described below.
Class description:
A Vertex Convolution layer Transform (N, k, d) feature to (N, d) feature by transform matrix and 1-D convolution
Method signatures and docstrings:
- def __init__(self, dim_in, k): :param dim_in: input feature dimension :param k: k neighbors
-... | Implement the Python class `VertexConv` described below.
Class description:
A Vertex Convolution layer Transform (N, k, d) feature to (N, d) feature by transform matrix and 1-D convolution
Method signatures and docstrings:
- def __init__(self, dim_in, k): :param dim_in: input feature dimension :param k: k neighbors
-... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class VertexConv:
"""A Vertex Convolution layer Transform (N, k, d) feature to (N, d) feature by transform matrix and 1-D convolution"""
def __init__(self, dim_in, k):
""":param dim_in: input feature dimension :param k: k neighbors"""
<|body_0|>
def forward(self, region_feats)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VertexConv:
"""A Vertex Convolution layer Transform (N, k, d) feature to (N, d) feature by transform matrix and 1-D convolution"""
def __init__(self, dim_in, k):
""":param dim_in: input feature dimension :param k: k neighbors"""
super().__init__()
self.trans = Transform(dim_in, k)... | the_stack_v2_python_sparse | generated/test_iMoonLab_DHGNN.py | jansel/pytorch-jit-paritybench | train | 35 |
bb0342287ef95e0fe6e85b91b5cfac4993d3814d | [
"from torch.utils.data import DataLoader\nsuper().__init__(size=size, batch_size=batch_size)\nif not isinstance(iterator, DataLoader):\n raise TypeError(f'Expected instance of PyTorch `DataLoader, received {type(iterator)} instead.`')\nself._iterator: DataLoader = iterator\nself._current = iter(self.iterator)",
... | <|body_start_0|>
from torch.utils.data import DataLoader
super().__init__(size=size, batch_size=batch_size)
if not isinstance(iterator, DataLoader):
raise TypeError(f'Expected instance of PyTorch `DataLoader, received {type(iterator)} instead.`')
self._iterator: DataLoader = ... | Wrapper class on top of the PyTorch native data loader :class:`torch.utils.data.DataLoader`. | PyTorchDataGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PyTorchDataGenerator:
"""Wrapper class on top of the PyTorch native data loader :class:`torch.utils.data.DataLoader`."""
def __init__(self, iterator: 'torch.utils.data.DataLoader', size: int, batch_size: int) -> None:
"""Create a data generator wrapper on top of a PyTorch :class:`Dat... | stack_v2_sparse_classes_36k_train_033166 | 15,829 | permissive | [
{
"docstring": "Create a data generator wrapper on top of a PyTorch :class:`DataLoader`. :param iterator: A PyTorch data generator. :param size: Total size of the dataset. :param batch_size: Size of the minibatches.",
"name": "__init__",
"signature": "def __init__(self, iterator: 'torch.utils.data.DataL... | 2 | stack_v2_sparse_classes_30k_train_016487 | Implement the Python class `PyTorchDataGenerator` described below.
Class description:
Wrapper class on top of the PyTorch native data loader :class:`torch.utils.data.DataLoader`.
Method signatures and docstrings:
- def __init__(self, iterator: 'torch.utils.data.DataLoader', size: int, batch_size: int) -> None: Create... | Implement the Python class `PyTorchDataGenerator` described below.
Class description:
Wrapper class on top of the PyTorch native data loader :class:`torch.utils.data.DataLoader`.
Method signatures and docstrings:
- def __init__(self, iterator: 'torch.utils.data.DataLoader', size: int, batch_size: int) -> None: Create... | 6b424dadac60631c126e864551bd7202c2e19478 | <|skeleton|>
class PyTorchDataGenerator:
"""Wrapper class on top of the PyTorch native data loader :class:`torch.utils.data.DataLoader`."""
def __init__(self, iterator: 'torch.utils.data.DataLoader', size: int, batch_size: int) -> None:
"""Create a data generator wrapper on top of a PyTorch :class:`Dat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PyTorchDataGenerator:
"""Wrapper class on top of the PyTorch native data loader :class:`torch.utils.data.DataLoader`."""
def __init__(self, iterator: 'torch.utils.data.DataLoader', size: int, batch_size: int) -> None:
"""Create a data generator wrapper on top of a PyTorch :class:`DataLoader`. :pa... | the_stack_v2_python_sparse | art/data_generators.py | kztakemoto/adversarial-robustness-toolbox | train | 0 |
5db6b9df6d28a7b0fcd204894db9c74e31b7a4a1 | [
"self.speaker = speaker\nself.elements = elements\nself.speaker_info = speaker_info",
"if isinstance(other, self.__class__):\n return all((a == b for a, b in zip(self.elements, other.elements))) and self.speaker == other.speaker and (self.speaker_info == other.speaker_info)\nreturn False",
"json = {'speaker'... | <|body_start_0|>
self.speaker = speaker
self.elements = elements
self.speaker_info = speaker_info
<|end_body_0|>
<|body_start_1|>
if isinstance(other, self.__class__):
return all((a == b for a, b in zip(self.elements, other.elements))) and self.speaker == other.speaker and (... | Monologue | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Monologue:
def __init__(self, speaker, elements, speaker_info=None):
""":param speaker: speaker identified for this monologue :param elements: list of elements spoken in this monologue :param speaker_info: information about the speaker if available"""
<|body_0|>
def __eq__(s... | stack_v2_sparse_classes_36k_train_033167 | 4,574 | permissive | [
{
"docstring": ":param speaker: speaker identified for this monologue :param elements: list of elements spoken in this monologue :param speaker_info: information about the speaker if available",
"name": "__init__",
"signature": "def __init__(self, speaker, elements, speaker_info=None)"
},
{
"doc... | 4 | stack_v2_sparse_classes_30k_train_005101 | Implement the Python class `Monologue` described below.
Class description:
Implement the Monologue class.
Method signatures and docstrings:
- def __init__(self, speaker, elements, speaker_info=None): :param speaker: speaker identified for this monologue :param elements: list of elements spoken in this monologue :para... | Implement the Python class `Monologue` described below.
Class description:
Implement the Monologue class.
Method signatures and docstrings:
- def __init__(self, speaker, elements, speaker_info=None): :param speaker: speaker identified for this monologue :param elements: list of elements spoken in this monologue :para... | 80466d21bc743cd1e5ed1aea9fcfa592393f916d | <|skeleton|>
class Monologue:
def __init__(self, speaker, elements, speaker_info=None):
""":param speaker: speaker identified for this monologue :param elements: list of elements spoken in this monologue :param speaker_info: information about the speaker if available"""
<|body_0|>
def __eq__(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Monologue:
def __init__(self, speaker, elements, speaker_info=None):
""":param speaker: speaker identified for this monologue :param elements: list of elements spoken in this monologue :param speaker_info: information about the speaker if available"""
self.speaker = speaker
self.elemen... | the_stack_v2_python_sparse | src/rev_ai/models/asynchronous/transcript.py | revdotcom/revai-python-sdk | train | 45 | |
0e2229b616d9f49e9080b271842340ed4c456852 | [
"w = (out_features, in_features)\nb = (out_features, 1)\nself.params = {'weight': np.random.normal(0, 0.0001, w), 'bias': np.zeros(b)}\nself.grads = {'weight': np.zeros(w), 'bias': np.zeros(b)}\nprint('params_weight_init', self.params['weight'].shape)\nprint('params_bias_init', self.params['bias'].shape)\nprint('gr... | <|body_start_0|>
w = (out_features, in_features)
b = (out_features, 1)
self.params = {'weight': np.random.normal(0, 0.0001, w), 'bias': np.zeros(b)}
self.grads = {'weight': np.zeros(w), 'bias': np.zeros(b)}
print('params_weight_init', self.params['weight'].shape)
print('p... | Linear module. Applies a linear transformation to the input data. | LinearModule | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearModule:
"""Linear module. Applies a linear transformation to the input data."""
def __init__(self, in_features, out_features):
"""Initializes the parameters of the module. Args: in_features: size of each input sample out_features: size of each output sample"""
<|body_0|... | stack_v2_sparse_classes_36k_train_033168 | 5,181 | no_license | [
{
"docstring": "Initializes the parameters of the module. Args: in_features: size of each input sample out_features: size of each output sample",
"name": "__init__",
"signature": "def __init__(self, in_features, out_features)"
},
{
"docstring": "Forward pass. Args: x: input to the module Returns... | 3 | stack_v2_sparse_classes_30k_test_001046 | Implement the Python class `LinearModule` described below.
Class description:
Linear module. Applies a linear transformation to the input data.
Method signatures and docstrings:
- def __init__(self, in_features, out_features): Initializes the parameters of the module. Args: in_features: size of each input sample out_... | Implement the Python class `LinearModule` described below.
Class description:
Linear module. Applies a linear transformation to the input data.
Method signatures and docstrings:
- def __init__(self, in_features, out_features): Initializes the parameters of the module. Args: in_features: size of each input sample out_... | b2cd0d67337b101f3e204e519625e1aaf3cea43b | <|skeleton|>
class LinearModule:
"""Linear module. Applies a linear transformation to the input data."""
def __init__(self, in_features, out_features):
"""Initializes the parameters of the module. Args: in_features: size of each input sample out_features: size of each output sample"""
<|body_0|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinearModule:
"""Linear module. Applies a linear transformation to the input data."""
def __init__(self, in_features, out_features):
"""Initializes the parameters of the module. Args: in_features: size of each input sample out_features: size of each output sample"""
w = (out_features, in_... | the_stack_v2_python_sparse | assignment_1/code/modules.py | Ivan-Yovchev/uvadlc_practicals_2019 | train | 0 |
4851423a047891dd882583d003047f535464c38b | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn DocumentSet()",
"from .column_definition import ColumnDefinition\nfrom .content_type_info import ContentTypeInfo\nfrom .document_set_content import DocumentSetContent\nfrom .column_definition import ColumnDefinition\nfrom .content_type... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return DocumentSet()
<|end_body_0|>
<|body_start_1|>
from .column_definition import ColumnDefinition
from .content_type_info import ContentTypeInfo
from .document_set_content import Doc... | DocumentSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DocumentSet:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DocumentSet:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Do... | stack_v2_sparse_classes_36k_train_033169 | 5,010 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: DocumentSet",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(p... | 3 | null | Implement the Python class `DocumentSet` described below.
Class description:
Implement the DocumentSet class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DocumentSet: Creates a new instance of the appropriate class based on discriminator value Args:... | Implement the Python class `DocumentSet` described below.
Class description:
Implement the DocumentSet class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DocumentSet: Creates a new instance of the appropriate class based on discriminator value Args:... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class DocumentSet:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DocumentSet:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Do... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DocumentSet:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DocumentSet:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: DocumentSet"""
... | the_stack_v2_python_sparse | msgraph/generated/models/document_set.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
35c9c5d780a68275a7d94c678d778115f67acecb | [
"if not matrix or not matrix[0]:\n return\nrows, cols = (len(matrix), len(matrix[0]))\nfor r in range(rows):\n for c in range(cols):\n if c != 0:\n matrix[r][c] += matrix[r][c - 1]\n if r != 0:\n matrix[r][c] += matrix[r - 1][c]\n if c != 0 and r != 0:\n m... | <|body_start_0|>
if not matrix or not matrix[0]:
return
rows, cols = (len(matrix), len(matrix[0]))
for r in range(rows):
for c in range(cols):
if c != 0:
matrix[r][c] += matrix[r][c - 1]
if r != 0:
ma... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_033170 | 1,679 | no_license | [
{
"docstring": ":type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int",
"name": "sumRegion",
"signature": "def sumRegion(self, row1, col1, row2, col2)"
... | 2 | null | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | 05e0beff0047f0ad399d0b46d625bb8d3459814e | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
if not matrix or not matrix[0]:
return
rows, cols = (len(matrix), len(matrix[0]))
for r in range(rows):
for c in range(cols):
if c != 0:
matrix... | the_stack_v2_python_sparse | python_1_to_1000/304_Range_Sum_Query_2D-Immutable.py | jakehoare/leetcode | train | 58 | |
2590c26528939dd5be2ef405a001557d30688d9e | [
"super(QCustomActionGroup, self).__init__(*args, **kwargs)\nself.triggered.connect(self.onTriggered)\nself._last_checked = None",
"if action.isCheckable() and action.isChecked():\n if self.isExclusive():\n last = self._last_checked\n if last is not None and last is not action:\n last.s... | <|body_start_0|>
super(QCustomActionGroup, self).__init__(*args, **kwargs)
self.triggered.connect(self.onTriggered)
self._last_checked = None
<|end_body_0|>
<|body_start_1|>
if action.isCheckable() and action.isChecked():
if self.isExclusive():
last = self._l... | A QActionGroup subclass which fixes some toggling issues. When a QActionGroup is set from non-exclusive to exclusive, it doesn't uncheck the non-current actions. It also does not keep track of the most recently checked widget when in non-exclusive mode, so that state is lost. This subclass corrects these issues. | QCustomActionGroup | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QCustomActionGroup:
"""A QActionGroup subclass which fixes some toggling issues. When a QActionGroup is set from non-exclusive to exclusive, it doesn't uncheck the non-current actions. It also does not keep track of the most recently checked widget when in non-exclusive mode, so that state is los... | stack_v2_sparse_classes_36k_train_033171 | 6,993 | permissive | [
{
"docstring": "Initialize a QCustomActionGroup. Parameters ---------- *args, **kwargs The positional and keyword arguments needed to initialize a QActionGroup.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "The signal handler for the 'triggered' sign... | 3 | stack_v2_sparse_classes_30k_train_011393 | Implement the Python class `QCustomActionGroup` described below.
Class description:
A QActionGroup subclass which fixes some toggling issues. When a QActionGroup is set from non-exclusive to exclusive, it doesn't uncheck the non-current actions. It also does not keep track of the most recently checked widget when in n... | Implement the Python class `QCustomActionGroup` described below.
Class description:
A QActionGroup subclass which fixes some toggling issues. When a QActionGroup is set from non-exclusive to exclusive, it doesn't uncheck the non-current actions. It also does not keep track of the most recently checked widget when in n... | 1544e7fb371b8f941cfa2fde682795e479380284 | <|skeleton|>
class QCustomActionGroup:
"""A QActionGroup subclass which fixes some toggling issues. When a QActionGroup is set from non-exclusive to exclusive, it doesn't uncheck the non-current actions. It also does not keep track of the most recently checked widget when in non-exclusive mode, so that state is los... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QCustomActionGroup:
"""A QActionGroup subclass which fixes some toggling issues. When a QActionGroup is set from non-exclusive to exclusive, it doesn't uncheck the non-current actions. It also does not keep track of the most recently checked widget when in non-exclusive mode, so that state is lost. This subcl... | the_stack_v2_python_sparse | enaml/qt/qt_action_group.py | MatthieuDartiailh/enaml | train | 26 |
df328a078f81c39ea77630553ea31e64133a8103 | [
"assert len(num_kernels) + 1 == num_layers\nsuper(ConvAutoencoder, self).__init__()\nnum_kernels = [3] + num_kernels\nself.num_layers = num_layers\nself.num_kernels = num_kernels\nself.kernel_size = kernel_size\nlayers = []\nfor i in range(num_layers - 1):\n layers.append(nn.Conv2d(num_kernels[i], num_kernels[i ... | <|body_start_0|>
assert len(num_kernels) + 1 == num_layers
super(ConvAutoencoder, self).__init__()
num_kernels = [3] + num_kernels
self.num_layers = num_layers
self.num_kernels = num_kernels
self.kernel_size = kernel_size
layers = []
for i in range(num_lay... | Simple fully convolutional autoencoder for image denoising Args: ----- num_layers: integer number of convolutional layers in encoder and decoder num_kernels: list of integers number of convolutional kernels in each of the layers kernel_size: integer size of the convolutional kernels | ConvAutoencoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvAutoencoder:
"""Simple fully convolutional autoencoder for image denoising Args: ----- num_layers: integer number of convolutional layers in encoder and decoder num_kernels: list of integers number of convolutional kernels in each of the layers kernel_size: integer size of the convolutional k... | stack_v2_sparse_classes_36k_train_033172 | 4,853 | permissive | [
{
"docstring": "Initialization of the model",
"name": "__init__",
"signature": "def __init__(self, num_layers=4, num_kernels=[64, 128, 256], kernel_size=5)"
},
{
"docstring": "Forward pass through the autoencoder model",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017256 | Implement the Python class `ConvAutoencoder` described below.
Class description:
Simple fully convolutional autoencoder for image denoising Args: ----- num_layers: integer number of convolutional layers in encoder and decoder num_kernels: list of integers number of convolutional kernels in each of the layers kernel_si... | Implement the Python class `ConvAutoencoder` described below.
Class description:
Simple fully convolutional autoencoder for image denoising Args: ----- num_layers: integer number of convolutional layers in encoder and decoder num_kernels: list of integers number of convolutional kernels in each of the layers kernel_si... | 979966036775b96c7ee7855a2968937403731763 | <|skeleton|>
class ConvAutoencoder:
"""Simple fully convolutional autoencoder for image denoising Args: ----- num_layers: integer number of convolutional layers in encoder and decoder num_kernels: list of integers number of convolutional kernels in each of the layers kernel_size: integer size of the convolutional k... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConvAutoencoder:
"""Simple fully convolutional autoencoder for image denoising Args: ----- num_layers: integer number of convolutional layers in encoder and decoder num_kernels: list of integers number of convolutional kernels in each of the layers kernel_size: integer size of the convolutional kernels"""
... | the_stack_v2_python_sparse | src/models/denoising_autoencoder.py | angelvillar96/super-resolution-noisy-images | train | 7 |
12a12f273fd81ab25d9cd1ffd45dfd660b37bec6 | [
"myThread = threading.currentThread()\nif logger is None:\n logger = myThread.logger\nif dbi is None:\n dbi = myThread.dbi\nDBCreator.__init__(self, logger, dbi)\nself.create['01wm_components'] = 'CREATE TABLE wm_components (\\n id INTEGER PRIMARY KEY AUTO_INCREMENT,\\n ... | <|body_start_0|>
myThread = threading.currentThread()
if logger is None:
logger = myThread.logger
if dbi is None:
dbi = myThread.dbi
DBCreator.__init__(self, logger, dbi)
self.create['01wm_components'] = 'CREATE TABLE wm_components (\n id ... | CreateAgentBase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateAgentBase:
def __init__(self, logger=None, dbi=None, params=None):
"""_init_ Call the DBCreator constructor and create the list of required tables."""
<|body_0|>
def execute(self, conn=None, transaction=None):
"""_execute_ Check to make sure that all required t... | stack_v2_sparse_classes_36k_train_033173 | 2,495 | permissive | [
{
"docstring": "_init_ Call the DBCreator constructor and create the list of required tables.",
"name": "__init__",
"signature": "def __init__(self, logger=None, dbi=None, params=None)"
},
{
"docstring": "_execute_ Check to make sure that all required tables have been defined. If everything is i... | 2 | stack_v2_sparse_classes_30k_train_017923 | Implement the Python class `CreateAgentBase` described below.
Class description:
Implement the CreateAgentBase class.
Method signatures and docstrings:
- def __init__(self, logger=None, dbi=None, params=None): _init_ Call the DBCreator constructor and create the list of required tables.
- def execute(self, conn=None,... | Implement the Python class `CreateAgentBase` described below.
Class description:
Implement the CreateAgentBase class.
Method signatures and docstrings:
- def __init__(self, logger=None, dbi=None, params=None): _init_ Call the DBCreator constructor and create the list of required tables.
- def execute(self, conn=None,... | de110ccf6fc63ef5589b4e871ef4d51d5bce7a25 | <|skeleton|>
class CreateAgentBase:
def __init__(self, logger=None, dbi=None, params=None):
"""_init_ Call the DBCreator constructor and create the list of required tables."""
<|body_0|>
def execute(self, conn=None, transaction=None):
"""_execute_ Check to make sure that all required t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateAgentBase:
def __init__(self, logger=None, dbi=None, params=None):
"""_init_ Call the DBCreator constructor and create the list of required tables."""
myThread = threading.currentThread()
if logger is None:
logger = myThread.logger
if dbi is None:
... | the_stack_v2_python_sparse | src/python/WMCore/Agent/Database/CreateAgentBase.py | vkuznet/WMCore | train | 0 | |
4c8e79852ff3681bafa6567d62425cf4fbb3050e | [
"from . import keystore\nif not isinstance(keystore_obj, keystore.KeyStore):\n log.error('%s must be an instance of KeyStore', str(keystore))\n self.keyobject = None\n return\nself._keystore = keystore_obj.keystore\nif keystore_obj.session.subsystem == apis.kType_SSS_SE_SE05x:\n self.keyobject = apis.ss... | <|body_start_0|>
from . import keystore
if not isinstance(keystore_obj, keystore.KeyStore):
log.error('%s must be an instance of KeyStore', str(keystore))
self.keyobject = None
return
self._keystore = keystore_obj.keystore
if keystore_obj.session.subsy... | Key object operation | KeyObject | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeyObject:
"""Key object operation"""
def __init__(self, keystore_obj):
"""Constructor :param keystore_obj: Instance of key store"""
<|body_0|>
def allocate_handle(self, key_id, key_part, cypher_type, key_len, object_type):
"""Allocate handle to inject or generat... | stack_v2_sparse_classes_36k_train_033174 | 3,608 | permissive | [
{
"docstring": "Constructor :param keystore_obj: Instance of key store",
"name": "__init__",
"signature": "def __init__(self, keystore_obj)"
},
{
"docstring": "Allocate handle to inject or generate key or certificate :param key_id: Key index to set or generate key :param key_part: Key type :para... | 4 | stack_v2_sparse_classes_30k_train_006764 | Implement the Python class `KeyObject` described below.
Class description:
Key object operation
Method signatures and docstrings:
- def __init__(self, keystore_obj): Constructor :param keystore_obj: Instance of key store
- def allocate_handle(self, key_id, key_part, cypher_type, key_len, object_type): Allocate handle... | Implement the Python class `KeyObject` described below.
Class description:
Key object operation
Method signatures and docstrings:
- def __init__(self, keystore_obj): Constructor :param keystore_obj: Instance of key store
- def allocate_handle(self, key_id, key_part, cypher_type, key_len, object_type): Allocate handle... | ab42459602787e9a557c3a00df40b20a52879fc7 | <|skeleton|>
class KeyObject:
"""Key object operation"""
def __init__(self, keystore_obj):
"""Constructor :param keystore_obj: Instance of key store"""
<|body_0|>
def allocate_handle(self, key_id, key_part, cypher_type, key_len, object_type):
"""Allocate handle to inject or generat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KeyObject:
"""Key object operation"""
def __init__(self, keystore_obj):
"""Constructor :param keystore_obj: Instance of key store"""
from . import keystore
if not isinstance(keystore_obj, keystore.KeyStore):
log.error('%s must be an instance of KeyStore', str(keystore)... | the_stack_v2_python_sparse | src/salt/base/state/secure_element/se05x_sss/sss/keyobject.py | autopi-io/autopi-core | train | 141 |
d5e3e884ada5fb6b5f337a0144963a5076229000 | [
"super(NormalizeImage, self).__init__()\nself.mean = mean\nself.std = std\nself.is_scale = is_scale\nif not (isinstance(self.mean, list) and isinstance(self.std, list) and isinstance(self.is_scale, bool)):\n raise TypeError('{}: input type is invalid.'.format(self))\nfrom functools import reduce\nif reduce(lambd... | <|body_start_0|>
super(NormalizeImage, self).__init__()
self.mean = mean
self.std = std
self.is_scale = is_scale
if not (isinstance(self.mean, list) and isinstance(self.std, list) and isinstance(self.is_scale, bool)):
raise TypeError('{}: input type is invalid.'.forma... | NormalizeImage | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NormalizeImage:
def __init__(self, mean=[0.485, 0.456, 0.406], std=[1, 1, 1], is_scale=True):
"""Args: mean (list): the pixel mean std (list): the pixel variance"""
<|body_0|>
def apply(self, sample, context=None):
"""Normalize the image. Operators: 1.(optional) Scal... | stack_v2_sparse_classes_36k_train_033175 | 7,146 | permissive | [
{
"docstring": "Args: mean (list): the pixel mean std (list): the pixel variance",
"name": "__init__",
"signature": "def __init__(self, mean=[0.485, 0.456, 0.406], std=[1, 1, 1], is_scale=True)"
},
{
"docstring": "Normalize the image. Operators: 1.(optional) Scale the image to [0,1] 2. Each pixe... | 2 | stack_v2_sparse_classes_30k_train_021238 | Implement the Python class `NormalizeImage` described below.
Class description:
Implement the NormalizeImage class.
Method signatures and docstrings:
- def __init__(self, mean=[0.485, 0.456, 0.406], std=[1, 1, 1], is_scale=True): Args: mean (list): the pixel mean std (list): the pixel variance
- def apply(self, sampl... | Implement the Python class `NormalizeImage` described below.
Class description:
Implement the NormalizeImage class.
Method signatures and docstrings:
- def __init__(self, mean=[0.485, 0.456, 0.406], std=[1, 1, 1], is_scale=True): Args: mean (list): the pixel mean std (list): the pixel variance
- def apply(self, sampl... | 8042c21b690ffc0162095e749a41b94dd38732da | <|skeleton|>
class NormalizeImage:
def __init__(self, mean=[0.485, 0.456, 0.406], std=[1, 1, 1], is_scale=True):
"""Args: mean (list): the pixel mean std (list): the pixel variance"""
<|body_0|>
def apply(self, sample, context=None):
"""Normalize the image. Operators: 1.(optional) Scal... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NormalizeImage:
def __init__(self, mean=[0.485, 0.456, 0.406], std=[1, 1, 1], is_scale=True):
"""Args: mean (list): the pixel mean std (list): the pixel variance"""
super(NormalizeImage, self).__init__()
self.mean = mean
self.std = std
self.is_scale = is_scale
i... | the_stack_v2_python_sparse | tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/operators.py | PaddlePaddle/models | train | 7,633 | |
580a97a91cabdb1b11a70a8ba9431c7bbf1574dd | [
"res = []\nif not root:\n return res\nstack = [([root], target - root.val)]\nwhile stack:\n path, target = stack.pop()\n root = path[-1]\n if not root.left and (not root.right) and (target == 0):\n res.append([node.val for node in path])\n if root.left:\n stack.append((path + [root.left... | <|body_start_0|>
res = []
if not root:
return res
stack = [([root], target - root.val)]
while stack:
path, target = stack.pop()
root = path[-1]
if not root.left and (not root.right) and (target == 0):
res.append([node.val fo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def pathSum_1(self, root: TreeNode, target: int) -> List[List[int]]:
"""1. 栈,保存节点路径和剩余的值"""
<|body_0|>
def pathSum(self, root: TreeNode, target: int) -> List[List[int]]:
"""2. 栈,保存节点和值列表"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res ... | stack_v2_sparse_classes_36k_train_033176 | 2,326 | no_license | [
{
"docstring": "1. 栈,保存节点路径和剩余的值",
"name": "pathSum_1",
"signature": "def pathSum_1(self, root: TreeNode, target: int) -> List[List[int]]"
},
{
"docstring": "2. 栈,保存节点和值列表",
"name": "pathSum",
"signature": "def pathSum(self, root: TreeNode, target: int) -> List[List[int]]"
}
] | 2 | stack_v2_sparse_classes_30k_train_002615 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum_1(self, root: TreeNode, target: int) -> List[List[int]]: 1. 栈,保存节点路径和剩余的值
- def pathSum(self, root: TreeNode, target: int) -> List[List[int]]: 2. 栈,保存节点和值列表 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum_1(self, root: TreeNode, target: int) -> List[List[int]]: 1. 栈,保存节点路径和剩余的值
- def pathSum(self, root: TreeNode, target: int) -> List[List[int]]: 2. 栈,保存节点和值列表
<|skelet... | 4732fb80710a08a715c3e7080c394f5298b8326d | <|skeleton|>
class Solution:
def pathSum_1(self, root: TreeNode, target: int) -> List[List[int]]:
"""1. 栈,保存节点路径和剩余的值"""
<|body_0|>
def pathSum(self, root: TreeNode, target: int) -> List[List[int]]:
"""2. 栈,保存节点和值列表"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def pathSum_1(self, root: TreeNode, target: int) -> List[List[int]]:
"""1. 栈,保存节点路径和剩余的值"""
res = []
if not root:
return res
stack = [([root], target - root.val)]
while stack:
path, target = stack.pop()
root = path[-1]
... | the_stack_v2_python_sparse | .leetcode/113.路径总和-ii.py | xiaoruijiang/algorithm | train | 0 | |
237efaeea62e6a113d91c6f3fd90a2d66f293ae1 | [
"existing = get_user_model().objects.filter(email__iexact=self.cleaned_data['email'])\nif existing.exists():\n raise forms.ValidationError(self.error_messages['exist_email'], code='exist_email')\nelse:\n return self.cleaned_data['email']",
"data = self.cleaned_data.get(name, None)\nif not data:\n self.cl... | <|body_start_0|>
existing = get_user_model().objects.filter(email__iexact=self.cleaned_data['email'])
if existing.exists():
raise forms.ValidationError(self.error_messages['exist_email'], code='exist_email')
else:
return self.cleaned_data['email']
<|end_body_0|>
<|body_s... | 注册页面表单 | RegistrationForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistrationForm:
"""注册页面表单"""
def clean_email(self):
"""验证电子邮件是否被使用"""
<|body_0|>
def get_and_set_cleaned_data(self, name):
"""获得验证后的数据, 当数据为空时,设置该值为None并返回None"""
<|body_1|>
def clean(self):
"""对表单合法性进行最终验证"""
<|body_2|>
<|end_skel... | stack_v2_sparse_classes_36k_train_033177 | 8,928 | no_license | [
{
"docstring": "验证电子邮件是否被使用",
"name": "clean_email",
"signature": "def clean_email(self)"
},
{
"docstring": "获得验证后的数据, 当数据为空时,设置该值为None并返回None",
"name": "get_and_set_cleaned_data",
"signature": "def get_and_set_cleaned_data(self, name)"
},
{
"docstring": "对表单合法性进行最终验证",
"name... | 3 | stack_v2_sparse_classes_30k_train_003043 | Implement the Python class `RegistrationForm` described below.
Class description:
注册页面表单
Method signatures and docstrings:
- def clean_email(self): 验证电子邮件是否被使用
- def get_and_set_cleaned_data(self, name): 获得验证后的数据, 当数据为空时,设置该值为None并返回None
- def clean(self): 对表单合法性进行最终验证 | Implement the Python class `RegistrationForm` described below.
Class description:
注册页面表单
Method signatures and docstrings:
- def clean_email(self): 验证电子邮件是否被使用
- def get_and_set_cleaned_data(self, name): 获得验证后的数据, 当数据为空时,设置该值为None并返回None
- def clean(self): 对表单合法性进行最终验证
<|skeleton|>
class RegistrationForm:
"""注册页... | d52681a84bc75615dcfd7a373e579833e1ebece8 | <|skeleton|>
class RegistrationForm:
"""注册页面表单"""
def clean_email(self):
"""验证电子邮件是否被使用"""
<|body_0|>
def get_and_set_cleaned_data(self, name):
"""获得验证后的数据, 当数据为空时,设置该值为None并返回None"""
<|body_1|>
def clean(self):
"""对表单合法性进行最终验证"""
<|body_2|>
<|end_skel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegistrationForm:
"""注册页面表单"""
def clean_email(self):
"""验证电子邮件是否被使用"""
existing = get_user_model().objects.filter(email__iexact=self.cleaned_data['email'])
if existing.exists():
raise forms.ValidationError(self.error_messages['exist_email'], code='exist_email')
... | the_stack_v2_python_sparse | citi/apps/account/forms.py | doraemonext/citi | train | 0 |
f982d471fdd28f95a84fbfd0a0f1a8dfa3dedfbd | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.windowsInformationProtectionDesktopApp'.cas... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
try:
mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
except AttributeError:
mapping_value = None
if mapping_value and mapping_value.casefold() ==... | App for Windows information protection | WindowsInformationProtectionApp | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WindowsInformationProtectionApp:
"""App for Windows information protection"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsInformationProtectionApp:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node... | stack_v2_sparse_classes_36k_train_033178 | 4,821 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: WindowsInformationProtectionApp",
"name": "create_from_discriminator_value",
"signature": "def create_from_d... | 3 | null | Implement the Python class `WindowsInformationProtectionApp` described below.
Class description:
App for Windows information protection
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsInformationProtectionApp: Creates a new instance of the approp... | Implement the Python class `WindowsInformationProtectionApp` described below.
Class description:
App for Windows information protection
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsInformationProtectionApp: Creates a new instance of the approp... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class WindowsInformationProtectionApp:
"""App for Windows information protection"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsInformationProtectionApp:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WindowsInformationProtectionApp:
"""App for Windows information protection"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsInformationProtectionApp:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse n... | the_stack_v2_python_sparse | msgraph/generated/models/windows_information_protection_app.py | microsoftgraph/msgraph-sdk-python | train | 135 |
6614603460b8fd51230e57809d6de1dbd62674fb | [
"super(BasicBlock, self).__init__()\nself.expansion = 1\nself.norm1 = ops.BatchNorm2d(planes)\nself.norm2 = ops.BatchNorm2d(planes)\nself.conv1 = ops.Conv2d(inplanes, planes, 3, stride=stride, padding=dilation, dilation=dilation, bias=False)\nself.conv2 = ops.Conv2d(planes, planes, 3, padding=1, bias=False)\nself.r... | <|body_start_0|>
super(BasicBlock, self).__init__()
self.expansion = 1
self.norm1 = ops.BatchNorm2d(planes)
self.norm2 = ops.BatchNorm2d(planes)
self.conv1 = ops.Conv2d(inplanes, planes, 3, stride=stride, padding=dilation, dilation=dilation, bias=False)
self.conv2 = ops.C... | This is the class of BasicBlock block for ResNet. | BasicBlock | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicBlock:
"""This is the class of BasicBlock block for ResNet."""
def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, style='pytorch', with_cp=False):
"""Init BasicBlock."""
<|body_0|>
def call(self, x):
"""Forward compute. :param x: inp... | stack_v2_sparse_classes_36k_train_033179 | 12,928 | permissive | [
{
"docstring": "Init BasicBlock.",
"name": "__init__",
"signature": "def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, style='pytorch', with_cp=False)"
},
{
"docstring": "Forward compute. :param x: input feature map :type x: torch.Tensor :return: output feature map :rty... | 2 | null | Implement the Python class `BasicBlock` described below.
Class description:
This is the class of BasicBlock block for ResNet.
Method signatures and docstrings:
- def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, style='pytorch', with_cp=False): Init BasicBlock.
- def call(self, x): Forward c... | Implement the Python class `BasicBlock` described below.
Class description:
This is the class of BasicBlock block for ResNet.
Method signatures and docstrings:
- def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, style='pytorch', with_cp=False): Init BasicBlock.
- def call(self, x): Forward c... | e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04 | <|skeleton|>
class BasicBlock:
"""This is the class of BasicBlock block for ResNet."""
def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, style='pytorch', with_cp=False):
"""Init BasicBlock."""
<|body_0|>
def call(self, x):
"""Forward compute. :param x: inp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BasicBlock:
"""This is the class of BasicBlock block for ResNet."""
def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, style='pytorch', with_cp=False):
"""Init BasicBlock."""
super(BasicBlock, self).__init__()
self.expansion = 1
self.norm1 = ops.Ba... | the_stack_v2_python_sparse | zeus/networks/necks.py | huawei-noah/xingtian | train | 308 |
43fade2ea45337f9296070f76be96efda1b2913e | [
"self._session = session_obj\nself._ctx_ks = KeyStore(self._session)\nself._ctx_key = KeyObject(self._ctx_ks)\nself.key_type = apis.kSSS_KeyPart_Default\nself.cypher_type = apis.kSSS_CipherType_PCR",
"if pcr_value_init is not None:\n pcr_int_data_len = len(pcr_value_init)\nelse:\n pcr_value_init = []\n p... | <|body_start_0|>
self._session = session_obj
self._ctx_ks = KeyStore(self._session)
self._ctx_key = KeyObject(self._ctx_ks)
self.key_type = apis.kSSS_KeyPart_Default
self.cypher_type = apis.kSSS_CipherType_PCR
<|end_body_0|>
<|body_start_1|>
if pcr_value_init is not None... | PCR Operation | PCR | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PCR:
"""PCR Operation"""
def __init__(self, session_obj):
"""Constructor :param session_obj: Instance of session"""
<|body_0|>
def do_write_pcr(self, key_id, pcr_value_init, pcr_value_update, policy=None):
"""Write PCR :param key_id: Key index :param pcr_value_in... | stack_v2_sparse_classes_36k_train_033180 | 2,656 | permissive | [
{
"docstring": "Constructor :param session_obj: Instance of session",
"name": "__init__",
"signature": "def __init__(self, session_obj)"
},
{
"docstring": "Write PCR :param key_id: Key index :param pcr_value_init: PCR initial value :param pcr_value_update: PCR Updated value :param policy: Policy... | 2 | null | Implement the Python class `PCR` described below.
Class description:
PCR Operation
Method signatures and docstrings:
- def __init__(self, session_obj): Constructor :param session_obj: Instance of session
- def do_write_pcr(self, key_id, pcr_value_init, pcr_value_update, policy=None): Write PCR :param key_id: Key inde... | Implement the Python class `PCR` described below.
Class description:
PCR Operation
Method signatures and docstrings:
- def __init__(self, session_obj): Constructor :param session_obj: Instance of session
- def do_write_pcr(self, key_id, pcr_value_init, pcr_value_update, policy=None): Write PCR :param key_id: Key inde... | ab42459602787e9a557c3a00df40b20a52879fc7 | <|skeleton|>
class PCR:
"""PCR Operation"""
def __init__(self, session_obj):
"""Constructor :param session_obj: Instance of session"""
<|body_0|>
def do_write_pcr(self, key_id, pcr_value_init, pcr_value_update, policy=None):
"""Write PCR :param key_id: Key index :param pcr_value_in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PCR:
"""PCR Operation"""
def __init__(self, session_obj):
"""Constructor :param session_obj: Instance of session"""
self._session = session_obj
self._ctx_ks = KeyStore(self._session)
self._ctx_key = KeyObject(self._ctx_ks)
self.key_type = apis.kSSS_KeyPart_Default
... | the_stack_v2_python_sparse | src/salt/base/state/secure_element/se05x_sss/sss/pcr.py | autopi-io/autopi-core | train | 141 |
353968c3a6343a5c194548a6c34c8e34bf14885a | [
"super(Psi, self).__init__()\nself.in_emb_dims = in_emb_dims\nself.upsamp = nn.UpsamplingBilinear2d(scale_factor=(2, 2))\nself.upsamp_time = nn.UpsamplingBilinear2d(size=(T, 1))\nout_c = min(in_emb_dims)\nself.c1 = nn.Conv2d(in_emb_dims[0], out_c, kernel_size=3, padding='same')\nself.c2 = nn.Conv2d(in_emb_dims[1], ... | <|body_start_0|>
super(Psi, self).__init__()
self.in_emb_dims = in_emb_dims
self.upsamp = nn.UpsamplingBilinear2d(scale_factor=(2, 2))
self.upsamp_time = nn.UpsamplingBilinear2d(size=(T, 1))
out_c = min(in_emb_dims)
self.c1 = nn.Conv2d(in_emb_dims[0], out_c, kernel_size=3... | Convolutional Layers to estimate NMF Activations from Classifier Representations Arguments --------- n_comp : int Number of NMF components (or equivalently number of neurons at the output per timestep) T: int The targeted length along the time dimension in_emb_dims: List with int elements A list with length 3 that cont... | Psi | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-permissive"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Psi:
"""Convolutional Layers to estimate NMF Activations from Classifier Representations Arguments --------- n_comp : int Number of NMF components (or equivalently number of neurons at the output per timestep) T: int The targeted length along the time dimension in_emb_dims: List with int elements... | stack_v2_sparse_classes_36k_train_033181 | 11,147 | permissive | [
{
"docstring": "Computes NMF activations given classifier hidden representations",
"name": "__init__",
"signature": "def __init__(self, n_comp=100, T=431, in_emb_dims=[2048, 1024, 512])"
},
{
"docstring": "This forward function returns the NMF time activations given classifier activations Argume... | 2 | stack_v2_sparse_classes_30k_test_000780 | Implement the Python class `Psi` described below.
Class description:
Convolutional Layers to estimate NMF Activations from Classifier Representations Arguments --------- n_comp : int Number of NMF components (or equivalently number of neurons at the output per timestep) T: int The targeted length along the time dimens... | Implement the Python class `Psi` described below.
Class description:
Convolutional Layers to estimate NMF Activations from Classifier Representations Arguments --------- n_comp : int Number of NMF components (or equivalently number of neurons at the output per timestep) T: int The targeted length along the time dimens... | 92acc188d3a0f634de58463b6676e70df83ef808 | <|skeleton|>
class Psi:
"""Convolutional Layers to estimate NMF Activations from Classifier Representations Arguments --------- n_comp : int Number of NMF components (or equivalently number of neurons at the output per timestep) T: int The targeted length along the time dimension in_emb_dims: List with int elements... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Psi:
"""Convolutional Layers to estimate NMF Activations from Classifier Representations Arguments --------- n_comp : int Number of NMF components (or equivalently number of neurons at the output per timestep) T: int The targeted length along the time dimension in_emb_dims: List with int elements A list with ... | the_stack_v2_python_sparse | PyTorch/dev/perf/speechbrain-tdnn/speechbrain/lobes/models/L2I.py | Ascend/ModelZoo-PyTorch | train | 23 |
40a96bfe0a1328d123da5121b4fac09389faa053 | [
"if token_cache is None:\n token_cache = JSONFileCache(self._SSO_TOKEN_CACHE_DIR)\nself._token_cache = token_cache\nif cache is None:\n cache = {}\nself.cache = cache\nself._load_config = load_config\nself._client_creator = client_creator\nself._profile_name = profile_name",
"loaded_config = self._load_conf... | <|body_start_0|>
if token_cache is None:
token_cache = JSONFileCache(self._SSO_TOKEN_CACHE_DIR)
self._token_cache = token_cache
if cache is None:
cache = {}
self.cache = cache
self._load_config = load_config
self._client_creator = client_creator
... | AWS SSO credential provider. | SSOProvider | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SSOProvider:
"""AWS SSO credential provider."""
def __init__(self, load_config, client_creator, profile_name, cache=None, token_cache=None):
"""Instantiate class."""
<|body_0|>
def _load_sso_config(self):
"""Load sso config."""
<|body_1|>
def load(se... | stack_v2_sparse_classes_36k_train_033182 | 11,021 | permissive | [
{
"docstring": "Instantiate class.",
"name": "__init__",
"signature": "def __init__(self, load_config, client_creator, profile_name, cache=None, token_cache=None)"
},
{
"docstring": "Load sso config.",
"name": "_load_sso_config",
"signature": "def _load_sso_config(self)"
},
{
"do... | 3 | stack_v2_sparse_classes_30k_train_013551 | Implement the Python class `SSOProvider` described below.
Class description:
AWS SSO credential provider.
Method signatures and docstrings:
- def __init__(self, load_config, client_creator, profile_name, cache=None, token_cache=None): Instantiate class.
- def _load_sso_config(self): Load sso config.
- def load(self):... | Implement the Python class `SSOProvider` described below.
Class description:
AWS SSO credential provider.
Method signatures and docstrings:
- def __init__(self, load_config, client_creator, profile_name, cache=None, token_cache=None): Instantiate class.
- def _load_sso_config(self): Load sso config.
- def load(self):... | 0763b06aee07d2cf3f037a49ca0cb81a048c5deb | <|skeleton|>
class SSOProvider:
"""AWS SSO credential provider."""
def __init__(self, load_config, client_creator, profile_name, cache=None, token_cache=None):
"""Instantiate class."""
<|body_0|>
def _load_sso_config(self):
"""Load sso config."""
<|body_1|>
def load(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SSOProvider:
"""AWS SSO credential provider."""
def __init__(self, load_config, client_creator, profile_name, cache=None, token_cache=None):
"""Instantiate class."""
if token_cache is None:
token_cache = JSONFileCache(self._SSO_TOKEN_CACHE_DIR)
self._token_cache = toke... | the_stack_v2_python_sparse | runway/aws_sso_botocore/credentials.py | onicagroup/runway | train | 156 |
3f990c7c8201db9a9fe9032bcfd8804b8710731b | [
"self.time_epoch = time_epoch\nself.time = time\nself.temp_c = temp_c\nself.temp_f = temp_f\nself.is_day = is_day\nself.condition = condition\nself.wind_mph = wind_mph\nself.wind_kph = wind_kph\nself.wind_degree = wind_degree\nself.wind_dir = wind_dir\nself.pressure_mb = pressure_mb\nself.pressure_in = pressure_in\... | <|body_start_0|>
self.time_epoch = time_epoch
self.time = time
self.temp_c = temp_c
self.temp_f = temp_f
self.is_day = is_day
self.condition = condition
self.wind_mph = wind_mph
self.wind_kph = wind_kph
self.wind_degree = wind_degree
self.w... | Implementation of the 'Hour' model. TODO: type model description here. Attributes: time_epoch (int): Time as epoch time (string): Date and time temp_c (float): Temperature in celsius temp_f (float): Temperature in fahrenheit is_day (int): 1 = Yes 0 = No <br />Whether to show day condition icon or night icon condition (... | Hour | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Hour:
"""Implementation of the 'Hour' model. TODO: type model description here. Attributes: time_epoch (int): Time as epoch time (string): Date and time temp_c (float): Temperature in celsius temp_f (float): Temperature in fahrenheit is_day (int): 1 = Yes 0 = No <br />Whether to show day conditio... | stack_v2_sparse_classes_36k_train_033183 | 6,429 | permissive | [
{
"docstring": "Constructor for the Hour class",
"name": "__init__",
"signature": "def __init__(self, time_epoch=None, time=None, temp_c=None, temp_f=None, is_day=None, condition=None, wind_mph=None, wind_kph=None, wind_degree=None, wind_dir=None, pressure_mb=None, pressure_in=None, precip_mm=None, prec... | 2 | stack_v2_sparse_classes_30k_train_002805 | Implement the Python class `Hour` described below.
Class description:
Implementation of the 'Hour' model. TODO: type model description here. Attributes: time_epoch (int): Time as epoch time (string): Date and time temp_c (float): Temperature in celsius temp_f (float): Temperature in fahrenheit is_day (int): 1 = Yes 0 ... | Implement the Python class `Hour` described below.
Class description:
Implementation of the 'Hour' model. TODO: type model description here. Attributes: time_epoch (int): Time as epoch time (string): Date and time temp_c (float): Temperature in celsius temp_f (float): Temperature in fahrenheit is_day (int): 1 = Yes 0 ... | 790588175af26133562e0f7bf714e1de37d5d400 | <|skeleton|>
class Hour:
"""Implementation of the 'Hour' model. TODO: type model description here. Attributes: time_epoch (int): Time as epoch time (string): Date and time temp_c (float): Temperature in celsius temp_f (float): Temperature in fahrenheit is_day (int): 1 = Yes 0 = No <br />Whether to show day conditio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Hour:
"""Implementation of the 'Hour' model. TODO: type model description here. Attributes: time_epoch (int): Time as epoch time (string): Date and time temp_c (float): Temperature in celsius temp_f (float): Temperature in fahrenheit is_day (int): 1 = Yes 0 = No <br />Whether to show day condition icon or nig... | the_stack_v2_python_sparse | py07api/weatherapi-Python-CodeGen-PY/weatherapi/models/hour.py | marcin-se/python-learn | train | 1 |
e6835be5eaa30e8c9bb696db6b2e4f31b40b415d | [
"self.selenium.get(''.join([self.live_server_url, '/portfolio/']))\nself.assertEqual(self.selenium.title, 'Django Website|Portfolio')\nheader_title = self.selenium.find_element_by_tag_name('h1')\nself.assertEqual('Portfolio', header_title.text)\nlinks = self.selenium.find_elements_by_css_selector('#header_portfolio... | <|body_start_0|>
self.selenium.get(''.join([self.live_server_url, '/portfolio/']))
self.assertEqual(self.selenium.title, 'Django Website|Portfolio')
header_title = self.selenium.find_element_by_tag_name('h1')
self.assertEqual('Portfolio', header_title.text)
links = self.selenium.... | Tests for portfolio.html and project.html | BrowsePortfolioTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BrowsePortfolioTests:
"""Tests for portfolio.html and project.html"""
def test_portfolio(self):
"""tests for portfolio page"""
<|body_0|>
def test_project(self):
"""tests for project page"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.sele... | stack_v2_sparse_classes_36k_train_033184 | 3,396 | no_license | [
{
"docstring": "tests for portfolio page",
"name": "test_portfolio",
"signature": "def test_portfolio(self)"
},
{
"docstring": "tests for project page",
"name": "test_project",
"signature": "def test_project(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015336 | Implement the Python class `BrowsePortfolioTests` described below.
Class description:
Tests for portfolio.html and project.html
Method signatures and docstrings:
- def test_portfolio(self): tests for portfolio page
- def test_project(self): tests for project page | Implement the Python class `BrowsePortfolioTests` described below.
Class description:
Tests for portfolio.html and project.html
Method signatures and docstrings:
- def test_portfolio(self): tests for portfolio page
- def test_project(self): tests for project page
<|skeleton|>
class BrowsePortfolioTests:
"""Tests... | 68d6689ec9fb3246c6fb9d2040fe2276281e5de9 | <|skeleton|>
class BrowsePortfolioTests:
"""Tests for portfolio.html and project.html"""
def test_portfolio(self):
"""tests for portfolio page"""
<|body_0|>
def test_project(self):
"""tests for project page"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BrowsePortfolioTests:
"""Tests for portfolio.html and project.html"""
def test_portfolio(self):
"""tests for portfolio page"""
self.selenium.get(''.join([self.live_server_url, '/portfolio/']))
self.assertEqual(self.selenium.title, 'Django Website|Portfolio')
header_title =... | the_stack_v2_python_sparse | websiteapp/portfolioapp/tests.py | JBthePenguin/DjangoWebSite | train | 0 |
f62297ec3132436b7b695756b1f0164b00081209 | [
"self.hass = hass\nself.ip_address = ip_address\nself.dev_id = dev_id\nself._count = config[CONF_PING_COUNT]\nself._ping_cmd = ['ping', '-n', '-q', '-c1', '-W1', ip_address]",
"with subprocess.Popen(self._ping_cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, close_fds=False) as pinger:\n try:\n p... | <|body_start_0|>
self.hass = hass
self.ip_address = ip_address
self.dev_id = dev_id
self._count = config[CONF_PING_COUNT]
self._ping_cmd = ['ping', '-n', '-q', '-c1', '-W1', ip_address]
<|end_body_0|>
<|body_start_1|>
with subprocess.Popen(self._ping_cmd, stdout=subproce... | Host object with ping detection. | HostSubProcess | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HostSubProcess:
"""Host object with ping detection."""
def __init__(self, ip_address: str, dev_id: str, hass: HomeAssistant, config: ConfigType, privileged: bool | None) -> None:
"""Initialize the Host pinger."""
<|body_0|>
def ping(self) -> bool | None:
"""Send ... | stack_v2_sparse_classes_36k_train_033185 | 5,236 | permissive | [
{
"docstring": "Initialize the Host pinger.",
"name": "__init__",
"signature": "def __init__(self, ip_address: str, dev_id: str, hass: HomeAssistant, config: ConfigType, privileged: bool | None) -> None"
},
{
"docstring": "Send an ICMP echo request and return True if success.",
"name": "ping... | 3 | null | Implement the Python class `HostSubProcess` described below.
Class description:
Host object with ping detection.
Method signatures and docstrings:
- def __init__(self, ip_address: str, dev_id: str, hass: HomeAssistant, config: ConfigType, privileged: bool | None) -> None: Initialize the Host pinger.
- def ping(self) ... | Implement the Python class `HostSubProcess` described below.
Class description:
Host object with ping detection.
Method signatures and docstrings:
- def __init__(self, ip_address: str, dev_id: str, hass: HomeAssistant, config: ConfigType, privileged: bool | None) -> None: Initialize the Host pinger.
- def ping(self) ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class HostSubProcess:
"""Host object with ping detection."""
def __init__(self, ip_address: str, dev_id: str, hass: HomeAssistant, config: ConfigType, privileged: bool | None) -> None:
"""Initialize the Host pinger."""
<|body_0|>
def ping(self) -> bool | None:
"""Send ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HostSubProcess:
"""Host object with ping detection."""
def __init__(self, ip_address: str, dev_id: str, hass: HomeAssistant, config: ConfigType, privileged: bool | None) -> None:
"""Initialize the Host pinger."""
self.hass = hass
self.ip_address = ip_address
self.dev_id = ... | the_stack_v2_python_sparse | homeassistant/components/ping/device_tracker.py | home-assistant/core | train | 35,501 |
7380f91b693d8f107dc3531aae1016f08af0926c | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('hxjia_jiahaozh', 'hxjia_jiahaozh')\nurl = 'http://bostonopendata-boston.opendata.arcgis.com/datasets/7a7aca614ad740e99b060e0ee787a228_3.csv'\nbl = pd.read_csv(url)\nnew_bl = pd.DataFrame({'Name': bl['Nam... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('hxjia_jiahaozh', 'hxjia_jiahaozh')
url = 'http://bostonopendata-boston.opendata.arcgis.com/datasets/7a7aca614ad740e99b060e0ee787a228_3.csv'
bl = p... | Get_Boston_Landmark | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Get_Boston_Landmark:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing ever... | stack_v2_sparse_classes_36k_train_033186 | 4,333 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | stack_v2_sparse_classes_30k_train_017324 | Implement the Python class `Get_Boston_Landmark` described below.
Class description:
Implement the Get_Boston_Landmark class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), start... | Implement the Python class `Get_Boston_Landmark` described below.
Class description:
Implement the Get_Boston_Landmark class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), start... | 90284cf3debbac36eead07b8d2339cdd191b86cf | <|skeleton|>
class Get_Boston_Landmark:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing ever... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Get_Boston_Landmark:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('hxjia_jiahaozh', 'hxjia_jiahaoz... | the_stack_v2_python_sparse | hxjia_jiahaozh/Get_Boston_Landmark.py | maximega/course-2019-spr-proj | train | 2 | |
f36c00e47483e93eacd027b61f423e1e87887a6b | [
"self.device = device\nself.device_entry = device_entry\nsuper().__init__(hass, LOGGER, name=device.name, update_interval=update_interval)",
"try:\n return await self.device.async_get_data()\nexcept UpnpCommunicationError as exception:\n LOGGER.debug('Caught exception when updating device: %s, exception: %s... | <|body_start_0|>
self.device = device
self.device_entry = device_entry
super().__init__(hass, LOGGER, name=device.name, update_interval=update_interval)
<|end_body_0|>
<|body_start_1|>
try:
return await self.device.async_get_data()
except UpnpCommunicationError as ex... | Define an object to update data from UPNP device. | UpnpDataUpdateCoordinator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpnpDataUpdateCoordinator:
"""Define an object to update data from UPNP device."""
def __init__(self, hass: HomeAssistant, device: Device, device_entry: DeviceEntry, update_interval: timedelta) -> None:
"""Initialize."""
<|body_0|>
async def _async_update_data(self) -> d... | stack_v2_sparse_classes_36k_train_033187 | 1,540 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, device: Device, device_entry: DeviceEntry, update_interval: timedelta) -> None"
},
{
"docstring": "Update data.",
"name": "_async_update_data",
"signature": "async def _async_update_da... | 2 | stack_v2_sparse_classes_30k_train_004119 | Implement the Python class `UpnpDataUpdateCoordinator` described below.
Class description:
Define an object to update data from UPNP device.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, device: Device, device_entry: DeviceEntry, update_interval: timedelta) -> None: Initialize.
- async d... | Implement the Python class `UpnpDataUpdateCoordinator` described below.
Class description:
Define an object to update data from UPNP device.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, device: Device, device_entry: DeviceEntry, update_interval: timedelta) -> None: Initialize.
- async d... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class UpnpDataUpdateCoordinator:
"""Define an object to update data from UPNP device."""
def __init__(self, hass: HomeAssistant, device: Device, device_entry: DeviceEntry, update_interval: timedelta) -> None:
"""Initialize."""
<|body_0|>
async def _async_update_data(self) -> d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpnpDataUpdateCoordinator:
"""Define an object to update data from UPNP device."""
def __init__(self, hass: HomeAssistant, device: Device, device_entry: DeviceEntry, update_interval: timedelta) -> None:
"""Initialize."""
self.device = device
self.device_entry = device_entry
... | the_stack_v2_python_sparse | homeassistant/components/upnp/coordinator.py | home-assistant/core | train | 35,501 |
956f48cde8a0a5351b9aebef0bb33400c9549ac6 | [
"self.get_players()\nself.setup_player(self.player1)\nself.setup_player(self.player2)",
"clear_screen()\nprint('Welcome to the Battleship game. You need two players. \\nPlease give the name of the first player:')\nself.player1 = Player()\nprint(\"Thank you. So {} is playing.\\nNow please provide the second player... | <|body_start_0|>
self.get_players()
self.setup_player(self.player1)
self.setup_player(self.player2)
<|end_body_0|>
<|body_start_1|>
clear_screen()
print('Welcome to the Battleship game. You need two players. \nPlease give the name of the first player:')
self.player1 = Pl... | Initiation of the Game Class starts the Battleship Game | Game | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Game:
"""Initiation of the Game Class starts the Battleship Game"""
def setup(self):
"""This methods sets up the game."""
<|body_0|>
def get_players(self):
"""This gets the names of the players and prompts them to continue into the single player setup for both pl... | stack_v2_sparse_classes_36k_train_033188 | 2,637 | no_license | [
{
"docstring": "This methods sets up the game.",
"name": "setup",
"signature": "def setup(self)"
},
{
"docstring": "This gets the names of the players and prompts them to continue into the single player setup for both players.",
"name": "get_players",
"signature": "def get_players(self)"... | 6 | stack_v2_sparse_classes_30k_train_015187 | Implement the Python class `Game` described below.
Class description:
Initiation of the Game Class starts the Battleship Game
Method signatures and docstrings:
- def setup(self): This methods sets up the game.
- def get_players(self): This gets the names of the players and prompts them to continue into the single pla... | Implement the Python class `Game` described below.
Class description:
Initiation of the Game Class starts the Battleship Game
Method signatures and docstrings:
- def setup(self): This methods sets up the game.
- def get_players(self): This gets the names of the players and prompts them to continue into the single pla... | 8bfbba09132b405f7c68cbfd9a0e7596223c3a53 | <|skeleton|>
class Game:
"""Initiation of the Game Class starts the Battleship Game"""
def setup(self):
"""This methods sets up the game."""
<|body_0|>
def get_players(self):
"""This gets the names of the players and prompts them to continue into the single player setup for both pl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Game:
"""Initiation of the Game Class starts the Battleship Game"""
def setup(self):
"""This methods sets up the game."""
self.get_players()
self.setup_player(self.player1)
self.setup_player(self.player2)
def get_players(self):
"""This gets the names of the pl... | the_stack_v2_python_sparse | project02_python_battleshipgame/game.py | sabinem/treehouse-python-techdegree | train | 3 |
148b09c773b11db25aedab8fca0c32ee0b0d063b | [
"message = ugettext('Deleted')\nself.body = message\nself.deleted_on = timezone.now()",
"message = _('%(user)s mentionned you on document <a href=\"%(url)s\">%(doc)s</a> (revision %(revision)02d)') % {'user': self.author.name, 'url': self.document.get_absolute_url(), 'doc': self.document.document_key, 'revision':... | <|body_start_0|>
message = ugettext('Deleted')
self.body = message
self.deleted_on = timezone.now()
<|end_body_0|>
<|body_start_1|>
message = _('%(user)s mentionned you on document <a href="%(url)s">%(doc)s</a> (revision %(revision)02d)') % {'user': self.author.name, 'url': self.documen... | A single message in a discussion thread. Discussion threads are for a single revision under review, and limited to the member of the distribution list. | Note | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Note:
"""A single message in a discussion thread. Discussion threads are for a single revision under review, and limited to the member of the distribution list."""
def soft_delete(self):
"""Mark object as deleted, but keep in db. Discussion items should no be really deleted, as it co... | stack_v2_sparse_classes_36k_train_033189 | 2,471 | permissive | [
{
"docstring": "Mark object as deleted, but keep in db. Discussion items should no be really deleted, as it could cause confusion and change the meaning of existing discussion threads. Instead, we just mark the item as deleted, and show an empty message.",
"name": "soft_delete",
"signature": "def soft_d... | 3 | null | Implement the Python class `Note` described below.
Class description:
A single message in a discussion thread. Discussion threads are for a single revision under review, and limited to the member of the distribution list.
Method signatures and docstrings:
- def soft_delete(self): Mark object as deleted, but keep in d... | Implement the Python class `Note` described below.
Class description:
A single message in a discussion thread. Discussion threads are for a single revision under review, and limited to the member of the distribution list.
Method signatures and docstrings:
- def soft_delete(self): Mark object as deleted, but keep in d... | 60ff6f37778971ae356c5b2b20e0d174a8288bfe | <|skeleton|>
class Note:
"""A single message in a discussion thread. Discussion threads are for a single revision under review, and limited to the member of the distribution list."""
def soft_delete(self):
"""Mark object as deleted, but keep in db. Discussion items should no be really deleted, as it co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Note:
"""A single message in a discussion thread. Discussion threads are for a single revision under review, and limited to the member of the distribution list."""
def soft_delete(self):
"""Mark object as deleted, but keep in db. Discussion items should no be really deleted, as it could cause con... | the_stack_v2_python_sparse | src/discussion/models.py | Talengi/phase | train | 8 |
7b2370e4b0f035ebc56231189247cc430a484900 | [
"soup = BeautifulSoup(html, 'lxml')\ncontent = soup.find('section', id='mediacontentstory')\ntitle = content.find('h1', class_='headline').text.strip()\nif parse_datetime:\n credit = content.find('div', class_='credit')\n date_string = credit.find('abbr').text.strip()\n try:\n published_datetime = d... | <|body_start_0|>
soup = BeautifulSoup(html, 'lxml')
content = soup.find('section', id='mediacontentstory')
title = content.find('h1', class_='headline').text.strip()
if parse_datetime:
credit = content.find('div', class_='credit')
date_string = credit.find('abbr')... | Parsing HTML articles from Yahoo Finance. | ArticleParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArticleParser:
"""Parsing HTML articles from Yahoo Finance."""
def native_yahoo(self, html, parse_datetime=False):
"""Parse a native yahoo finance article."""
<|body_0|>
def __yahoo_parse_text(self, content):
"""Edit article text to suitable format."""
<|... | stack_v2_sparse_classes_36k_train_033190 | 2,284 | no_license | [
{
"docstring": "Parse a native yahoo finance article.",
"name": "native_yahoo",
"signature": "def native_yahoo(self, html, parse_datetime=False)"
},
{
"docstring": "Edit article text to suitable format.",
"name": "__yahoo_parse_text",
"signature": "def __yahoo_parse_text(self, content)"
... | 2 | stack_v2_sparse_classes_30k_train_014340 | Implement the Python class `ArticleParser` described below.
Class description:
Parsing HTML articles from Yahoo Finance.
Method signatures and docstrings:
- def native_yahoo(self, html, parse_datetime=False): Parse a native yahoo finance article.
- def __yahoo_parse_text(self, content): Edit article text to suitable ... | Implement the Python class `ArticleParser` described below.
Class description:
Parsing HTML articles from Yahoo Finance.
Method signatures and docstrings:
- def native_yahoo(self, html, parse_datetime=False): Parse a native yahoo finance article.
- def __yahoo_parse_text(self, content): Edit article text to suitable ... | 1c01ee715fab44a09d953eb9955ec0ad228b3289 | <|skeleton|>
class ArticleParser:
"""Parsing HTML articles from Yahoo Finance."""
def native_yahoo(self, html, parse_datetime=False):
"""Parse a native yahoo finance article."""
<|body_0|>
def __yahoo_parse_text(self, content):
"""Edit article text to suitable format."""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArticleParser:
"""Parsing HTML articles from Yahoo Finance."""
def native_yahoo(self, html, parse_datetime=False):
"""Parse a native yahoo finance article."""
soup = BeautifulSoup(html, 'lxml')
content = soup.find('section', id='mediacontentstory')
title = content.find('h1... | the_stack_v2_python_sparse | DataGetter/src/classes/ArticleParser.py | jontesek/mendelu-finance-analyzer | train | 0 |
f4a970bfe22b3238cbe37aca7bab7b56f3cc7a4a | [
"if not request.user.is_active:\n return Response({'status': 'UNAUTHORIZED', 'message': 'Requesting user is no longer active.'}, status=status.HTTP_401_UNAUTHORIZED)\nqueryset = Recipe.objects.filter(account=request.user)\nserializer = RecipeSerializer(queryset, many=True)\nretData = [dict(id=x.get('id'), name=x... | <|body_start_0|>
if not request.user.is_active:
return Response({'status': 'UNAUTHORIZED', 'message': 'Requesting user is no longer active.'}, status=status.HTTP_401_UNAUTHORIZED)
queryset = Recipe.objects.filter(account=request.user)
serializer = RecipeSerializer(queryset, many=True... | Handle requests for CRUD opts on recipes | RecipeViewSet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecipeViewSet:
"""Handle requests for CRUD opts on recipes"""
def list(self, request):
"""List all of a user's recipes. Only return the ID and the name. While this may seem initially uneeded, as the number of recipes grows limiting data will be important."""
<|body_0|>
d... | stack_v2_sparse_classes_36k_train_033191 | 4,760 | permissive | [
{
"docstring": "List all of a user's recipes. Only return the ID and the name. While this may seem initially uneeded, as the number of recipes grows limiting data will be important.",
"name": "list",
"signature": "def list(self, request)"
},
{
"docstring": "Get all the specifics of a recipe.",
... | 5 | stack_v2_sparse_classes_30k_train_002648 | Implement the Python class `RecipeViewSet` described below.
Class description:
Handle requests for CRUD opts on recipes
Method signatures and docstrings:
- def list(self, request): List all of a user's recipes. Only return the ID and the name. While this may seem initially uneeded, as the number of recipes grows limi... | Implement the Python class `RecipeViewSet` described below.
Class description:
Handle requests for CRUD opts on recipes
Method signatures and docstrings:
- def list(self, request): List all of a user's recipes. Only return the ID and the name. While this may seem initially uneeded, as the number of recipes grows limi... | 6d0a31f021755425d420394d84aa7250f86f5ebe | <|skeleton|>
class RecipeViewSet:
"""Handle requests for CRUD opts on recipes"""
def list(self, request):
"""List all of a user's recipes. Only return the ID and the name. While this may seem initially uneeded, as the number of recipes grows limiting data will be important."""
<|body_0|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RecipeViewSet:
"""Handle requests for CRUD opts on recipes"""
def list(self, request):
"""List all of a user's recipes. Only return the ID and the name. While this may seem initially uneeded, as the number of recipes grows limiting data will be important."""
if not request.user.is_active:... | the_stack_v2_python_sparse | brew_journal/recipies/views.py | moonboy13/brew-journal | train | 0 |
9cf7479ac7893d4c1e9b1041b07c465c6840fb3e | [
"with h5py.File(file_name, 'w') as f:\n f.attrs['name'] = self.name\n f.attrs['description'] = self.description\n f.attrs['interpolation_degree'] = self.interpolation_degree\n f.attrs['spline_smoothing_factor'] = self.spline_smoothing_factor\n f.create_dataset('energies', data=self.energies, compress... | <|body_start_0|>
with h5py.File(file_name, 'w') as f:
f.attrs['name'] = self.name
f.attrs['description'] = self.description
f.attrs['interpolation_degree'] = self.interpolation_degree
f.attrs['spline_smoothing_factor'] = self.spline_smoothing_factor
f.... | simple container to read and write the data to an hdf5 file | TemplateFile | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TemplateFile:
"""simple container to read and write the data to an hdf5 file"""
def save(self, file_name: str):
"""serialize the contents to a file :param file_name: :type file_name: str :returns:"""
<|body_0|>
def from_file(cls, file_name: str):
"""read contents... | stack_v2_sparse_classes_36k_train_033192 | 30,788 | permissive | [
{
"docstring": "serialize the contents to a file :param file_name: :type file_name: str :returns:",
"name": "save",
"signature": "def save(self, file_name: str)"
},
{
"docstring": "read contents from a file :param cls: :type cls: :param file_name: :type file_name: str :returns:",
"name": "fr... | 2 | stack_v2_sparse_classes_30k_test_000620 | Implement the Python class `TemplateFile` described below.
Class description:
simple container to read and write the data to an hdf5 file
Method signatures and docstrings:
- def save(self, file_name: str): serialize the contents to a file :param file_name: :type file_name: str :returns:
- def from_file(cls, file_name... | Implement the Python class `TemplateFile` described below.
Class description:
simple container to read and write the data to an hdf5 file
Method signatures and docstrings:
- def save(self, file_name: str): serialize the contents to a file :param file_name: :type file_name: str :returns:
- def from_file(cls, file_name... | 1ffa3f8d9f5459fa181864e91eab6cb1945c69c7 | <|skeleton|>
class TemplateFile:
"""simple container to read and write the data to an hdf5 file"""
def save(self, file_name: str):
"""serialize the contents to a file :param file_name: :type file_name: str :returns:"""
<|body_0|>
def from_file(cls, file_name: str):
"""read contents... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TemplateFile:
"""simple container to read and write the data to an hdf5 file"""
def save(self, file_name: str):
"""serialize the contents to a file :param file_name: :type file_name: str :returns:"""
with h5py.File(file_name, 'w') as f:
f.attrs['name'] = self.name
... | the_stack_v2_python_sparse | astromodels/functions/template_model.py | threeML/astromodels | train | 30 |
17bd9e791118ca7532b5366c5a30cdf06b6bbb46 | [
"releases = self.client.nlst()\nreleases = [x.lstrip('UDRI') for x in releases if x.startswith('UDRI')]\nreleases = sorted(releases)\nself.release = releases[-1]",
"try:\n current_release = self.src_doc.get('download', {}).get('release')\nexcept:\n current_release = False\nif not current_release or int(self... | <|body_start_0|>
releases = self.client.nlst()
releases = [x.lstrip('UDRI') for x in releases if x.startswith('UDRI')]
releases = sorted(releases)
self.release = releases[-1]
<|end_body_0|>
<|body_start_1|>
try:
current_release = self.src_doc.get('download', {}).get(... | Unichem_biothings_sdkDumper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Unichem_biothings_sdkDumper:
def get_newest_info(self):
"""Get the release number of the most recent dump directory"""
<|body_0|>
def new_release_available(self):
"""Determine if newest release needs to be downloaded"""
<|body_1|>
def create_todump_list(... | stack_v2_sparse_classes_36k_train_033193 | 2,713 | permissive | [
{
"docstring": "Get the release number of the most recent dump directory",
"name": "get_newest_info",
"signature": "def get_newest_info(self)"
},
{
"docstring": "Determine if newest release needs to be downloaded",
"name": "new_release_available",
"signature": "def new_release_available(... | 4 | null | Implement the Python class `Unichem_biothings_sdkDumper` described below.
Class description:
Implement the Unichem_biothings_sdkDumper class.
Method signatures and docstrings:
- def get_newest_info(self): Get the release number of the most recent dump directory
- def new_release_available(self): Determine if newest r... | Implement the Python class `Unichem_biothings_sdkDumper` described below.
Class description:
Implement the Unichem_biothings_sdkDumper class.
Method signatures and docstrings:
- def get_newest_info(self): Get the release number of the most recent dump directory
- def new_release_available(self): Determine if newest r... | 42ff7cf8091e8efaaff92cb37afb3c95fbf688b4 | <|skeleton|>
class Unichem_biothings_sdkDumper:
def get_newest_info(self):
"""Get the release number of the most recent dump directory"""
<|body_0|>
def new_release_available(self):
"""Determine if newest release needs to be downloaded"""
<|body_1|>
def create_todump_list(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Unichem_biothings_sdkDumper:
def get_newest_info(self):
"""Get the release number of the most recent dump directory"""
releases = self.client.nlst()
releases = [x.lstrip('UDRI') for x in releases if x.startswith('UDRI')]
releases = sorted(releases)
self.release = releas... | the_stack_v2_python_sparse | src/hub/dataload/sources/unichem/dump.py | biothings/mychem.info | train | 14 | |
e075372cc751608e976f3158ff9fc191014742a3 | [
"super(TempMediaMixin, self).setup_test_environment()\nsettings._original_media_root = settings.MEDIA_ROOT\nsettings._original_file_storage = settings.DEFAULT_FILE_STORAGE\nself._temp_media = tempfile.mkdtemp()\nsettings.MEDIA_ROOT = self._temp_media\nsettings.DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileS... | <|body_start_0|>
super(TempMediaMixin, self).setup_test_environment()
settings._original_media_root = settings.MEDIA_ROOT
settings._original_file_storage = settings.DEFAULT_FILE_STORAGE
self._temp_media = tempfile.mkdtemp()
settings.MEDIA_ROOT = self._temp_media
settings.... | Mixin to create MEDIA_ROOT in temp and tear down when complete. | TempMediaMixin | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TempMediaMixin:
"""Mixin to create MEDIA_ROOT in temp and tear down when complete."""
def setup_test_environment(self):
"""Create temp directory and update MEDIA_ROOT and default storage."""
<|body_0|>
def teardown_test_environment(self):
"""Delete temp storage."... | stack_v2_sparse_classes_36k_train_033194 | 1,207 | permissive | [
{
"docstring": "Create temp directory and update MEDIA_ROOT and default storage.",
"name": "setup_test_environment",
"signature": "def setup_test_environment(self)"
},
{
"docstring": "Delete temp storage.",
"name": "teardown_test_environment",
"signature": "def teardown_test_environment(... | 2 | stack_v2_sparse_classes_30k_train_009581 | Implement the Python class `TempMediaMixin` described below.
Class description:
Mixin to create MEDIA_ROOT in temp and tear down when complete.
Method signatures and docstrings:
- def setup_test_environment(self): Create temp directory and update MEDIA_ROOT and default storage.
- def teardown_test_environment(self): ... | Implement the Python class `TempMediaMixin` described below.
Class description:
Mixin to create MEDIA_ROOT in temp and tear down when complete.
Method signatures and docstrings:
- def setup_test_environment(self): Create temp directory and update MEDIA_ROOT and default storage.
- def teardown_test_environment(self): ... | bb3512caf7c2a6d14f6e0b425d9605b9831fab2d | <|skeleton|>
class TempMediaMixin:
"""Mixin to create MEDIA_ROOT in temp and tear down when complete."""
def setup_test_environment(self):
"""Create temp directory and update MEDIA_ROOT and default storage."""
<|body_0|>
def teardown_test_environment(self):
"""Delete temp storage."... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TempMediaMixin:
"""Mixin to create MEDIA_ROOT in temp and tear down when complete."""
def setup_test_environment(self):
"""Create temp directory and update MEDIA_ROOT and default storage."""
super(TempMediaMixin, self).setup_test_environment()
settings._original_media_root = setti... | the_stack_v2_python_sparse | service_info/runner.py | theirc/ServiceInfo | train | 2 |
a633699ff4bf888ffd3e50e4216654aabe4b0eff | [
"super().__init__(grid_sys, pi_star)\nself.name = 'Epsilon Greedy Controller'\nself.epsilon = epsilon",
"x = y\nif np.random.uniform(0, 1) < self.epsilon:\n u = self.lookup_table_selection(x)\nelse:\n random_index = int(np.random.uniform(0, self.grid_sys.actions_n))\n u = self.grid_sys.input_from_action_... | <|body_start_0|>
super().__init__(grid_sys, pi_star)
self.name = 'Epsilon Greedy Controller'
self.epsilon = epsilon
<|end_body_0|>
<|body_start_1|>
x = y
if np.random.uniform(0, 1) < self.epsilon:
u = self.lookup_table_selection(x)
else:
random_in... | EpsilonGreedyController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EpsilonGreedyController:
def __init__(self, grid_sys, pi_star, epsilon=0.7):
"""Pyro controller based on a discretized lookpup table of optimal control inputs where the optimal action is taken with probability espsilon, else a random action is taken. Parameters ---------- grid_sys : pyro... | stack_v2_sparse_classes_36k_train_033195 | 7,663 | permissive | [
{
"docstring": "Pyro controller based on a discretized lookpup table of optimal control inputs where the optimal action is taken with probability espsilon, else a random action is taken. Parameters ---------- grid_sys : pyro GridDynamicSystem class A discretized dynamic system pi_star : numpy array, dim = self.... | 2 | stack_v2_sparse_classes_30k_train_011740 | Implement the Python class `EpsilonGreedyController` described below.
Class description:
Implement the EpsilonGreedyController class.
Method signatures and docstrings:
- def __init__(self, grid_sys, pi_star, epsilon=0.7): Pyro controller based on a discretized lookpup table of optimal control inputs where the optimal... | Implement the Python class `EpsilonGreedyController` described below.
Class description:
Implement the EpsilonGreedyController class.
Method signatures and docstrings:
- def __init__(self, grid_sys, pi_star, epsilon=0.7): Pyro controller based on a discretized lookpup table of optimal control inputs where the optimal... | baed84610d6090d42b814183931709fcdf61d012 | <|skeleton|>
class EpsilonGreedyController:
def __init__(self, grid_sys, pi_star, epsilon=0.7):
"""Pyro controller based on a discretized lookpup table of optimal control inputs where the optimal action is taken with probability espsilon, else a random action is taken. Parameters ---------- grid_sys : pyro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EpsilonGreedyController:
def __init__(self, grid_sys, pi_star, epsilon=0.7):
"""Pyro controller based on a discretized lookpup table of optimal control inputs where the optimal action is taken with probability espsilon, else a random action is taken. Parameters ---------- grid_sys : pyro GridDynamicSy... | the_stack_v2_python_sparse | dev/reinforcement_learning/rl_tests/reinforcementlearning.py | SherbyRobotics/pyro | train | 35 | |
81152518d7634bb40b1211dd2618335e696f2908 | [
"cnt, currNode = (1, head)\nwhile currNode and cnt < n:\n currNode = currNode.next\n cnt += 1\nif not currNode:\n return None\nnewHead = currNode.next\ncurrNode.next = None\nreturn newHead",
"currNode = preHead\nwhile h1 and h2:\n if h1.val <= h2.val:\n currNode.next, h1 = (h1, h1.next)\n el... | <|body_start_0|>
cnt, currNode = (1, head)
while currNode and cnt < n:
currNode = currNode.next
cnt += 1
if not currNode:
return None
newHead = currNode.next
currNode.next = None
return newHead
<|end_body_0|>
<|body_start_1|>
c... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _cut_list(self, head: ListNode, n: int) -> ListNode:
"""Cut the first n node from head and return the head of the remaining list."""
<|body_0|>
def _merge_list(self, h1: ListNode, h2: ListNode, preHead: ListNode) -> ListNode:
"""Merge two sorted lists a... | stack_v2_sparse_classes_36k_train_033196 | 2,292 | no_license | [
{
"docstring": "Cut the first n node from head and return the head of the remaining list.",
"name": "_cut_list",
"signature": "def _cut_list(self, head: ListNode, n: int) -> ListNode"
},
{
"docstring": "Merge two sorted lists and return the tail of the new list.",
"name": "_merge_list",
... | 3 | stack_v2_sparse_classes_30k_train_010434 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _cut_list(self, head: ListNode, n: int) -> ListNode: Cut the first n node from head and return the head of the remaining list.
- def _merge_list(self, h1: ListNode, h2: ListN... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _cut_list(self, head: ListNode, n: int) -> ListNode: Cut the first n node from head and return the head of the remaining list.
- def _merge_list(self, h1: ListNode, h2: ListN... | edb870f83f0c4568cce0cacec04ee70cf6b545bf | <|skeleton|>
class Solution:
def _cut_list(self, head: ListNode, n: int) -> ListNode:
"""Cut the first n node from head and return the head of the remaining list."""
<|body_0|>
def _merge_list(self, h1: ListNode, h2: ListNode, preHead: ListNode) -> ListNode:
"""Merge two sorted lists a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def _cut_list(self, head: ListNode, n: int) -> ListNode:
"""Cut the first n node from head and return the head of the remaining list."""
cnt, currNode = (1, head)
while currNode and cnt < n:
currNode = currNode.next
cnt += 1
if not currNode:
... | the_stack_v2_python_sparse | 2019/sort_list.py | eronekogin/leetcode | train | 0 | |
5777296b894b4b56347dc16a6290550e3ae30462 | [
"self.desc = desc\nself.time_avg = time_avg\nself.time_dev = time_dev\nself.cv = cv\nself.unit = unit\nself.sample_num = samples",
"if self.sample_num > 1:\n return '{}: {:.5f} σ={:.5f} {} with n={} cv={}'.format(self.desc, self.time_avg, self.time_dev, self.unit, self.sample_num, self.cv)\nelse:\n return '... | <|body_start_0|>
self.desc = desc
self.time_avg = time_avg
self.time_dev = time_dev
self.cv = cv
self.unit = unit
self.sample_num = samples
<|end_body_0|>
<|body_start_1|>
if self.sample_num > 1:
return '{}: {:.5f} σ={:.5f} {} with n={} cv={}'.format(... | LineStats | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LineStats:
def __init__(self, desc: str, unit: str, time_avg: float, time_dev: float, cv: float, samples: int) -> None:
"""A corpus of stats about a particular line from a given test's output. Args: desc (str): Descriptive text of the line in question. unit (str): The units of measure th... | stack_v2_sparse_classes_36k_train_033197 | 13,376 | permissive | [
{
"docstring": "A corpus of stats about a particular line from a given test's output. Args: desc (str): Descriptive text of the line in question. unit (str): The units of measure that the line's result is in. time_avg (float): The average measurement. time_dev (float): The standard deviation of the measurement.... | 2 | null | Implement the Python class `LineStats` described below.
Class description:
Implement the LineStats class.
Method signatures and docstrings:
- def __init__(self, desc: str, unit: str, time_avg: float, time_dev: float, cv: float, samples: int) -> None: A corpus of stats about a particular line from a given test's outpu... | Implement the Python class `LineStats` described below.
Class description:
Implement the LineStats class.
Method signatures and docstrings:
- def __init__(self, desc: str, unit: str, time_avg: float, time_dev: float, cv: float, samples: int) -> None: A corpus of stats about a particular line from a given test's outpu... | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | <|skeleton|>
class LineStats:
def __init__(self, desc: str, unit: str, time_avg: float, time_dev: float, cv: float, samples: int) -> None:
"""A corpus of stats about a particular line from a given test's output. Args: desc (str): Descriptive text of the line in question. unit (str): The units of measure th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LineStats:
def __init__(self, desc: str, unit: str, time_avg: float, time_dev: float, cv: float, samples: int) -> None:
"""A corpus of stats about a particular line from a given test's output. Args: desc (str): Descriptive text of the line in question. unit (str): The units of measure that the line's ... | the_stack_v2_python_sparse | tools/fuchsia/comparative_tester/generate_perf_report.py | chromium/chromium | train | 17,408 | |
fcf047a85d18a87216609c25a5b9e306797de300 | [
"super(NetworksClient, self).__init__(serialize_format, deserialize_format)\nself.auth_token = auth_token\nself.default_headers['X-Auth-Token'] = auth_token\nct = '{content_type}/{content_subtype}'.format(content_type='application', content_subtype=self.serialize_format)\naccept = '{content_type}/{content_subtype}'... | <|body_start_0|>
super(NetworksClient, self).__init__(serialize_format, deserialize_format)
self.auth_token = auth_token
self.default_headers['X-Auth-Token'] = auth_token
ct = '{content_type}/{content_subtype}'.format(content_type='application', content_subtype=self.serialize_format)
... | NetworksClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NetworksClient:
def __init__(self, url, auth_token, serialize_format=None, deserialize_format=None, tenant_id=None):
"""@param url: Base URL for the networks service @type url: string @param auth_token: Auth token to be used for all requests @type auth_token: string @param serialize_form... | stack_v2_sparse_classes_36k_train_033198 | 7,935 | permissive | [
{
"docstring": "@param url: Base URL for the networks service @type url: string @param auth_token: Auth token to be used for all requests @type auth_token: string @param serialize_format: Format for serializing requests @type serialize_format: string @param deserialize_format: Format for de-serializing response... | 6 | stack_v2_sparse_classes_30k_train_009199 | Implement the Python class `NetworksClient` described below.
Class description:
Implement the NetworksClient class.
Method signatures and docstrings:
- def __init__(self, url, auth_token, serialize_format=None, deserialize_format=None, tenant_id=None): @param url: Base URL for the networks service @type url: string @... | Implement the Python class `NetworksClient` described below.
Class description:
Implement the NetworksClient class.
Method signatures and docstrings:
- def __init__(self, url, auth_token, serialize_format=None, deserialize_format=None, tenant_id=None): @param url: Base URL for the networks service @type url: string @... | 7d49cf6bfd7e1a6e5b739e7de52f2e18e5ccf924 | <|skeleton|>
class NetworksClient:
def __init__(self, url, auth_token, serialize_format=None, deserialize_format=None, tenant_id=None):
"""@param url: Base URL for the networks service @type url: string @param auth_token: Auth token to be used for all requests @type auth_token: string @param serialize_form... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NetworksClient:
def __init__(self, url, auth_token, serialize_format=None, deserialize_format=None, tenant_id=None):
"""@param url: Base URL for the networks service @type url: string @param auth_token: Auth token to be used for all requests @type auth_token: string @param serialize_format: Format for... | the_stack_v2_python_sparse | cloudcafe/networking/networks/networks_api/client.py | kurhula/cloudcafe | train | 0 | |
e59c138015eb4cb1bd22d60604ba1e0588687204 | [
"self.root = Node()\nself.m = max(map(len, words))\nself.initials = set([word[0] for word in words])\nl = []\nfor word in words:\n l += list(word)\nself.letters = set(l)\nself.trie = Trie()\nself.stream = ''",
"if letter not in self.letters:\n self.stream = ''\n return False\nif len(self.stream) == 0 and... | <|body_start_0|>
self.root = Node()
self.m = max(map(len, words))
self.initials = set([word[0] for word in words])
l = []
for word in words:
l += list(word)
self.letters = set(l)
self.trie = Trie()
self.stream = ''
<|end_body_0|>
<|body_start_... | StreamChecker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StreamChecker:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def query(self, letter):
""":type letter: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.root = Node()
self.m = max(map(len, words))
... | stack_v2_sparse_classes_36k_train_033199 | 2,195 | no_license | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type letter: str :rtype: bool",
"name": "query",
"signature": "def query(self, letter)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010868 | Implement the Python class `StreamChecker` described below.
Class description:
Implement the StreamChecker class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def query(self, letter): :type letter: str :rtype: bool | Implement the Python class `StreamChecker` described below.
Class description:
Implement the StreamChecker class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def query(self, letter): :type letter: str :rtype: bool
<|skeleton|>
class StreamChecker:
def __init__(self, w... | 0c3ae35908cb6aa73c0962376facbdd750854f48 | <|skeleton|>
class StreamChecker:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def query(self, letter):
""":type letter: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StreamChecker:
def __init__(self, words):
""":type words: List[str]"""
self.root = Node()
self.m = max(map(len, words))
self.initials = set([word[0] for word in words])
l = []
for word in words:
l += list(word)
self.letters = set(l)
s... | the_stack_v2_python_sparse | theory/data_structures/trie/stream_of_characters.py | tHeMaskedMan981/coding_practice | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.