blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b74fb267649690646423689cd5a55a3b2f7629b8 | [
"users = User.objects.filter(Q(username__iexact=username_or_email) | Q(email__iexact=username_or_email))\nif not users:\n return None\nuser = users[0]\nif user.check_password(password):\n return user\nreturn None",
"try:\n user = User.objects.get(pk=user_id)\n if user.is_active:\n return user\n... | <|body_start_0|>
users = User.objects.filter(Q(username__iexact=username_or_email) | Q(email__iexact=username_or_email))
if not users:
return None
user = users[0]
if user.check_password(password):
return user
return None
<|end_body_0|>
<|body_start_1|>
... | Authenticates user using a case insensitive match on username or email. | CaseInsensitiveAuth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CaseInsensitiveAuth:
"""Authenticates user using a case insensitive match on username or email."""
def authenticate(self, username_or_email=None, password=None):
"""Return an instance of User using the supplied username or email (case insensitive) and verify the password."""
... | stack_v2_sparse_classes_75kplus_train_004000 | 1,137 | no_license | [
{
"docstring": "Return an instance of User using the supplied username or email (case insensitive) and verify the password.",
"name": "authenticate",
"signature": "def authenticate(self, username_or_email=None, password=None)"
},
{
"docstring": "Used by the Django authentication system to retrie... | 2 | stack_v2_sparse_classes_30k_train_012464 | Implement the Python class `CaseInsensitiveAuth` described below.
Class description:
Authenticates user using a case insensitive match on username or email.
Method signatures and docstrings:
- def authenticate(self, username_or_email=None, password=None): Return an instance of User using the supplied username or emai... | Implement the Python class `CaseInsensitiveAuth` described below.
Class description:
Authenticates user using a case insensitive match on username or email.
Method signatures and docstrings:
- def authenticate(self, username_or_email=None, password=None): Return an instance of User using the supplied username or emai... | 377146ae7b1f35e178ce64891f38b261eeb04ff1 | <|skeleton|>
class CaseInsensitiveAuth:
"""Authenticates user using a case insensitive match on username or email."""
def authenticate(self, username_or_email=None, password=None):
"""Return an instance of User using the supplied username or email (case insensitive) and verify the password."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CaseInsensitiveAuth:
"""Authenticates user using a case insensitive match on username or email."""
def authenticate(self, username_or_email=None, password=None):
"""Return an instance of User using the supplied username or email (case insensitive) and verify the password."""
users = User.... | the_stack_v2_python_sparse | accounts/backends.py | Code-Institute-Submissions/dashing-data | train | 0 |
f738d5dbf35d5ce8fe261b005b02267ca9569566 | [
"try:\n with open(run_file, 'r') as f:\n run_json = json.load(f)\nexcept:\n print('Problem decoding {}'.format(run_file))\n run_json = []\nassert isinstance(run_json, list), 'Expecting a list of dictionaries'\nassert all((isinstance(d, dict) for d in run_json)), 'Expecting only dictionaries'\nself.j... | <|body_start_0|>
try:
with open(run_file, 'r') as f:
run_json = json.load(f)
except:
print('Problem decoding {}'.format(run_file))
run_json = []
assert isinstance(run_json, list), 'Expecting a list of dictionaries'
assert all((isinstanc... | Utility class to mediate between JSON log file and parameter dictionary | JSONLog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JSONLog:
"""Utility class to mediate between JSON log file and parameter dictionary"""
def __init__(self, run_file, keys=[], parameters='parameters'):
"""run_file: log file name, typically 'run.#.json' keys: to be retrieved from JSON files parameters: typically 'parameters', expectin... | stack_v2_sparse_classes_75kplus_train_004001 | 17,591 | no_license | [
{
"docstring": "run_file: log file name, typically 'run.#.json' keys: to be retrieved from JSON files parameters: typically 'parameters', expecting a list of strings which receive special treatment, each gets parsed into {key:value}",
"name": "__init__",
"signature": "def __init__(self, run_file, keys=[... | 4 | null | Implement the Python class `JSONLog` described below.
Class description:
Utility class to mediate between JSON log file and parameter dictionary
Method signatures and docstrings:
- def __init__(self, run_file, keys=[], parameters='parameters'): run_file: log file name, typically 'run.#.json' keys: to be retrieved fro... | Implement the Python class `JSONLog` described below.
Class description:
Utility class to mediate between JSON log file and parameter dictionary
Method signatures and docstrings:
- def __init__(self, run_file, keys=[], parameters='parameters'): run_file: log file name, typically 'run.#.json' keys: to be retrieved fro... | eb9ad22297119c76a345c2cfb9a0519e27ec7eaa | <|skeleton|>
class JSONLog:
"""Utility class to mediate between JSON log file and parameter dictionary"""
def __init__(self, run_file, keys=[], parameters='parameters'):
"""run_file: log file name, typically 'run.#.json' keys: to be retrieved from JSON files parameters: typically 'parameters', expectin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JSONLog:
"""Utility class to mediate between JSON log file and parameter dictionary"""
def __init__(self, run_file, keys=[], parameters='parameters'):
"""run_file: log file name, typically 'run.#.json' keys: to be retrieved from JSON files parameters: typically 'parameters', expecting a list of s... | the_stack_v2_python_sparse | GPR_Qualitative_Kernel/run_data_old.py | ECP-CANDLE/Scratch | train | 1 |
9ecafeda1118d35d3ee09f56e1e41b27d7971af8 | [
"text = (path / 'config.json').read_text()\ndata = json.loads(text)\nreturn cls(path, URL(data['url']), data['provider'], datetime.datetime.fromisoformat(data['updated']))",
"data = {'url': str(self.url), 'provider': self.provider, 'updated': self.updated.isoformat()}\ntext = json.dumps(data)\n(self.path / 'confi... | <|body_start_0|>
text = (path / 'config.json').read_text()
data = json.loads(text)
return cls(path, URL(data['url']), data['provider'], datetime.datetime.fromisoformat(data['updated']))
<|end_body_0|>
<|body_start_1|>
data = {'url': str(self.url), 'provider': self.provider, 'updated': s... | Record describing the storage for a package repository. | StorageRecord | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StorageRecord:
"""Record describing the storage for a package repository."""
def load(cls, path: pathlib.Path) -> StorageRecord:
"""Deserialize a JSON file to a record."""
<|body_0|>
def dump(self) -> None:
"""Serialize the record to a JSON file."""
<|bod... | stack_v2_sparse_classes_75kplus_train_004002 | 4,432 | permissive | [
{
"docstring": "Deserialize a JSON file to a record.",
"name": "load",
"signature": "def load(cls, path: pathlib.Path) -> StorageRecord"
},
{
"docstring": "Serialize the record to a JSON file.",
"name": "dump",
"signature": "def dump(self) -> None"
}
] | 2 | stack_v2_sparse_classes_30k_train_045502 | Implement the Python class `StorageRecord` described below.
Class description:
Record describing the storage for a package repository.
Method signatures and docstrings:
- def load(cls, path: pathlib.Path) -> StorageRecord: Deserialize a JSON file to a record.
- def dump(self) -> None: Serialize the record to a JSON f... | Implement the Python class `StorageRecord` described below.
Class description:
Record describing the storage for a package repository.
Method signatures and docstrings:
- def load(cls, path: pathlib.Path) -> StorageRecord: Deserialize a JSON file to a record.
- def dump(self) -> None: Serialize the record to a JSON f... | c6b26377153d60d5da825002e03f9a28467378a9 | <|skeleton|>
class StorageRecord:
"""Record describing the storage for a package repository."""
def load(cls, path: pathlib.Path) -> StorageRecord:
"""Deserialize a JSON file to a record."""
<|body_0|>
def dump(self) -> None:
"""Serialize the record to a JSON file."""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StorageRecord:
"""Record describing the storage for a package repository."""
def load(cls, path: pathlib.Path) -> StorageRecord:
"""Deserialize a JSON file to a record."""
text = (path / 'config.json').read_text()
data = json.loads(text)
return cls(path, URL(data['url']), ... | the_stack_v2_python_sparse | src/cutty/packages/adapters/storage.py | cjolowicz/cutty | train | 4 |
b55967d731f3ea8a3b13613a0822efde5c7c7abb | [
"try:\n username = self.apikey_handler.validate(request.query_params['access_key'], request.query_params['secret_key'])\n if username:\n sciper = get_sciper(username)\n schema = Rancher.get_schema(schema_id)\n unit_id = schema['unit_id']\n if Rancher.validate(schema_id, sciper) or ... | <|body_start_0|>
try:
username = self.apikey_handler.validate(request.query_params['access_key'], request.query_params['secret_key'])
if username:
sciper = get_sciper(username)
schema = Rancher.get_schema(schema_id)
unit_id = schema['unit_i... | SchemaDetail | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SchemaDetail:
def get(self, request, schema_id):
"""Return the schema 'schema_id' --- Response messages: - code: 200 message: OK - code: 403 message: Invalid APIKey - code: 403 message: This user isn't allowed to access to the schema - code: 404 message: Access key or secret key no found... | stack_v2_sparse_classes_75kplus_train_004003 | 14,178 | permissive | [
{
"docstring": "Return the schema 'schema_id' --- Response messages: - code: 200 message: OK - code: 403 message: Invalid APIKey - code: 403 message: This user isn't allowed to access to the schema - code: 404 message: Access key or secret key no found",
"name": "get",
"signature": "def get(self, reques... | 3 | stack_v2_sparse_classes_30k_train_048504 | Implement the Python class `SchemaDetail` described below.
Class description:
Implement the SchemaDetail class.
Method signatures and docstrings:
- def get(self, request, schema_id): Return the schema 'schema_id' --- Response messages: - code: 200 message: OK - code: 403 message: Invalid APIKey - code: 403 message: T... | Implement the Python class `SchemaDetail` described below.
Class description:
Implement the SchemaDetail class.
Method signatures and docstrings:
- def get(self, request, schema_id): Return the schema 'schema_id' --- Response messages: - code: 200 message: OK - code: 403 message: Invalid APIKey - code: 403 message: T... | db02f6e0cb0435b84c619dd105b7bee5eafd17e2 | <|skeleton|>
class SchemaDetail:
def get(self, request, schema_id):
"""Return the schema 'schema_id' --- Response messages: - code: 200 message: OK - code: 403 message: Invalid APIKey - code: 403 message: This user isn't allowed to access to the schema - code: 404 message: Access key or secret key no found... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SchemaDetail:
def get(self, request, schema_id):
"""Return the schema 'schema_id' --- Response messages: - code: 200 message: OK - code: 403 message: Invalid APIKey - code: 403 message: This user isn't allowed to access to the schema - code: 404 message: Access key or secret key no found"""
tr... | the_stack_v2_python_sparse | src/api/views.py | epfl-si/amm | train | 3 | |
45cbc2986e39d8e377f4348f4322fa830cd1c9ed | [
"self.num_components = num_components\nself.mixture_weights = list()\nself.component_distributions = list()\nself.expected_component_counts = dict()\nself.expected_observation_counts = dict()\nself.log_likelihood = 0\nself.initialise(initial_mixture_weights, initial_geometric_parameters)",
"if initial_mixture_wei... | <|body_start_0|>
self.num_components = num_components
self.mixture_weights = list()
self.component_distributions = list()
self.expected_component_counts = dict()
self.expected_observation_counts = dict()
self.log_likelihood = 0
self.initialise(initial_mixture_weig... | A geometric mixture model that can be trained using EM | EM | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EM:
"""A geometric mixture model that can be trained using EM"""
def __init__(self, num_components=5, initial_mixture_weights=None, initial_geometric_parameters=None):
"""Constructor :param num_components: The number of mixture components in this model :param initial_mixture_weights:... | stack_v2_sparse_classes_75kplus_train_004004 | 9,378 | no_license | [
{
"docstring": "Constructor :param num_components: The number of mixture components in this model :param initial_mixture_weights: A list of initial mixture weights (weights are initialised randomly if no list is provided) :param initial_geometric_parameters: A list of initial component parameters (initialised r... | 6 | stack_v2_sparse_classes_30k_train_022507 | Implement the Python class `EM` described below.
Class description:
A geometric mixture model that can be trained using EM
Method signatures and docstrings:
- def __init__(self, num_components=5, initial_mixture_weights=None, initial_geometric_parameters=None): Constructor :param num_components: The number of mixture... | Implement the Python class `EM` described below.
Class description:
A geometric mixture model that can be trained using EM
Method signatures and docstrings:
- def __init__(self, num_components=5, initial_mixture_weights=None, initial_geometric_parameters=None): Constructor :param num_components: The number of mixture... | 7bda62bb49f502f1f61f1bc7a5f82fea10e369f2 | <|skeleton|>
class EM:
"""A geometric mixture model that can be trained using EM"""
def __init__(self, num_components=5, initial_mixture_weights=None, initial_geometric_parameters=None):
"""Constructor :param num_components: The number of mixture components in this model :param initial_mixture_weights:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EM:
"""A geometric mixture model that can be trained using EM"""
def __init__(self, num_components=5, initial_mixture_weights=None, initial_geometric_parameters=None):
"""Constructor :param num_components: The number of mixture components in this model :param initial_mixture_weights: A list of in... | the_stack_v2_python_sparse | week5/assesment/two/expectation_maximisation.py | HaukurPall/basic_prob | train | 0 |
01cf05a89820cee3873a3e6beebdf1f591a003c9 | [
"super().__init__()\nself.h_size = h_size\nself.h_size_inner = h_size_inner\nself.encoder_activation = encoder_activation\nself.preembed_size = preembed_size\nself.input_size = input_size\nself.rnn_type = rnn_type\nself.depth = depth\nself.dropout = dropout\nself.node_fdim = node_fdim\nself._build_layers()",
"enc... | <|body_start_0|>
super().__init__()
self.h_size = h_size
self.h_size_inner = h_size_inner
self.encoder_activation = encoder_activation
self.preembed_size = preembed_size
self.input_size = input_size
self.rnn_type = rnn_type
self.depth = depth
self.... | MessagePassing Network based encoder. Messages are updated using an RNN and the final message is used to update atom embeddings. | MPNEncoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MPNEncoder:
"""MessagePassing Network based encoder. Messages are updated using an RNN and the final message is used to update atom embeddings."""
def __init__(self, rnn_type: str, input_size: int, node_fdim: int, h_size: int, h_size_inner: int=None, preembed_size: int=None, depth: int=3, dr... | stack_v2_sparse_classes_75kplus_train_004005 | 31,930 | permissive | [
{
"docstring": "Parameters ---------- rnn_type: str, Type of RNN used (gru/lstm) input_size: int, Input size node_fdim: int, Number of node features h_size: int, Hidden state size depth: int, Number of time steps in the RNN",
"name": "__init__",
"signature": "def __init__(self, rnn_type: str, input_size... | 3 | stack_v2_sparse_classes_30k_train_035320 | Implement the Python class `MPNEncoder` described below.
Class description:
MessagePassing Network based encoder. Messages are updated using an RNN and the final message is used to update atom embeddings.
Method signatures and docstrings:
- def __init__(self, rnn_type: str, input_size: int, node_fdim: int, h_size: in... | Implement the Python class `MPNEncoder` described below.
Class description:
MessagePassing Network based encoder. Messages are updated using an RNN and the final message is used to update atom embeddings.
Method signatures and docstrings:
- def __init__(self, rnn_type: str, input_size: int, node_fdim: int, h_size: in... | 8480822d0d8ad74e46edf693ad1cdc787291f422 | <|skeleton|>
class MPNEncoder:
"""MessagePassing Network based encoder. Messages are updated using an RNN and the final message is used to update atom embeddings."""
def __init__(self, rnn_type: str, input_size: int, node_fdim: int, h_size: int, h_size_inner: int=None, preembed_size: int=None, depth: int=3, dr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MPNEncoder:
"""MessagePassing Network based encoder. Messages are updated using an RNN and the final message is used to update atom embeddings."""
def __init__(self, rnn_type: str, input_size: int, node_fdim: int, h_size: int, h_size_inner: int=None, preembed_size: int=None, depth: int=3, dropout: float=... | the_stack_v2_python_sparse | rxnebm/model/G2E.py | rnaimehaom/rxn-ebm | train | 0 |
39286c7d7d038c205e614719750c8cf1ac45a85d | [
"super().__init__(count_per_class)\nself.confidence_channel = confidence_channel\nself.search_count_multiplier = search_count_multiplier\nself.search_proportion = search_proportion\nassert search_count_multiplier is None or search_proportion is None, f'Cannot specify both search_count_multiplier (={search_count_mul... | <|body_start_0|>
super().__init__(count_per_class)
self.confidence_channel = confidence_channel
self.search_count_multiplier = search_count_multiplier
self.search_proportion = search_proportion
assert search_count_multiplier is None or search_proportion is None, f'Cannot specify ... | Samples DensePose data from DensePose predictions. Samples for each class are drawn using confidence value estimates. | DensePoseConfidenceBasedSampler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DensePoseConfidenceBasedSampler:
"""Samples DensePose data from DensePose predictions. Samples for each class are drawn using confidence value estimates."""
def __init__(self, confidence_channel: str, count_per_class: int=8, search_count_multiplier: Optional[float]=None, search_proportion: O... | stack_v2_sparse_classes_75kplus_train_004006 | 4,801 | permissive | [
{
"docstring": "Constructor Args: confidence_channel (str): confidence channel to use for sampling; possible values: \"sigma_2\": confidences for UV values \"fine_segm_confidence\": confidences for fine segmentation \"coarse_segm_confidence\": confidences for coarse segmentation (default: \"sigma_2\") count_per... | 3 | stack_v2_sparse_classes_30k_train_014916 | Implement the Python class `DensePoseConfidenceBasedSampler` described below.
Class description:
Samples DensePose data from DensePose predictions. Samples for each class are drawn using confidence value estimates.
Method signatures and docstrings:
- def __init__(self, confidence_channel: str, count_per_class: int=8,... | Implement the Python class `DensePoseConfidenceBasedSampler` described below.
Class description:
Samples DensePose data from DensePose predictions. Samples for each class are drawn using confidence value estimates.
Method signatures and docstrings:
- def __init__(self, confidence_channel: str, count_per_class: int=8,... | 80307d2d5e06f06a8a677cc2653f23a4c56402ac | <|skeleton|>
class DensePoseConfidenceBasedSampler:
"""Samples DensePose data from DensePose predictions. Samples for each class are drawn using confidence value estimates."""
def __init__(self, confidence_channel: str, count_per_class: int=8, search_count_multiplier: Optional[float]=None, search_proportion: O... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DensePoseConfidenceBasedSampler:
"""Samples DensePose data from DensePose predictions. Samples for each class are drawn using confidence value estimates."""
def __init__(self, confidence_channel: str, count_per_class: int=8, search_count_multiplier: Optional[float]=None, search_proportion: Optional[float... | the_stack_v2_python_sparse | projects/DensePose/densepose/data/samplers/densepose_confidence_based.py | facebookresearch/detectron2 | train | 27,469 |
5648299478f8283ce1d66ed093898dbbbe8e8113 | [
"if self.request.validated['tender_status'] == 'active.tendering' and calculate_business_date(get_now(), TENDERING_EXTRA_PERIOD, self.request.validated['tender']) > self.request.validated['tender'].tenderPeriod.endDate:\n raise_operation_error(self.request, 'tenderPeriod should be extended by {0.days} days'.form... | <|body_start_0|>
if self.request.validated['tender_status'] == 'active.tendering' and calculate_business_date(get_now(), TENDERING_EXTRA_PERIOD, self.request.validated['tender']) > self.request.validated['tender'].tenderPeriod.endDate:
raise_operation_error(self.request, 'tenderPeriod should be exte... | TenderUaDocumentResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TenderUaDocumentResource:
def validate_update_tender(self):
"""TODO move validators This class is inherited in cd stage 2 package, but validate_update_tender function has different validators. For now, we have no way to use different validators on methods according to procedure type."""
... | stack_v2_sparse_classes_75kplus_train_004007 | 5,027 | permissive | [
{
"docstring": "TODO move validators This class is inherited in cd stage 2 package, but validate_update_tender function has different validators. For now, we have no way to use different validators on methods according to procedure type.",
"name": "validate_update_tender",
"signature": "def validate_upd... | 4 | stack_v2_sparse_classes_30k_train_051194 | Implement the Python class `TenderUaDocumentResource` described below.
Class description:
Implement the TenderUaDocumentResource class.
Method signatures and docstrings:
- def validate_update_tender(self): TODO move validators This class is inherited in cd stage 2 package, but validate_update_tender function has diff... | Implement the Python class `TenderUaDocumentResource` described below.
Class description:
Implement the TenderUaDocumentResource class.
Method signatures and docstrings:
- def validate_update_tender(self): TODO move validators This class is inherited in cd stage 2 package, but validate_update_tender function has diff... | 5586f483021ff1d8e89ba0e932e4db53c8c06e74 | <|skeleton|>
class TenderUaDocumentResource:
def validate_update_tender(self):
"""TODO move validators This class is inherited in cd stage 2 package, but validate_update_tender function has different validators. For now, we have no way to use different validators on methods according to procedure type."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TenderUaDocumentResource:
def validate_update_tender(self):
"""TODO move validators This class is inherited in cd stage 2 package, but validate_update_tender function has different validators. For now, we have no way to use different validators on methods according to procedure type."""
if sel... | the_stack_v2_python_sparse | openprocurement/tender/openua/views/tender_document.py | ProzorroUKR/openprocurement.tender.openua | train | 0 | |
590cb5a77903b616a3634f3a461cb866695a2b91 | [
"self._ip_address = host\nif sys.platform == 'win32':\n self._ping_cmd = ['ping', '-n', '1', '-w', '2000', host]\nelse:\n self._ping_cmd = ['ping', '-n', '-q', '-c1', '-W2', host]",
"if port > 0:\n return self._ping_socket(port)\nreturn self._ping()",
"with subprocess.Popen(self._ping_cmd, stdout=subpr... | <|body_start_0|>
self._ip_address = host
if sys.platform == 'win32':
self._ping_cmd = ['ping', '-n', '1', '-w', '2000', host]
else:
self._ping_cmd = ['ping', '-n', '-q', '-c1', '-W2', host]
<|end_body_0|>
<|body_start_1|>
if port > 0:
return self._pin... | Class for handling Ping to a specific host. | Ping | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ping:
"""Class for handling Ping to a specific host."""
def __init__(self, host):
"""Initialize the object."""
<|body_0|>
def ping(self, port=0):
"""Check if IP is available using ICMP or trying open a specific port."""
<|body_1|>
def _ping(self):
... | stack_v2_sparse_classes_75kplus_train_004008 | 43,343 | permissive | [
{
"docstring": "Initialize the object.",
"name": "__init__",
"signature": "def __init__(self, host)"
},
{
"docstring": "Check if IP is available using ICMP or trying open a specific port.",
"name": "ping",
"signature": "def ping(self, port=0)"
},
{
"docstring": "Send ICMP echo re... | 4 | null | Implement the Python class `Ping` described below.
Class description:
Class for handling Ping to a specific host.
Method signatures and docstrings:
- def __init__(self, host): Initialize the object.
- def ping(self, port=0): Check if IP is available using ICMP or trying open a specific port.
- def _ping(self): Send I... | Implement the Python class `Ping` described below.
Class description:
Class for handling Ping to a specific host.
Method signatures and docstrings:
- def __init__(self, host): Initialize the object.
- def ping(self, port=0): Check if IP is available using ICMP or trying open a specific port.
- def _ping(self): Send I... | 8548d9999ddd54f13d6a307e013abcb8c897a74e | <|skeleton|>
class Ping:
"""Class for handling Ping to a specific host."""
def __init__(self, host):
"""Initialize the object."""
<|body_0|>
def ping(self, port=0):
"""Check if IP is available using ICMP or trying open a specific port."""
<|body_1|>
def _ping(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Ping:
"""Class for handling Ping to a specific host."""
def __init__(self, host):
"""Initialize the object."""
self._ip_address = host
if sys.platform == 'win32':
self._ping_cmd = ['ping', '-n', '1', '-w', '2000', host]
else:
self._ping_cmd = ['ping... | the_stack_v2_python_sparse | custom_components/samsungtv_smart/api/samsungws.py | bacco007/HomeAssistantConfig | train | 98 |
d998425f5fe1e80a3dea29e8a37bd3d399940772 | [
"if not default_data is None and (not isinstance(default_data, (list, dict))):\n raise TypeError('Default data should be a dict or a list')\nself._filepath = filepath\nself._hold_for = hold_for\nself._check_every = check_every\nself._default_data = default_data\nself._data: JsonSuppored = DataNotLoaded()\nself._... | <|body_start_0|>
if not default_data is None and (not isinstance(default_data, (list, dict))):
raise TypeError('Default data should be a dict or a list')
self._filepath = filepath
self._hold_for = hold_for
self._check_every = check_every
self._default_data = default_d... | The bot uses a couple of json files that store data. Storing this data always in memory can be bad, especially at night for example, when usually no one uses the bot. When accessing json data files using this object, the data will be loaded to memory and will stay in memory for X seconds. If the data isn't accessed ano... | DynamicData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DynamicData:
"""The bot uses a couple of json files that store data. Storing this data always in memory can be bad, especially at night for example, when usually no one uses the bot. When accessing json data files using this object, the data will be loaded to memory and will stay in memory for X ... | stack_v2_sparse_classes_75kplus_train_004009 | 4,802 | no_license | [
{
"docstring": "Creates a dynamic data instance. When calling the constructor, the file is not actually read. `hold_for` is the number of seconds that the data will be stored in the memory before moving it to the local storage. By default, the data will be stored in the memory for 15 seconds. `check_every` dete... | 6 | stack_v2_sparse_classes_30k_train_053109 | Implement the Python class `DynamicData` described below.
Class description:
The bot uses a couple of json files that store data. Storing this data always in memory can be bad, especially at night for example, when usually no one uses the bot. When accessing json data files using this object, the data will be loaded t... | Implement the Python class `DynamicData` described below.
Class description:
The bot uses a couple of json files that store data. Storing this data always in memory can be bad, especially at night for example, when usually no one uses the bot. When accessing json data files using this object, the data will be loaded t... | 3c4029e82efa709ec24d8f893d63bd1cad2d77d6 | <|skeleton|>
class DynamicData:
"""The bot uses a couple of json files that store data. Storing this data always in memory can be bad, especially at night for example, when usually no one uses the bot. When accessing json data files using this object, the data will be loaded to memory and will stay in memory for X ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DynamicData:
"""The bot uses a couple of json files that store data. Storing this data always in memory can be bad, especially at night for example, when usually no one uses the bot. When accessing json data files using this object, the data will be loaded to memory and will stay in memory for X seconds. If t... | the_stack_v2_python_sparse | gadi/data.py | RealA10N/gadi | train | 0 |
6e1f8e1e9ee9ad086b422271aca57108b0514b14 | [
"profile.addListsToCraftTypeRepository('skeinforge_tools.craft_plugins.wipe.html', self)\nself.fileNameInput = settings.FileNameInput().getFromFileName(interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Wipe', self, '')\nself.openWikiManualHelpPage = settings.HelpPage().getOpenFromAbsolute('http://www.... | <|body_start_0|>
profile.addListsToCraftTypeRepository('skeinforge_tools.craft_plugins.wipe.html', self)
self.fileNameInput = settings.FileNameInput().getFromFileName(interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Wipe', self, '')
self.openWikiManualHelpPage = settings.HelpPage(... | A class to handle the wipe settings. | WipeRepository | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WipeRepository:
"""A class to handle the wipe settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
<|body_0|>
def execute(self):
"""Wipe button has been clicked."""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_75kplus_train_004010 | 11,511 | no_license | [
{
"docstring": "Set the default settings, execute title & settings fileName.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Wipe button has been clicked.",
"name": "execute",
"signature": "def execute(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_029201 | Implement the Python class `WipeRepository` described below.
Class description:
A class to handle the wipe settings.
Method signatures and docstrings:
- def __init__(self): Set the default settings, execute title & settings fileName.
- def execute(self): Wipe button has been clicked. | Implement the Python class `WipeRepository` described below.
Class description:
A class to handle the wipe settings.
Method signatures and docstrings:
- def __init__(self): Set the default settings, execute title & settings fileName.
- def execute(self): Wipe button has been clicked.
<|skeleton|>
class WipeRepositor... | fd69d8e856780c826386dc973ceabcc03623f3e8 | <|skeleton|>
class WipeRepository:
"""A class to handle the wipe settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
<|body_0|>
def execute(self):
"""Wipe button has been clicked."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WipeRepository:
"""A class to handle the wipe settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
profile.addListsToCraftTypeRepository('skeinforge_tools.craft_plugins.wipe.html', self)
self.fileNameInput = settings.FileNameInput().g... | the_stack_v2_python_sparse | skeinforge_tools/craft_plugins/wipe.py | bmander/skeinforge | train | 34 |
c8bbff64c1995e6d0b2779a71f30c4e6236bcfd3 | [
"try:\n return obj.authorized_user(self.context['request'].user)\nexcept TypeError:\n return False",
"try:\n return Like.liked(obj, self.context['request'].user)\nexcept TypeError:\n return False"
] | <|body_start_0|>
try:
return obj.authorized_user(self.context['request'].user)
except TypeError:
return False
<|end_body_0|>
<|body_start_1|>
try:
return Like.liked(obj, self.context['request'].user)
except TypeError:
return False
<|end_bo... | CampaignSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CampaignSerializer:
def get_auth(self, obj) -> bool:
"""Checks to see if current user is an authorized user of this Campaign. This is only used to display admin UI; this function does not grant the user any privileges. See Also -------- https://www.django-rest-framework.org/api-guide/fie... | stack_v2_sparse_classes_75kplus_train_004011 | 2,397 | no_license | [
{
"docstring": "Checks to see if current user is an authorized user of this Campaign. This is only used to display admin UI; this function does not grant the user any privileges. See Also -------- https://www.django-rest-framework.org/api-guide/fields/#serializermethodfield Parameters ---------- obj: Campaign R... | 2 | stack_v2_sparse_classes_30k_train_030820 | Implement the Python class `CampaignSerializer` described below.
Class description:
Implement the CampaignSerializer class.
Method signatures and docstrings:
- def get_auth(self, obj) -> bool: Checks to see if current user is an authorized user of this Campaign. This is only used to display admin UI; this function do... | Implement the Python class `CampaignSerializer` described below.
Class description:
Implement the CampaignSerializer class.
Method signatures and docstrings:
- def get_auth(self, obj) -> bool: Checks to see if current user is an authorized user of this Campaign. This is only used to display admin UI; this function do... | aab0ee4c058484315e073debf82b0669332de649 | <|skeleton|>
class CampaignSerializer:
def get_auth(self, obj) -> bool:
"""Checks to see if current user is an authorized user of this Campaign. This is only used to display admin UI; this function does not grant the user any privileges. See Also -------- https://www.django-rest-framework.org/api-guide/fie... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CampaignSerializer:
def get_auth(self, obj) -> bool:
"""Checks to see if current user is an authorized user of this Campaign. This is only used to display admin UI; this function does not grant the user any privileges. See Also -------- https://www.django-rest-framework.org/api-guide/fields/#serialize... | the_stack_v2_python_sparse | campaign/serializers.py | PoorRican/LoveOurNeighbor | train | 0 | |
f798c6ea485d1105d482eb62d6dc1acc62fb6d6e | [
"fs = executive.fileserver\ntry:\n stream = fs.open(uri=uri)\nexcept fs.GenericError as error:\n raise cls.LoadingError(codec=cls, uri=uri) from error\nshelf = cls.shelf(stream=stream, uri=uri, locator=tracking.file(source=str(uri)))\nreturn shelf",
"if not scheme:\n scheme = 'vfs'\ncfgpath = list((str(f... | <|body_start_0|>
fs = executive.fileserver
try:
stream = fs.open(uri=uri)
except fs.GenericError as error:
raise cls.LoadingError(codec=cls, uri=uri) from error
shelf = cls.shelf(stream=stream, uri=uri, locator=tracking.file(source=str(uri)))
return shelf
... | This component codec recognizes uris of the form vfs:/path/module.py/factory#name file:/path/module.py/factory#name which is interpreted as a request to import the file {module.py} from the indicated path, look for the symbol {factory}, and optionally instantiate whatever component class is recovered using {name} | ODB | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ODB:
"""This component codec recognizes uris of the form vfs:/path/module.py/factory#name file:/path/module.py/factory#name which is interpreted as a request to import the file {module.py} from the indicated path, look for the symbol {factory}, and optionally instantiate whatever component class ... | stack_v2_sparse_classes_75kplus_train_004012 | 3,908 | permissive | [
{
"docstring": "Interpret {uri} as a shelf to be loaded",
"name": "load",
"signature": "def load(cls, executive, uri, **kwds)"
},
{
"docstring": "Locate candidate shelves from the given {uri}",
"name": "locateShelves",
"signature": "def locateShelves(cls, executive, protocol, scheme, con... | 4 | stack_v2_sparse_classes_30k_test_002671 | Implement the Python class `ODB` described below.
Class description:
This component codec recognizes uris of the form vfs:/path/module.py/factory#name file:/path/module.py/factory#name which is interpreted as a request to import the file {module.py} from the indicated path, look for the symbol {factory}, and optionall... | Implement the Python class `ODB` described below.
Class description:
This component codec recognizes uris of the form vfs:/path/module.py/factory#name file:/path/module.py/factory#name which is interpreted as a request to import the file {module.py} from the indicated path, look for the symbol {factory}, and optionall... | d741c44ffb3e9e1f726bf492202ac8738bb4aa1c | <|skeleton|>
class ODB:
"""This component codec recognizes uris of the form vfs:/path/module.py/factory#name file:/path/module.py/factory#name which is interpreted as a request to import the file {module.py} from the indicated path, look for the symbol {factory}, and optionally instantiate whatever component class ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ODB:
"""This component codec recognizes uris of the form vfs:/path/module.py/factory#name file:/path/module.py/factory#name which is interpreted as a request to import the file {module.py} from the indicated path, look for the symbol {factory}, and optionally instantiate whatever component class is recovered ... | the_stack_v2_python_sparse | packages/pyre/config/odb/ODB.py | pyre/pyre | train | 27 |
2f50ec901fd873f9d4948d9c4f3361acd3933f5c | [
"node_a = headA\nnode_b = headB\nwhile node_a:\n while node_b:\n if node_a == node_b:\n return node_a\n node_b = node_b.next\n node_a = node_a.next\n node_b = headB\nreturn None",
"visited = {}\nnode = headA\nwhile node:\n visited[node] = True\n node = node.next\nnode = hea... | <|body_start_0|>
node_a = headA
node_b = headB
while node_a:
while node_b:
if node_a == node_b:
return node_a
node_b = node_b.next
node_a = node_a.next
node_b = headB
return None
<|end_body_0|>
<|bod... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getIntersectionNodeBruteForce(self, headA, headB):
""":type head1, head1: ListNode :rtype: ListNode"""
<|body_0|>
def getIntersectionNodeHashMap(self, headA, headB):
""":type head1, head1: ListNode :rtype: ListNode"""
<|body_1|>
def getInte... | stack_v2_sparse_classes_75kplus_train_004013 | 1,580 | no_license | [
{
"docstring": ":type head1, head1: ListNode :rtype: ListNode",
"name": "getIntersectionNodeBruteForce",
"signature": "def getIntersectionNodeBruteForce(self, headA, headB)"
},
{
"docstring": ":type head1, head1: ListNode :rtype: ListNode",
"name": "getIntersectionNodeHashMap",
"signatur... | 3 | stack_v2_sparse_classes_30k_train_001189 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getIntersectionNodeBruteForce(self, headA, headB): :type head1, head1: ListNode :rtype: ListNode
- def getIntersectionNodeHashMap(self, headA, headB): :type head1, head1: Lis... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getIntersectionNodeBruteForce(self, headA, headB): :type head1, head1: ListNode :rtype: ListNode
- def getIntersectionNodeHashMap(self, headA, headB): :type head1, head1: Lis... | 5c2473f859da5efec73120256faad06ab8e0e359 | <|skeleton|>
class Solution:
def getIntersectionNodeBruteForce(self, headA, headB):
""":type head1, head1: ListNode :rtype: ListNode"""
<|body_0|>
def getIntersectionNodeHashMap(self, headA, headB):
""":type head1, head1: ListNode :rtype: ListNode"""
<|body_1|>
def getInte... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def getIntersectionNodeBruteForce(self, headA, headB):
""":type head1, head1: ListNode :rtype: ListNode"""
node_a = headA
node_b = headB
while node_a:
while node_b:
if node_a == node_b:
return node_a
node... | the_stack_v2_python_sparse | leetcode/intersection_of_two_linked_lists.py | chlos/exercises_in_futility | train | 0 | |
40945192289a85450cdb0fc908d685fb62969052 | [
"if len(layout) == 0:\n return LayoutProtest()\nnum_entries = len(layout[0].entrants)\nif any((len(x.entrants) != num_entries for x in layout)):\n raise IndexError('Some games have differing numbers of entries')\nprotest = LayoutProtest()\nfor game in layout:\n protest.protests[game.protest_score()] += 1\n... | <|body_start_0|>
if len(layout) == 0:
return LayoutProtest()
num_entries = len(layout[0].entrants)
if any((len(x.entrants) != num_entries for x in layout)):
raise IndexError('Some games have differing numbers of entries')
protest = LayoutProtest()
for game... | Allocate tables by determining all possible options and allocating based on fewest protests. Algorithm: Protest: - Assume a game has two entrants (who have a history of tables played on) - When a table is proposed one, or both, entrants may protest - This gives a protest score of 0, 1, 2 (no-protest -> both protest) La... | ProtestAvoidanceStrategy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProtestAvoidanceStrategy:
"""Allocate tables by determining all possible options and allocating based on fewest protests. Algorithm: Protest: - Assume a game has two entrants (who have a history of tables played on) - When a table is proposed one, or both, entrants may protest - This gives a prot... | stack_v2_sparse_classes_75kplus_train_004014 | 4,545 | no_license | [
{
"docstring": "Get the protest scores for a single layout Expects: List of Table Note that the game might simply be the string 'BYE' Returns: A LayoutProtest",
"name": "get_protest_score_for_layout",
"signature": "def get_protest_score_for_layout(layout)"
},
{
"docstring": "The main method that... | 2 | stack_v2_sparse_classes_30k_train_006364 | Implement the Python class `ProtestAvoidanceStrategy` described below.
Class description:
Allocate tables by determining all possible options and allocating based on fewest protests. Algorithm: Protest: - Assume a game has two entrants (who have a history of tables played on) - When a table is proposed one, or both, e... | Implement the Python class `ProtestAvoidanceStrategy` described below.
Class description:
Allocate tables by determining all possible options and allocating based on fewest protests. Algorithm: Protest: - Assume a game has two entrants (who have a history of tables played on) - When a table is proposed one, or both, e... | 5affa81dfbe6697d79972f0013595f7efcfbe9ea | <|skeleton|>
class ProtestAvoidanceStrategy:
"""Allocate tables by determining all possible options and allocating based on fewest protests. Algorithm: Protest: - Assume a game has two entrants (who have a history of tables played on) - When a table is proposed one, or both, entrants may protest - This gives a prot... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProtestAvoidanceStrategy:
"""Allocate tables by determining all possible options and allocating based on fewest protests. Algorithm: Protest: - Assume a game has two entrants (who have a history of tables played on) - When a table is proposed one, or both, entrants may protest - This gives a protest score of ... | the_stack_v2_python_sparse | daoserver/src/models/table_strategy.py | roberthiggins/tournament-organiser | train | 1 |
138fc0c8c81448148c05c338b856b8dc1a3bd749 | [
"assert 'service_key' in event_info\nassert isinstance(event_info['service_key'], basestring)\nassert 'event_type' in event_info\nassert event_info['event_type'] in cls.EVENT_TYPES\nif event_info['event_type'] != cls.EVENT_TYPES[0]:\n assert 'incident_key' in event_info\n assert isinstance(event_info['inciden... | <|body_start_0|>
assert 'service_key' in event_info
assert isinstance(event_info['service_key'], basestring)
assert 'event_type' in event_info
assert event_info['event_type'] in cls.EVENT_TYPES
if event_info['event_type'] != cls.EVENT_TYPES[0]:
assert 'incident_key' i... | Event | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Event:
def validate(cls, event_info):
"""Validate that provided event information is valid."""
<|body_0|>
def create(cls, data=None, api_key=None, endpoint=None, add_headers=None, **kwargs):
"""Create an event on your PagerDuty account."""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_004015 | 1,812 | permissive | [
{
"docstring": "Validate that provided event information is valid.",
"name": "validate",
"signature": "def validate(cls, event_info)"
},
{
"docstring": "Create an event on your PagerDuty account.",
"name": "create",
"signature": "def create(cls, data=None, api_key=None, endpoint=None, ad... | 2 | stack_v2_sparse_classes_30k_train_018928 | Implement the Python class `Event` described below.
Class description:
Implement the Event class.
Method signatures and docstrings:
- def validate(cls, event_info): Validate that provided event information is valid.
- def create(cls, data=None, api_key=None, endpoint=None, add_headers=None, **kwargs): Create an event... | Implement the Python class `Event` described below.
Class description:
Implement the Event class.
Method signatures and docstrings:
- def validate(cls, event_info): Validate that provided event information is valid.
- def create(cls, data=None, api_key=None, endpoint=None, add_headers=None, **kwargs): Create an event... | 5e5abbfb59f5b99fa90c79907fa1eb023aa08e9c | <|skeleton|>
class Event:
def validate(cls, event_info):
"""Validate that provided event information is valid."""
<|body_0|>
def create(cls, data=None, api_key=None, endpoint=None, add_headers=None, **kwargs):
"""Create an event on your PagerDuty account."""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Event:
def validate(cls, event_info):
"""Validate that provided event information is valid."""
assert 'service_key' in event_info
assert isinstance(event_info['service_key'], basestring)
assert 'event_type' in event_info
assert event_info['event_type'] in cls.EVENT_TYPE... | the_stack_v2_python_sparse | pypd/models/event.py | ryplo/helpme | train | 2 | |
7d1b9baa94cd53c41b2e78671dae21d926f7bd39 | [
"self.lrow = len(matrix)\nif self.lrow == 0:\n self.dp = [[]]\n return\nself.lcol = len(matrix[0])\nself.dp = [[0 for _ in range(self.lcol)] for _ in range(self.lrow)]\nfor i in range(self.lrow):\n for j in range(self.lcol):\n self.dp[i][j] = self.dp[i][j - 1] + matrix[i][j]",
"r = 0\nfor row in r... | <|body_start_0|>
self.lrow = len(matrix)
if self.lrow == 0:
self.dp = [[]]
return
self.lcol = len(matrix[0])
self.dp = [[0 for _ in range(self.lcol)] for _ in range(self.lrow)]
for i in range(self.lrow):
for j in range(self.lcol):
... | NumMatrix | [
"MIT"
] | 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_75kplus_train_004016 | 1,038 | permissive | [
{
"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 | stack_v2_sparse_classes_30k_train_023637 | 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:... | 65549f72c565d9f11641c86d6cef9c7988805817 | <|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_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
self.lrow = len(matrix)
if self.lrow == 0:
self.dp = [[]]
return
self.lcol = len(matrix[0])
self.dp = [[0 for _ in range(self.lcol)] for _ in range(self.lrow)]
for... | the_stack_v2_python_sparse | utils/numSumMatrix.py | wisesky/LeetCode-Practice | train | 0 | |
3cff045a82cc2ee9b8af6c67bdf6796c71f1ae90 | [
"if not email:\n raise ValueError('Users must have an email address')\nuser = self.model(email=self.normalize_email(email), username=username, steamid=steamid)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"buy_orders = None\nbuy_orders_item_ids = set()\nitems_to_buy = []\nsell_orders ... | <|body_start_0|>
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email), username=username, steamid=steamid)
user.set_password(password)
user.save(using=self._db)
return user
<|end_body_0|>
<|body_start_... | CSRuby_UserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CSRuby_UserManager:
def create_user(self, email, username, password=None, steamid=None):
"""Creates and saves a User with the given email, password and steamid"""
<|body_0|>
def get_user_trades(self, user_id):
"""Return items from buy, sell orders and favorites as a ... | stack_v2_sparse_classes_75kplus_train_004017 | 11,447 | no_license | [
{
"docstring": "Creates and saves a User with the given email, password and steamid",
"name": "create_user",
"signature": "def create_user(self, email, username, password=None, steamid=None)"
},
{
"docstring": "Return items from buy, sell orders and favorites as a set (items_to_buy, items_to_sel... | 3 | stack_v2_sparse_classes_30k_train_041706 | Implement the Python class `CSRuby_UserManager` described below.
Class description:
Implement the CSRuby_UserManager class.
Method signatures and docstrings:
- def create_user(self, email, username, password=None, steamid=None): Creates and saves a User with the given email, password and steamid
- def get_user_trades... | Implement the Python class `CSRuby_UserManager` described below.
Class description:
Implement the CSRuby_UserManager class.
Method signatures and docstrings:
- def create_user(self, email, username, password=None, steamid=None): Creates and saves a User with the given email, password and steamid
- def get_user_trades... | 72609868cdb01ec3b54d3b6147f8999631864320 | <|skeleton|>
class CSRuby_UserManager:
def create_user(self, email, username, password=None, steamid=None):
"""Creates and saves a User with the given email, password and steamid"""
<|body_0|>
def get_user_trades(self, user_id):
"""Return items from buy, sell orders and favorites as a ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CSRuby_UserManager:
def create_user(self, email, username, password=None, steamid=None):
"""Creates and saves a User with the given email, password and steamid"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email... | the_stack_v2_python_sparse | csruby_app/models.py | HE-Arc/CSRuby | train | 4 | |
005bd3775095a99becf367841957a66fbe46ba48 | [
"CheckClientDataFormat.missing_mandatory_data(client_data=client_data)\nfor key, value in client_data.items():\n if value:\n try:\n if key == 'identity_card':\n self.identity_card(identity_card=value)\n if key == 'email':\n self.email(email=value)\n ... | <|body_start_0|>
CheckClientDataFormat.missing_mandatory_data(client_data=client_data)
for key, value in client_data.items():
if value:
try:
if key == 'identity_card':
self.identity_card(identity_card=value)
if k... | Check th Client Data Format | CheckClientDataFormat | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckClientDataFormat:
"""Check th Client Data Format"""
def __init__(self, client_data: dict):
"""Check Client Data Format Init. **client_data: id: client id name: client name last_name: client last name identity_card: client identity card email: client email phone_1: client phone 1... | stack_v2_sparse_classes_75kplus_train_004018 | 2,818 | no_license | [
{
"docstring": "Check Client Data Format Init. **client_data: id: client id name: client name last_name: client last name identity_card: client identity card email: client email phone_1: client phone 1 phone_2: client phone 2s address: client address.",
"name": "__init__",
"signature": "def __init__(sel... | 5 | stack_v2_sparse_classes_30k_train_013046 | Implement the Python class `CheckClientDataFormat` described below.
Class description:
Check th Client Data Format
Method signatures and docstrings:
- def __init__(self, client_data: dict): Check Client Data Format Init. **client_data: id: client id name: client name last_name: client last name identity_card: client ... | Implement the Python class `CheckClientDataFormat` described below.
Class description:
Check th Client Data Format
Method signatures and docstrings:
- def __init__(self, client_data: dict): Check Client Data Format Init. **client_data: id: client id name: client name last_name: client last name identity_card: client ... | 839974384248d201b8d2baffa612cffd3be6d0d3 | <|skeleton|>
class CheckClientDataFormat:
"""Check th Client Data Format"""
def __init__(self, client_data: dict):
"""Check Client Data Format Init. **client_data: id: client id name: client name last_name: client last name identity_card: client identity card email: client email phone_1: client phone 1... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CheckClientDataFormat:
"""Check th Client Data Format"""
def __init__(self, client_data: dict):
"""Check Client Data Format Init. **client_data: id: client id name: client name last_name: client last name identity_card: client identity card email: client email phone_1: client phone 1 phone_2: cli... | the_stack_v2_python_sparse | backend/service/check_client_data.py | echeniquegrecia/mechanical_repair_sofware | train | 0 |
0b9fa952ad01308c79cbf3aaf9c3359c7c45c285 | [
"data = response.xpath('//script[@seph-json-to-js=\"sku\"]/text()').extract_first()\nif not data:\n return None\nrecord = json.loads(data)\nproduct_loader = ProductItemLoader(ProductItem(), response)\nproduct_loader.add_value('id', record['id'])\nproduct_loader.add_value('sku', record['sku_number'])\nproduct_loa... | <|body_start_0|>
data = response.xpath('//script[@seph-json-to-js="sku"]/text()').extract_first()
if not data:
return None
record = json.loads(data)
product_loader = ProductItemLoader(ProductItem(), response)
product_loader.add_value('id', record['id'])
produc... | Sephora Products Spider | SephoraProductsSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SephoraProductsSpider:
"""Sephora Products Spider"""
def parse(self, response):
"""Extract product details"""
<|body_0|>
def parse_reviews(self, response):
"""Extract reviews"""
<|body_1|>
def extract_review(self, data):
"""Extract review inf... | stack_v2_sparse_classes_75kplus_train_004019 | 5,747 | no_license | [
{
"docstring": "Extract product details",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "Extract reviews",
"name": "parse_reviews",
"signature": "def parse_reviews(self, response)"
},
{
"docstring": "Extract review information",
"name": "extract_... | 4 | stack_v2_sparse_classes_30k_train_016844 | Implement the Python class `SephoraProductsSpider` described below.
Class description:
Sephora Products Spider
Method signatures and docstrings:
- def parse(self, response): Extract product details
- def parse_reviews(self, response): Extract reviews
- def extract_review(self, data): Extract review information
- def ... | Implement the Python class `SephoraProductsSpider` described below.
Class description:
Sephora Products Spider
Method signatures and docstrings:
- def parse(self, response): Extract product details
- def parse_reviews(self, response): Extract reviews
- def extract_review(self, data): Extract review information
- def ... | 67eeb08962725fd3aff8c8cb7e16360ffd651f06 | <|skeleton|>
class SephoraProductsSpider:
"""Sephora Products Spider"""
def parse(self, response):
"""Extract product details"""
<|body_0|>
def parse_reviews(self, response):
"""Extract reviews"""
<|body_1|>
def extract_review(self, data):
"""Extract review inf... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SephoraProductsSpider:
"""Sephora Products Spider"""
def parse(self, response):
"""Extract product details"""
data = response.xpath('//script[@seph-json-to-js="sku"]/text()').extract_first()
if not data:
return None
record = json.loads(data)
product_loa... | the_stack_v2_python_sparse | pipeline/pipeline/spiders/sephora.py | DataRetrieval/pipeline | train | 1 |
5fa8bc81fb10ab6373e857100fb5c289ee3ca6e1 | [
"self.f = f\nself.gp = GP(X_init, Y_init, l, sigma_f)\nself.X_s = np.linspace(bounds[0], bounds[1], ac_samples).reshape(ac_samples, 1)\nself.xsi = xsi\nself.minimize = minimize",
"mu_sample, sigma_sample = self.gp.predict(self.X_s)\nif self.minimize is True:\n Y_sample_opt = np.min(self.gp.Y)\n imp = Y_samp... | <|body_start_0|>
self.f = f
self.gp = GP(X_init, Y_init, l, sigma_f)
self.X_s = np.linspace(bounds[0], bounds[1], ac_samples).reshape(ac_samples, 1)
self.xsi = xsi
self.minimize = minimize
<|end_body_0|>
<|body_start_1|>
mu_sample, sigma_sample = self.gp.predict(self.X_s... | Bayesian | BayesianOptimization | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BayesianOptimization:
"""Bayesian"""
def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True):
"""Class constructor Args: f: the black-box function to be optimized. X_init (np.ndarray): shape (t, 1) representing the inputs already sampled wit... | stack_v2_sparse_classes_75kplus_train_004020 | 4,199 | no_license | [
{
"docstring": "Class constructor Args: f: the black-box function to be optimized. X_init (np.ndarray): shape (t, 1) representing the inputs already sampled with the black-box function. Y_init (np.ndarray): shape (t, 1) representing the outputs of the black-box function for each input in X_init. t: number of in... | 3 | null | Implement the Python class `BayesianOptimization` described below.
Class description:
Bayesian
Method signatures and docstrings:
- def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True): Class constructor Args: f: the black-box function to be optimized. X_init (np.ndarray):... | Implement the Python class `BayesianOptimization` described below.
Class description:
Bayesian
Method signatures and docstrings:
- def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True): Class constructor Args: f: the black-box function to be optimized. X_init (np.ndarray):... | 5aff923277cfe9f2b5324a773e4e5c3cac810a0c | <|skeleton|>
class BayesianOptimization:
"""Bayesian"""
def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True):
"""Class constructor Args: f: the black-box function to be optimized. X_init (np.ndarray): shape (t, 1) representing the inputs already sampled wit... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BayesianOptimization:
"""Bayesian"""
def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True):
"""Class constructor Args: f: the black-box function to be optimized. X_init (np.ndarray): shape (t, 1) representing the inputs already sampled with the black-b... | the_stack_v2_python_sparse | unsupervised_learning/0x03-hyperparameter_tuning/5-bayes_opt.py | cmmolanos1/holbertonschool-machine_learning | train | 1 |
a4d28c47f952f4ded6e1ef676d79fea9a00520bc | [
"logging.Handler.__init__(self)\nself._comm = comm\nself._formatter = logging.Formatter()",
"msg = self._formatter.format(rec)\nentry = LogEvent(rec.created, rec.levelname, os.path.basename(rec.pathname), rec.funcName, rec.lineno, msg)\nself._comm.log_message(entry)"
] | <|body_start_0|>
logging.Handler.__init__(self)
self._comm = comm
self._formatter = logging.Formatter()
<|end_body_0|>
<|body_start_1|>
msg = self._formatter.format(rec)
entry = LogEvent(rec.created, rec.levelname, os.path.basename(rec.pathname), rec.funcName, rec.lineno, msg)
... | A logging handler that sends all messages through a Comm module. | CommLoggingHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommLoggingHandler:
"""A logging handler that sends all messages through a Comm module."""
def __init__(self, comm: 'Comm'):
"""Create a new logging handler. Args: comm: Comm module to use."""
<|body_0|>
def emit(self, rec: Any) -> None:
"""Send a new log entry t... | stack_v2_sparse_classes_75kplus_train_004021 | 995 | permissive | [
{
"docstring": "Create a new logging handler. Args: comm: Comm module to use.",
"name": "__init__",
"signature": "def __init__(self, comm: 'Comm')"
},
{
"docstring": "Send a new log entry to the comm module. Args: rec: Log record to send.",
"name": "emit",
"signature": "def emit(self, re... | 2 | stack_v2_sparse_classes_30k_train_014651 | Implement the Python class `CommLoggingHandler` described below.
Class description:
A logging handler that sends all messages through a Comm module.
Method signatures and docstrings:
- def __init__(self, comm: 'Comm'): Create a new logging handler. Args: comm: Comm module to use.
- def emit(self, rec: Any) -> None: S... | Implement the Python class `CommLoggingHandler` described below.
Class description:
A logging handler that sends all messages through a Comm module.
Method signatures and docstrings:
- def __init__(self, comm: 'Comm'): Create a new logging handler. Args: comm: Comm module to use.
- def emit(self, rec: Any) -> None: S... | 2d7a06e5485b61b6ca7e51d99b08651ea6021086 | <|skeleton|>
class CommLoggingHandler:
"""A logging handler that sends all messages through a Comm module."""
def __init__(self, comm: 'Comm'):
"""Create a new logging handler. Args: comm: Comm module to use."""
<|body_0|>
def emit(self, rec: Any) -> None:
"""Send a new log entry t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CommLoggingHandler:
"""A logging handler that sends all messages through a Comm module."""
def __init__(self, comm: 'Comm'):
"""Create a new logging handler. Args: comm: Comm module to use."""
logging.Handler.__init__(self)
self._comm = comm
self._formatter = logging.Forma... | the_stack_v2_python_sparse | pyobs/comm/commlogging.py | pyobs/pyobs-core | train | 9 |
9f6b1e822018698bfe8c348de6eaff99e4d53de0 | [
"serializer_context = {'request': request}\nfollower = request.user\ntry:\n followee = User.objects.get(username=username)\nexcept User.DoesNotExist:\n raise NotFound('User with this username does not exist')\nfollower.follow(followee)\nserializer = self.serializer_class(followee, context=serializer_context)\... | <|body_start_0|>
serializer_context = {'request': request}
follower = request.user
try:
followee = User.objects.get(username=username)
except User.DoesNotExist:
raise NotFound('User with this username does not exist')
follower.follow(followee)
seri... | FollowUserView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FollowUserView:
def post(self, request, username=None):
"""Follow user specified by username"""
<|body_0|>
def delete(self, request, username=None):
"""Unfollow user specified by username"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
serializer_co... | stack_v2_sparse_classes_75kplus_train_004022 | 4,007 | no_license | [
{
"docstring": "Follow user specified by username",
"name": "post",
"signature": "def post(self, request, username=None)"
},
{
"docstring": "Unfollow user specified by username",
"name": "delete",
"signature": "def delete(self, request, username=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005006 | Implement the Python class `FollowUserView` described below.
Class description:
Implement the FollowUserView class.
Method signatures and docstrings:
- def post(self, request, username=None): Follow user specified by username
- def delete(self, request, username=None): Unfollow user specified by username | Implement the Python class `FollowUserView` described below.
Class description:
Implement the FollowUserView class.
Method signatures and docstrings:
- def post(self, request, username=None): Follow user specified by username
- def delete(self, request, username=None): Unfollow user specified by username
<|skeleton|... | 1865b06b496f5e961d8c77e7056eb7f4563e8f33 | <|skeleton|>
class FollowUserView:
def post(self, request, username=None):
"""Follow user specified by username"""
<|body_0|>
def delete(self, request, username=None):
"""Unfollow user specified by username"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FollowUserView:
def post(self, request, username=None):
"""Follow user specified by username"""
serializer_context = {'request': request}
follower = request.user
try:
followee = User.objects.get(username=username)
except User.DoesNotExist:
raise ... | the_stack_v2_python_sparse | api/Views/users.py | myrage/blog-api | train | 0 | |
dc6f46607dff4520cfc2334d91b227d487ad7acc | [
"out_put_file = open(PARSE_OUT_FILE, 'w')\ndat_dict = dict()\ndat_dict['last_catch_logs_date'] = self.last_catch_logs_date\ndat_dict['last_catch_logs_line_num'] = self.last_catch_logs_line_num\npickle.dump(dat_dict, out_put_file)\nout_put_file.close()",
"if os.path.exists(PARSE_OUT_FILE):\n out_put_file = open... | <|body_start_0|>
out_put_file = open(PARSE_OUT_FILE, 'w')
dat_dict = dict()
dat_dict['last_catch_logs_date'] = self.last_catch_logs_date
dat_dict['last_catch_logs_line_num'] = self.last_catch_logs_line_num
pickle.dump(dat_dict, out_put_file)
out_put_file.close()
<|end_bod... | CatchData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CatchData:
def put(self):
"""保存配置"""
<|body_0|>
def load(self):
"""加载"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
out_put_file = open(PARSE_OUT_FILE, 'w')
dat_dict = dict()
dat_dict['last_catch_logs_date'] = self.last_catch_logs_... | stack_v2_sparse_classes_75kplus_train_004023 | 3,325 | no_license | [
{
"docstring": "保存配置",
"name": "put",
"signature": "def put(self)"
},
{
"docstring": "加载",
"name": "load",
"signature": "def load(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_030094 | Implement the Python class `CatchData` described below.
Class description:
Implement the CatchData class.
Method signatures and docstrings:
- def put(self): 保存配置
- def load(self): 加载 | Implement the Python class `CatchData` described below.
Class description:
Implement the CatchData class.
Method signatures and docstrings:
- def put(self): 保存配置
- def load(self): 加载
<|skeleton|>
class CatchData:
def put(self):
"""保存配置"""
<|body_0|>
def load(self):
"""加载"""
... | ff2afd6d29e9dce6157a66ff62b4d1ea97d04184 | <|skeleton|>
class CatchData:
def put(self):
"""保存配置"""
<|body_0|>
def load(self):
"""加载"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CatchData:
def put(self):
"""保存配置"""
out_put_file = open(PARSE_OUT_FILE, 'w')
dat_dict = dict()
dat_dict['last_catch_logs_date'] = self.last_catch_logs_date
dat_dict['last_catch_logs_line_num'] = self.last_catch_logs_line_num
pickle.dump(dat_dict, out_put_file)
... | the_stack_v2_python_sparse | apps/logs/catch_game_logs.py | robot-nan/GameLogServer | train | 0 | |
4f5627fc3183b6714c6c39d26d80be832e9f5f16 | [
"self.fileHandle = fileHandle\nself.dagPath = dagPath\nself.fFluid = OpenMayaFX.MFnFluid(dagPath)",
"xPtr = OpenMaya.MScriptUtil().asDoublePtr()\nyPtr = OpenMaya.MScriptUtil().asDoublePtr()\nzPtr = OpenMaya.MScriptUtil().asDoublePtr()\nself.fFluid.getDimensions(xPtr, yPtr, zPtr)\ndimX = OpenMaya.MScriptUtil(xPtr)... | <|body_start_0|>
self.fileHandle = fileHandle
self.dagPath = dagPath
self.fFluid = OpenMayaFX.MFnFluid(dagPath)
<|end_body_0|>
<|body_start_1|>
xPtr = OpenMaya.MScriptUtil().asDoublePtr()
yPtr = OpenMaya.MScriptUtil().asDoublePtr()
zPtr = OpenMaya.MScriptUtil().asDoubleP... | Fluid volume export module | Volume | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Volume:
"""Fluid volume export module"""
def __init__(self, fileHandle, dagPath):
"""Set up the objects we're dealing with"""
<|body_0|>
def getOutput(self):
"""Read Fluid data and export as volumegrid"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_004024 | 2,972 | no_license | [
{
"docstring": "Set up the objects we're dealing with",
"name": "__init__",
"signature": "def __init__(self, fileHandle, dagPath)"
},
{
"docstring": "Read Fluid data and export as volumegrid",
"name": "getOutput",
"signature": "def getOutput(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_030942 | Implement the Python class `Volume` described below.
Class description:
Fluid volume export module
Method signatures and docstrings:
- def __init__(self, fileHandle, dagPath): Set up the objects we're dealing with
- def getOutput(self): Read Fluid data and export as volumegrid | Implement the Python class `Volume` described below.
Class description:
Fluid volume export module
Method signatures and docstrings:
- def __init__(self, fileHandle, dagPath): Set up the objects we're dealing with
- def getOutput(self): Read Fluid data and export as volumegrid
<|skeleton|>
class Volume:
"""Fluid... | 3891e40c3c4c3a054e5ff1ff16d051d4e690cc4a | <|skeleton|>
class Volume:
"""Fluid volume export module"""
def __init__(self, fileHandle, dagPath):
"""Set up the objects we're dealing with"""
<|body_0|>
def getOutput(self):
"""Read Fluid data and export as volumegrid"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Volume:
"""Fluid volume export module"""
def __init__(self, fileHandle, dagPath):
"""Set up the objects we're dealing with"""
self.fileHandle = fileHandle
self.dagPath = dagPath
self.fFluid = OpenMayaFX.MFnFluid(dagPath)
def getOutput(self):
"""Read Fluid data... | the_stack_v2_python_sparse | luxPlugin/Lux/LuxExportModules/Volume.py | LuxRender/LuxMaya | train | 0 |
77f4b885c34dec43a89b98579f3acba70fc5d839 | [
"responses.add(responses.GET, 'https://textit.in/api/v2/contacts.json?urn=whatsapp%3A27820001001', json={'results': [], 'next': None})\nmcimport = MomConnectImport.objects.create()\nmcimport.rows.create(row_number=2, msisdn='+27820001001', messaging_consent=True, facility_code='123456', edd_year=2021, edd_month=12,... | <|body_start_0|>
responses.add(responses.GET, 'https://textit.in/api/v2/contacts.json?urn=whatsapp%3A27820001001', json={'results': [], 'next': None})
mcimport = MomConnectImport.objects.create()
mcimport.rows.create(row_number=2, msisdn='+27820001001', messaging_consent=True, facility_code='123... | ValidateMomConnectImportTests | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidateMomConnectImportTests:
def test_success(self, upload_momconnect_import):
"""If the validation passes, then should be updated to validation complete"""
<|body_0|>
def test_fail_previously_opted_out(self):
"""If the mother has previously opted out, and hasn't c... | stack_v2_sparse_classes_75kplus_train_004025 | 31,403 | permissive | [
{
"docstring": "If the validation passes, then should be updated to validation complete",
"name": "test_success",
"signature": "def test_success(self, upload_momconnect_import)"
},
{
"docstring": "If the mother has previously opted out, and hasn't chosen to opt in again, then validation should f... | 4 | stack_v2_sparse_classes_30k_train_010649 | Implement the Python class `ValidateMomConnectImportTests` described below.
Class description:
Implement the ValidateMomConnectImportTests class.
Method signatures and docstrings:
- def test_success(self, upload_momconnect_import): If the validation passes, then should be updated to validation complete
- def test_fai... | Implement the Python class `ValidateMomConnectImportTests` described below.
Class description:
Implement the ValidateMomConnectImportTests class.
Method signatures and docstrings:
- def test_success(self, upload_momconnect_import): If the validation passes, then should be updated to validation complete
- def test_fai... | e1ea0beaf079f4f4d5f9562fb9d9a4f0670f459f | <|skeleton|>
class ValidateMomConnectImportTests:
def test_success(self, upload_momconnect_import):
"""If the validation passes, then should be updated to validation complete"""
<|body_0|>
def test_fail_previously_opted_out(self):
"""If the mother has previously opted out, and hasn't c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ValidateMomConnectImportTests:
def test_success(self, upload_momconnect_import):
"""If the validation passes, then should be updated to validation complete"""
responses.add(responses.GET, 'https://textit.in/api/v2/contacts.json?urn=whatsapp%3A27820001001', json={'results': [], 'next': None})
... | the_stack_v2_python_sparse | eventstore/test_tasks.py | praekeltfoundation/ndoh-hub | train | 0 | |
87a368408756c0dfec2f5f4fd0813045dbd19d0b | [
"self.num_units = num_units\nself.layer_norm = layer_norm\nself.recurrent_dropout = recurrent_dropout\nself.activation_fn = activation_fn",
"with tf.variable_scope(scope or type(self).__name__):\n lstm_cell = tf.contrib.rnn.LayerNormBasicLSTMCell(num_units=self.num_units, activation=self.activation_fn, layer_n... | <|body_start_0|>
self.num_units = num_units
self.layer_norm = layer_norm
self.recurrent_dropout = recurrent_dropout
self.activation_fn = activation_fn
<|end_body_0|>
<|body_start_1|>
with tf.variable_scope(scope or type(self).__name__):
lstm_cell = tf.contrib.rnn.Lay... | a LSTM layer | LSTMLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LSTMLayer:
"""a LSTM layer"""
def __init__(self, num_units, layer_norm=False, recurrent_dropout=1.0, activation_fn=tf.nn.tanh):
"""LSTMLayer constructor Args: num_units: The number of units in the one directon layer_norm: whether layer normalization should be applied recurrent_dropou... | stack_v2_sparse_classes_75kplus_train_004026 | 49,091 | permissive | [
{
"docstring": "LSTMLayer constructor Args: num_units: The number of units in the one directon layer_norm: whether layer normalization should be applied recurrent_dropout: the recurrent dropout keep probability activation_fn: activation function",
"name": "__init__",
"signature": "def __init__(self, num... | 2 | null | Implement the Python class `LSTMLayer` described below.
Class description:
a LSTM layer
Method signatures and docstrings:
- def __init__(self, num_units, layer_norm=False, recurrent_dropout=1.0, activation_fn=tf.nn.tanh): LSTMLayer constructor Args: num_units: The number of units in the one directon layer_norm: wheth... | Implement the Python class `LSTMLayer` described below.
Class description:
a LSTM layer
Method signatures and docstrings:
- def __init__(self, num_units, layer_norm=False, recurrent_dropout=1.0, activation_fn=tf.nn.tanh): LSTMLayer constructor Args: num_units: The number of units in the one directon layer_norm: wheth... | 5e862cbf846d45b8a317f87588533f3fde9f0726 | <|skeleton|>
class LSTMLayer:
"""a LSTM layer"""
def __init__(self, num_units, layer_norm=False, recurrent_dropout=1.0, activation_fn=tf.nn.tanh):
"""LSTMLayer constructor Args: num_units: The number of units in the one directon layer_norm: whether layer normalization should be applied recurrent_dropou... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LSTMLayer:
"""a LSTM layer"""
def __init__(self, num_units, layer_norm=False, recurrent_dropout=1.0, activation_fn=tf.nn.tanh):
"""LSTMLayer constructor Args: num_units: The number of units in the one directon layer_norm: whether layer normalization should be applied recurrent_dropout: the recurr... | the_stack_v2_python_sparse | nabu/neuralnetworks/components/layer.py | JeroenZegers/Nabu-MSSS | train | 19 |
713bd4e449f9662e217a021f40188011afd95300 | [
"self.rawdata = {}\nf = open(filename, 'r')\nheader = f.readline().strip().split(',')\nfor line in f:\n items = line.strip().split(',')\n date = re.match('(\\\\d\\\\d\\\\d\\\\d)(\\\\d\\\\d)(\\\\d\\\\d)', items[header.index('DATE')])\n year = int(date.group(1))\n month = int(date.group(2))\n day = int... | <|body_start_0|>
self.rawdata = {}
f = open(filename, 'r')
header = f.readline().strip().split(',')
for line in f:
items = line.strip().split(',')
date = re.match('(\\d\\d\\d\\d)(\\d\\d)(\\d\\d)', items[header.index('DATE')])
year = int(date.group(1))
... | The collection of temperature records loaded from given csv file | Climate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Climate:
"""The collection of temperature records loaded from given csv file"""
def __init__(self, filename):
"""Initialize a Climate instance, which stores the temperature records loaded from a given csv file specified by filename. Args: filename: name of the csv file (str)"""
... | stack_v2_sparse_classes_75kplus_train_004027 | 15,636 | no_license | [
{
"docstring": "Initialize a Climate instance, which stores the temperature records loaded from a given csv file specified by filename. Args: filename: name of the csv file (str)",
"name": "__init__",
"signature": "def __init__(self, filename)"
},
{
"docstring": "Get the daily temperatures for t... | 3 | stack_v2_sparse_classes_30k_train_043235 | Implement the Python class `Climate` described below.
Class description:
The collection of temperature records loaded from given csv file
Method signatures and docstrings:
- def __init__(self, filename): Initialize a Climate instance, which stores the temperature records loaded from a given csv file specified by file... | Implement the Python class `Climate` described below.
Class description:
The collection of temperature records loaded from given csv file
Method signatures and docstrings:
- def __init__(self, filename): Initialize a Climate instance, which stores the temperature records loaded from a given csv file specified by file... | 46cda997697c80e6e9d1ca51218d5e8d1620eb29 | <|skeleton|>
class Climate:
"""The collection of temperature records loaded from given csv file"""
def __init__(self, filename):
"""Initialize a Climate instance, which stores the temperature records loaded from a given csv file specified by filename. Args: filename: name of the csv file (str)"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Climate:
"""The collection of temperature records loaded from given csv file"""
def __init__(self, filename):
"""Initialize a Climate instance, which stores the temperature records loaded from a given csv file specified by filename. Args: filename: name of the csv file (str)"""
self.rawda... | the_stack_v2_python_sparse | MIT/MIT_60002/ProblemSets/PS5/ps5.py | mplefort/Python_Learning | train | 0 |
4262b2b4fcbe9671580ccfbd2775317d3cbdbfa8 | [
"self.fifties = fifties\nself.twenties = twenties\nself.tens = tens\nself.fives = fives\nself.ones = ones\nself.quarters = quarters\nself.dimes = dimes\nself.nickels = nickels\nself.pennies = pennies\nif total_value == None or total_value > 0:\n self.total_value = total_value\nelse:\n self.total_value = 50 * ... | <|body_start_0|>
self.fifties = fifties
self.twenties = twenties
self.tens = tens
self.fives = fives
self.ones = ones
self.quarters = quarters
self.dimes = dimes
self.nickels = nickels
self.pennies = pennies
if total_value == None or total_... | A change set object. Contains a collection of all the types of change available and their counts. fifties, twenties, tens, fives, ones, quarters, dimes, nickels, and pennies. All integers. | Change_Set | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Change_Set:
"""A change set object. Contains a collection of all the types of change available and their counts. fifties, twenties, tens, fives, ones, quarters, dimes, nickels, and pennies. All integers."""
def __init__(self, fifties, twenties, tens, fives, ones, quarters, dimes, nickels, pe... | stack_v2_sparse_classes_75kplus_train_004028 | 5,456 | no_license | [
{
"docstring": "Initializes a change set. Pass in a zero for total value to have it calculated for you. :param fifties: :param twenties: :param tens: :param fives: :param ones: :param quarters: :param dimes: :param nickels: :param pennies: :param total_value:",
"name": "__init__",
"signature": "def __in... | 5 | stack_v2_sparse_classes_30k_train_041061 | Implement the Python class `Change_Set` described below.
Class description:
A change set object. Contains a collection of all the types of change available and their counts. fifties, twenties, tens, fives, ones, quarters, dimes, nickels, and pennies. All integers.
Method signatures and docstrings:
- def __init__(self... | Implement the Python class `Change_Set` described below.
Class description:
A change set object. Contains a collection of all the types of change available and their counts. fifties, twenties, tens, fives, ones, quarters, dimes, nickels, and pennies. All integers.
Method signatures and docstrings:
- def __init__(self... | e38d65f72573a59f49adece591d34e13a0f13697 | <|skeleton|>
class Change_Set:
"""A change set object. Contains a collection of all the types of change available and their counts. fifties, twenties, tens, fives, ones, quarters, dimes, nickels, and pennies. All integers."""
def __init__(self, fifties, twenties, tens, fives, ones, quarters, dimes, nickels, pe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Change_Set:
"""A change set object. Contains a collection of all the types of change available and their counts. fifties, twenties, tens, fives, ones, quarters, dimes, nickels, and pennies. All integers."""
def __init__(self, fifties, twenties, tens, fives, ones, quarters, dimes, nickels, pennies, total_... | the_stack_v2_python_sparse | practice/change/makechange.py | dylanbrams/Classnotes | train | 0 |
7aaee75a4f1b6a275c1cef8d344f4f92051525bb | [
"super(DeleteForm, self).__init__(*args, **kwargs)\nself.current_user = current_user\nself.target_permission_id = target_permission_id\nself.permission_id.default = target_permission_id\nself.permission_id.validators = [AnyOf([target_permission_id])]",
"initial_validation = super(DeleteForm, self).validate(extra_... | <|body_start_0|>
super(DeleteForm, self).__init__(*args, **kwargs)
self.current_user = current_user
self.target_permission_id = target_permission_id
self.permission_id.default = target_permission_id
self.permission_id.validators = [AnyOf([target_permission_id])]
<|end_body_0|>
<... | Permission delete form. | DeleteForm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeleteForm:
"""Permission delete form."""
def __init__(self, current_user, target_permission_id, *args, **kwargs):
"""Create instance."""
<|body_0|>
def validate(self, extra_validators=None):
"""Validate the form."""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_75kplus_train_004029 | 10,553 | permissive | [
{
"docstring": "Create instance.",
"name": "__init__",
"signature": "def __init__(self, current_user, target_permission_id, *args, **kwargs)"
},
{
"docstring": "Validate the form.",
"name": "validate",
"signature": "def validate(self, extra_validators=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010768 | Implement the Python class `DeleteForm` described below.
Class description:
Permission delete form.
Method signatures and docstrings:
- def __init__(self, current_user, target_permission_id, *args, **kwargs): Create instance.
- def validate(self, extra_validators=None): Validate the form. | Implement the Python class `DeleteForm` described below.
Class description:
Permission delete form.
Method signatures and docstrings:
- def __init__(self, current_user, target_permission_id, *args, **kwargs): Create instance.
- def validate(self, extra_validators=None): Validate the form.
<|skeleton|>
class DeleteFo... | d2b66717d87ee2452edf0f6c04f6fdf4533091ba | <|skeleton|>
class DeleteForm:
"""Permission delete form."""
def __init__(self, current_user, target_permission_id, *args, **kwargs):
"""Create instance."""
<|body_0|>
def validate(self, extra_validators=None):
"""Validate the form."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeleteForm:
"""Permission delete form."""
def __init__(self, current_user, target_permission_id, *args, **kwargs):
"""Create instance."""
super(DeleteForm, self).__init__(*args, **kwargs)
self.current_user = current_user
self.target_permission_id = target_permission_id
... | the_stack_v2_python_sparse | xl_auth/permission/forms.py | libris/xl_auth | train | 8 |
62cd61bfa3959fc8f1aa859460607a59ba2dbd90 | [
"res = 0\ncounter = Counter()\nfor num1 in A:\n num2 = int(str(num1)[::-1])\n res += counter[num1 - num2]\n counter[num1 - num2] += 1\nreturn res % MOD",
"res = 0\nC = Counter((num - int(str(num)[::-1]) for num in A))\nfor count in C.values():\n res += count * (count - 1) // 2\nreturn res % MOD"
] | <|body_start_0|>
res = 0
counter = Counter()
for num1 in A:
num2 = int(str(num1)[::-1])
res += counter[num1 - num2]
counter[num1 - num2] += 1
return res % MOD
<|end_body_0|>
<|body_start_1|>
res = 0
C = Counter((num - int(str(num)[::-1... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countNicePairs(self, A: List[int]) -> int:
"""一遍遍历 前不看后"""
<|body_0|>
def countNicePairs2(self, A: List[int]) -> int:
"""先全部存起来再统计"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = 0
counter = Counter()
for num1 in ... | stack_v2_sparse_classes_75kplus_train_004030 | 1,195 | no_license | [
{
"docstring": "一遍遍历 前不看后",
"name": "countNicePairs",
"signature": "def countNicePairs(self, A: List[int]) -> int"
},
{
"docstring": "先全部存起来再统计",
"name": "countNicePairs2",
"signature": "def countNicePairs2(self, A: List[int]) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_019353 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countNicePairs(self, A: List[int]) -> int: 一遍遍历 前不看后
- def countNicePairs2(self, A: List[int]) -> int: 先全部存起来再统计 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countNicePairs(self, A: List[int]) -> int: 一遍遍历 前不看后
- def countNicePairs2(self, A: List[int]) -> int: 先全部存起来再统计
<|skeleton|>
class Solution:
def countNicePairs(self, A... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def countNicePairs(self, A: List[int]) -> int:
"""一遍遍历 前不看后"""
<|body_0|>
def countNicePairs2(self, A: List[int]) -> int:
"""先全部存起来再统计"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def countNicePairs(self, A: List[int]) -> int:
"""一遍遍历 前不看后"""
res = 0
counter = Counter()
for num1 in A:
num2 = int(str(num1)[::-1])
res += counter[num1 - num2]
counter[num1 - num2] += 1
return res % MOD
def countNiceP... | the_stack_v2_python_sparse | 19_数学/组合/组合配对/1814. 统计一个数组中好对子的数目.py | 981377660LMT/algorithm-study | train | 225 | |
c3e876561c8e5375d108e5ecc706a11f192da1c6 | [
"try:\n x = cls.get_list_val(x)\nexcept AssertionError:\n return False\nreturn x == cls.OK",
"try:\n x = cls.get_list_val(x)\nexcept AssertionError:\n return False\nreturn cls.has(x) and x != cls.OK",
"val1 = cls.get_list_val(val1)\nval2 = cls.get_list_val(val2)\nreturn cls.has(val1) and cls.has(val... | <|body_start_0|>
try:
x = cls.get_list_val(x)
except AssertionError:
return False
return x == cls.OK
<|end_body_0|>
<|body_start_1|>
try:
x = cls.get_list_val(x)
except AssertionError:
return False
return cls.has(x) and x !... | Error codes generated by instrument drivers and agents | InstErrorCode | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstErrorCode:
"""Error codes generated by instrument drivers and agents"""
def is_ok(cls, x):
"""Success test functional synonym. Will need iterable type checking if success codes get additional info in the future. @param x a str, tuple or list to match to an error code success valu... | stack_v2_sparse_classes_75kplus_train_004031 | 9,909 | permissive | [
{
"docstring": "Success test functional synonym. Will need iterable type checking if success codes get additional info in the future. @param x a str, tuple or list to match to an error code success value. @retval True if x is a success value, False otherwise.",
"name": "is_ok",
"signature": "def is_ok(c... | 5 | stack_v2_sparse_classes_30k_train_035952 | Implement the Python class `InstErrorCode` described below.
Class description:
Error codes generated by instrument drivers and agents
Method signatures and docstrings:
- def is_ok(cls, x): Success test functional synonym. Will need iterable type checking if success codes get additional info in the future. @param x a ... | Implement the Python class `InstErrorCode` described below.
Class description:
Error codes generated by instrument drivers and agents
Method signatures and docstrings:
- def is_ok(cls, x): Success test functional synonym. Will need iterable type checking if success codes get additional info in the future. @param x a ... | 122c629290d27f32f2f41dafd5c12469295e8acf | <|skeleton|>
class InstErrorCode:
"""Error codes generated by instrument drivers and agents"""
def is_ok(cls, x):
"""Success test functional synonym. Will need iterable type checking if success codes get additional info in the future. @param x a str, tuple or list to match to an error code success valu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InstErrorCode:
"""Error codes generated by instrument drivers and agents"""
def is_ok(cls, x):
"""Success test functional synonym. Will need iterable type checking if success codes get additional info in the future. @param x a str, tuple or list to match to an error code success value. @retval Tr... | the_stack_v2_python_sparse | pyon/agent/common.py | ooici/pyon | train | 9 |
1f339091d4d17b82737552178a4e467d0bbda83a | [
"self.reserve_capacity_data_file = reserve_capacity_data_file\nself.capacity_file = open(self.reserve_capacity_data_file, 'r')\nScale.__init__(self, sim=sim, scale_rate=scale_rate, startup_delay_func=startup_delay_func, shutdown_delay=shutdown_delay)",
"last_arrival_count = self.sim.user_generator.user_count_sinc... | <|body_start_0|>
self.reserve_capacity_data_file = reserve_capacity_data_file
self.capacity_file = open(self.reserve_capacity_data_file, 'r')
Scale.__init__(self, sim=sim, scale_rate=scale_rate, startup_delay_func=startup_delay_func, shutdown_delay=shutdown_delay)
<|end_body_0|>
<|body_start_1|... | Wake up periodically and Scale the cluster This scaler uses a data file driven reserve policy to request and release server resources from the cluster. | DataDrivenReservePolicy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataDrivenReservePolicy:
"""Wake up periodically and Scale the cluster This scaler uses a data file driven reserve policy to request and release server resources from the cluster."""
def __init__(self, sim, scale_rate, startup_delay_func, shutdown_delay, reserve_capacity_data_file):
... | stack_v2_sparse_classes_75kplus_train_004032 | 14,183 | no_license | [
{
"docstring": "Initializes a DataDrivenReservePolicy object parameters: sim -- The Simulation containing a cluster cluster object this scale function is managing scale_rate -- The interarrival time between scale events in seconds startup_delay_func -- A callable that returns the time a server spends in the boo... | 2 | null | Implement the Python class `DataDrivenReservePolicy` described below.
Class description:
Wake up periodically and Scale the cluster This scaler uses a data file driven reserve policy to request and release server resources from the cluster.
Method signatures and docstrings:
- def __init__(self, sim, scale_rate, start... | Implement the Python class `DataDrivenReservePolicy` described below.
Class description:
Wake up periodically and Scale the cluster This scaler uses a data file driven reserve policy to request and release server resources from the cluster.
Method signatures and docstrings:
- def __init__(self, sim, scale_rate, start... | 30dc0702f6189307ff776525a2f3006ec471de47 | <|skeleton|>
class DataDrivenReservePolicy:
"""Wake up periodically and Scale the cluster This scaler uses a data file driven reserve policy to request and release server resources from the cluster."""
def __init__(self, sim, scale_rate, startup_delay_func, shutdown_delay, reserve_capacity_data_file):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataDrivenReservePolicy:
"""Wake up periodically and Scale the cluster This scaler uses a data file driven reserve policy to request and release server resources from the cluster."""
def __init__(self, sim, scale_rate, startup_delay_func, shutdown_delay, reserve_capacity_data_file):
"""Initialize... | the_stack_v2_python_sparse | appsim/scaler/reserve_policy.py | bmbouter/vcl_simulation | train | 0 |
a6e991983146c68eebe494fbaa3a6f09e2a127d8 | [
"super(AddConstrParaReprBottleneck, self).__init__()\nif planes <= c_constr_para_repr:\n raise ValueError('Number of planes within AddConstrParaReprBottleneck should be greater than number of channels of constraint parameter representation.')\nself.c_constr_para_repr = c_c... | <|body_start_0|>
super(AddConstrParaReprBottleneck, self).__init__()
if planes <= c_constr_para_repr:
raise ValueError('Number of planes within AddConstrParaReprBottleneck should be greater than number of channels of constraint parameter representation... | Incorporate the constraint parameter representation g(s) via an additional input to the Bottleneck. This module has the constraint parameter representation g(s) as an additional input. The constraint parameter tensor is concatenated to the input of the first conv1x1 layer and the output channels are kept constant. The ... | AddConstrParaReprBottleneck | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddConstrParaReprBottleneck:
"""Incorporate the constraint parameter representation g(s) via an additional input to the Bottleneck. This module has the constraint parameter representation g(s) as an additional input. The constraint parameter tensor is concatenated to the input of the first conv1x... | stack_v2_sparse_classes_75kplus_train_004033 | 18,529 | permissive | [
{
"docstring": "Initialization. Args: c_constr_para_repr (int): Number of channels of constraint parameter representation tensor. inplanes (int): Number of input channels. downsample (obj): Torch nn.Module for replacing identity bypass with conv1x1 as a parametric bypass. Especially for the first Bottleneck wit... | 2 | stack_v2_sparse_classes_30k_test_001946 | Implement the Python class `AddConstrParaReprBottleneck` described below.
Class description:
Incorporate the constraint parameter representation g(s) via an additional input to the Bottleneck. This module has the constraint parameter representation g(s) as an additional input. The constraint parameter tensor is concat... | Implement the Python class `AddConstrParaReprBottleneck` described below.
Class description:
Incorporate the constraint parameter representation g(s) via an additional input to the Bottleneck. This module has the constraint parameter representation g(s) as an additional input. The constraint parameter tensor is concat... | 3f53a4694f3c6b229679ef9014ac98573f45fd43 | <|skeleton|>
class AddConstrParaReprBottleneck:
"""Incorporate the constraint parameter representation g(s) via an additional input to the Bottleneck. This module has the constraint parameter representation g(s) as an additional input. The constraint parameter tensor is concatenated to the input of the first conv1x... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AddConstrParaReprBottleneck:
"""Incorporate the constraint parameter representation g(s) via an additional input to the Bottleneck. This module has the constraint parameter representation g(s) as an additional input. The constraint parameter tensor is concatenated to the input of the first conv1x1 layer and t... | the_stack_v2_python_sparse | models/constraintnet.py | mbroso/constraintnet_facial_detect | train | 0 |
b991229cf13061246019878587a49fedd6b5c882 | [
"Conversion.__init__(self, esM, name, physicalUnit, commodityConversionFactors, **kwargs)\nself.modelingClass = ConversionDynamicModel\nself.downTimeMin = downTimeMin\nself.upTimeMin = upTimeMin\nself.rampUpMax = rampUpMax\nself.rampDownMax = rampDownMax\nutils.checkConversionDynamicSpecficDesignInputParams(self, e... | <|body_start_0|>
Conversion.__init__(self, esM, name, physicalUnit, commodityConversionFactors, **kwargs)
self.modelingClass = ConversionDynamicModel
self.downTimeMin = downTimeMin
self.upTimeMin = upTimeMin
self.rampUpMax = rampUpMax
self.rampDownMax = rampDownMax
... | Extension of the conversion class with more specific ramping behavior | ConversionDynamic | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConversionDynamic:
"""Extension of the conversion class with more specific ramping behavior"""
def __init__(self, esM, name, physicalUnit, commodityConversionFactors, downTimeMin=None, upTimeMin=None, rampUpMax=None, rampDownMax=None, **kwargs):
"""Constructor for creating a Conversi... | stack_v2_sparse_classes_75kplus_train_004034 | 20,610 | permissive | [
{
"docstring": "Constructor for creating a ConversionDynamic class instance. The ConversionDynamic component specific input arguments are described below. The Conversion specific input arguments are described in the Conversion class and the general component input arguments are described in the Component class.... | 2 | stack_v2_sparse_classes_30k_train_001384 | Implement the Python class `ConversionDynamic` described below.
Class description:
Extension of the conversion class with more specific ramping behavior
Method signatures and docstrings:
- def __init__(self, esM, name, physicalUnit, commodityConversionFactors, downTimeMin=None, upTimeMin=None, rampUpMax=None, rampDow... | Implement the Python class `ConversionDynamic` described below.
Class description:
Extension of the conversion class with more specific ramping behavior
Method signatures and docstrings:
- def __init__(self, esM, name, physicalUnit, commodityConversionFactors, downTimeMin=None, upTimeMin=None, rampUpMax=None, rampDow... | 18c5a983f194ec4fc4bd168db38ff36aa53d5ebd | <|skeleton|>
class ConversionDynamic:
"""Extension of the conversion class with more specific ramping behavior"""
def __init__(self, esM, name, physicalUnit, commodityConversionFactors, downTimeMin=None, upTimeMin=None, rampUpMax=None, rampDownMax=None, **kwargs):
"""Constructor for creating a Conversi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConversionDynamic:
"""Extension of the conversion class with more specific ramping behavior"""
def __init__(self, esM, name, physicalUnit, commodityConversionFactors, downTimeMin=None, upTimeMin=None, rampUpMax=None, rampDownMax=None, **kwargs):
"""Constructor for creating a ConversionDynamic cla... | the_stack_v2_python_sparse | FINE/subclasses/conversionDynamic.py | OfficialCodexplosive/FINE-GL | train | 1 |
cfd71df9fda3d8beecdc432794abd6638b18ac74 | [
"keys_list = []\nvalue_list = []\nfor key in sorted(input_entry.keys()):\n resp_in = input_entry[key]\n for elements in resp_in:\n for key_in in sorted(elements.keys()):\n keys_list.append(key_in)\n value_list.append(elements[key_in])\nkeys = keys_list\nvalues = value_list\nreturn... | <|body_start_0|>
keys_list = []
value_list = []
for key in sorted(input_entry.keys()):
resp_in = input_entry[key]
for elements in resp_in:
for key_in in sorted(elements.keys()):
keys_list.append(key_in)
value_list.ap... | This class converts JSONs from the MCenter time capture to pandas Dataframes | JsonToDf | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JsonToDf:
"""This class converts JSONs from the MCenter time capture to pandas Dataframes"""
def parse_bar(input_entry):
"""This function extracts the bargraph line. each row is spanned: Name, time, keys, values :param input_entry: line to parse :return: parsed_entry"""
<|bod... | stack_v2_sparse_classes_75kplus_train_004035 | 3,063 | permissive | [
{
"docstring": "This function extracts the bargraph line. each row is spanned: Name, time, keys, values :param input_entry: line to parse :return: parsed_entry",
"name": "parse_bar",
"signature": "def parse_bar(input_entry)"
},
{
"docstring": "This function extracts the linegraph/multilinegraph/... | 4 | null | Implement the Python class `JsonToDf` described below.
Class description:
This class converts JSONs from the MCenter time capture to pandas Dataframes
Method signatures and docstrings:
- def parse_bar(input_entry): This function extracts the bargraph line. each row is spanned: Name, time, keys, values :param input_en... | Implement the Python class `JsonToDf` described below.
Class description:
This class converts JSONs from the MCenter time capture to pandas Dataframes
Method signatures and docstrings:
- def parse_bar(input_entry): This function extracts the bargraph line. each row is spanned: Name, time, keys, values :param input_en... | 738356ce6d5e691a5d813acafa3f0ff730e76136 | <|skeleton|>
class JsonToDf:
"""This class converts JSONs from the MCenter time capture to pandas Dataframes"""
def parse_bar(input_entry):
"""This function extracts the bargraph line. each row is spanned: Name, time, keys, values :param input_entry: line to parse :return: parsed_entry"""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JsonToDf:
"""This class converts JSONs from the MCenter time capture to pandas Dataframes"""
def parse_bar(input_entry):
"""This function extracts the bargraph line. each row is spanned: Name, time, keys, values :param input_entry: line to parse :return: parsed_entry"""
keys_list = []
... | the_stack_v2_python_sparse | mlops/parallelm/mlops/time_capture/json_to_df.py | theromis/mlpiper | train | 0 |
2691735d5158747afb8d5a30c471541d3adad40d | [
"if root is None:\n return 0\nself.__findNode(root, 1)\nreturn self.__answer",
"if node.left is None and node.right is None:\n if depth < self.__answer:\n self.__answer = depth\nif node.left is not None:\n self.__findNode(node.left, depth + 1)\nif node.right is not None:\n self.__findNode(node.... | <|body_start_0|>
if root is None:
return 0
self.__findNode(root, 1)
return self.__answer
<|end_body_0|>
<|body_start_1|>
if node.left is None and node.right is None:
if depth < self.__answer:
self.__answer = depth
if node.left is not None:... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def __findNode(self, node, depth):
""":type node: TreeNode :type depth: int :rtype: None"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if root is None:
... | stack_v2_sparse_classes_75kplus_train_004036 | 1,283 | permissive | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "minDepth",
"signature": "def minDepth(self, root)"
},
{
"docstring": ":type node: TreeNode :type depth: int :rtype: None",
"name": "__findNode",
"signature": "def __findNode(self, node, depth)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDepth(self, root): :type root: TreeNode :rtype: int
- def __findNode(self, node, depth): :type node: TreeNode :type depth: int :rtype: None | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDepth(self, root): :type root: TreeNode :rtype: int
- def __findNode(self, node, depth): :type node: TreeNode :type depth: int :rtype: None
<|skeleton|>
class Solution:
... | c60b332866caa28e1ae5e216cbfc2c6f869a751a | <|skeleton|>
class Solution:
def minDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def __findNode(self, node, depth):
""":type node: TreeNode :type depth: int :rtype: None"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minDepth(self, root):
""":type root: TreeNode :rtype: int"""
if root is None:
return 0
self.__findNode(root, 1)
return self.__answer
def __findNode(self, node, depth):
""":type node: TreeNode :type depth: int :rtype: None"""
if nod... | the_stack_v2_python_sparse | leetcode/easy/tree/test_minimum_depth_of_binary_tree.py | yenbohuang/online-contest-python | train | 0 | |
06c00d0eb0bad3e2504838b58eceb3dd66113bfd | [
"context = {}\nwizardPost = request.session.get('wizardPost')\nwizard_form = SettingsWizardForm(wizardPost)\nif wizardPost and 'shelly_types' in wizardPost:\n shelly_type = wizardPost['shelly_types']\n shelly_choices = []\n shellies = Shellies.objects.filter(shelly_type=shelly_type).order_by('shelly_type',... | <|body_start_0|>
context = {}
wizardPost = request.session.get('wizardPost')
wizard_form = SettingsWizardForm(wizardPost)
if wizardPost and 'shelly_types' in wizardPost:
shelly_type = wizardPost['shelly_types']
shelly_choices = []
shellies = Shellies.o... | View for the first page of the Shelly Settings wizard Select Shelly Type, Shellies and settings area For switching between the wizard-pages data will be stored in a session | ShellyWizardSelectView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShellyWizardSelectView:
"""View for the first page of the Shelly Settings wizard Select Shelly Type, Shellies and settings area For switching between the wizard-pages data will be stored in a session"""
def get(self, request, *args, **kwargs):
"""GET view with pre-filled form"""
... | stack_v2_sparse_classes_75kplus_train_004037 | 10,264 | permissive | [
{
"docstring": "GET view with pre-filled form",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "POST view with prefilled form based on POST request",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_048205 | Implement the Python class `ShellyWizardSelectView` described below.
Class description:
View for the first page of the Shelly Settings wizard Select Shelly Type, Shellies and settings area For switching between the wizard-pages data will be stored in a session
Method signatures and docstrings:
- def get(self, request... | Implement the Python class `ShellyWizardSelectView` described below.
Class description:
View for the first page of the Shelly Settings wizard Select Shelly Type, Shellies and settings area For switching between the wizard-pages data will be stored in a session
Method signatures and docstrings:
- def get(self, request... | 23f1551dd6e55d1d1145a3b9c8a0c728a169a5db | <|skeleton|>
class ShellyWizardSelectView:
"""View for the first page of the Shelly Settings wizard Select Shelly Type, Shellies and settings area For switching between the wizard-pages data will be stored in a session"""
def get(self, request, *args, **kwargs):
"""GET view with pre-filled form"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ShellyWizardSelectView:
"""View for the first page of the Shelly Settings wizard Select Shelly Type, Shellies and settings area For switching between the wizard-pages data will be stored in a session"""
def get(self, request, *args, **kwargs):
"""GET view with pre-filled form"""
context =... | the_stack_v2_python_sparse | shellyupdater/setter/views.py | nicx/shellyupdater | train | 0 |
7f21dcf95b011292844fa197982adee16c80fead | [
"super().__init__()\nt = int(abs(math.log(in_channels, 2) + beta) / gamma)\nkernel_size = max(t if t % 2 else t + 1, 3)\npadding = (kernel_size - 1) // 2\nself.conv = nn.Conv1d(1, 1, kernel_size=kernel_size, padding=padding, bias=False)\nself.gate = Activation(gate_activation)",
"B = x.shape[0]\ny = x.mean((2, 3)... | <|body_start_0|>
super().__init__()
t = int(abs(math.log(in_channels, 2) + beta) / gamma)
kernel_size = max(t if t % 2 else t + 1, 3)
padding = (kernel_size - 1) // 2
self.conv = nn.Conv1d(1, 1, kernel_size=kernel_size, padding=padding, bias=False)
self.gate = Activation(... | ECA | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ECA:
def __init__(self, in_channels: int, beta: int=1, gamma: int=2, gate_activation: str='sigmoid', **kwargs) -> None:
"""Efficient Channel Attention (ECA). https://arxiv.org/abs/1910.03151 Parameters ---------- in_channels : int Number of input channels. beta : int, default=1 Coefficie... | stack_v2_sparse_classes_75kplus_train_004038 | 11,576 | permissive | [
{
"docstring": "Efficient Channel Attention (ECA). https://arxiv.org/abs/1910.03151 Parameters ---------- in_channels : int Number of input channels. beta : int, default=1 Coefficient used to compute the kernel size adaptively. gamma : int, default=2 Coefficient used to compute the kernel size adaptively. gate_... | 2 | stack_v2_sparse_classes_30k_train_051860 | Implement the Python class `ECA` described below.
Class description:
Implement the ECA class.
Method signatures and docstrings:
- def __init__(self, in_channels: int, beta: int=1, gamma: int=2, gate_activation: str='sigmoid', **kwargs) -> None: Efficient Channel Attention (ECA). https://arxiv.org/abs/1910.03151 Param... | Implement the Python class `ECA` described below.
Class description:
Implement the ECA class.
Method signatures and docstrings:
- def __init__(self, in_channels: int, beta: int=1, gamma: int=2, gate_activation: str='sigmoid', **kwargs) -> None: Efficient Channel Attention (ECA). https://arxiv.org/abs/1910.03151 Param... | 7f79405012eb934b419bbdba8de23f35e840ca85 | <|skeleton|>
class ECA:
def __init__(self, in_channels: int, beta: int=1, gamma: int=2, gate_activation: str='sigmoid', **kwargs) -> None:
"""Efficient Channel Attention (ECA). https://arxiv.org/abs/1910.03151 Parameters ---------- in_channels : int Number of input channels. beta : int, default=1 Coefficie... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ECA:
def __init__(self, in_channels: int, beta: int=1, gamma: int=2, gate_activation: str='sigmoid', **kwargs) -> None:
"""Efficient Channel Attention (ECA). https://arxiv.org/abs/1910.03151 Parameters ---------- in_channels : int Number of input channels. beta : int, default=1 Coefficient used to com... | the_stack_v2_python_sparse | cellseg_models_pytorch/modules/attention_modules.py | okunator/cellseg_models.pytorch | train | 43 | |
a0bf1ec2ab33c557ab9447c3edd3a876c713f504 | [
"checkpoint = {'model': model_state_dict, 'opt': opt, 'epoch': epoch, 'best_accuracy': best_accuracy, 'history': history}\nif save_type == 0:\n print('Backing up model...')\n model_name = '%s.pt' % opt.save_model\nelif save_type == 1:\n print('Saving the best model...')\n model_name = '%s_best.pt' % opt... | <|body_start_0|>
checkpoint = {'model': model_state_dict, 'opt': opt, 'epoch': epoch, 'best_accuracy': best_accuracy, 'history': history}
if save_type == 0:
print('Backing up model...')
model_name = '%s.pt' % opt.save_model
elif save_type == 1:
print('Saving t... | Saver | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Saver:
def save_model(model_state_dict, opt, epoch, best_accuracy, history, save_type=0):
"""Save our network. -------------------- Arguments: model_state_dict (dict): contains modules and its parameters. opt (args object): option for the training procedure. epoch (int): checkpoint of ep... | stack_v2_sparse_classes_75kplus_train_004039 | 8,090 | permissive | [
{
"docstring": "Save our network. -------------------- Arguments: model_state_dict (dict): contains modules and its parameters. opt (args object): option for the training procedure. epoch (int): checkpoint of epoch. best_accuracy (float): the best accuracy at the saving time. history (list): previous accuracies... | 2 | stack_v2_sparse_classes_30k_train_038636 | Implement the Python class `Saver` described below.
Class description:
Implement the Saver class.
Method signatures and docstrings:
- def save_model(model_state_dict, opt, epoch, best_accuracy, history, save_type=0): Save our network. -------------------- Arguments: model_state_dict (dict): contains modules and its p... | Implement the Python class `Saver` described below.
Class description:
Implement the Saver class.
Method signatures and docstrings:
- def save_model(model_state_dict, opt, epoch, best_accuracy, history, save_type=0): Save our network. -------------------- Arguments: model_state_dict (dict): contains modules and its p... | 4bd82682b30a471edf19f6d88a87ef4399e7c4ba | <|skeleton|>
class Saver:
def save_model(model_state_dict, opt, epoch, best_accuracy, history, save_type=0):
"""Save our network. -------------------- Arguments: model_state_dict (dict): contains modules and its parameters. opt (args object): option for the training procedure. epoch (int): checkpoint of ep... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Saver:
def save_model(model_state_dict, opt, epoch, best_accuracy, history, save_type=0):
"""Save our network. -------------------- Arguments: model_state_dict (dict): contains modules and its parameters. opt (args object): option for the training procedure. epoch (int): checkpoint of epoch. best_accu... | the_stack_v2_python_sparse | dense_coattn/util/utils.py | yuzhiw/Dense-CoAttention-Network | train | 1 | |
240e22d2073d26269e45654f312638034d67002d | [
"head_list = ListNode(0)\nhead_list.next = head\ntemp = head_list\nwhile temp.next and temp.next.next:\n node_1 = temp.next\n node_2 = temp.next.next\n temp.next = node_2\n node_1.next = node_2.next\n node_2.next = node_1\n temp = node_1\nreturn head_list.next",
"if head and head.next:\n node... | <|body_start_0|>
head_list = ListNode(0)
head_list.next = head
temp = head_list
while temp.next and temp.next.next:
node_1 = temp.next
node_2 = temp.next.next
temp.next = node_2
node_1.next = node_2.next
node_2.next = node_1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def swapPairs(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def swapPairsRecursion(self, head):
""":type head: ListNode :rtype: Lis tNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
head_list = ListNode(0)
... | stack_v2_sparse_classes_75kplus_train_004040 | 947 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "swapPairs",
"signature": "def swapPairs(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: Lis tNode",
"name": "swapPairsRecursion",
"signature": "def swapPairsRecursion(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004272 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swapPairs(self, head): :type head: ListNode :rtype: ListNode
- def swapPairsRecursion(self, head): :type head: ListNode :rtype: Lis tNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swapPairs(self, head): :type head: ListNode :rtype: ListNode
- def swapPairsRecursion(self, head): :type head: ListNode :rtype: Lis tNode
<|skeleton|>
class Solution:
d... | 9648096c8508884c348a55ff4967d61773ef1a0c | <|skeleton|>
class Solution:
def swapPairs(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def swapPairsRecursion(self, head):
""":type head: ListNode :rtype: Lis tNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def swapPairs(self, head):
""":type head: ListNode :rtype: ListNode"""
head_list = ListNode(0)
head_list.next = head
temp = head_list
while temp.next and temp.next.next:
node_1 = temp.next
node_2 = temp.next.next
temp.next =... | the_stack_v2_python_sparse | AlgorithmProblem/两两交换链表中的节点.py | Darr-en1/practice | train | 2 | |
7a08fae5d220f1111339dcec9547605ed1f1adac | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn SynchronizationJob()",
"from .entity import Entity\nfrom .key_value_pair import KeyValuePair\nfrom .synchronization_schedule import SynchronizationSchedule\nfrom .synchronization_schema import SynchronizationSchema\nfrom .synchronizati... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return SynchronizationJob()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .key_value_pair import KeyValuePair
from .synchronization_schedule import SynchronizationSche... | SynchronizationJob | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SynchronizationJob:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SynchronizationJob:
"""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 obje... | stack_v2_sparse_classes_75kplus_train_004041 | 4,015 | 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: SynchronizationJob",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_... | 3 | stack_v2_sparse_classes_30k_train_021359 | Implement the Python class `SynchronizationJob` described below.
Class description:
Implement the SynchronizationJob class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SynchronizationJob: Creates a new instance of the appropriate class based on disc... | Implement the Python class `SynchronizationJob` described below.
Class description:
Implement the SynchronizationJob class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SynchronizationJob: Creates a new instance of the appropriate class based on disc... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class SynchronizationJob:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SynchronizationJob:
"""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 obje... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SynchronizationJob:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SynchronizationJob:
"""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: Sy... | the_stack_v2_python_sparse | msgraph/generated/models/synchronization_job.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
4c231424109f9ebd43336ce8213490328a2f8caa | [
"self.done = False\nself.success = False\nself.x_init = init_state[0]\nself.x_lim = 0.0\nself.xd_max = 0.0001\nself.delta_x_min = 0.1\nself.sign = 1 if positive else -1\nself.u_max = self.sign * np.array([1.5])\nself._t0 = None\nself._t_max = 10.0\nself._t_min = 2.0",
"x, _, _, xd, _ = obs\nif self._t0 is None:\n... | <|body_start_0|>
self.done = False
self.success = False
self.x_init = init_state[0]
self.x_lim = 0.0
self.xd_max = 0.0001
self.delta_x_min = 0.1
self.sign = 1 if positive else -1
self.u_max = self.sign * np.array([1.5])
self._t0 = None
self... | Controller for going to one of the joint limits (part of the calibration routine) | QCartPoleGoToLimCtrl | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QCartPoleGoToLimCtrl:
"""Controller for going to one of the joint limits (part of the calibration routine)"""
def __init__(self, init_state: np.ndarray, positive: bool=True):
"""Constructor :param init_state: initial state of the system :param positive: direction switch"""
<|... | stack_v2_sparse_classes_75kplus_train_004042 | 32,197 | permissive | [
{
"docstring": "Constructor :param init_state: initial state of the system :param positive: direction switch",
"name": "__init__",
"signature": "def __init__(self, init_state: np.ndarray, positive: bool=True)"
},
{
"docstring": "Go to joint limits by applying u_max and save limit value in th_lim... | 2 | stack_v2_sparse_classes_30k_train_000890 | Implement the Python class `QCartPoleGoToLimCtrl` described below.
Class description:
Controller for going to one of the joint limits (part of the calibration routine)
Method signatures and docstrings:
- def __init__(self, init_state: np.ndarray, positive: bool=True): Constructor :param init_state: initial state of t... | Implement the Python class `QCartPoleGoToLimCtrl` described below.
Class description:
Controller for going to one of the joint limits (part of the calibration routine)
Method signatures and docstrings:
- def __init__(self, init_state: np.ndarray, positive: bool=True): Constructor :param init_state: initial state of t... | d7e9cd191ccb318d5f1e580babc2fc38b5b3675a | <|skeleton|>
class QCartPoleGoToLimCtrl:
"""Controller for going to one of the joint limits (part of the calibration routine)"""
def __init__(self, init_state: np.ndarray, positive: bool=True):
"""Constructor :param init_state: initial state of the system :param positive: direction switch"""
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QCartPoleGoToLimCtrl:
"""Controller for going to one of the joint limits (part of the calibration routine)"""
def __init__(self, init_state: np.ndarray, positive: bool=True):
"""Constructor :param init_state: initial state of the system :param positive: direction switch"""
self.done = Fal... | the_stack_v2_python_sparse | Pyrado/pyrado/policies/special/environment_specific.py | 1abner1/SimuRLacra | train | 0 |
f2bee36372386b72cd7497612d447b32f893e3ba | [
"self.positivePath, self.negetivePath = self.getPath()\nself.get_picture_path()\nself.rotate()\nself.split_images()\nif save:\n self.save()",
"front_viwe = np.load(front_viwe_path, allow_pickle=True).item()\npositivePath = front_viwe['81']\nnegetivePath = []\nfor key, paths in front_viwe.items():\n if key !... | <|body_start_0|>
self.positivePath, self.negetivePath = self.getPath()
self.get_picture_path()
self.rotate()
self.split_images()
if save:
self.save()
<|end_body_0|>
<|body_start_1|>
front_viwe = np.load(front_viwe_path, allow_pickle=True).item()
posit... | imagePocess | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class imagePocess:
def __init__(self, save: bool=True):
"""Parameters ---------- save : bool, optional The value is control when this class func finish whether save the result. Tue default is True Returns ------- None."""
<|body_0|>
def getPath(self, front_viwe_path: str='./data/f... | stack_v2_sparse_classes_75kplus_train_004043 | 5,760 | permissive | [
{
"docstring": "Parameters ---------- save : bool, optional The value is control when this class func finish whether save the result. Tue default is True Returns ------- None.",
"name": "__init__",
"signature": "def __init__(self, save: bool=True)"
},
{
"docstring": "Parameters ---------- front_... | 6 | stack_v2_sparse_classes_30k_test_001039 | Implement the Python class `imagePocess` described below.
Class description:
Implement the imagePocess class.
Method signatures and docstrings:
- def __init__(self, save: bool=True): Parameters ---------- save : bool, optional The value is control when this class func finish whether save the result. Tue default is Tr... | Implement the Python class `imagePocess` described below.
Class description:
Implement the imagePocess class.
Method signatures and docstrings:
- def __init__(self, save: bool=True): Parameters ---------- save : bool, optional The value is control when this class func finish whether save the result. Tue default is Tr... | 084b8c2b0437e3a30e2d74132cc3a55a06f18968 | <|skeleton|>
class imagePocess:
def __init__(self, save: bool=True):
"""Parameters ---------- save : bool, optional The value is control when this class func finish whether save the result. Tue default is True Returns ------- None."""
<|body_0|>
def getPath(self, front_viwe_path: str='./data/f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class imagePocess:
def __init__(self, save: bool=True):
"""Parameters ---------- save : bool, optional The value is control when this class func finish whether save the result. Tue default is True Returns ------- None."""
self.positivePath, self.negetivePath = self.getPath()
self.get_picture... | the_stack_v2_python_sparse | packages/prepare.py | YYYYifan/Real_Time_Car_Recognication_Embedded_System_Based_on_Convolution_Neural_Network | train | 0 | |
1d9e97d9551137e600416e0d8f55e802b234d908 | [
"self.noun_to_adj = {}\nfor noun in noun_list:\n self.noun_to_adj[noun] = []\nself.tokenizer = TreebankWordTokenizer()\nself.bert_model = Bert()\nself.adj_tags = ['JJ', 'JJR', 'JJS']\nself.noun_tags = ['NN', 'NNS', 'NNP', 'NNPS']\nself.noun_list = noun_list\nself.adj_list = adj_list",
"for sent in sentences:\n... | <|body_start_0|>
self.noun_to_adj = {}
for noun in noun_list:
self.noun_to_adj[noun] = []
self.tokenizer = TreebankWordTokenizer()
self.bert_model = Bert()
self.adj_tags = ['JJ', 'JJR', 'JJS']
self.noun_tags = ['NN', 'NNS', 'NNP', 'NNPS']
self.noun_lis... | Add adjectives for nouns in dictionary noun_to_adj. Attributes: noun_to_adj : Noun to adjective dictionary. tokenizer : An instance of nltk's tokenizer. bert_model : An instance of class bert. adj_tags : Tags of adjectives in nltk. noun_tags : Tags of nouns in nltk. noun_list : List of nouns that we are working on. adj... | NounToAdjGen | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NounToAdjGen:
"""Add adjectives for nouns in dictionary noun_to_adj. Attributes: noun_to_adj : Noun to adjective dictionary. tokenizer : An instance of nltk's tokenizer. bert_model : An instance of class bert. adj_tags : Tags of adjectives in nltk. noun_tags : Tags of nouns in nltk. noun_list : L... | stack_v2_sparse_classes_75kplus_train_004044 | 4,308 | permissive | [
{
"docstring": "Initializing noun to adjective dictionary.",
"name": "__init__",
"signature": "def __init__(self, noun_list, adj_list)"
},
{
"docstring": "Add adjectives for nouns by perturbing sentence to noun_to_adj. Args: sentences : The list of sentences for which to look up for nouns and ad... | 4 | stack_v2_sparse_classes_30k_train_023855 | Implement the Python class `NounToAdjGen` described below.
Class description:
Add adjectives for nouns in dictionary noun_to_adj. Attributes: noun_to_adj : Noun to adjective dictionary. tokenizer : An instance of nltk's tokenizer. bert_model : An instance of class bert. adj_tags : Tags of adjectives in nltk. noun_tags... | Implement the Python class `NounToAdjGen` described below.
Class description:
Add adjectives for nouns in dictionary noun_to_adj. Attributes: noun_to_adj : Noun to adjective dictionary. tokenizer : An instance of nltk's tokenizer. bert_model : An instance of class bert. adj_tags : Tags of adjectives in nltk. noun_tags... | 8029927bfd45d378dd920c9b27f2ca0d06063fa5 | <|skeleton|>
class NounToAdjGen:
"""Add adjectives for nouns in dictionary noun_to_adj. Attributes: noun_to_adj : Noun to adjective dictionary. tokenizer : An instance of nltk's tokenizer. bert_model : An instance of class bert. adj_tags : Tags of adjectives in nltk. noun_tags : Tags of nouns in nltk. noun_list : L... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NounToAdjGen:
"""Add adjectives for nouns in dictionary noun_to_adj. Attributes: noun_to_adj : Noun to adjective dictionary. tokenizer : An instance of nltk's tokenizer. bert_model : An instance of class bert. adj_tags : Tags of adjectives in nltk. noun_tags : Tags of nouns in nltk. noun_list : List of nouns ... | the_stack_v2_python_sparse | generate_noun_to_adj_list/noun_to_adj_gen.py | googleinterns/contextual-adjectives | train | 1 |
b18498e199f4e0a5b7b0594be8f212f284b4f733 | [
"count = apply_tweet_filter_criteria(self, Tweets.objects).count()\nif count is None:\n return 0\nreturn count",
"queryset = apply_tweet_filter_criteria(self, Tweets.objects).filter(state=state)\nif sincePastNDays is not None:\n queryset = queryset.annotate(diff_in_days=Func(F('data__created_at'), function=... | <|body_start_0|>
count = apply_tweet_filter_criteria(self, Tweets.objects).count()
if count is None:
return 0
return count
<|end_body_0|>
<|body_start_1|>
queryset = apply_tweet_filter_criteria(self, Tweets.objects).filter(state=state)
if sincePastNDays is not None:
... | Columns configuring what to display for each social platform. | SocialColumns | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SocialColumns:
"""Columns configuring what to display for each social platform."""
def total_tweets(self):
"""Count the number of tweets for the column"""
<|body_0|>
def total_tweets_for_state(self, state, sincePastNDays=None):
"""Count the number of active tweet... | stack_v2_sparse_classes_75kplus_train_004045 | 8,576 | no_license | [
{
"docstring": "Count the number of tweets for the column",
"name": "total_tweets",
"signature": "def total_tweets(self)"
},
{
"docstring": "Count the number of active tweets for the column",
"name": "total_tweets_for_state",
"signature": "def total_tweets_for_state(self, state, sincePas... | 2 | stack_v2_sparse_classes_30k_train_000472 | Implement the Python class `SocialColumns` described below.
Class description:
Columns configuring what to display for each social platform.
Method signatures and docstrings:
- def total_tweets(self): Count the number of tweets for the column
- def total_tweets_for_state(self, state, sincePastNDays=None): Count the n... | Implement the Python class `SocialColumns` described below.
Class description:
Columns configuring what to display for each social platform.
Method signatures and docstrings:
- def total_tweets(self): Count the number of tweets for the column
- def total_tweets_for_state(self, state, sincePastNDays=None): Count the n... | 01aa6c3fe101e9c7f2290e40c979f270cbf43e83 | <|skeleton|>
class SocialColumns:
"""Columns configuring what to display for each social platform."""
def total_tweets(self):
"""Count the number of tweets for the column"""
<|body_0|>
def total_tweets_for_state(self, state, sincePastNDays=None):
"""Count the number of active tweet... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SocialColumns:
"""Columns configuring what to display for each social platform."""
def total_tweets(self):
"""Count the number of tweets for the column"""
count = apply_tweet_filter_criteria(self, Tweets.objects).count()
if count is None:
return 0
return count
... | the_stack_v2_python_sparse | django/scremsong/app/models.py | keithamoss/scremsong | train | 5 |
d278a5e47cf280bb5ad5cbd8c8306ad3e6541332 | [
"super().__init__()\nself._images_map = images_map\nself._scale_factor = scale_factor\nself._center_crop_factor = center_crop_factor",
"example = generate_image_triplet_example(triplet_dict, self._scale_factor, self._center_crop_factor)\nif example:\n return [example.SerializeToString()]\nelse:\n return []"... | <|body_start_0|>
super().__init__()
self._images_map = images_map
self._scale_factor = scale_factor
self._center_crop_factor = center_crop_factor
<|end_body_0|>
<|body_start_1|>
example = generate_image_triplet_example(triplet_dict, self._scale_factor, self._center_crop_factor)
... | Generate a tf.train.Example per input image triplet filepaths. | ExampleGenerator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExampleGenerator:
"""Generate a tf.train.Example per input image triplet filepaths."""
def __init__(self, images_map: Mapping[str, Any], scale_factor: int=1, center_crop_factor: int=1):
"""Initializes the map of 3 images to add to each tf.train.Example. Args: images_map: Map from ima... | stack_v2_sparse_classes_75kplus_train_004046 | 7,599 | permissive | [
{
"docstring": "Initializes the map of 3 images to add to each tf.train.Example. Args: images_map: Map from image key to image filepath. scale_factor: A scale factor to downsample frames. center_crop_factor: A factor to centercrop and downsize frames.",
"name": "__init__",
"signature": "def __init__(sel... | 2 | stack_v2_sparse_classes_30k_train_019283 | Implement the Python class `ExampleGenerator` described below.
Class description:
Generate a tf.train.Example per input image triplet filepaths.
Method signatures and docstrings:
- def __init__(self, images_map: Mapping[str, Any], scale_factor: int=1, center_crop_factor: int=1): Initializes the map of 3 images to add... | Implement the Python class `ExampleGenerator` described below.
Class description:
Generate a tf.train.Example per input image triplet filepaths.
Method signatures and docstrings:
- def __init__(self, images_map: Mapping[str, Any], scale_factor: int=1, center_crop_factor: int=1): Initializes the map of 3 images to add... | 4108849dc72ad5ea4a91bb13463860bec3b181d7 | <|skeleton|>
class ExampleGenerator:
"""Generate a tf.train.Example per input image triplet filepaths."""
def __init__(self, images_map: Mapping[str, Any], scale_factor: int=1, center_crop_factor: int=1):
"""Initializes the map of 3 images to add to each tf.train.Example. Args: images_map: Map from ima... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExampleGenerator:
"""Generate a tf.train.Example per input image triplet filepaths."""
def __init__(self, images_map: Mapping[str, Any], scale_factor: int=1, center_crop_factor: int=1):
"""Initializes the map of 3 images to add to each tf.train.Example. Args: images_map: Map from image key to ima... | the_stack_v2_python_sparse | docker/frame-interpolation/src/datasets/util.py | sbetzin/neural-style-azure | train | 4 |
e01d79ea55a7a7667092d85dc0dc249867207720 | [
"self.xint = xint\nself.yint = yint\nself.n = len(xint)\nw = np.ones(self.n)\nself.C = (np.max(xint) - np.min(xint)) / 4\nshuffle = np.random.permutation(self.n - 1)\nfor j in range(self.n):\n temp = (xint[j] - np.delete(xint, j)) / self.C\n temp = temp[shuffle]\n w[j] /= np.product(temp)\nself.weights = w... | <|body_start_0|>
self.xint = xint
self.yint = yint
self.n = len(xint)
w = np.ones(self.n)
self.C = (np.max(xint) - np.min(xint)) / 4
shuffle = np.random.permutation(self.n - 1)
for j in range(self.n):
temp = (xint[j] - np.delete(xint, j)) / self.C
... | Class for performing Barycentric Lagrange interpolation. Attributes: w ((n,) ndarray): Array of Barycentric weights. n (int): Number of interpolation points. x ((n,) ndarray): x values of interpolating points. y ((n,) ndarray): y values of interpolating points. | Barycentric | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Barycentric:
"""Class for performing Barycentric Lagrange interpolation. Attributes: w ((n,) ndarray): Array of Barycentric weights. n (int): Number of interpolation points. x ((n,) ndarray): x values of interpolating points. y ((n,) ndarray): y values of interpolating points."""
def __init_... | stack_v2_sparse_classes_75kplus_train_004047 | 6,344 | no_license | [
{
"docstring": "Calculate the Barycentric weights using initial interpolating points. Parameters: xint ((n,) ndarray): x values of interpolating points. yint ((n,) ndarray): y values of interpolating points.",
"name": "__init__",
"signature": "def __init__(self, xint, yint)"
},
{
"docstring": "U... | 3 | stack_v2_sparse_classes_30k_train_048627 | Implement the Python class `Barycentric` described below.
Class description:
Class for performing Barycentric Lagrange interpolation. Attributes: w ((n,) ndarray): Array of Barycentric weights. n (int): Number of interpolation points. x ((n,) ndarray): x values of interpolating points. y ((n,) ndarray): y values of in... | Implement the Python class `Barycentric` described below.
Class description:
Class for performing Barycentric Lagrange interpolation. Attributes: w ((n,) ndarray): Array of Barycentric weights. n (int): Number of interpolation points. x ((n,) ndarray): x values of interpolating points. y ((n,) ndarray): y values of in... | 6e969de3a8337b0bd9bb4ba7abac722ab5c065ab | <|skeleton|>
class Barycentric:
"""Class for performing Barycentric Lagrange interpolation. Attributes: w ((n,) ndarray): Array of Barycentric weights. n (int): Number of interpolation points. x ((n,) ndarray): x values of interpolating points. y ((n,) ndarray): y values of interpolating points."""
def __init_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Barycentric:
"""Class for performing Barycentric Lagrange interpolation. Attributes: w ((n,) ndarray): Array of Barycentric weights. n (int): Number of interpolation points. x ((n,) ndarray): x values of interpolating points. y ((n,) ndarray): y values of interpolating points."""
def __init__(self, xint,... | the_stack_v2_python_sparse | Class/ACME_Volume_2-Python/PolynomialInterpolation/polynomial_interpolation.py | scj1420/Class-Projects-Research | train | 0 |
4ae754fe248c3c85f5a79e1e4b7a167dbff76125 | [
"self.cache_dir = cache_dir\nif self.cache_dir is not None:\n if not os.path.isdir(cache_dir):\n logging.error('The cache_dir does not exist.')\n raise ValueError('The cache_dir does not exist.')\nself.world_hires = None\nself.countries_hires = None\nself.world_lores = None\nself.countries_lores = ... | <|body_start_0|>
self.cache_dir = cache_dir
if self.cache_dir is not None:
if not os.path.isdir(cache_dir):
logging.error('The cache_dir does not exist.')
raise ValueError('The cache_dir does not exist.')
self.world_hires = None
self.countries_... | Retrieve Natural Earth world boundaries. | NaturalEarth | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NaturalEarth:
"""Retrieve Natural Earth world boundaries."""
def __init__(self, cache_dir: str=None) -> None:
"""Initialise. Args: cache_dir: Optionally provide a location to cache boundary definition files locally and avoid unnecsessary downloads. Raises: ValueError: If the cache_di... | stack_v2_sparse_classes_75kplus_train_004048 | 5,419 | permissive | [
{
"docstring": "Initialise. Args: cache_dir: Optionally provide a location to cache boundary definition files locally and avoid unnecsessary downloads. Raises: ValueError: If the cache_dir does not exist.",
"name": "__init__",
"signature": "def __init__(self, cache_dir: str=None) -> None"
},
{
"... | 4 | stack_v2_sparse_classes_30k_train_007621 | Implement the Python class `NaturalEarth` described below.
Class description:
Retrieve Natural Earth world boundaries.
Method signatures and docstrings:
- def __init__(self, cache_dir: str=None) -> None: Initialise. Args: cache_dir: Optionally provide a location to cache boundary definition files locally and avoid un... | Implement the Python class `NaturalEarth` described below.
Class description:
Retrieve Natural Earth world boundaries.
Method signatures and docstrings:
- def __init__(self, cache_dir: str=None) -> None: Initialise. Args: cache_dir: Optionally provide a location to cache boundary definition files locally and avoid un... | 60d682c406a50c448658063121d7d13a85121920 | <|skeleton|>
class NaturalEarth:
"""Retrieve Natural Earth world boundaries."""
def __init__(self, cache_dir: str=None) -> None:
"""Initialise. Args: cache_dir: Optionally provide a location to cache boundary definition files locally and avoid unnecsessary downloads. Raises: ValueError: If the cache_di... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NaturalEarth:
"""Retrieve Natural Earth world boundaries."""
def __init__(self, cache_dir: str=None) -> None:
"""Initialise. Args: cache_dir: Optionally provide a location to cache boundary definition files locally and avoid unnecsessary downloads. Raises: ValueError: If the cache_dir does not ex... | the_stack_v2_python_sparse | pvoutput/grid_search/natural_earth.py | openclimatefix/pvoutput | train | 29 |
bc8fadbfb0a470e712c3eef3b4d98c7db0cdf3aa | [
"self.t = t\nself.r = r / 100\nself.sigma = sigma / 100\nself.s = int(s)\nself.nper_per_year = int(nper_per_year)",
"format_s = format_s = '(s=$' + '{0:.{1}f}'.format(self.s, 2)\nformat_t = ', t=' + '{0:.{1}f}'.format(self.t, 2)\nformat_r = ' (years), r=' + '{0:.{1}f}'.format(self.r * 100, 4)\nformat_sigma = ', s... | <|body_start_0|>
self.t = t
self.r = r / 100
self.sigma = sigma / 100
self.s = int(s)
self.nper_per_year = int(nper_per_year)
<|end_body_0|>
<|body_start_1|>
format_s = format_s = '(s=$' + '{0:.{1}f}'.format(self.s, 2)
format_t = ', t=' + '{0:.{1}f}'.format(self.... | This is the base class for option pricing using Monte Carlo simulation. It includes the methods for generating lists of returns and stock values. | MCStockSimulator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MCStockSimulator:
"""This is the base class for option pricing using Monte Carlo simulation. It includes the methods for generating lists of returns and stock values."""
def __init__(self, t, r, sigma, s=100, nper_per_year=250):
"""Creates an object for base class using Monte Carlo S... | stack_v2_sparse_classes_75kplus_train_004049 | 3,395 | no_license | [
{
"docstring": "Creates an object for base class using Monte Carlo Simulation Variables: s = beginning value t = years r = daily expected return (%) sigma = standard deviation of daily returns (%) nper_per_year = trading days in a year",
"name": "__init__",
"signature": "def __init__(self, t, r, sigma, ... | 5 | null | Implement the Python class `MCStockSimulator` described below.
Class description:
This is the base class for option pricing using Monte Carlo simulation. It includes the methods for generating lists of returns and stock values.
Method signatures and docstrings:
- def __init__(self, t, r, sigma, s=100, nper_per_year=2... | Implement the Python class `MCStockSimulator` described below.
Class description:
This is the base class for option pricing using Monte Carlo simulation. It includes the methods for generating lists of returns and stock values.
Method signatures and docstrings:
- def __init__(self, t, r, sigma, s=100, nper_per_year=2... | cba7379a9a611c743ef1376192b9755178da3fa4 | <|skeleton|>
class MCStockSimulator:
"""This is the base class for option pricing using Monte Carlo simulation. It includes the methods for generating lists of returns and stock values."""
def __init__(self, t, r, sigma, s=100, nper_per_year=250):
"""Creates an object for base class using Monte Carlo S... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MCStockSimulator:
"""This is the base class for option pricing using Monte Carlo simulation. It includes the methods for generating lists of returns and stock values."""
def __init__(self, t, r, sigma, s=100, nper_per_year=250):
"""Creates an object for base class using Monte Carlo Simulation Var... | the_stack_v2_python_sparse | MonteCarlo.py | aarwitz/PortfolioOptimizer | train | 1 |
754503282e85f93da799d11aaa717818f1a7e263 | [
"super().__init__()\nif padding is None:\n padding = (kernel_size - 1) // 2\nself.depthwise = nn.Conv2d(nin, nin, kernel_size=kernel_size, stride=stride, padding=padding, groups=nin)\nself.pointwise = nn.Conv2d(nin, nout, kernel_size=1)",
"out = self.depthwise(x)\nout = self.pointwise(out)\nreturn out"
] | <|body_start_0|>
super().__init__()
if padding is None:
padding = (kernel_size - 1) // 2
self.depthwise = nn.Conv2d(nin, nin, kernel_size=kernel_size, stride=stride, padding=padding, groups=nin)
self.pointwise = nn.Conv2d(nin, nout, kernel_size=1)
<|end_body_0|>
<|body_start... | Depthwise seperable convolution operation. | depthwise_separable_conv_general | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class depthwise_separable_conv_general:
"""Depthwise seperable convolution operation."""
def __init__(self, nin, nout, stride, kernel_size=3, padding=None):
"""Initialize depthwise_separable_conv_general."""
<|body_0|>
def forward(self, x):
"""Implement forward."""
... | stack_v2_sparse_classes_75kplus_train_004050 | 2,586 | permissive | [
{
"docstring": "Initialize depthwise_separable_conv_general.",
"name": "__init__",
"signature": "def __init__(self, nin, nout, stride, kernel_size=3, padding=None)"
},
{
"docstring": "Implement forward.",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021577 | Implement the Python class `depthwise_separable_conv_general` described below.
Class description:
Depthwise seperable convolution operation.
Method signatures and docstrings:
- def __init__(self, nin, nout, stride, kernel_size=3, padding=None): Initialize depthwise_separable_conv_general.
- def forward(self, x): Impl... | Implement the Python class `depthwise_separable_conv_general` described below.
Class description:
Depthwise seperable convolution operation.
Method signatures and docstrings:
- def __init__(self, nin, nout, stride, kernel_size=3, padding=None): Initialize depthwise_separable_conv_general.
- def forward(self, x): Impl... | 12e37a1991eb6771a2999fe0a46ddda920c47948 | <|skeleton|>
class depthwise_separable_conv_general:
"""Depthwise seperable convolution operation."""
def __init__(self, nin, nout, stride, kernel_size=3, padding=None):
"""Initialize depthwise_separable_conv_general."""
<|body_0|>
def forward(self, x):
"""Implement forward."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class depthwise_separable_conv_general:
"""Depthwise seperable convolution operation."""
def __init__(self, nin, nout, stride, kernel_size=3, padding=None):
"""Initialize depthwise_separable_conv_general."""
super().__init__()
if padding is None:
padding = (kernel_size - 1) ... | the_stack_v2_python_sparse | vega/networks/pytorch/customs/utils/ops.py | huawei-noah/vega | train | 850 |
04ea0e54f21c04dfcfc6f7f6927b8fc97c66fda8 | [
"super(GenSlice, self).__init__()\nself.slice = slice\nself.decoder = decoder\nself.axis = axis",
"z1 = inputs\nposterior = Normal(self.decoder(inputs))\nz2 = posterior.sample()\nz = tf.concat([z1, z2], axis=self.axis)\nldj = -posterior.log_prob(z2)\nreturn (z, ldj)",
"z1 = inputs\nz2 = Normal(self.decoder(inpu... | <|body_start_0|>
super(GenSlice, self).__init__()
self.slice = slice
self.decoder = decoder
self.axis = axis
<|end_body_0|>
<|body_start_1|>
z1 = inputs
posterior = Normal(self.decoder(inputs))
z2 = posterior.sample()
z = tf.concat([z1, z2], axis=self.axi... | Tensor slice for generative surjection. | GenSlice | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenSlice:
"""Tensor slice for generative surjection."""
def __init__(self, slice, decoder, axis=-1):
"""Initializer. Args: slice: int, slice size. decoder: tf.keras.Model, posterior approximator (deterministic). axis: int, slice axis."""
<|body_0|>
def call(self, inputs)... | stack_v2_sparse_classes_75kplus_train_004051 | 4,364 | permissive | [
{
"docstring": "Initializer. Args: slice: int, slice size. decoder: tf.keras.Model, posterior approximator (deterministic). axis: int, slice axis.",
"name": "__init__",
"signature": "def __init__(self, slice, decoder, axis=-1)"
},
{
"docstring": "Recover the sliced tensor and compute log-determi... | 4 | null | Implement the Python class `GenSlice` described below.
Class description:
Tensor slice for generative surjection.
Method signatures and docstrings:
- def __init__(self, slice, decoder, axis=-1): Initializer. Args: slice: int, slice size. decoder: tf.keras.Model, posterior approximator (deterministic). axis: int, slic... | Implement the Python class `GenSlice` described below.
Class description:
Tensor slice for generative surjection.
Method signatures and docstrings:
- def __init__(self, slice, decoder, axis=-1): Initializer. Args: slice: int, slice size. decoder: tf.keras.Model, posterior approximator (deterministic). axis: int, slic... | 950a06c5e85ffedec6a024e81dc5fae557e2aae8 | <|skeleton|>
class GenSlice:
"""Tensor slice for generative surjection."""
def __init__(self, slice, decoder, axis=-1):
"""Initializer. Args: slice: int, slice size. decoder: tf.keras.Model, posterior approximator (deterministic). axis: int, slice axis."""
<|body_0|>
def call(self, inputs)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GenSlice:
"""Tensor slice for generative surjection."""
def __init__(self, slice, decoder, axis=-1):
"""Initializer. Args: slice: int, slice size. decoder: tf.keras.Model, posterior approximator (deterministic). axis: int, slice axis."""
super(GenSlice, self).__init__()
self.slice... | the_stack_v2_python_sparse | survaeflow/transform/surjection/slice.py | revsic/tf-survae-flows | train | 2 |
27a5979383ab444ed1d28855f47099a0130a2c9d | [
"if obj.archive_id is None:\n return '<div class=\"right-align\"><button type=\"submit\" value=\"Save and add another\" class=\"waves-effect waves-light btn white-text\" name=\"_continue\">Process</button></div>'\nelse:\n import qrcode\n qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR... | <|body_start_0|>
if obj.archive_id is None:
return '<div class="right-align"><button type="submit" value="Save and add another" class="waves-effect waves-light btn white-text" name="_continue">Process</button></div>'
else:
import qrcode
qr = qrcode.QRCode(version=1, e... | LendAdmin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LendAdmin:
def _QR_Code(self, obj):
"""Generate QrCode using the python QRCode Library and save it in the media folders :param obj: Lending Record being edited :return: Markup Element"""
<|body_0|>
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""O... | stack_v2_sparse_classes_75kplus_train_004052 | 5,806 | permissive | [
{
"docstring": "Generate QrCode using the python QRCode Library and save it in the media folders :param obj: Lending Record being edited :return: Markup Element",
"name": "_QR_Code",
"signature": "def _QR_Code(self, obj)"
},
{
"docstring": "Only display books which are available. :param db_field... | 4 | stack_v2_sparse_classes_30k_test_000798 | Implement the Python class `LendAdmin` described below.
Class description:
Implement the LendAdmin class.
Method signatures and docstrings:
- def _QR_Code(self, obj): Generate QrCode using the python QRCode Library and save it in the media folders :param obj: Lending Record being edited :return: Markup Element
- def ... | Implement the Python class `LendAdmin` described below.
Class description:
Implement the LendAdmin class.
Method signatures and docstrings:
- def _QR_Code(self, obj): Generate QrCode using the python QRCode Library and save it in the media folders :param obj: Lending Record being edited :return: Markup Element
- def ... | c18dff5c3c89b75c9293044854e938030bb69299 | <|skeleton|>
class LendAdmin:
def _QR_Code(self, obj):
"""Generate QrCode using the python QRCode Library and save it in the media folders :param obj: Lending Record being edited :return: Markup Element"""
<|body_0|>
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""O... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LendAdmin:
def _QR_Code(self, obj):
"""Generate QrCode using the python QRCode Library and save it in the media folders :param obj: Lending Record being edited :return: Markup Element"""
if obj.archive_id is None:
return '<div class="right-align"><button type="submit" value="Save a... | the_stack_v2_python_sparse | librarybuddy/TransactionManager/admin.py | op3ntrap/mylibrary | train | 0 | |
bedc7e55f00d9abf808a7c3cd1a03e00f0a55fb0 | [
"super().__init__()\nself.device = device\nself.phase_delay = torch.exp(-np.pi * 1j * R2 / wavelength / f).to(device)",
"Eout = 1 * field * self.phase_delay\nif field.ndim == 2:\n return Eout.squeeze()\nelse:\n return Eout"
] | <|body_start_0|>
super().__init__()
self.device = device
self.phase_delay = torch.exp(-np.pi * 1j * R2 / wavelength / f).to(device)
<|end_body_0|>
<|body_start_1|>
Eout = 1 * field * self.phase_delay
if field.ndim == 2:
return Eout.squeeze()
else:
... | Thin_Lens | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Thin_Lens:
def __init__(self, f, wavelength, R2, device=torch.device('cpu'), dtype=torch.complex128):
"""Applies a quadratic phase to the field from Goodman's Introduction to Fourier Optics Ch5 pg 99 Parameters ========== f : float Focal length of lens (matching units with wavelength) wa... | stack_v2_sparse_classes_75kplus_train_004053 | 1,816 | no_license | [
{
"docstring": "Applies a quadratic phase to the field from Goodman's Introduction to Fourier Optics Ch5 pg 99 Parameters ========== f : float Focal length of lens (matching units with wavelength) wavelength : float wavelength R2 : float tensor Aperture coordinates in radius",
"name": "__init__",
"signa... | 2 | stack_v2_sparse_classes_30k_val_002491 | Implement the Python class `Thin_Lens` described below.
Class description:
Implement the Thin_Lens class.
Method signatures and docstrings:
- def __init__(self, f, wavelength, R2, device=torch.device('cpu'), dtype=torch.complex128): Applies a quadratic phase to the field from Goodman's Introduction to Fourier Optics ... | Implement the Python class `Thin_Lens` described below.
Class description:
Implement the Thin_Lens class.
Method signatures and docstrings:
- def __init__(self, f, wavelength, R2, device=torch.device('cpu'), dtype=torch.complex128): Applies a quadratic phase to the field from Goodman's Introduction to Fourier Optics ... | d10eec48c70b13bbc7b8a51877f20bbf9a87b177 | <|skeleton|>
class Thin_Lens:
def __init__(self, f, wavelength, R2, device=torch.device('cpu'), dtype=torch.complex128):
"""Applies a quadratic phase to the field from Goodman's Introduction to Fourier Optics Ch5 pg 99 Parameters ========== f : float Focal length of lens (matching units with wavelength) wa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Thin_Lens:
def __init__(self, f, wavelength, R2, device=torch.device('cpu'), dtype=torch.complex128):
"""Applies a quadratic phase to the field from Goodman's Introduction to Fourier Optics Ch5 pg 99 Parameters ========== f : float Focal length of lens (matching units with wavelength) wavelength : flo... | the_stack_v2_python_sparse | Optical_Components/Thin_Lens.py | lfiske1/Tocohpy | train | 0 | |
889d0f42cf5a96aa4b46ee8db75fb7541d15a309 | [
"cmd = ['hostnamectl', 'status', '|', 'grep', 'hostname', '|', 'tr', '-d', ' ', '|', 'cut', '-d:', '-f2']\nrc, out, _ = self._m.runCmd(cmd)\nif rc:\n return None\nreturn out.strip()",
"cmd = ['hostnamectl', 'set-hostname', name]\nrc, _, err = self._m.runCmd(cmd)\nif rc:\n raise Exception('Unable to set host... | <|body_start_0|>
cmd = ['hostnamectl', 'status', '|', 'grep', 'hostname', '|', 'tr', '-d', ' ', '|', 'cut', '-d:', '-f2']
rc, out, _ = self._m.runCmd(cmd)
if rc:
return None
return out.strip()
<|end_body_0|>
<|body_start_1|>
cmd = ['hostnamectl', 'set-hostname', name... | Handles hostname on >= RHEL7 systems Follows: http://www.itzgeek.com/how-tos/linux/centos-how-tos/ change-hostname-in-centos-7-rhel-7.html#axzz3IkdUGHUl | HostnameCtlHandler | [
"Apache-2.0",
"GPL-2.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HostnameCtlHandler:
"""Handles hostname on >= RHEL7 systems Follows: http://www.itzgeek.com/how-tos/linux/centos-how-tos/ change-hostname-in-centos-7-rhel-7.html#axzz3IkdUGHUl"""
def get_hostname(self):
"""Get hostname Returns: str: Hostname"""
<|body_0|>
def set_hostnam... | stack_v2_sparse_classes_75kplus_train_004054 | 18,818 | permissive | [
{
"docstring": "Get hostname Returns: str: Hostname",
"name": "get_hostname",
"signature": "def get_hostname(self)"
},
{
"docstring": "Set hostname persistently Args: name (str): Hostname to be set",
"name": "set_hostname",
"signature": "def set_hostname(self, name)"
}
] | 2 | stack_v2_sparse_classes_30k_train_033106 | Implement the Python class `HostnameCtlHandler` described below.
Class description:
Handles hostname on >= RHEL7 systems Follows: http://www.itzgeek.com/how-tos/linux/centos-how-tos/ change-hostname-in-centos-7-rhel-7.html#axzz3IkdUGHUl
Method signatures and docstrings:
- def get_hostname(self): Get hostname Returns:... | Implement the Python class `HostnameCtlHandler` described below.
Class description:
Handles hostname on >= RHEL7 systems Follows: http://www.itzgeek.com/how-tos/linux/centos-how-tos/ change-hostname-in-centos-7-rhel-7.html#axzz3IkdUGHUl
Method signatures and docstrings:
- def get_hostname(self): Get hostname Returns:... | 9a2730d9a61b268f45e9d3115b8bbba039b954db | <|skeleton|>
class HostnameCtlHandler:
"""Handles hostname on >= RHEL7 systems Follows: http://www.itzgeek.com/how-tos/linux/centos-how-tos/ change-hostname-in-centos-7-rhel-7.html#axzz3IkdUGHUl"""
def get_hostname(self):
"""Get hostname Returns: str: Hostname"""
<|body_0|>
def set_hostnam... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HostnameCtlHandler:
"""Handles hostname on >= RHEL7 systems Follows: http://www.itzgeek.com/how-tos/linux/centos-how-tos/ change-hostname-in-centos-7-rhel-7.html#axzz3IkdUGHUl"""
def get_hostname(self):
"""Get hostname Returns: str: Hostname"""
cmd = ['hostnamectl', 'status', '|', 'grep',... | the_stack_v2_python_sparse | rrmng/rrmngmnt/network.py | avihaie/bug-hunter | train | 0 |
7b861f1cef95e301af512c5a4505a5dab7701523 | [
"d = defaultdict(int)\nfor num in nums:\n d[num] += 1\nfor k, v in d.items():\n if v == 1:\n return k",
"res = 0\nfor i in range(32):\n sums = 0\n for num in nums:\n sums += num >> i & 1\n res |= sums % 3 << i\nreturn res"
] | <|body_start_0|>
d = defaultdict(int)
for num in nums:
d[num] += 1
for k, v in d.items():
if v == 1:
return k
<|end_body_0|>
<|body_start_1|>
res = 0
for i in range(32):
sums = 0
for num in nums:
sum... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def singleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def single_number(self, nums):
"""把每一个数对应位相加对3取余, 就是single number对应位的数字 :param nums: List[int] :return: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
d ... | stack_v2_sparse_classes_75kplus_train_004055 | 1,301 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "singleNumber",
"signature": "def singleNumber(self, nums)"
},
{
"docstring": "把每一个数对应位相加对3取余, 就是single number对应位的数字 :param nums: List[int] :return: int",
"name": "single_number",
"signature": "def single_number(self, nums)"
}... | 2 | stack_v2_sparse_classes_30k_train_020401 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber(self, nums): :type nums: List[int] :rtype: int
- def single_number(self, nums): 把每一个数对应位相加对3取余, 就是single number对应位的数字 :param nums: List[int] :return: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber(self, nums): :type nums: List[int] :rtype: int
- def single_number(self, nums): 把每一个数对应位相加对3取余, 就是single number对应位的数字 :param nums: List[int] :return: int
<|skel... | 215d513b3564a7a76db3d2b29e4acc341a68e8ee | <|skeleton|>
class Solution:
def singleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def single_number(self, nums):
"""把每一个数对应位相加对3取余, 就是single number对应位的数字 :param nums: List[int] :return: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def singleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
d = defaultdict(int)
for num in nums:
d[num] += 1
for k, v in d.items():
if v == 1:
return k
def single_number(self, nums):
"""把每一个数对应位相加对3取余, 就是... | the_stack_v2_python_sparse | python/bit-manipulation/single-number2.py | euxuoh/leetcode | train | 0 | |
0a7878929c443e79526ed7d337fcf224b0d4a603 | [
"user = request.user\nif not order_id:\n return redirect(reverse('user:order', kwargs={'page': 1}))\ntry:\n order = OrderInfo.objects.get(order_id=order_id, user=user)\nexcept OrderInfo.DoesNotExist:\n return redirect(reverse('user:order', kwargs={'page': 1}))\norder.status_name = OrderInfo.ORDER_STATUS[or... | <|body_start_0|>
user = request.user
if not order_id:
return redirect(reverse('user:order', kwargs={'page': 1}))
try:
order = OrderInfo.objects.get(order_id=order_id, user=user)
except OrderInfo.DoesNotExist:
return redirect(reverse('user:order', kwarg... | 订单评论 | CommentView | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentView:
"""订单评论"""
def get(self, request, order_id):
"""提供评论页面"""
<|body_0|>
def post(self, request, order_id):
"""处理评论内容"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
user = request.user
if not order_id:
return redire... | stack_v2_sparse_classes_75kplus_train_004056 | 25,239 | permissive | [
{
"docstring": "提供评论页面",
"name": "get",
"signature": "def get(self, request, order_id)"
},
{
"docstring": "处理评论内容",
"name": "post",
"signature": "def post(self, request, order_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002697 | Implement the Python class `CommentView` described below.
Class description:
订单评论
Method signatures and docstrings:
- def get(self, request, order_id): 提供评论页面
- def post(self, request, order_id): 处理评论内容 | Implement the Python class `CommentView` described below.
Class description:
订单评论
Method signatures and docstrings:
- def get(self, request, order_id): 提供评论页面
- def post(self, request, order_id): 处理评论内容
<|skeleton|>
class CommentView:
"""订单评论"""
def get(self, request, order_id):
"""提供评论页面"""
... | 2ce0e0a6cc09dbcb02b48e010e268fad2b41aef6 | <|skeleton|>
class CommentView:
"""订单评论"""
def get(self, request, order_id):
"""提供评论页面"""
<|body_0|>
def post(self, request, order_id):
"""处理评论内容"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CommentView:
"""订单评论"""
def get(self, request, order_id):
"""提供评论页面"""
user = request.user
if not order_id:
return redirect(reverse('user:order', kwargs={'page': 1}))
try:
order = OrderInfo.objects.get(order_id=order_id, user=user)
except Or... | the_stack_v2_python_sparse | apps/order/views.py | rivertoday/ecmexample | train | 1 |
1df2a7b9b344b978f4d863397f6f96c8901d7dd6 | [
"env_opt = 'NOSE_WITH_%s' % self.name.upper()\nenv_opt.replace('-', '_')\nparser.add_option('--with-%s' % self.name, dest=self.enableOpt, type='string', default='', help='Setup Pylons environment with the config file specified by ATTR [NOSE_ATTR]')",
"self.config_file = None\nself.conf = conf\nif hasattr(options,... | <|body_start_0|>
env_opt = 'NOSE_WITH_%s' % self.name.upper()
env_opt.replace('-', '_')
parser.add_option('--with-%s' % self.name, dest=self.enableOpt, type='string', default='', help='Setup Pylons environment with the config file specified by ATTR [NOSE_ATTR]')
<|end_body_0|>
<|body_start_1|>
... | Nose plugin extension For use with nose to allow a project to be configured before nose proceeds to scan the project for doc tests and unit tests. This prevents modules from being loaded without a configured Pylons environment. | PylonsPlugin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PylonsPlugin:
"""Nose plugin extension For use with nose to allow a project to be configured before nose proceeds to scan the project for doc tests and unit tests. This prevents modules from being loaded without a configured Pylons environment."""
def add_options(self, parser, env=os.environ... | stack_v2_sparse_classes_75kplus_train_004057 | 2,384 | no_license | [
{
"docstring": "Add command-line options for this plugin",
"name": "add_options",
"signature": "def add_options(self, parser, env=os.environ)"
},
{
"docstring": "Configure the plugin",
"name": "configure",
"signature": "def configure(self, options, conf)"
},
{
"docstring": "Calle... | 3 | stack_v2_sparse_classes_30k_train_032923 | Implement the Python class `PylonsPlugin` described below.
Class description:
Nose plugin extension For use with nose to allow a project to be configured before nose proceeds to scan the project for doc tests and unit tests. This prevents modules from being loaded without a configured Pylons environment.
Method signa... | Implement the Python class `PylonsPlugin` described below.
Class description:
Nose plugin extension For use with nose to allow a project to be configured before nose proceeds to scan the project for doc tests and unit tests. This prevents modules from being loaded without a configured Pylons environment.
Method signa... | 89e1cac49b282106ff4595f54a4eb84bcc8d2ee9 | <|skeleton|>
class PylonsPlugin:
"""Nose plugin extension For use with nose to allow a project to be configured before nose proceeds to scan the project for doc tests and unit tests. This prevents modules from being loaded without a configured Pylons environment."""
def add_options(self, parser, env=os.environ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PylonsPlugin:
"""Nose plugin extension For use with nose to allow a project to be configured before nose proceeds to scan the project for doc tests and unit tests. This prevents modules from being loaded without a configured Pylons environment."""
def add_options(self, parser, env=os.environ):
""... | the_stack_v2_python_sparse | lib/default/lib/python2.7/site-packages/pylons/test.py | Saifinbox/CKANPROJECT | train | 1 |
eaa433abbca9c56428cb8314d8a4c8c73e5e7f75 | [
"try:\n set_up()\n customer = (1, 'Amy', 'Walker', 'Washington', '12345', 'amywalker@gmail.com', True, 750)\n add_customer(*customer)\n a_customer = Customer.get(Customer.customer_id == 1)\n self.assertEqual(a_customer.customer_id, 1)\n self.assertEqual(a_customer.first_name, 'Amy')\n self.asse... | <|body_start_0|>
try:
set_up()
customer = (1, 'Amy', 'Walker', 'Washington', '12345', 'amywalker@gmail.com', True, 750)
add_customer(*customer)
a_customer = Customer.get(Customer.customer_id == 1)
self.assertEqual(a_customer.customer_id, 1)
... | BasicOperationsTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicOperationsTests:
def test_add_customer(self):
"""Test add_customer :return: None"""
<|body_0|>
def test_search_customer(self):
"""Test search_customer :return: None"""
<|body_1|>
def test_delete_customer(self):
"""Test delete_customer :retur... | stack_v2_sparse_classes_75kplus_train_004058 | 3,131 | no_license | [
{
"docstring": "Test add_customer :return: None",
"name": "test_add_customer",
"signature": "def test_add_customer(self)"
},
{
"docstring": "Test search_customer :return: None",
"name": "test_search_customer",
"signature": "def test_search_customer(self)"
},
{
"docstring": "Test ... | 5 | stack_v2_sparse_classes_30k_test_001335 | Implement the Python class `BasicOperationsTests` described below.
Class description:
Implement the BasicOperationsTests class.
Method signatures and docstrings:
- def test_add_customer(self): Test add_customer :return: None
- def test_search_customer(self): Test search_customer :return: None
- def test_delete_custom... | Implement the Python class `BasicOperationsTests` described below.
Class description:
Implement the BasicOperationsTests class.
Method signatures and docstrings:
- def test_add_customer(self): Test add_customer :return: None
- def test_search_customer(self): Test search_customer :return: None
- def test_delete_custom... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class BasicOperationsTests:
def test_add_customer(self):
"""Test add_customer :return: None"""
<|body_0|>
def test_search_customer(self):
"""Test search_customer :return: None"""
<|body_1|>
def test_delete_customer(self):
"""Test delete_customer :retur... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BasicOperationsTests:
def test_add_customer(self):
"""Test add_customer :return: None"""
try:
set_up()
customer = (1, 'Amy', 'Walker', 'Washington', '12345', 'amywalker@gmail.com', True, 750)
add_customer(*customer)
a_customer = Customer.get(Cust... | the_stack_v2_python_sparse | students/Luyao_Xu/lesson04/test.py | JavaRod/SP_Python220B_2019 | train | 1 | |
65df2dfd2ceab372b1d9bac26a6cd877f02734d9 | [
"mock_result = mocker.patch('OracleIAM.CommandResults')\nargs = {'scim': '{\"id\": \"1234\"}'}\nwith requests_mock.Mocker() as m:\n m.post('https://test.com/oauth2/v1/token', json={})\n m.get('https://test.com/admin/v1/Groups/1234', json=APP_GROUP_OUTPUT)\n client = mock_client()\n get_group_command(cli... | <|body_start_0|>
mock_result = mocker.patch('OracleIAM.CommandResults')
args = {'scim': '{"id": "1234"}'}
with requests_mock.Mocker() as m:
m.post('https://test.com/oauth2/v1/token', json={})
m.get('https://test.com/admin/v1/Groups/1234', json=APP_GROUP_OUTPUT)
... | TestGetGroupCommand | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestGetGroupCommand:
def test_with_id(self, mocker):
"""Given: - An app client object - A scim argument that contains an ID of a group When: - The group exists in the application - Calling the main function with 'iam-get-group' command Then: - Ensure the resulted 'CommandResults' object ... | stack_v2_sparse_classes_75kplus_train_004059 | 25,823 | permissive | [
{
"docstring": "Given: - An app client object - A scim argument that contains an ID of a group When: - The group exists in the application - Calling the main function with 'iam-get-group' command Then: - Ensure the resulted 'CommandResults' object holds the correct group details",
"name": "test_with_id",
... | 4 | stack_v2_sparse_classes_30k_train_030466 | Implement the Python class `TestGetGroupCommand` described below.
Class description:
Implement the TestGetGroupCommand class.
Method signatures and docstrings:
- def test_with_id(self, mocker): Given: - An app client object - A scim argument that contains an ID of a group When: - The group exists in the application -... | Implement the Python class `TestGetGroupCommand` described below.
Class description:
Implement the TestGetGroupCommand class.
Method signatures and docstrings:
- def test_with_id(self, mocker): Given: - An app client object - A scim argument that contains an ID of a group When: - The group exists in the application -... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class TestGetGroupCommand:
def test_with_id(self, mocker):
"""Given: - An app client object - A scim argument that contains an ID of a group When: - The group exists in the application - Calling the main function with 'iam-get-group' command Then: - Ensure the resulted 'CommandResults' object ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestGetGroupCommand:
def test_with_id(self, mocker):
"""Given: - An app client object - A scim argument that contains an ID of a group When: - The group exists in the application - Calling the main function with 'iam-get-group' command Then: - Ensure the resulted 'CommandResults' object holds the corr... | the_stack_v2_python_sparse | Packs/Oracle_IAM/Integrations/OracleIAM/OracleIAM_test.py | demisto/content | train | 1,023 | |
7e7b605c5bc663ded2c2568ffdf2ccc5ceb0893e | [
"if not self.form.cleaned_data['ci_project']:\n raise exceptions.ValidationError('CI project is required to exclude by deployed on')\nif not self.form.cleaned_data['release']:\n raise exceptions.ValidationError('Release is required to exclude by deployed on')\nreturn queryset.extra(where=['\\n not ... | <|body_start_0|>
if not self.form.cleaned_data['ci_project']:
raise exceptions.ValidationError('CI project is required to exclude by deployed on')
if not self.form.cleaned_data['release']:
raise exceptions.ValidationError('Release is required to exclude by deployed on')
r... | Case filter to allow lookups for release, ci_project. | CaseFilter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CaseFilter:
"""Case filter to allow lookups for release, ci_project."""
def filter_exclude_deployed_on(self, queryset, value):
"""Implement ``exclude`` filter by deployed on instance."""
<|body_0|>
def filter_deployed_on(self, queryset, value):
"""Implement filte... | stack_v2_sparse_classes_75kplus_train_004060 | 9,486 | permissive | [
{
"docstring": "Implement ``exclude`` filter by deployed on instance.",
"name": "filter_exclude_deployed_on",
"signature": "def filter_exclude_deployed_on(self, queryset, value)"
},
{
"docstring": "Implement filter by deployed on instance.",
"name": "filter_deployed_on",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_048582 | Implement the Python class `CaseFilter` described below.
Class description:
Case filter to allow lookups for release, ci_project.
Method signatures and docstrings:
- def filter_exclude_deployed_on(self, queryset, value): Implement ``exclude`` filter by deployed on instance.
- def filter_deployed_on(self, queryset, va... | Implement the Python class `CaseFilter` described below.
Class description:
Case filter to allow lookups for release, ci_project.
Method signatures and docstrings:
- def filter_exclude_deployed_on(self, queryset, value): Implement ``exclude`` filter by deployed on instance.
- def filter_deployed_on(self, queryset, va... | 5c32aab78e48b5249fd458d9c837596a75698968 | <|skeleton|>
class CaseFilter:
"""Case filter to allow lookups for release, ci_project."""
def filter_exclude_deployed_on(self, queryset, value):
"""Implement ``exclude`` filter by deployed on instance."""
<|body_0|>
def filter_deployed_on(self, queryset, value):
"""Implement filte... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CaseFilter:
"""Case filter to allow lookups for release, ci_project."""
def filter_exclude_deployed_on(self, queryset, value):
"""Implement ``exclude`` filter by deployed on instance."""
if not self.form.cleaned_data['ci_project']:
raise exceptions.ValidationError('CI project ... | the_stack_v2_python_sparse | pdt/api/views.py | AbdulRahmanAlHamali/pdt | train | 0 |
85e8d112bd234641d7e2e89f9c46f3f62a558d34 | [
"from __builtin__ import reduce\nif '' == digits:\n return []\nkvmaps = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}\nreturn reduce(lambda acc, digit: [x + y for x in acc for y in kvmaps[digit]], digits, [''])",
"from __builtin__ import reduce\nif '' == dig... | <|body_start_0|>
from __builtin__ import reduce
if '' == digits:
return []
kvmaps = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
return reduce(lambda acc, digit: [x + y for x in acc for y in kvmaps[digit]], digits, [''])
<... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def letterCombinations(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_0|>
def rewrite(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_1|>
def rewrite2(self, digits):
""":type digits: str :rtype: List[str... | stack_v2_sparse_classes_75kplus_train_004061 | 2,869 | no_license | [
{
"docstring": ":type digits: str :rtype: List[str]",
"name": "letterCombinations",
"signature": "def letterCombinations(self, digits)"
},
{
"docstring": ":type digits: str :rtype: List[str]",
"name": "rewrite",
"signature": "def rewrite(self, digits)"
},
{
"docstring": ":type di... | 3 | stack_v2_sparse_classes_30k_test_000643 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCombinations(self, digits): :type digits: str :rtype: List[str]
- def rewrite(self, digits): :type digits: str :rtype: List[str]
- def rewrite2(self, digits): :type dig... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCombinations(self, digits): :type digits: str :rtype: List[str]
- def rewrite(self, digits): :type digits: str :rtype: List[str]
- def rewrite2(self, digits): :type dig... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def letterCombinations(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_0|>
def rewrite(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_1|>
def rewrite2(self, digits):
""":type digits: str :rtype: List[str... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def letterCombinations(self, digits):
""":type digits: str :rtype: List[str]"""
from __builtin__ import reduce
if '' == digits:
return []
kvmaps = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
re... | the_stack_v2_python_sparse | co_ms/17_Letter_Combinations_of_a_Phone_Number.py | vsdrun/lc_public | train | 6 | |
7d7f05f3d91e0e686f6b21602d64b6f280f8b29d | [
"forward = {i: set() for i in range(numCourses)}\nbackward = collections.defaultdict(set)\nfor i, j in prerequisites:\n forward[i].add(j)\n backward[j].add(i)\nqueue = collections.deque([node for node in forward if len(forward[node]) == 0])\ncount, res = (0, [])\nwhile queue:\n node = queue.popleft()\n ... | <|body_start_0|>
forward = {i: set() for i in range(numCourses)}
backward = collections.defaultdict(set)
for i, j in prerequisites:
forward[i].add(j)
backward[j].add(i)
queue = collections.deque([node for node in forward if len(forward[node]) == 0])
count,... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findOrder(self, numCourses, prerequisites):
""":type numCourses: int :type prerequisites: List[List[int]] :rtype: List[int]"""
<|body_0|>
def findOrder_1(self, numCourses, prerequisites):
""":type numCourses: int :type prerequisites: List[List[int]] :rt... | stack_v2_sparse_classes_75kplus_train_004062 | 3,709 | no_license | [
{
"docstring": ":type numCourses: int :type prerequisites: List[List[int]] :rtype: List[int]",
"name": "findOrder",
"signature": "def findOrder(self, numCourses, prerequisites)"
},
{
"docstring": ":type numCourses: int :type prerequisites: List[List[int]] :rtype: bool",
"name": "findOrder_1"... | 2 | stack_v2_sparse_classes_30k_train_010640 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findOrder(self, numCourses, prerequisites): :type numCourses: int :type prerequisites: List[List[int]] :rtype: List[int]
- def findOrder_1(self, numCourses, prerequisites): :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findOrder(self, numCourses, prerequisites): :type numCourses: int :type prerequisites: List[List[int]] :rtype: List[int]
- def findOrder_1(self, numCourses, prerequisites): :... | 3d9e0ad2f6ed92ec969556f75d97c51ea4854719 | <|skeleton|>
class Solution:
def findOrder(self, numCourses, prerequisites):
""":type numCourses: int :type prerequisites: List[List[int]] :rtype: List[int]"""
<|body_0|>
def findOrder_1(self, numCourses, prerequisites):
""":type numCourses: int :type prerequisites: List[List[int]] :rt... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findOrder(self, numCourses, prerequisites):
""":type numCourses: int :type prerequisites: List[List[int]] :rtype: List[int]"""
forward = {i: set() for i in range(numCourses)}
backward = collections.defaultdict(set)
for i, j in prerequisites:
forward[i]... | the_stack_v2_python_sparse | Solutions/0210_findOrder.py | YoupengLi/leetcode-sorting | train | 3 | |
eabaf9b2a96d6dd8e7d39317db497d6e4b535994 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn EducationFeedbackResourceOutcome()",
"from .education_feedback_resource_outcome_status import EducationFeedbackResourceOutcomeStatus\nfrom .education_outcome import EducationOutcome\nfrom .education_resource import EducationResource\nf... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return EducationFeedbackResourceOutcome()
<|end_body_0|>
<|body_start_1|>
from .education_feedback_resource_outcome_status import EducationFeedbackResourceOutcomeStatus
from .education_outcome ... | EducationFeedbackResourceOutcome | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EducationFeedbackResourceOutcome:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationFeedbackResourceOutcome:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminat... | stack_v2_sparse_classes_75kplus_train_004063 | 3,145 | 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: EducationFeedbackResourceOutcome",
"name": "create_from_discriminator_value",
"signature": "def create_from_... | 3 | stack_v2_sparse_classes_30k_train_052208 | Implement the Python class `EducationFeedbackResourceOutcome` described below.
Class description:
Implement the EducationFeedbackResourceOutcome class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationFeedbackResourceOutcome: Creates a new insta... | Implement the Python class `EducationFeedbackResourceOutcome` described below.
Class description:
Implement the EducationFeedbackResourceOutcome class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationFeedbackResourceOutcome: Creates a new insta... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class EducationFeedbackResourceOutcome:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationFeedbackResourceOutcome:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EducationFeedbackResourceOutcome:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationFeedbackResourceOutcome:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and c... | the_stack_v2_python_sparse | msgraph/generated/models/education_feedback_resource_outcome.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
077c7468449eda0adca737f4d0f98f2856763ca7 | [
"self.v_count = 0\nself.adj_matrix = []\nif start_edges is not None:\n v_count = 0\n for u, v, _ in start_edges:\n v_count = max(v_count, u, v)\n for _ in range(v_count + 1):\n self.add_vertex()\n for u, v, weight in start_edges:\n self.add_edge(u, v, weight)",
"if self.v_count ==... | <|body_start_0|>
self.v_count = 0
self.adj_matrix = []
if start_edges is not None:
v_count = 0
for u, v, _ in start_edges:
v_count = max(v_count, u, v)
for _ in range(v_count + 1):
self.add_vertex()
for u, v, weight ... | Implements weighted graph to test MST algorithms. Copied from my CS261 Directed Graph assignment. | Graph | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Graph:
"""Implements weighted graph to test MST algorithms. Copied from my CS261 Directed Graph assignment."""
def __init__(self, start_edges=None):
"""Store graph info as adjacency matrix DO NOT CHANGE THIS METHOD IN ANY WAY"""
<|body_0|>
def __str__(self):
"""R... | stack_v2_sparse_classes_75kplus_train_004064 | 6,160 | no_license | [
{
"docstring": "Store graph info as adjacency matrix DO NOT CHANGE THIS METHOD IN ANY WAY",
"name": "__init__",
"signature": "def __init__(self, start_edges=None)"
},
{
"docstring": "Return content of the graph in human-readable form DO NOT CHANGE THIS METHOD IN ANY WAY",
"name": "__str__",
... | 6 | stack_v2_sparse_classes_30k_train_039422 | Implement the Python class `Graph` described below.
Class description:
Implements weighted graph to test MST algorithms. Copied from my CS261 Directed Graph assignment.
Method signatures and docstrings:
- def __init__(self, start_edges=None): Store graph info as adjacency matrix DO NOT CHANGE THIS METHOD IN ANY WAY
-... | Implement the Python class `Graph` described below.
Class description:
Implements weighted graph to test MST algorithms. Copied from my CS261 Directed Graph assignment.
Method signatures and docstrings:
- def __init__(self, start_edges=None): Store graph info as adjacency matrix DO NOT CHANGE THIS METHOD IN ANY WAY
-... | dc1aae03fb6198a9a07c28f437123737161b1e49 | <|skeleton|>
class Graph:
"""Implements weighted graph to test MST algorithms. Copied from my CS261 Directed Graph assignment."""
def __init__(self, start_edges=None):
"""Store graph info as adjacency matrix DO NOT CHANGE THIS METHOD IN ANY WAY"""
<|body_0|>
def __str__(self):
"""R... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Graph:
"""Implements weighted graph to test MST algorithms. Copied from my CS261 Directed Graph assignment."""
def __init__(self, start_edges=None):
"""Store graph info as adjacency matrix DO NOT CHANGE THIS METHOD IN ANY WAY"""
self.v_count = 0
self.adj_matrix = []
if sta... | the_stack_v2_python_sparse | MST.py | teejayjan/CS325 | train | 0 |
c19d163fabf97daaa3483ba44ea2a200faa59dbb | [
"if len(candidates) == 0:\n return []\nlists = []\ncandidates = sorted(candidates)\nself.dfs(candidates, target, [], lists, 0)\nreturn lists",
"if target < 0:\n return\nif target == 0:\n tmp = []\n tmp.extend(path)\n ret.append(tmp)\n return\nfor i in range(index, len(candidates)):\n path.app... | <|body_start_0|>
if len(candidates) == 0:
return []
lists = []
candidates = sorted(candidates)
self.dfs(candidates, target, [], lists, 0)
return lists
<|end_body_0|>
<|body_start_1|>
if target < 0:
return
if target == 0:
tmp = ... | CombinationSum | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CombinationSum:
def combinationSum(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List[List[int]]"""
<|body_0|>
def dfs(self, candidates, target, path, ret, index):
""":param candidates: List[int] :param target: int :param path: L... | stack_v2_sparse_classes_75kplus_train_004065 | 1,508 | permissive | [
{
"docstring": ":type candidates: List[int] :type target: int :rtype: List[List[int]]",
"name": "combinationSum",
"signature": "def combinationSum(self, candidates, target)"
},
{
"docstring": ":param candidates: List[int] :param target: int :param path: List[int] :param ret: List[List[int]] :par... | 2 | stack_v2_sparse_classes_30k_train_054683 | Implement the Python class `CombinationSum` described below.
Class description:
Implement the CombinationSum class.
Method signatures and docstrings:
- def combinationSum(self, candidates, target): :type candidates: List[int] :type target: int :rtype: List[List[int]]
- def dfs(self, candidates, target, path, ret, ind... | Implement the Python class `CombinationSum` described below.
Class description:
Implement the CombinationSum class.
Method signatures and docstrings:
- def combinationSum(self, candidates, target): :type candidates: List[int] :type target: int :rtype: List[List[int]]
- def dfs(self, candidates, target, path, ret, ind... | 39f85cdedaaf5b85f7ce842ecef975301fc974cf | <|skeleton|>
class CombinationSum:
def combinationSum(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List[List[int]]"""
<|body_0|>
def dfs(self, candidates, target, path, ret, index):
""":param candidates: List[int] :param target: int :param path: L... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CombinationSum:
def combinationSum(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List[List[int]]"""
if len(candidates) == 0:
return []
lists = []
candidates = sorted(candidates)
self.dfs(candidates, target, [], lists, 0)... | the_stack_v2_python_sparse | Python/CombinationSum.py | santosh241/Windary | train | 2 | |
882252f3374f3d159fe73516793fc7aefbbceb81 | [
"self.size = 300\nself.times = [0 for _ in range(self.size)]\nself.hits = self.times[:]",
"idx = timestamp % self.size\nif self.times[idx] != timestamp:\n self.times[idx] = timestamp\n self.hits[idx] = 0\nself.hits[idx] += 1",
"res = 0\nfor i in range(self.size):\n if self.times[i] + self.size > timest... | <|body_start_0|>
self.size = 300
self.times = [0 for _ in range(self.size)]
self.hits = self.times[:]
<|end_body_0|>
<|body_start_1|>
idx = timestamp % self.size
if self.times[idx] != timestamp:
self.times[idx] = timestamp
self.hits[idx] = 0
self.... | HitCounter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HitCounter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def hit(self, timestamp: int) -> None:
"""Record a hit. @param timestamp - The current timestamp (in seconds granularity)."""
<|body_1|>
def getHits(self, timestamp: in... | stack_v2_sparse_classes_75kplus_train_004066 | 1,985 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Record a hit. @param timestamp - The current timestamp (in seconds granularity).",
"name": "hit",
"signature": "def hit(self, timestamp: int) -> None"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_050092 | Implement the Python class `HitCounter` described below.
Class description:
Implement the HitCounter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def hit(self, timestamp: int) -> None: Record a hit. @param timestamp - The current timestamp (in seconds granulari... | Implement the Python class `HitCounter` described below.
Class description:
Implement the HitCounter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def hit(self, timestamp: int) -> None: Record a hit. @param timestamp - The current timestamp (in seconds granulari... | 4c1288c99f78823c7c3bac0ceedd532e64af1258 | <|skeleton|>
class HitCounter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def hit(self, timestamp: int) -> None:
"""Record a hit. @param timestamp - The current timestamp (in seconds granularity)."""
<|body_1|>
def getHits(self, timestamp: in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HitCounter:
def __init__(self):
"""Initialize your data structure here."""
self.size = 300
self.times = [0 for _ in range(self.size)]
self.hits = self.times[:]
def hit(self, timestamp: int) -> None:
"""Record a hit. @param timestamp - The current timestamp (in seco... | the_stack_v2_python_sparse | Algorithms/0362 Design Hit Counter.py | cravo123/LeetCode | train | 6 | |
9e0fe874a7280b17ea72604b62f0ae8f8c2f90c2 | [
"def helper(curr):\n head, tail = (curr, curr)\n if curr.left:\n lhead, ltail = helper(curr.left)\n ltail.right = curr\n curr.left = ltail\n head = lhead\n if curr.right:\n rhead, rtail = helper(curr.right)\n rhead.left = curr\n curr.right = rhead\n t... | <|body_start_0|>
def helper(curr):
head, tail = (curr, curr)
if curr.left:
lhead, ltail = helper(curr.left)
ltail.right = curr
curr.left = ltail
head = lhead
if curr.right:
rhead, rtail = helper(c... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def treeToDoublyList(self, root):
""":type root: Node :rtype: Node Convert a BST to a sorted circular doubly-linked list in-place. Think of the left and right pointers as synonymous to the previous and next pointers in a doubly-linked list. Let's take the following BST as an ex... | stack_v2_sparse_classes_75kplus_train_004067 | 2,428 | permissive | [
{
"docstring": ":type root: Node :rtype: Node Convert a BST to a sorted circular doubly-linked list in-place. Think of the left and right pointers as synonymous to the previous and next pointers in a doubly-linked list. Let's take the following BST as an example, it may help you understand the problem better: W... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def treeToDoublyList(self, root): :type root: Node :rtype: Node Convert a BST to a sorted circular doubly-linked list in-place. Think of the left and right pointers as synonymous... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def treeToDoublyList(self, root): :type root: Node :rtype: Node Convert a BST to a sorted circular doubly-linked list in-place. Think of the left and right pointers as synonymous... | b13bb35fb3cdc9813c62944547d260be2f9cab02 | <|skeleton|>
class Solution:
def treeToDoublyList(self, root):
""":type root: Node :rtype: Node Convert a BST to a sorted circular doubly-linked list in-place. Think of the left and right pointers as synonymous to the previous and next pointers in a doubly-linked list. Let's take the following BST as an ex... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def treeToDoublyList(self, root):
""":type root: Node :rtype: Node Convert a BST to a sorted circular doubly-linked list in-place. Think of the left and right pointers as synonymous to the previous and next pointers in a doubly-linked list. Let's take the following BST as an example, it may ... | the_stack_v2_python_sparse | facebook/bstToDoublyLinkedList.py | rando3/leetcode-python | train | 0 | |
ff8a78df1256f7a0ee9a8f2b15d11e1cb27da634 | [
"while left <= right:\n mid = left + right >> 1\n if key == nums[mid]:\n return mid\n elif key < nums[mid]:\n right = mid - 1\n else:\n left = mid + 1\nreturn -1",
"length = len(nums)\nnums = sorted(nums)\nthreesums = set()\nfor i in range(length - 2):\n if nums[i] > 0:\n ... | <|body_start_0|>
while left <= right:
mid = left + right >> 1
if key == nums[mid]:
return mid
elif key < nums[mid]:
right = mid - 1
else:
left = mid + 1
return -1
<|end_body_0|>
<|body_start_1|>
leng... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def bin_search(self, nums, key, left, right):
"""二分查找key是否在nums里面, 存在则返回任何一个值等于key的数组下标, 不存在则返回-1 :param nums: :param key: :param left: :param right: :return:"""
<|body_0|>
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
... | stack_v2_sparse_classes_75kplus_train_004068 | 1,538 | no_license | [
{
"docstring": "二分查找key是否在nums里面, 存在则返回任何一个值等于key的数组下标, 不存在则返回-1 :param nums: :param key: :param left: :param right: :return:",
"name": "bin_search",
"signature": "def bin_search(self, nums, key, left, right)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeS... | 2 | stack_v2_sparse_classes_30k_train_039247 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def bin_search(self, nums, key, left, right): 二分查找key是否在nums里面, 存在则返回任何一个值等于key的数组下标, 不存在则返回-1 :param nums: :param key: :param left: :param right: :return:
- def threeSum(self, n... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def bin_search(self, nums, key, left, right): 二分查找key是否在nums里面, 存在则返回任何一个值等于key的数组下标, 不存在则返回-1 :param nums: :param key: :param left: :param right: :return:
- def threeSum(self, n... | 989b6ae678f9aa92a7400f6c67bbfedf31465315 | <|skeleton|>
class Solution:
def bin_search(self, nums, key, left, right):
"""二分查找key是否在nums里面, 存在则返回任何一个值等于key的数组下标, 不存在则返回-1 :param nums: :param key: :param left: :param right: :return:"""
<|body_0|>
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def bin_search(self, nums, key, left, right):
"""二分查找key是否在nums里面, 存在则返回任何一个值等于key的数组下标, 不存在则返回-1 :param nums: :param key: :param left: :param right: :return:"""
while left <= right:
mid = left + right >> 1
if key == nums[mid]:
return mid
... | the_stack_v2_python_sparse | 1-50/15.py | AaronJny/leetcode | train | 2 | |
68b7e1d666c8e12f2128e3e382243f1bafa60ee0 | [
"super().__init__(dat, frame, box_size, centre, arrow_width=arrow_width, arrow_head_width=arrow_head_width, arrow_head_length=arrow_head_length)\nself.displacements = dat.getDisplacements(frame, frame + dt, *self.particles, jump=jump)\nself.vmin, self.vmax = amplogwidth(self.displacements)\ntry:\n self.vmin = np... | <|body_start_0|>
super().__init__(dat, frame, box_size, centre, arrow_width=arrow_width, arrow_head_width=arrow_head_width, arrow_head_length=arrow_head_length)
self.displacements = dat.getDisplacements(frame, frame + dt, *self.particles, jump=jump)
self.vmin, self.vmax = amplogwidth(self.displa... | Plotting class specific to 'displacement' mode. | Displacement | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Displacement:
"""Plotting class specific to 'displacement' mode."""
def __init__(self, dat, frame, box_size, centre, arrow_width=_arrow_width, arrow_head_width=_arrow_head_width, arrow_head_length=_arrow_head_length, pad=_colormap_label_pad, dt=1, jump=1, label=False, **kwargs):
"""I... | stack_v2_sparse_classes_75kplus_train_004069 | 24,676 | permissive | [
{
"docstring": "Initialises and plots figure. Parameters ---------- dat : active_work.read.Dat Data object. frame : int Frame to render. box_size : float Length of the square box to render. centre : 2-uple like Centre of the box to render. arrow_width : float Width of the arrows. arrow_head_width : float Width ... | 2 | stack_v2_sparse_classes_30k_train_042333 | Implement the Python class `Displacement` described below.
Class description:
Plotting class specific to 'displacement' mode.
Method signatures and docstrings:
- def __init__(self, dat, frame, box_size, centre, arrow_width=_arrow_width, arrow_head_width=_arrow_head_width, arrow_head_length=_arrow_head_length, pad=_co... | Implement the Python class `Displacement` described below.
Class description:
Plotting class specific to 'displacement' mode.
Method signatures and docstrings:
- def __init__(self, dat, frame, box_size, centre, arrow_width=_arrow_width, arrow_head_width=_arrow_head_width, arrow_head_length=_arrow_head_length, pad=_co... | 99107a0d4935296b673f67469c1e2bd258954b9b | <|skeleton|>
class Displacement:
"""Plotting class specific to 'displacement' mode."""
def __init__(self, dat, frame, box_size, centre, arrow_width=_arrow_width, arrow_head_width=_arrow_head_width, arrow_head_length=_arrow_head_length, pad=_colormap_label_pad, dt=1, jump=1, label=False, **kwargs):
"""I... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Displacement:
"""Plotting class specific to 'displacement' mode."""
def __init__(self, dat, frame, box_size, centre, arrow_width=_arrow_width, arrow_head_width=_arrow_head_width, arrow_head_length=_arrow_head_length, pad=_colormap_label_pad, dt=1, jump=1, label=False, **kwargs):
"""Initialises an... | the_stack_v2_python_sparse | frame.py | yketa/active_work | train | 1 |
43b7e563fa9bb986f65b7e8b2a61d9ae1d6da077 | [
"sql = 'SELECT id, css\\n FROM image;'\nargs = ()\nquery = StorageIcon._make_select(sql, args)\nreturn query",
"sql = '\\n SELECT css\\n FROM image\\n WHERE id = %s;\\n '\nargs = (image_id,)\nicon = StorageIcon._make_select(sql, args)\nreturn icon[0]['... | <|body_start_0|>
sql = 'SELECT id, css\n FROM image;'
args = ()
query = StorageIcon._make_select(sql, args)
return query
<|end_body_0|>
<|body_start_1|>
sql = '\n SELECT css\n FROM image\n WHERE id = %s;\n '
a... | Model for interacting with icons. | StorageIcon | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StorageIcon:
"""Model for interacting with icons."""
def get_all_icons():
"""Returns a dict with id and css of all icons :return: list of available icons"""
<|body_0|>
def get_icon_by_id(image_id):
"""Getting icon from database by requested id :params: requested ... | stack_v2_sparse_classes_75kplus_train_004070 | 1,455 | no_license | [
{
"docstring": "Returns a dict with id and css of all icons :return: list of available icons",
"name": "get_all_icons",
"signature": "def get_all_icons()"
},
{
"docstring": "Getting icon from database by requested id :params: requested image id :returns: icon from database.",
"name": "get_ic... | 3 | stack_v2_sparse_classes_30k_test_002450 | Implement the Python class `StorageIcon` described below.
Class description:
Model for interacting with icons.
Method signatures and docstrings:
- def get_all_icons(): Returns a dict with id and css of all icons :return: list of available icons
- def get_icon_by_id(image_id): Getting icon from database by requested i... | Implement the Python class `StorageIcon` described below.
Class description:
Model for interacting with icons.
Method signatures and docstrings:
- def get_all_icons(): Returns a dict with id and css of all icons :return: list of available icons
- def get_icon_by_id(image_id): Getting icon from database by requested i... | 7d8f85323cd553e1b7788b407f84f14d2563bd2b | <|skeleton|>
class StorageIcon:
"""Model for interacting with icons."""
def get_all_icons():
"""Returns a dict with id and css of all icons :return: list of available icons"""
<|body_0|>
def get_icon_by_id(image_id):
"""Getting icon from database by requested id :params: requested ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StorageIcon:
"""Model for interacting with icons."""
def get_all_icons():
"""Returns a dict with id and css of all icons :return: list of available icons"""
sql = 'SELECT id, css\n FROM image;'
args = ()
query = StorageIcon._make_select(sql, args)
... | the_stack_v2_python_sparse | moneta/src/python/db/storage_icon.py | lv-386-python/moneta | train | 7 |
85979dcc8010de3f92d584613cbbf7816d814dd1 | [
"n = len(dp)\ncur_len = max(dp)\nans = []\nfor i in range(n - 1, -1, -1):\n if dp[i] == cur_len:\n ans.append(nums[i])\n cur_len -= 1\n if cur_len == 0:\n break\nreturn ans[::-1]",
"n = len(nums)\nif n == 0:\n return 0\ndp = [1] * n\nfor i in range(1, n):\n for j in range(... | <|body_start_0|>
n = len(dp)
cur_len = max(dp)
ans = []
for i in range(n - 1, -1, -1):
if dp[i] == cur_len:
ans.append(nums[i])
cur_len -= 1
if cur_len == 0:
break
return ans[::-1]
<|end_body_0|>
<|b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def get_one_LIS(self, dp):
"""获得任意一个 LIS dp[i] 其实记录了 每个元素 在 LIS 序列中的位置,可以按照值的大小反向找回去"""
<|body_0|>
def lengthOfLIS(self, nums: List[int]) -> int:
"""最长上升子序列, 不要求连续 dp[i]: 以 nums[i] 结尾的 LIS 长度 注意:指的是 nums[i] 作为最大元素的情况,因为 状态转移 状态转移: 0<=j < i dp[i] = max(d[j])... | stack_v2_sparse_classes_75kplus_train_004071 | 1,538 | no_license | [
{
"docstring": "获得任意一个 LIS dp[i] 其实记录了 每个元素 在 LIS 序列中的位置,可以按照值的大小反向找回去",
"name": "get_one_LIS",
"signature": "def get_one_LIS(self, dp)"
},
{
"docstring": "最长上升子序列, 不要求连续 dp[i]: 以 nums[i] 结尾的 LIS 长度 注意:指的是 nums[i] 作为最大元素的情况,因为 状态转移 状态转移: 0<=j < i dp[i] = max(d[j]) +1, 如果 nums[j] < nums[i] 严格上升",... | 2 | stack_v2_sparse_classes_30k_train_030138 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def get_one_LIS(self, dp): 获得任意一个 LIS dp[i] 其实记录了 每个元素 在 LIS 序列中的位置,可以按照值的大小反向找回去
- def lengthOfLIS(self, nums: List[int]) -> int: 最长上升子序列, 不要求连续 dp[i]: 以 nums[i] 结尾的 LIS 长度 注意:指... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def get_one_LIS(self, dp): 获得任意一个 LIS dp[i] 其实记录了 每个元素 在 LIS 序列中的位置,可以按照值的大小反向找回去
- def lengthOfLIS(self, nums: List[int]) -> int: 最长上升子序列, 不要求连续 dp[i]: 以 nums[i] 结尾的 LIS 长度 注意:指... | 4ca0ec2ab9510b12b7e8c65af52dee719f099ea6 | <|skeleton|>
class Solution:
def get_one_LIS(self, dp):
"""获得任意一个 LIS dp[i] 其实记录了 每个元素 在 LIS 序列中的位置,可以按照值的大小反向找回去"""
<|body_0|>
def lengthOfLIS(self, nums: List[int]) -> int:
"""最长上升子序列, 不要求连续 dp[i]: 以 nums[i] 结尾的 LIS 长度 注意:指的是 nums[i] 作为最大元素的情况,因为 状态转移 状态转移: 0<=j < i dp[i] = max(d[j])... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def get_one_LIS(self, dp):
"""获得任意一个 LIS dp[i] 其实记录了 每个元素 在 LIS 序列中的位置,可以按照值的大小反向找回去"""
n = len(dp)
cur_len = max(dp)
ans = []
for i in range(n - 1, -1, -1):
if dp[i] == cur_len:
ans.append(nums[i])
cur_len -= 1
... | the_stack_v2_python_sparse | case/dp/最长上升子序列.py | JDer-liuodngkai/LeetCode | train | 0 | |
58274478660c90881deb260cb53f46c742529c9a | [
"self.resultDir = resultDir\nself.can_check = True\ntry:\n self.results = pd.read_csv('{}/Results.csv'.format(self.resultDir))\nexcept (FileNotFoundError, pd.errors.EmptyDataError):\n self.can_check = False\n self.results = None",
"if self.can_check:\n r = self.results\n for p, v in params.items():... | <|body_start_0|>
self.resultDir = resultDir
self.can_check = True
try:
self.results = pd.read_csv('{}/Results.csv'.format(self.resultDir))
except (FileNotFoundError, pd.errors.EmptyDataError):
self.can_check = False
self.results = None
<|end_body_0|>
... | Class for handling task kill and task restart (for metrics) | StopRestart | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StopRestart:
"""Class for handling task kill and task restart (for metrics)"""
def __init__(self, resultDir):
"""Init :param resultDir: Directory where results are saved"""
<|body_0|>
def computed(self, **params):
"""Check if the given parameters exists in the CS... | stack_v2_sparse_classes_75kplus_train_004072 | 4,446 | no_license | [
{
"docstring": "Init :param resultDir: Directory where results are saved",
"name": "__init__",
"signature": "def __init__(self, resultDir)"
},
{
"docstring": "Check if the given parameters exists in the CSV. :param params: parameters to check if computation is done. :return: True if the metric i... | 2 | null | Implement the Python class `StopRestart` described below.
Class description:
Class for handling task kill and task restart (for metrics)
Method signatures and docstrings:
- def __init__(self, resultDir): Init :param resultDir: Directory where results are saved
- def computed(self, **params): Check if the given parame... | Implement the Python class `StopRestart` described below.
Class description:
Class for handling task kill and task restart (for metrics)
Method signatures and docstrings:
- def __init__(self, resultDir): Init :param resultDir: Directory where results are saved
- def computed(self, **params): Check if the given parame... | 3835ef5efc495c13a980c4eb064f4ec60ab6b7ed | <|skeleton|>
class StopRestart:
"""Class for handling task kill and task restart (for metrics)"""
def __init__(self, resultDir):
"""Init :param resultDir: Directory where results are saved"""
<|body_0|>
def computed(self, **params):
"""Check if the given parameters exists in the CS... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StopRestart:
"""Class for handling task kill and task restart (for metrics)"""
def __init__(self, resultDir):
"""Init :param resultDir: Directory where results are saved"""
self.resultDir = resultDir
self.can_check = True
try:
self.results = pd.read_csv('{}/Res... | the_stack_v2_python_sparse | dysan/Modules/Results.py | DynamicSanitizer/DySan | train | 3 |
f8a0c9d13bf87f17ea19e39fa8289049ed4ef75f | [
"if 'configuration' not in kwargs:\n kwargs['configuration'] = {}\nScript.__init__(self, **kwargs)\nself._camera = camera\nself._count = count\nself._binning = binning\nself._exptime = exptime\nif self._exptime == 0:\n self._ImageType = ImageType.BIAS\nelse:\n self._ImageType = ImageType.DARK",
"try:\n ... | <|body_start_0|>
if 'configuration' not in kwargs:
kwargs['configuration'] = {}
Script.__init__(self, **kwargs)
self._camera = camera
self._count = count
self._binning = binning
self._exptime = exptime
if self._exptime == 0:
self._ImageType... | Script for running darks or biases. | DarkBias | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DarkBias:
"""Script for running darks or biases."""
def __init__(self, camera: Union[str, ICamera], count: int=20, exptime: float=0, binning: Tuple[int, int]=(1, 1), **kwargs: Any):
"""Init a new DarkBias script. Args: camera: name of ICamera that takes the dark or bias count: aimed ... | stack_v2_sparse_classes_75kplus_train_004073 | 3,168 | permissive | [
{
"docstring": "Init a new DarkBias script. Args: camera: name of ICamera that takes the dark or bias count: aimed number of darks or biases exptime: exposure time [s], exptime=0 -> Bias binning: binning for dark or bias",
"name": "__init__",
"signature": "def __init__(self, camera: Union[str, ICamera],... | 3 | stack_v2_sparse_classes_30k_train_048634 | Implement the Python class `DarkBias` described below.
Class description:
Script for running darks or biases.
Method signatures and docstrings:
- def __init__(self, camera: Union[str, ICamera], count: int=20, exptime: float=0, binning: Tuple[int, int]=(1, 1), **kwargs: Any): Init a new DarkBias script. Args: camera: ... | Implement the Python class `DarkBias` described below.
Class description:
Script for running darks or biases.
Method signatures and docstrings:
- def __init__(self, camera: Union[str, ICamera], count: int=20, exptime: float=0, binning: Tuple[int, int]=(1, 1), **kwargs: Any): Init a new DarkBias script. Args: camera: ... | 2d7a06e5485b61b6ca7e51d99b08651ea6021086 | <|skeleton|>
class DarkBias:
"""Script for running darks or biases."""
def __init__(self, camera: Union[str, ICamera], count: int=20, exptime: float=0, binning: Tuple[int, int]=(1, 1), **kwargs: Any):
"""Init a new DarkBias script. Args: camera: name of ICamera that takes the dark or bias count: aimed ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DarkBias:
"""Script for running darks or biases."""
def __init__(self, camera: Union[str, ICamera], count: int=20, exptime: float=0, binning: Tuple[int, int]=(1, 1), **kwargs: Any):
"""Init a new DarkBias script. Args: camera: name of ICamera that takes the dark or bias count: aimed number of dar... | the_stack_v2_python_sparse | pyobs/robotic/scripts/darkbias.py | pyobs/pyobs-core | train | 9 |
8f9cc4a549f5a659488e6f4098dcfd8f5093f74c | [
"if msg is None:\n msg = '\"%s\" not found in \"%s\"' % (a, b)\nself.assert_(a in b, msg)",
"if msg is None:\n msg = '\"%s\" unexpectedly found in \"%s\"' % (a, b)\nself.assert_(a not in b, msg)",
"if chart is None:\n chart = self.chart\nparams = chart.display._Params(chart)\nreturn params[param_name]"... | <|body_start_0|>
if msg is None:
msg = '"%s" not found in "%s"' % (a, b)
self.assert_(a in b, msg)
<|end_body_0|>
<|body_start_1|>
if msg is None:
msg = '"%s" unexpectedly found in "%s"' % (a, b)
self.assert_(a not in b, msg)
<|end_body_1|>
<|body_start_2|>
... | Base class for other Graphy tests. | GraphyTest | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphyTest:
"""Base class for other Graphy tests."""
def assertIn(self, a, b, msg=None):
"""Just like self.assert_(a in b), but with a nicer default message."""
<|body_0|>
def assertNotIn(self, a, b, msg=None):
"""Just like self.assert_(a not in b), but with a ni... | stack_v2_sparse_classes_75kplus_train_004074 | 1,509 | permissive | [
{
"docstring": "Just like self.assert_(a in b), but with a nicer default message.",
"name": "assertIn",
"signature": "def assertIn(self, a, b, msg=None)"
},
{
"docstring": "Just like self.assert_(a not in b), but with a nicer default message.",
"name": "assertNotIn",
"signature": "def as... | 3 | stack_v2_sparse_classes_30k_train_017489 | Implement the Python class `GraphyTest` described below.
Class description:
Base class for other Graphy tests.
Method signatures and docstrings:
- def assertIn(self, a, b, msg=None): Just like self.assert_(a in b), but with a nicer default message.
- def assertNotIn(self, a, b, msg=None): Just like self.assert_(a not... | Implement the Python class `GraphyTest` described below.
Class description:
Base class for other Graphy tests.
Method signatures and docstrings:
- def assertIn(self, a, b, msg=None): Just like self.assert_(a in b), but with a nicer default message.
- def assertNotIn(self, a, b, msg=None): Just like self.assert_(a not... | 53102de187a48ac2cfc241fef54dcbc29c453a8e | <|skeleton|>
class GraphyTest:
"""Base class for other Graphy tests."""
def assertIn(self, a, b, msg=None):
"""Just like self.assert_(a in b), but with a nicer default message."""
<|body_0|>
def assertNotIn(self, a, b, msg=None):
"""Just like self.assert_(a not in b), but with a ni... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GraphyTest:
"""Base class for other Graphy tests."""
def assertIn(self, a, b, msg=None):
"""Just like self.assert_(a in b), but with a nicer default message."""
if msg is None:
msg = '"%s" not found in "%s"' % (a, b)
self.assert_(a in b, msg)
def assertNotIn(self,... | the_stack_v2_python_sparse | third_party/graphy/graphy/graphy_test.py | catapult-project/catapult | train | 2,032 |
baa3076f44a38f9538ea152da918f7dfaa005444 | [
"if config_true_value(req.environ.get('swift.crypto.override')):\n self.logger.debug('No decryption is necessary because of override')\n return None\ninfo = get_object_info(req.environ, self.app, swift_source='DCRYPT')\nif 'crypto-etag' not in info['sysmeta']:\n return None\nkey_id = crypto_meta.get('key_i... | <|body_start_0|>
if config_true_value(req.environ.get('swift.crypto.override')):
self.logger.debug('No decryption is necessary because of override')
return None
info = get_object_info(req.environ, self.app, swift_source='DCRYPT')
if 'crypto-etag' not in info['sysmeta']:
... | DecrypterObjContext | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecrypterObjContext:
def get_decryption_keys(self, req, crypto_meta=None):
"""Determine if a response should be decrypted, and if so then fetch keys. :param req: a Request object :returns: a dict of decryption keys"""
<|body_0|>
def decrypt_resp_headers(self, put_keys, post_... | stack_v2_sparse_classes_75kplus_train_004075 | 6,272 | permissive | [
{
"docstring": "Determine if a response should be decrypted, and if so then fetch keys. :param req: a Request object :returns: a dict of decryption keys",
"name": "get_decryption_keys",
"signature": "def get_decryption_keys(self, req, crypto_meta=None)"
},
{
"docstring": "Find encrypted headers ... | 2 | null | Implement the Python class `DecrypterObjContext` described below.
Class description:
Implement the DecrypterObjContext class.
Method signatures and docstrings:
- def get_decryption_keys(self, req, crypto_meta=None): Determine if a response should be decrypted, and if so then fetch keys. :param req: a Request object :... | Implement the Python class `DecrypterObjContext` described below.
Class description:
Implement the DecrypterObjContext class.
Method signatures and docstrings:
- def get_decryption_keys(self, req, crypto_meta=None): Determine if a response should be decrypted, and if so then fetch keys. :param req: a Request object :... | be94cf2e4294cc6d37c3f3ee87e31de32dfe406e | <|skeleton|>
class DecrypterObjContext:
def get_decryption_keys(self, req, crypto_meta=None):
"""Determine if a response should be decrypted, and if so then fetch keys. :param req: a Request object :returns: a dict of decryption keys"""
<|body_0|>
def decrypt_resp_headers(self, put_keys, post_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DecrypterObjContext:
def get_decryption_keys(self, req, crypto_meta=None):
"""Determine if a response should be decrypted, and if so then fetch keys. :param req: a Request object :returns: a dict of decryption keys"""
if config_true_value(req.environ.get('swift.crypto.override')):
... | the_stack_v2_python_sparse | oioswift/common/middleware/crypto/decrypter.py | open-io/oio-swift | train | 28 | |
f5af95b9bfc96834f3f828e6a28f337a8a1634ff | [
"\"\"\"\n\t\tNaive Solution\n\t\tnums = sorted(nums1+nums2)\n\t\treturn ((nums[(len(nums)//2)-1]+nums[len(nums)//2])/2.) if len(nums)%2==0 else nums[len(nums)//2]\n\t\t\"\"\"\nif len(nums1) >= len(nums2):\n a1, a2 = (nums1, nums2)\nelse:\n a1, a2 = (nums2, nums1)\ni = []\nfor num in a2:\n a1.insert(self.fi... | <|body_start_0|>
"""
Naive Solution
nums = sorted(nums1+nums2)
return ((nums[(len(nums)//2)-1]+nums[len(nums)//2])/2.) if len(nums)%2==0 else nums[len(nums)//2]
"""
if len(nums1) >= len(nums2):
a1, a2 = (nums1, nums2)
else:
a1, a2 =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
<|body_0|>
def findNumber(self, arr, num):
"""Returns index of a number if present else -1 :type arr: List[int] :type num: List[int] :rtype: in... | stack_v2_sparse_classes_75kplus_train_004076 | 1,390 | no_license | [
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: float",
"name": "findMedianSortedArrays",
"signature": "def findMedianSortedArrays(self, nums1, nums2)"
},
{
"docstring": "Returns index of a number if present else -1 :type arr: List[int] :type num: List[int] :rtype: int",
... | 2 | stack_v2_sparse_classes_30k_train_005626 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMedianSortedArrays(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: float
- def findNumber(self, arr, num): Returns index of a number if present... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMedianSortedArrays(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: float
- def findNumber(self, arr, num): Returns index of a number if present... | a090bdd48573f9bf666594348622455f8b289496 | <|skeleton|>
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
<|body_0|>
def findNumber(self, arr, num):
"""Returns index of a number if present else -1 :type arr: List[int] :type num: List[int] :rtype: in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
"""
Naive Solution
nums = sorted(nums1+nums2)
return ((nums[(len(nums)//2)-1]+nums[len(nums)//2])/2.) if len(nums)%2==0 else nums[len(nums)/... | the_stack_v2_python_sparse | l33tc0d3/4_median_of_two_sorted_arrays.py | singhay/py-examples | train | 0 | |
cf5f92be4d32a982f2987c83b0c88c4b1c79dd58 | [
"data = None\nkwargs = {'load_all': self.load_all}\nif form_kwargs:\n kwargs.update(form_kwargs)\nif len(self.request.GET):\n data = self.request.GET\nif self.searchqueryset is not None:\n kwargs['searchqueryset'] = self.searchqueryset\nreturn self.form_class(self.request, data, **kwargs)",
"self.request... | <|body_start_0|>
data = None
kwargs = {'load_all': self.load_all}
if form_kwargs:
kwargs.update(form_kwargs)
if len(self.request.GET):
data = self.request.GET
if self.searchqueryset is not None:
kwargs['searchqueryset'] = self.searchqueryset
... | CustomSearchView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomSearchView:
def build_form(self, form_kwargs=None):
"""Instantiates the form the class should use to process the search query."""
<|body_0|>
def __call__(self, request):
"""Generates the actual response to the search. Relies on internal, overridable methods to ... | stack_v2_sparse_classes_75kplus_train_004077 | 5,380 | no_license | [
{
"docstring": "Instantiates the form the class should use to process the search query.",
"name": "build_form",
"signature": "def build_form(self, form_kwargs=None)"
},
{
"docstring": "Generates the actual response to the search. Relies on internal, overridable methods to construct the response.... | 3 | stack_v2_sparse_classes_30k_train_024128 | Implement the Python class `CustomSearchView` described below.
Class description:
Implement the CustomSearchView class.
Method signatures and docstrings:
- def build_form(self, form_kwargs=None): Instantiates the form the class should use to process the search query.
- def __call__(self, request): Generates the actua... | Implement the Python class `CustomSearchView` described below.
Class description:
Implement the CustomSearchView class.
Method signatures and docstrings:
- def build_form(self, form_kwargs=None): Instantiates the form the class should use to process the search query.
- def __call__(self, request): Generates the actua... | 8f6a35dde214e809cdd6cbfebd8d913bafd68fb2 | <|skeleton|>
class CustomSearchView:
def build_form(self, form_kwargs=None):
"""Instantiates the form the class should use to process the search query."""
<|body_0|>
def __call__(self, request):
"""Generates the actual response to the search. Relies on internal, overridable methods to ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomSearchView:
def build_form(self, form_kwargs=None):
"""Instantiates the form the class should use to process the search query."""
data = None
kwargs = {'load_all': self.load_all}
if form_kwargs:
kwargs.update(form_kwargs)
if len(self.request.GET):
... | the_stack_v2_python_sparse | search/views.py | pymmrd/tuangou | train | 0 | |
446673c23c6df008d27813a75a718b499c6e50b5 | [
"m = 100\nctx.save_for_backward(k)\nk = k.double()\nanswer = (m / 2 - 1) * torch.log(k) - torch.log(scipy.special.ive(m / 2 - 1, k.cpu())) - k - m / 2 * np.log(2 * np.pi)\nanswer = answer.float()\nreturn answer",
"k, = ctx.saved_tensors\nm = 100\nk = k.double()\nx = -(scipy.special.ive(m / 2, k.cpu()) / scipy.spe... | <|body_start_0|>
m = 100
ctx.save_for_backward(k)
k = k.double()
answer = (m / 2 - 1) * torch.log(k) - torch.log(scipy.special.ive(m / 2 - 1, k.cpu())) - k - m / 2 * np.log(2 * np.pi)
answer = answer.float()
return answer
<|end_body_0|>
<|body_start_1|>
k, = ctx.... | The exponentially scaled modified Bessel function of the first kind | Logcmk | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Logcmk:
"""The exponentially scaled modified Bessel function of the first kind"""
def forward(ctx, k):
"""In the forward pass we receive a Tensor containing the input and return a Tensor containing the output. ctx is a context object that can be used to stash information for backward... | stack_v2_sparse_classes_75kplus_train_004078 | 11,289 | no_license | [
{
"docstring": "In the forward pass we receive a Tensor containing the input and return a Tensor containing the output. ctx is a context object that can be used to stash information for backward computation. You can cache arbitrary objects for use in the backward pass using the ctx.save_for_backward method.",
... | 2 | stack_v2_sparse_classes_30k_train_017918 | Implement the Python class `Logcmk` described below.
Class description:
The exponentially scaled modified Bessel function of the first kind
Method signatures and docstrings:
- def forward(ctx, k): In the forward pass we receive a Tensor containing the input and return a Tensor containing the output. ctx is a context ... | Implement the Python class `Logcmk` described below.
Class description:
The exponentially scaled modified Bessel function of the first kind
Method signatures and docstrings:
- def forward(ctx, k): In the forward pass we receive a Tensor containing the input and return a Tensor containing the output. ctx is a context ... | 251142b2e704e595e664031f5a469ebad6de8333 | <|skeleton|>
class Logcmk:
"""The exponentially scaled modified Bessel function of the first kind"""
def forward(ctx, k):
"""In the forward pass we receive a Tensor containing the input and return a Tensor containing the output. ctx is a context object that can be used to stash information for backward... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Logcmk:
"""The exponentially scaled modified Bessel function of the first kind"""
def forward(ctx, k):
"""In the forward pass we receive a Tensor containing the input and return a Tensor containing the output. ctx is a context object that can be used to stash information for backward computation.... | the_stack_v2_python_sparse | contrastive_vmf.py | dheeraj7596/Coarse2Fine | train | 1 |
1b86360c2208d537ab4c1ffa5b47c0ea9bd70823 | [
"super().__init__(econet_device)\nself.entity_description = description\nself._attr_name = f'{econet_device.device_name}_{description.name}'\nself._attr_unique_id = f'{econet_device.device_id}_{econet_device.device_name}_{description.name}'",
"value = getattr(self._econet, self.entity_description.key)\nif self.en... | <|body_start_0|>
super().__init__(econet_device)
self.entity_description = description
self._attr_name = f'{econet_device.device_name}_{description.name}'
self._attr_unique_id = f'{econet_device.device_id}_{econet_device.device_name}_{description.name}'
<|end_body_0|>
<|body_start_1|>
... | Define a Econet sensor. | EcoNetSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EcoNetSensor:
"""Define a Econet sensor."""
def __init__(self, econet_device: Equipment, description: SensorEntityDescription) -> None:
"""Initialize."""
<|body_0|>
def native_value(self):
"""Return sensors state."""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_75kplus_train_004079 | 4,025 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, econet_device: Equipment, description: SensorEntityDescription) -> None"
},
{
"docstring": "Return sensors state.",
"name": "native_value",
"signature": "def native_value(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021726 | Implement the Python class `EcoNetSensor` described below.
Class description:
Define a Econet sensor.
Method signatures and docstrings:
- def __init__(self, econet_device: Equipment, description: SensorEntityDescription) -> None: Initialize.
- def native_value(self): Return sensors state. | Implement the Python class `EcoNetSensor` described below.
Class description:
Define a Econet sensor.
Method signatures and docstrings:
- def __init__(self, econet_device: Equipment, description: SensorEntityDescription) -> None: Initialize.
- def native_value(self): Return sensors state.
<|skeleton|>
class EcoNetSe... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class EcoNetSensor:
"""Define a Econet sensor."""
def __init__(self, econet_device: Equipment, description: SensorEntityDescription) -> None:
"""Initialize."""
<|body_0|>
def native_value(self):
"""Return sensors state."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EcoNetSensor:
"""Define a Econet sensor."""
def __init__(self, econet_device: Equipment, description: SensorEntityDescription) -> None:
"""Initialize."""
super().__init__(econet_device)
self.entity_description = description
self._attr_name = f'{econet_device.device_name}_{... | the_stack_v2_python_sparse | homeassistant/components/econet/sensor.py | home-assistant/core | train | 35,501 |
7641960a108076227ad77c3b8252b259324a67d4 | [
"if not quota_max_calls:\n use_rate_limiter = False\nself._projects = None\nself._datasets = None\nself._tables = None\nsuper(BigQueryRepositoryClient, self).__init__(API_NAME, versions=['v2'], quota_max_calls=quota_max_calls, quota_period=quota_period, use_rate_limiter=use_rate_limiter)",
"if not self._projec... | <|body_start_0|>
if not quota_max_calls:
use_rate_limiter = False
self._projects = None
self._datasets = None
self._tables = None
super(BigQueryRepositoryClient, self).__init__(API_NAME, versions=['v2'], quota_max_calls=quota_max_calls, quota_period=quota_period, use_... | Big Query API Respository. | BigQueryRepositoryClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BigQueryRepositoryClient:
"""Big Query API Respository."""
def __init__(self, quota_max_calls=None, quota_period=100.0, use_rate_limiter=True):
"""Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period> for the API. quota_period (float): The time period to track... | stack_v2_sparse_classes_75kplus_train_004080 | 9,404 | permissive | [
{
"docstring": "Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period> for the API. quota_period (float): The time period to track requests over. use_rate_limiter (bool): Set to false to disable the use of a rate limiter for this service.",
"name": "__init__",
"signature": "def __... | 4 | stack_v2_sparse_classes_30k_train_015858 | Implement the Python class `BigQueryRepositoryClient` described below.
Class description:
Big Query API Respository.
Method signatures and docstrings:
- def __init__(self, quota_max_calls=None, quota_period=100.0, use_rate_limiter=True): Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period> fo... | Implement the Python class `BigQueryRepositoryClient` described below.
Class description:
Big Query API Respository.
Method signatures and docstrings:
- def __init__(self, quota_max_calls=None, quota_period=100.0, use_rate_limiter=True): Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period> fo... | d4421afa50a17ed47cbebe942044ebab3720e0f5 | <|skeleton|>
class BigQueryRepositoryClient:
"""Big Query API Respository."""
def __init__(self, quota_max_calls=None, quota_period=100.0, use_rate_limiter=True):
"""Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period> for the API. quota_period (float): The time period to track... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BigQueryRepositoryClient:
"""Big Query API Respository."""
def __init__(self, quota_max_calls=None, quota_period=100.0, use_rate_limiter=True):
"""Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period> for the API. quota_period (float): The time period to track requests ove... | the_stack_v2_python_sparse | google/cloud/forseti/common/gcp_api/bigquery.py | kevensen/forseti-security | train | 1 |
b32ddb58b38cb47faac78c10c42c11dfac080f07 | [
"url = reverse('users-list')\nuser_data = {'id': '1', 'username': 'testuser', 'firstname': 'testfirstname', 'lastname': 'testlastname', 'email': 'test@testuser.com', 'password': 'dedede', 'gender': 'K', 'birthdate': '03-23-1990', 'activitiesdone': '1', 'achievements': '1', 'points': '1', 'level': '1', 'objective': ... | <|body_start_0|>
url = reverse('users-list')
user_data = {'id': '1', 'username': 'testuser', 'firstname': 'testfirstname', 'lastname': 'testlastname', 'email': 'test@testuser.com', 'password': 'dedede', 'gender': 'K', 'birthdate': '03-23-1990', 'activitiesdone': '1', 'achievements': '1', 'points': '1', ... | UserRegistrationAPIViewTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserRegistrationAPIViewTestCase:
def test_invalid_password(self):
"""Test to verify that a post call with invalid passwords"""
<|body_0|>
def test_invalid_email(self):
"""Test to verify that a post call with invalid email"""
<|body_1|>
def test_user_regi... | stack_v2_sparse_classes_75kplus_train_004081 | 10,951 | no_license | [
{
"docstring": "Test to verify that a post call with invalid passwords",
"name": "test_invalid_password",
"signature": "def test_invalid_password(self)"
},
{
"docstring": "Test to verify that a post call with invalid email",
"name": "test_invalid_email",
"signature": "def test_invalid_em... | 5 | stack_v2_sparse_classes_30k_train_034657 | Implement the Python class `UserRegistrationAPIViewTestCase` described below.
Class description:
Implement the UserRegistrationAPIViewTestCase class.
Method signatures and docstrings:
- def test_invalid_password(self): Test to verify that a post call with invalid passwords
- def test_invalid_email(self): Test to veri... | Implement the Python class `UserRegistrationAPIViewTestCase` described below.
Class description:
Implement the UserRegistrationAPIViewTestCase class.
Method signatures and docstrings:
- def test_invalid_password(self): Test to verify that a post call with invalid passwords
- def test_invalid_email(self): Test to veri... | 6b2296994b6db3a828715d2f47b340d84e5b4c84 | <|skeleton|>
class UserRegistrationAPIViewTestCase:
def test_invalid_password(self):
"""Test to verify that a post call with invalid passwords"""
<|body_0|>
def test_invalid_email(self):
"""Test to verify that a post call with invalid email"""
<|body_1|>
def test_user_regi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserRegistrationAPIViewTestCase:
def test_invalid_password(self):
"""Test to verify that a post call with invalid passwords"""
url = reverse('users-list')
user_data = {'id': '1', 'username': 'testuser', 'firstname': 'testfirstname', 'lastname': 'testlastname', 'email': 'test@testuser.c... | the_stack_v2_python_sparse | app/users/tests.py | sergiii24/FitHaus_Backend | train | 0 | |
2e5c1977936ec7f0fcf7fa202e3530225bf17fa7 | [
"super(RNNDecoder, self).__init__()\nself.embedding = tf.keras.layers.Embedding(vocab, embedding)\nself.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)\nself.F = tf.keras.layers.Dense(vocab)\nself.units = units",
"attention = SelfAttention(self.un... | <|body_start_0|>
super(RNNDecoder, self).__init__()
self.embedding = tf.keras.layers.Embedding(vocab, embedding)
self.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)
self.F = tf.keras.layers.Dense(vocab)
self.unit... | This class decode for machine translation | RNNDecoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNDecoder:
"""This class decode for machine translation"""
def __init__(self, vocab, embedding, units, batch):
"""all begins here"""
<|body_0|>
def call(self, x, s_prev, hidden_states):
"""This method has the model to call"""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_75kplus_train_004082 | 1,755 | permissive | [
{
"docstring": "all begins here",
"name": "__init__",
"signature": "def __init__(self, vocab, embedding, units, batch)"
},
{
"docstring": "This method has the model to call",
"name": "call",
"signature": "def call(self, x, s_prev, hidden_states)"
}
] | 2 | stack_v2_sparse_classes_30k_train_022157 | Implement the Python class `RNNDecoder` described below.
Class description:
This class decode for machine translation
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): all begins here
- def call(self, x, s_prev, hidden_states): This method has the model to call | Implement the Python class `RNNDecoder` described below.
Class description:
This class decode for machine translation
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): all begins here
- def call(self, x, s_prev, hidden_states): This method has the model to call
<|skeleton|>
clas... | 58c367f3014919f95157426121093b9fe14d4035 | <|skeleton|>
class RNNDecoder:
"""This class decode for machine translation"""
def __init__(self, vocab, embedding, units, batch):
"""all begins here"""
<|body_0|>
def call(self, x, s_prev, hidden_states):
"""This method has the model to call"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RNNDecoder:
"""This class decode for machine translation"""
def __init__(self, vocab, embedding, units, batch):
"""all begins here"""
super(RNNDecoder, self).__init__()
self.embedding = tf.keras.layers.Embedding(vocab, embedding)
self.gru = tf.keras.layers.GRU(units, recur... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/2-rnn_decoder.py | linkem97/holbertonschool-machine_learning | train | 0 |
f6857c5dae8531ce714b8de3aff8cabf587b6db4 | [
"password_meter = self.data['passwordMeterId']\nif int(password_meter) < FORTALEZA_CONTRASENHA:\n raise forms.ValidationError(_('La contraseña es débil'))\nreturn self.cleaned_data['clave']",
"verificar_contrasenha = self.cleaned_data['verificar_contrasenha']\ncontrasenha = self.data['clave']\nif contrasenha !... | <|body_start_0|>
password_meter = self.data['passwordMeterId']
if int(password_meter) < FORTALEZA_CONTRASENHA:
raise forms.ValidationError(_('La contraseña es débil'))
return self.cleaned_data['clave']
<|end_body_0|>
<|body_start_1|>
verificar_contrasenha = self.cleaned_data... | ! Clase que muestra el formulario para la modificación de claves @author Ing. Roldan Vargas (rvargas at cenditel.gob.ve) @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a> @date 19-08-2016 @version 1.0.0 | ModificarClaveForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModificarClaveForm:
"""! Clase que muestra el formulario para la modificación de claves @author Ing. Roldan Vargas (rvargas at cenditel.gob.ve) @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a> @date 19-08-2016 @version 1.0.0"""
def clean_... | stack_v2_sparse_classes_75kplus_train_004083 | 16,425 | no_license | [
{
"docstring": "! Método que permite validar el campo de password @author Ing. Roldan Vargas (rvargas at cenditel.gob.ve) @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a> @date 19-08-2016 @param self <b>{object}</b> Objeto que instancia la clase @return Devu... | 2 | stack_v2_sparse_classes_30k_test_000485 | Implement the Python class `ModificarClaveForm` described below.
Class description:
! Clase que muestra el formulario para la modificación de claves @author Ing. Roldan Vargas (rvargas at cenditel.gob.ve) @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a> @date 19-08... | Implement the Python class `ModificarClaveForm` described below.
Class description:
! Clase que muestra el formulario para la modificación de claves @author Ing. Roldan Vargas (rvargas at cenditel.gob.ve) @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a> @date 19-08... | 72c4b8d9c74b05e0056e11721e3888409f37069e | <|skeleton|>
class ModificarClaveForm:
"""! Clase que muestra el formulario para la modificación de claves @author Ing. Roldan Vargas (rvargas at cenditel.gob.ve) @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a> @date 19-08-2016 @version 1.0.0"""
def clean_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ModificarClaveForm:
"""! Clase que muestra el formulario para la modificación de claves @author Ing. Roldan Vargas (rvargas at cenditel.gob.ve) @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a> @date 19-08-2016 @version 1.0.0"""
def clean_clave(self):
... | the_stack_v2_python_sparse | usuario/forms.py | lbarrios1985/seiven-cenditel | train | 0 |
de984d0702fe0b8e205afa8c9d34c4fabb328c66 | [
"self.lossf = lossf\nself.resize_x = resize_x\nself.align_corners = align_corners",
"if self.resize_x:\n x = auto_interpolate_2d(size=y.shape[-2:], align_corners=self.align_corners)(x)\nelse:\n y = auto_interpolate_2d(size=x.shape[-2:], align_corners=self.align_corners)(y)\nl = self.lossf(x, y)\nreturn l"
] | <|body_start_0|>
self.lossf = lossf
self.resize_x = resize_x
self.align_corners = align_corners
<|end_body_0|>
<|body_start_1|>
if self.resize_x:
x = auto_interpolate_2d(size=y.shape[-2:], align_corners=self.align_corners)(x)
else:
y = auto_interpolate_2d... | This function add a intepolation on input x or y before the loss computation. This function uses the auto_interpolate_2d that resize tensor automatically based on its type | interpolate_2d_lossf | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class interpolate_2d_lossf:
"""This function add a intepolation on input x or y before the loss computation. This function uses the auto_interpolate_2d that resize tensor automatically based on its type"""
def __init__(self, lossf, resize_x=False, align_corners=True, **kwargs):
"""Args: lo... | stack_v2_sparse_classes_75kplus_train_004084 | 15,122 | no_license | [
{
"docstring": "Args: lossf: a torch.nn specified loss function. Reduction has to be \"none\". Or an element wise-operation on two same size torch.Tensor. resize_x: a bool. When True, x is resized to y (ground truth) size, vise versa. align_corners: bool, whether aligns the corner.",
"name": "__init__",
... | 2 | stack_v2_sparse_classes_30k_train_016028 | Implement the Python class `interpolate_2d_lossf` described below.
Class description:
This function add a intepolation on input x or y before the loss computation. This function uses the auto_interpolate_2d that resize tensor automatically based on its type
Method signatures and docstrings:
- def __init__(self, lossf... | Implement the Python class `interpolate_2d_lossf` described below.
Class description:
This function add a intepolation on input x or y before the loss computation. This function uses the auto_interpolate_2d that resize tensor automatically based on its type
Method signatures and docstrings:
- def __init__(self, lossf... | f14b1eef7229ec3338b85531958d988ef26c2adc | <|skeleton|>
class interpolate_2d_lossf:
"""This function add a intepolation on input x or y before the loss computation. This function uses the auto_interpolate_2d that resize tensor automatically based on its type"""
def __init__(self, lossf, resize_x=False, align_corners=True, **kwargs):
"""Args: lo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class interpolate_2d_lossf:
"""This function add a intepolation on input x or y before the loss computation. This function uses the auto_interpolate_2d that resize tensor automatically based on its type"""
def __init__(self, lossf, resize_x=False, align_corners=True, **kwargs):
"""Args: lossf: a torch.... | the_stack_v2_python_sparse | lib/torchutils.py | tanmayj000/Rethinking-Text-Segmentation | train | 0 |
288c11ad1b4f875bbeb199bc49397a132f52b121 | [
"super().__init__(session_factory)\nself.coin_category = 'BTC'\nself.chain_api = BtcOP(config)",
"now = datetime.datetime.now()\naccount_name = '{}_{}_{}_{}'.format(self.coin_category, now.strftime('%Y%m%d'), cnt, now.timestamp())\nret = copy.deepcopy(self._address_template)\nret['account'] = account_name\npub_ad... | <|body_start_0|>
super().__init__(session_factory)
self.coin_category = 'BTC'
self.chain_api = BtcOP(config)
<|end_body_0|>
<|body_start_1|>
now = datetime.datetime.now()
account_name = '{}_{}_{}_{}'.format(self.coin_category, now.strftime('%Y%m%d'), cnt, now.timestamp())
... | BtcManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BtcManager:
def __init__(self, session_factory):
""":param session_factory: mysql_session_maker"""
<|body_0|>
def generate_address(self, cnt: int) -> dict:
"""产生比特币地址账户 :param cnt: 编号 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().... | stack_v2_sparse_classes_75kplus_train_004085 | 1,363 | no_license | [
{
"docstring": ":param session_factory: mysql_session_maker",
"name": "__init__",
"signature": "def __init__(self, session_factory)"
},
{
"docstring": "产生比特币地址账户 :param cnt: 编号 :return:",
"name": "generate_address",
"signature": "def generate_address(self, cnt: int) -> dict"
}
] | 2 | stack_v2_sparse_classes_30k_test_001872 | Implement the Python class `BtcManager` described below.
Class description:
Implement the BtcManager class.
Method signatures and docstrings:
- def __init__(self, session_factory): :param session_factory: mysql_session_maker
- def generate_address(self, cnt: int) -> dict: 产生比特币地址账户 :param cnt: 编号 :return: | Implement the Python class `BtcManager` described below.
Class description:
Implement the BtcManager class.
Method signatures and docstrings:
- def __init__(self, session_factory): :param session_factory: mysql_session_maker
- def generate_address(self, cnt: int) -> dict: 产生比特币地址账户 :param cnt: 编号 :return:
<|skeleton... | 4ddca9c77c2361a8b9f0a708353809449094137d | <|skeleton|>
class BtcManager:
def __init__(self, session_factory):
""":param session_factory: mysql_session_maker"""
<|body_0|>
def generate_address(self, cnt: int) -> dict:
"""产生比特币地址账户 :param cnt: 编号 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BtcManager:
def __init__(self, session_factory):
""":param session_factory: mysql_session_maker"""
super().__init__(session_factory)
self.coin_category = 'BTC'
self.chain_api = BtcOP(config)
def generate_address(self, cnt: int) -> dict:
"""产生比特币地址账户 :param cnt: 编号 ... | the_stack_v2_python_sparse | source/common/address_manager/btc.py | buyongji/wallet | train | 1 | |
d38f409c49090bbab57c3bf5ee46a05821cd688d | [
"self.n_components = n_components\nself.signal_cov = signal_cov\nself.reg = reg\nself.method_params = method_params",
"X, y = self._check_Xy(X, y)\nself.classes_ = np.unique(y)\nself.filters_, self.patterns_, _ = _fit_xdawn(X, y, n_components=self.n_components, reg=self.reg, signal_cov=self.signal_cov, method_par... | <|body_start_0|>
self.n_components = n_components
self.signal_cov = signal_cov
self.reg = reg
self.method_params = method_params
<|end_body_0|>
<|body_start_1|>
X, y = self._check_Xy(X, y)
self.classes_ = np.unique(y)
self.filters_, self.patterns_, _ = _fit_xdawn... | Implementation of the Xdawn Algorithm compatible with scikit-learn. Xdawn is a spatial filtering method designed to improve the signal to signal + noise ratio (SSNR) of the event related responses. Xdawn was originally designed for P300 evoked potential by enhancing the target response with respect to the non-target re... | _XdawnTransformer | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _XdawnTransformer:
"""Implementation of the Xdawn Algorithm compatible with scikit-learn. Xdawn is a spatial filtering method designed to improve the signal to signal + noise ratio (SSNR) of the event related responses. Xdawn was originally designed for P300 evoked potential by enhancing the targ... | stack_v2_sparse_classes_75kplus_train_004086 | 24,789 | permissive | [
{
"docstring": "Init.",
"name": "__init__",
"signature": "def __init__(self, n_components=2, reg=None, signal_cov=None, method_params=None)"
},
{
"docstring": "Fit Xdawn spatial filters. Parameters ---------- X : array, shape (n_epochs, n_channels, n_samples) The target data. y : array, shape (n... | 5 | null | Implement the Python class `_XdawnTransformer` described below.
Class description:
Implementation of the Xdawn Algorithm compatible with scikit-learn. Xdawn is a spatial filtering method designed to improve the signal to signal + noise ratio (SSNR) of the event related responses. Xdawn was originally designed for P300... | Implement the Python class `_XdawnTransformer` described below.
Class description:
Implementation of the Xdawn Algorithm compatible with scikit-learn. Xdawn is a spatial filtering method designed to improve the signal to signal + noise ratio (SSNR) of the event related responses. Xdawn was originally designed for P300... | f44636f00666b8eb869417960926d01690ff4f42 | <|skeleton|>
class _XdawnTransformer:
"""Implementation of the Xdawn Algorithm compatible with scikit-learn. Xdawn is a spatial filtering method designed to improve the signal to signal + noise ratio (SSNR) of the event related responses. Xdawn was originally designed for P300 evoked potential by enhancing the targ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _XdawnTransformer:
"""Implementation of the Xdawn Algorithm compatible with scikit-learn. Xdawn is a spatial filtering method designed to improve the signal to signal + noise ratio (SSNR) of the event related responses. Xdawn was originally designed for P300 evoked potential by enhancing the target response w... | the_stack_v2_python_sparse | mne/preprocessing/xdawn.py | mne-tools/mne-python | train | 2,437 |
719d78b5fc72a0524b9c6c21fc50e2df08176e42 | [
"super().__init__()\nself.init_point = init_point\nself.groups = groups",
"if X.shape[-2] != 1:\n raise NotImplementedError('group-lasso has not been implemented for q>1 yet.')\nregularization_term = group_lasso_regularizer(X=X.squeeze(-2) - self.init_point, groups=self.groups)\nreturn regularization_term"
] | <|body_start_0|>
super().__init__()
self.init_point = init_point
self.groups = groups
<|end_body_0|>
<|body_start_1|>
if X.shape[-2] != 1:
raise NotImplementedError('group-lasso has not been implemented for q>1 yet.')
regularization_term = group_lasso_regularizer(X=X... | Group lasso penalty class to be added to any arbitrary acquisition function to construct a PenalizedAcquisitionFunction. | GroupLassoPenalty | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupLassoPenalty:
"""Group lasso penalty class to be added to any arbitrary acquisition function to construct a PenalizedAcquisitionFunction."""
def __init__(self, init_point: Tensor, groups: List[List[int]]):
"""Initializing Group-Lasso regularization. Args: init_point: The "1 x di... | stack_v2_sparse_classes_75kplus_train_004087 | 14,396 | permissive | [
{
"docstring": "Initializing Group-Lasso regularization. Args: init_point: The \"1 x dim\" reference point against which we want to regularize. groups: Groups of indices used in group lasso.",
"name": "__init__",
"signature": "def __init__(self, init_point: Tensor, groups: List[List[int]])"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_040003 | Implement the Python class `GroupLassoPenalty` described below.
Class description:
Group lasso penalty class to be added to any arbitrary acquisition function to construct a PenalizedAcquisitionFunction.
Method signatures and docstrings:
- def __init__(self, init_point: Tensor, groups: List[List[int]]): Initializing ... | Implement the Python class `GroupLassoPenalty` described below.
Class description:
Group lasso penalty class to be added to any arbitrary acquisition function to construct a PenalizedAcquisitionFunction.
Method signatures and docstrings:
- def __init__(self, init_point: Tensor, groups: List[List[int]]): Initializing ... | 4cc5ed59b2e8a9c780f786830c548e05cc74d53c | <|skeleton|>
class GroupLassoPenalty:
"""Group lasso penalty class to be added to any arbitrary acquisition function to construct a PenalizedAcquisitionFunction."""
def __init__(self, init_point: Tensor, groups: List[List[int]]):
"""Initializing Group-Lasso regularization. Args: init_point: The "1 x di... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GroupLassoPenalty:
"""Group lasso penalty class to be added to any arbitrary acquisition function to construct a PenalizedAcquisitionFunction."""
def __init__(self, init_point: Tensor, groups: List[List[int]]):
"""Initializing Group-Lasso regularization. Args: init_point: The "1 x dim" reference ... | the_stack_v2_python_sparse | botorch/acquisition/penalized.py | pytorch/botorch | train | 2,891 |
d35ee51f0b5f8719bcaf23426219d957fc69b013 | [
"vals = []\ncur, stack = (root, [])\nwhile cur or stack:\n while cur:\n vals.append(cur.val)\n stack.append(cur)\n cur = cur.left\n cur = stack.pop()\n cur = cur.right\nreturn ' '.join(map(str, vals))",
"vals = list(map(int, data.split()))\n\ndef build(vals):\n if not vals:\n ... | <|body_start_0|>
vals = []
cur, stack = (root, [])
while cur or stack:
while cur:
vals.append(cur.val)
stack.append(cur)
cur = cur.left
cur = stack.pop()
cur = cur.right
return ' '.join(map(str, vals))
<|... | Codec | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_004088 | 1,361 | permissive | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_030586 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 3719f5cb059eefd66b83eb8ae990652f4b7fd124 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
vals = []
cur, stack = (root, [])
while cur or stack:
while cur:
vals.append(cur.val)
stack.append(cur)
cur = ... | the_stack_v2_python_sparse | Python3/0449-Serialize-and-Deserialize-BST/soln-1.py | wyaadarsh/LeetCode-Solutions | train | 0 | |
491228c1e200e88d6cb3bb7e4516c45739d14f1e | [
"d = {}\nd.update(training_job_result.__dict__)\nif d['training_request'] is not None:\n coder = TrainingJobRequestCoder()\n d['training_request'] = coder.encode(d['training_request'])\nreturn json.dumps(d)",
"r = TrainingJobResult()\nd = json.loads(training_job_result_string)\nif d['training_request'] is n... | <|body_start_0|>
d = {}
d.update(training_job_result.__dict__)
if d['training_request'] is not None:
coder = TrainingJobRequestCoder()
d['training_request'] = coder.encode(d['training_request'])
return json.dumps(d)
<|end_body_0|>
<|body_start_1|>
r = Tra... | Custom coder for TrainingJobResult. | TrainingJobResultCoder | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrainingJobResultCoder:
"""Custom coder for TrainingJobResult."""
def encode(self, training_job_result):
"""Encode a TrainingJobResult object into a JSON string. Args: training_job_result: A TrainingJobResult object. Returns: A JSON string"""
<|body_0|>
def decode(self, ... | stack_v2_sparse_classes_75kplus_train_004089 | 15,207 | permissive | [
{
"docstring": "Encode a TrainingJobResult object into a JSON string. Args: training_job_result: A TrainingJobResult object. Returns: A JSON string",
"name": "encode",
"signature": "def encode(self, training_job_result)"
},
{
"docstring": "Decode a string to a TrainingJobResult object. Args: tra... | 2 | null | Implement the Python class `TrainingJobResultCoder` described below.
Class description:
Custom coder for TrainingJobResult.
Method signatures and docstrings:
- def encode(self, training_job_result): Encode a TrainingJobResult object into a JSON string. Args: training_job_result: A TrainingJobResult object. Returns: A... | Implement the Python class `TrainingJobResultCoder` described below.
Class description:
Custom coder for TrainingJobResult.
Method signatures and docstrings:
- def encode(self, training_job_result): Encode a TrainingJobResult object into a JSON string. Args: training_job_result: A TrainingJobResult object. Returns: A... | 85bb264e273568b5a0408f733b403c56373e2508 | <|skeleton|>
class TrainingJobResultCoder:
"""Custom coder for TrainingJobResult."""
def encode(self, training_job_result):
"""Encode a TrainingJobResult object into a JSON string. Args: training_job_result: A TrainingJobResult object. Returns: A JSON string"""
<|body_0|>
def decode(self, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TrainingJobResultCoder:
"""Custom coder for TrainingJobResult."""
def encode(self, training_job_result):
"""Encode a TrainingJobResult object into a JSON string. Args: training_job_result: A TrainingJobResult object. Returns: A JSON string"""
d = {}
d.update(training_job_result.__... | the_stack_v2_python_sparse | google-cloud-sdk/lib/third_party/ml_sdk/cloud/ml/io/coders.py | bopopescu/socialliteapp | train | 0 |
5fa072b812c652cfbaef5c51691709aac47560f5 | [
"super(RelativeTransformerLayers, self).__init__(name=name, **kwargs)\nif intermediate_size is None:\n intermediate_size = 4 * hidden_size\nself.hidden_size = hidden_size\nself.num_hidden_layers = num_hidden_layers\nself.num_attention_heads = num_attention_heads\nself.intermediate_size = intermediate_size\nself.... | <|body_start_0|>
super(RelativeTransformerLayers, self).__init__(name=name, **kwargs)
if intermediate_size is None:
intermediate_size = 4 * hidden_size
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_h... | A sequence of Transformer encoder layers with optional relative attention. Just like the original Transformer, this layer uses full attention and scales quadratically with the input length. To efficiently handle large inputs, ETC uses `GlobalLocalTransformerLayers` instead. We just include this layer as a convenience s... | RelativeTransformerLayers | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelativeTransformerLayers:
"""A sequence of Transformer encoder layers with optional relative attention. Just like the original Transformer, this layer uses full attention and scales quadratically with the input length. To efficiently handle large inputs, ETC uses `GlobalLocalTransformerLayers` i... | stack_v2_sparse_classes_75kplus_train_004090 | 27,776 | permissive | [
{
"docstring": "Init. Args: hidden_size: Size of the output hidden dimension. Must match the input hidden dimension size. num_hidden_layers: Number of Transformer layers. Each layer includes both an attention sublayer and a feed-forward sublayer. num_attention_heads: Number of attention heads. Must evenly divid... | 2 | stack_v2_sparse_classes_30k_train_042711 | Implement the Python class `RelativeTransformerLayers` described below.
Class description:
A sequence of Transformer encoder layers with optional relative attention. Just like the original Transformer, this layer uses full attention and scales quadratically with the input length. To efficiently handle large inputs, ET... | Implement the Python class `RelativeTransformerLayers` described below.
Class description:
A sequence of Transformer encoder layers with optional relative attention. Just like the original Transformer, this layer uses full attention and scales quadratically with the input length. To efficiently handle large inputs, ET... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class RelativeTransformerLayers:
"""A sequence of Transformer encoder layers with optional relative attention. Just like the original Transformer, this layer uses full attention and scales quadratically with the input length. To efficiently handle large inputs, ETC uses `GlobalLocalTransformerLayers` i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RelativeTransformerLayers:
"""A sequence of Transformer encoder layers with optional relative attention. Just like the original Transformer, this layer uses full attention and scales quadratically with the input length. To efficiently handle large inputs, ETC uses `GlobalLocalTransformerLayers` instead. We ju... | the_stack_v2_python_sparse | etcmodel/layers/transformer.py | Jimmy-INL/google-research | train | 1 |
c8055f8df2dd0e440c0cbf9c24a845bb97ef7111 | [
"Connection = namedtuple('Connection', ['target', 'connection'])\nall_connections = []\nfor entity in file.values():\n if entity.connections is not None:\n for connection in entity.connections:\n all_connections.append(Connection(entity.code, connection))\nreturn all_connections",
"for entity... | <|body_start_0|>
Connection = namedtuple('Connection', ['target', 'connection'])
all_connections = []
for entity in file.values():
if entity.connections is not None:
for connection in entity.connections:
all_connections.append(Connection(entity.cod... | Quantifies whether connections between entities were correctly and completely defined in the proposed file. | EntityConnectionIdentification | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EntityConnectionIdentification:
"""Quantifies whether connections between entities were correctly and completely defined in the proposed file."""
def _isolate_connections(file: DeserializedFile) -> ConnectionsList:
"""Distill individual connections from each entity prior to inclusion... | stack_v2_sparse_classes_75kplus_train_004091 | 3,696 | permissive | [
{
"docstring": "Distill individual connections from each entity prior to inclusion in sets for global comparison.",
"name": "_isolate_connections",
"signature": "def _isolate_connections(file: DeserializedFile) -> ConnectionsList"
},
{
"docstring": "Returns an entity's `cloud_device_id` if avail... | 4 | null | Implement the Python class `EntityConnectionIdentification` described below.
Class description:
Quantifies whether connections between entities were correctly and completely defined in the proposed file.
Method signatures and docstrings:
- def _isolate_connections(file: DeserializedFile) -> ConnectionsList: Distill i... | Implement the Python class `EntityConnectionIdentification` described below.
Class description:
Quantifies whether connections between entities were correctly and completely defined in the proposed file.
Method signatures and docstrings:
- def _isolate_connections(file: DeserializedFile) -> ConnectionsList: Distill i... | 0ffe5b61769143826142da4bada3c712b1fd0222 | <|skeleton|>
class EntityConnectionIdentification:
"""Quantifies whether connections between entities were correctly and completely defined in the proposed file."""
def _isolate_connections(file: DeserializedFile) -> ConnectionsList:
"""Distill individual connections from each entity prior to inclusion... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EntityConnectionIdentification:
"""Quantifies whether connections between entities were correctly and completely defined in the proposed file."""
def _isolate_connections(file: DeserializedFile) -> ConnectionsList:
"""Distill individual connections from each entity prior to inclusion in sets for ... | the_stack_v2_python_sparse | tools/scoring/score/dimensions/entity_connection_identification.py | google/digitalbuildings | train | 319 |
eef3718ee480754b7d9d55b44adf559f1b560000 | [
"self.name = BOT_NAME\nself.oauth = {'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, 'scope': 'bot'}\nself.collection_name = 'slack'\nself.verification = VERIFICATION\nself.client = SlackClient(token)",
"if not code:\n return {'text': 'Code expected', 'status': 404}\nauth_response = self.client.api_cal... | <|body_start_0|>
self.name = BOT_NAME
self.oauth = {'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, 'scope': 'bot'}
self.collection_name = 'slack'
self.verification = VERIFICATION
self.client = SlackClient(token)
<|end_body_0|>
<|body_start_1|>
if not code:
... | Bot | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bot:
def __init__(self, token=None):
"""connect slack client with slack bot :param token:"""
<|body_0|>
def auth(self, code, broker):
"""Authentificate bot: 1. send oauth.access api method with params below 2. getting team and token 3. Save team_id as key and token a... | stack_v2_sparse_classes_75kplus_train_004092 | 3,352 | permissive | [
{
"docstring": "connect slack client with slack bot :param token:",
"name": "__init__",
"signature": "def __init__(self, token=None)"
},
{
"docstring": "Authentificate bot: 1. send oauth.access api method with params below 2. getting team and token 3. Save team_id as key and token as value :para... | 2 | stack_v2_sparse_classes_30k_train_026545 | Implement the Python class `Bot` described below.
Class description:
Implement the Bot class.
Method signatures and docstrings:
- def __init__(self, token=None): connect slack client with slack bot :param token:
- def auth(self, code, broker): Authentificate bot: 1. send oauth.access api method with params below 2. g... | Implement the Python class `Bot` described below.
Class description:
Implement the Bot class.
Method signatures and docstrings:
- def __init__(self, token=None): connect slack client with slack bot :param token:
- def auth(self, code, broker): Authentificate bot: 1. send oauth.access api method with params below 2. g... | b2b73a41d67c9ac6e53c105315eea8b0e287b307 | <|skeleton|>
class Bot:
def __init__(self, token=None):
"""connect slack client with slack bot :param token:"""
<|body_0|>
def auth(self, code, broker):
"""Authentificate bot: 1. send oauth.access api method with params below 2. getting team and token 3. Save team_id as key and token a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Bot:
def __init__(self, token=None):
"""connect slack client with slack bot :param token:"""
self.name = BOT_NAME
self.oauth = {'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, 'scope': 'bot'}
self.collection_name = 'slack'
self.verification = VERIFICATION
... | the_stack_v2_python_sparse | codexbot/services/slack/Bot.py | codex-team/codex.bot | train | 35 | |
13eb46e82c7f48dc220a2614eed09cc91e51e09c | [
"super().__init__()\nself.server_ip = server_ip\nself.port = port\nif server_ip is None or port is None:\n self.url = None\nelse:\n self.url = 'http://' + self.server_ip + ':' + str(self.port) + endpoint\nlogger.info(f'endpoint: {self.url}')",
"if self.url is None:\n logger.error('No punctuation server, ... | <|body_start_0|>
super().__init__()
self.server_ip = server_ip
self.port = port
if server_ip is None or port is None:
self.url = None
else:
self.url = 'http://' + self.server_ip + ':' + str(self.port) + endpoint
logger.info(f'endpoint: {self.url}')... | ASRHttpHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ASRHttpHandler:
def __init__(self, server_ip=None, port=None, endpoint='/paddlespeech/asr'):
"""The ASR client http request Args: server_ip (str, optional): the http asr server ip. Defaults to "127.0.0.1". port (int, optional): the http asr server port. Defaults to 8090."""
<|bod... | stack_v2_sparse_classes_75kplus_train_004093 | 21,059 | permissive | [
{
"docstring": "The ASR client http request Args: server_ip (str, optional): the http asr server ip. Defaults to \"127.0.0.1\". port (int, optional): the http asr server port. Defaults to 8090.",
"name": "__init__",
"signature": "def __init__(self, server_ip=None, port=None, endpoint='/paddlespeech/asr'... | 2 | null | Implement the Python class `ASRHttpHandler` described below.
Class description:
Implement the ASRHttpHandler class.
Method signatures and docstrings:
- def __init__(self, server_ip=None, port=None, endpoint='/paddlespeech/asr'): The ASR client http request Args: server_ip (str, optional): the http asr server ip. Defa... | Implement the Python class `ASRHttpHandler` described below.
Class description:
Implement the ASRHttpHandler class.
Method signatures and docstrings:
- def __init__(self, server_ip=None, port=None, endpoint='/paddlespeech/asr'): The ASR client http request Args: server_ip (str, optional): the http asr server ip. Defa... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class ASRHttpHandler:
def __init__(self, server_ip=None, port=None, endpoint='/paddlespeech/asr'):
"""The ASR client http request Args: server_ip (str, optional): the http asr server ip. Defaults to "127.0.0.1". port (int, optional): the http asr server port. Defaults to 8090."""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ASRHttpHandler:
def __init__(self, server_ip=None, port=None, endpoint='/paddlespeech/asr'):
"""The ASR client http request Args: server_ip (str, optional): the http asr server ip. Defaults to "127.0.0.1". port (int, optional): the http asr server port. Defaults to 8090."""
super().__init__()
... | the_stack_v2_python_sparse | paddlespeech/server/utils/audio_handler.py | anniyanvr/DeepSpeech-1 | train | 0 | |
7b5b7e1027dcf1da2d9dc12721fc343039831fdc | [
"response = CommentReplyChecker.check_exists(comment_pk, article_slug, reply_pk)\nif not isinstance(response, list):\n return response\nreply = response[2]\nreply.delete()\nreturn Response({'message': 'Reply deleted successfully'}, status=status.HTTP_200_OK)",
"reply_data = request.data.get('reply', {})\nresp ... | <|body_start_0|>
response = CommentReplyChecker.check_exists(comment_pk, article_slug, reply_pk)
if not isinstance(response, list):
return response
reply = response[2]
reply.delete()
return Response({'message': 'Reply deleted successfully'}, status=status.HTTP_200_OK)... | delete a comment's reply or update a reply | UpdateDestroyReplyAPIView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateDestroyReplyAPIView:
"""delete a comment's reply or update a reply"""
def destroy(self, request, article_slug=None, comment_pk=None, reply_pk=None):
"""delete comment with comment_id of article with specified slug"""
<|body_0|>
def update(self, request, article_slu... | stack_v2_sparse_classes_75kplus_train_004094 | 4,801 | permissive | [
{
"docstring": "delete comment with comment_id of article with specified slug",
"name": "destroy",
"signature": "def destroy(self, request, article_slug=None, comment_pk=None, reply_pk=None)"
},
{
"docstring": "update comment with comment_id or artcle_slug",
"name": "update",
"signature"... | 2 | null | Implement the Python class `UpdateDestroyReplyAPIView` described below.
Class description:
delete a comment's reply or update a reply
Method signatures and docstrings:
- def destroy(self, request, article_slug=None, comment_pk=None, reply_pk=None): delete comment with comment_id of article with specified slug
- def u... | Implement the Python class `UpdateDestroyReplyAPIView` described below.
Class description:
delete a comment's reply or update a reply
Method signatures and docstrings:
- def destroy(self, request, article_slug=None, comment_pk=None, reply_pk=None): delete comment with comment_id of article with specified slug
- def u... | c199e6dd432bdb4a5e1152f90cb1716b09af2c4e | <|skeleton|>
class UpdateDestroyReplyAPIView:
"""delete a comment's reply or update a reply"""
def destroy(self, request, article_slug=None, comment_pk=None, reply_pk=None):
"""delete comment with comment_id of article with specified slug"""
<|body_0|>
def update(self, request, article_slu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UpdateDestroyReplyAPIView:
"""delete a comment's reply or update a reply"""
def destroy(self, request, article_slug=None, comment_pk=None, reply_pk=None):
"""delete comment with comment_id of article with specified slug"""
response = CommentReplyChecker.check_exists(comment_pk, article_sl... | the_stack_v2_python_sparse | authors/apps/articles/views/reply.py | andela/ah-technocrats | train | 1 |
6f7b9a779abd8fe5f117f7610525cc19a0a63d52 | [
"super().__init__()\nself._initialize_arguments(args)\nself.embedding = nn.Linear(self.input_dim, self.rnn_units)\ntorch.nn.init.normal_(self.embedding.weight)\nself.gat_layers = nn.ModuleList([gat_cell.GATGRUCell(args) for _ in range(self.num_rnn_layers)])\nself.dropout = nn.Dropout(self.dropout)\nself.tanh = nn.T... | <|body_start_0|>
super().__init__()
self._initialize_arguments(args)
self.embedding = nn.Linear(self.input_dim, self.rnn_units)
torch.nn.init.normal_(self.embedding.weight)
self.gat_layers = nn.ModuleList([gat_cell.GATGRUCell(args) for _ in range(self.num_rnn_layers)])
se... | Implements GATRNN encoder model. Encodes the input time series sequence to the hidden vector. | Encoder | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
"""Implements GATRNN encoder model. Encodes the input time series sequence to the hidden vector."""
def __init__(self, args):
"""Instantiates the GATRNN encoder model. Args: args: python argparse.ArgumentParser class, we only use model-related arguments here."""
<|bo... | stack_v2_sparse_classes_75kplus_train_004095 | 13,550 | permissive | [
{
"docstring": "Instantiates the GATRNN encoder model. Args: args: python argparse.ArgumentParser class, we only use model-related arguments here.",
"name": "__init__",
"signature": "def __init__(self, args)"
},
{
"docstring": "Encoder forward pass. Args: inputs: input one-step time series, with... | 2 | stack_v2_sparse_classes_30k_train_009934 | Implement the Python class `Encoder` described below.
Class description:
Implements GATRNN encoder model. Encodes the input time series sequence to the hidden vector.
Method signatures and docstrings:
- def __init__(self, args): Instantiates the GATRNN encoder model. Args: args: python argparse.ArgumentParser class, ... | Implement the Python class `Encoder` described below.
Class description:
Implements GATRNN encoder model. Encodes the input time series sequence to the hidden vector.
Method signatures and docstrings:
- def __init__(self, args): Instantiates the GATRNN encoder model. Args: args: python argparse.ArgumentParser class, ... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class Encoder:
"""Implements GATRNN encoder model. Encodes the input time series sequence to the hidden vector."""
def __init__(self, args):
"""Instantiates the GATRNN encoder model. Args: args: python argparse.ArgumentParser class, we only use model-related arguments here."""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Encoder:
"""Implements GATRNN encoder model. Encodes the input time series sequence to the hidden vector."""
def __init__(self, args):
"""Instantiates the GATRNN encoder model. Args: args: python argparse.ArgumentParser class, we only use model-related arguments here."""
super().__init__(... | the_stack_v2_python_sparse | editable_graph_temporal/model/gat_model.py | Jimmy-INL/google-research | train | 1 |
3ee06a92d26c70c566a25478bb4fb9d9644dd7a6 | [
"self.iterator = iterator\nself.inext = None\nself.isNext = False",
"if not self.iterator.hasNext() and (not self.isNext):\n return None\nif self.iterator.hasNext() and self.isNext == False:\n self.inext = self.iterator.next()\n self.isNext = True\nreturn self.inext",
"if self.isNext:\n self.isNext ... | <|body_start_0|>
self.iterator = iterator
self.inext = None
self.isNext = False
<|end_body_0|>
<|body_start_1|>
if not self.iterator.hasNext() and (not self.isNext):
return None
if self.iterator.hasNext() and self.isNext == False:
self.inext = self.iterat... | PeekingIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PeekingIterator:
def __init__(self, iterator):
"""Initialize your data structure here. :type iterator: Iterator"""
<|body_0|>
def peek(self):
"""Returns the next element in the iteration without advancing the iterator. :rtype: int"""
<|body_1|>
def next(... | stack_v2_sparse_classes_75kplus_train_004096 | 1,093 | no_license | [
{
"docstring": "Initialize your data structure here. :type iterator: Iterator",
"name": "__init__",
"signature": "def __init__(self, iterator)"
},
{
"docstring": "Returns the next element in the iteration without advancing the iterator. :rtype: int",
"name": "peek",
"signature": "def pee... | 4 | null | Implement the Python class `PeekingIterator` described below.
Class description:
Implement the PeekingIterator class.
Method signatures and docstrings:
- def __init__(self, iterator): Initialize your data structure here. :type iterator: Iterator
- def peek(self): Returns the next element in the iteration without adva... | Implement the Python class `PeekingIterator` described below.
Class description:
Implement the PeekingIterator class.
Method signatures and docstrings:
- def __init__(self, iterator): Initialize your data structure here. :type iterator: Iterator
- def peek(self): Returns the next element in the iteration without adva... | 0699107eb39c51c0ec77c59748ce21deefd6765a | <|skeleton|>
class PeekingIterator:
def __init__(self, iterator):
"""Initialize your data structure here. :type iterator: Iterator"""
<|body_0|>
def peek(self):
"""Returns the next element in the iteration without advancing the iterator. :rtype: int"""
<|body_1|>
def next(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PeekingIterator:
def __init__(self, iterator):
"""Initialize your data structure here. :type iterator: Iterator"""
self.iterator = iterator
self.inext = None
self.isNext = False
def peek(self):
"""Returns the next element in the iteration without advancing the iter... | the_stack_v2_python_sparse | E22/lc284.py | adslchen/leetcode | train | 0 | |
56800ac7321d940126cf1ca6ba7c6a937bc7b49d | [
"self.lst = lst\nself.totals = []\nself.total = 0\nfor number in self.lst:\n self.total += number\n self.totals.append(self.total)",
"if i > len(self.lst) or j < 0 or j < i:\n return 0\nreturn self.totals[j - 1] - self.totals[i]"
] | <|body_start_0|>
self.lst = lst
self.totals = []
self.total = 0
for number in self.lst:
self.total += number
self.totals.append(self.total)
<|end_body_0|>
<|body_start_1|>
if i > len(self.lst) or j < 0 or j < i:
return 0
return self.to... | A class to optimize summing lists. | OptimizedSum | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptimizedSum:
"""A class to optimize summing lists."""
def __init__(self, lst):
"""Preprocess the list."""
<|body_0|>
def sum(self, i, j):
"""Sum the elements from i to j."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.lst = lst
se... | stack_v2_sparse_classes_75kplus_train_004097 | 1,111 | no_license | [
{
"docstring": "Preprocess the list.",
"name": "__init__",
"signature": "def __init__(self, lst)"
},
{
"docstring": "Sum the elements from i to j.",
"name": "sum",
"signature": "def sum(self, i, j)"
}
] | 2 | stack_v2_sparse_classes_30k_train_029204 | Implement the Python class `OptimizedSum` described below.
Class description:
A class to optimize summing lists.
Method signatures and docstrings:
- def __init__(self, lst): Preprocess the list.
- def sum(self, i, j): Sum the elements from i to j. | Implement the Python class `OptimizedSum` described below.
Class description:
A class to optimize summing lists.
Method signatures and docstrings:
- def __init__(self, lst): Preprocess the list.
- def sum(self, i, j): Sum the elements from i to j.
<|skeleton|>
class OptimizedSum:
"""A class to optimize summing l... | 97eae3ee806756f4d646d600f434b1e68164ad34 | <|skeleton|>
class OptimizedSum:
"""A class to optimize summing lists."""
def __init__(self, lst):
"""Preprocess the list."""
<|body_0|>
def sum(self, i, j):
"""Sum the elements from i to j."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OptimizedSum:
"""A class to optimize summing lists."""
def __init__(self, lst):
"""Preprocess the list."""
self.lst = lst
self.totals = []
self.total = 0
for number in self.lst:
self.total += number
self.totals.append(self.total)
def su... | the_stack_v2_python_sparse | Python/2019_06_13_Problem_149_Optimized_Sum.py | BaoCaiH/Daily_Coding_Problem | train | 0 |
b24e3c863e48554ff311e98e5fbd9828f15ac5e4 | [
"super(DecoderBlock, self).__init__()\nself.mha1 = MultiHeadAttention(dm, h)\nself.mha2 = MultiHeadAttention(dm, h)\nself.dense_hidden = tf.keras.layers.Dense(units=hidden, activation='relu')\nself.dense_output = tf.keras.layers.Dense(units=dm)\nself.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)\ns... | <|body_start_0|>
super(DecoderBlock, self).__init__()
self.mha1 = MultiHeadAttention(dm, h)
self.mha2 = MultiHeadAttention(dm, h)
self.dense_hidden = tf.keras.layers.Dense(units=hidden, activation='relu')
self.dense_output = tf.keras.layers.Dense(units=dm)
self.layernorm1... | Class to create an decoder block for a transformer | DecoderBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecoderBlock:
"""Class to create an decoder block for a transformer"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""Class constructor :param dm: an integer representing the dimensionality of the model :param h: an integer representing the number of heads :param hidden: the nu... | stack_v2_sparse_classes_75kplus_train_004098 | 2,864 | no_license | [
{
"docstring": "Class constructor :param dm: an integer representing the dimensionality of the model :param h: an integer representing the number of heads :param hidden: the number of hidden units in the fully connected layer :param drop_rate: the dropout rate",
"name": "__init__",
"signature": "def __i... | 2 | stack_v2_sparse_classes_30k_train_023651 | Implement the Python class `DecoderBlock` described below.
Class description:
Class to create an decoder block for a transformer
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): Class constructor :param dm: an integer representing the dimensionality of the model :param h: an integ... | Implement the Python class `DecoderBlock` described below.
Class description:
Class to create an decoder block for a transformer
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): Class constructor :param dm: an integer representing the dimensionality of the model :param h: an integ... | 856ee36006c2ff656877d592c2ddb7c941d63780 | <|skeleton|>
class DecoderBlock:
"""Class to create an decoder block for a transformer"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""Class constructor :param dm: an integer representing the dimensionality of the model :param h: an integer representing the number of heads :param hidden: the nu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DecoderBlock:
"""Class to create an decoder block for a transformer"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""Class constructor :param dm: an integer representing the dimensionality of the model :param h: an integer representing the number of heads :param hidden: the number of hidde... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/8-transformer_decoder_block.py | garimasinghgryffindor/holbertonschool-machine_learning | train | 0 |
55fe386e3c7c7e20ac8a2535570acba93789768f | [
"form = AgendamientoForm()\ncontext = {'form': form, 'success_message': ''}\nreturn render(request, 'servicios/add_agendamiento.html', context)",
"form = AgendamientoForm(request.POST)\nif form.is_valid():\n new = form.save()\n data = {'mensaje': 'El Agendamiento fue registrado correctamente.', 'type': 'suc... | <|body_start_0|>
form = AgendamientoForm()
context = {'form': form, 'success_message': ''}
return render(request, 'servicios/add_agendamiento.html', context)
<|end_body_0|>
<|body_start_1|>
form = AgendamientoForm(request.POST)
if form.is_valid():
new = form.save()
... | CreateAgendamientoView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateAgendamientoView:
def get(self, request):
"""esto cmuestra un formulario para crear un Agendamiento :param request: :return:"""
<|body_0|>
def post(self, request):
"""esto cmuestra un formulario para crear un Agendamiento :param request: :return:"""
<|b... | stack_v2_sparse_classes_75kplus_train_004099 | 12,273 | no_license | [
{
"docstring": "esto cmuestra un formulario para crear un Agendamiento :param request: :return:",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "esto cmuestra un formulario para crear un Agendamiento :param request: :return:",
"name": "post",
"signature": "def po... | 2 | stack_v2_sparse_classes_30k_train_037719 | Implement the Python class `CreateAgendamientoView` described below.
Class description:
Implement the CreateAgendamientoView class.
Method signatures and docstrings:
- def get(self, request): esto cmuestra un formulario para crear un Agendamiento :param request: :return:
- def post(self, request): esto cmuestra un fo... | Implement the Python class `CreateAgendamientoView` described below.
Class description:
Implement the CreateAgendamientoView class.
Method signatures and docstrings:
- def get(self, request): esto cmuestra un formulario para crear un Agendamiento :param request: :return:
- def post(self, request): esto cmuestra un fo... | 47e219a91e39fe35fe1573cb09dbe6cc7ff8964d | <|skeleton|>
class CreateAgendamientoView:
def get(self, request):
"""esto cmuestra un formulario para crear un Agendamiento :param request: :return:"""
<|body_0|>
def post(self, request):
"""esto cmuestra un formulario para crear un Agendamiento :param request: :return:"""
<|b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CreateAgendamientoView:
def get(self, request):
"""esto cmuestra un formulario para crear un Agendamiento :param request: :return:"""
form = AgendamientoForm()
context = {'form': form, 'success_message': ''}
return render(request, 'servicios/add_agendamiento.html', context)
... | the_stack_v2_python_sparse | servicios/views.py | franckiito/ServiceAir | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.