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
6eb90a844972897c51a6fa09ddfa3ff2baaf7e37
[ "if not s:\n return []\ncache = {}\n\ndef is_pal(string):\n left, right = (0, len(string) - 1)\n while left < right:\n if string[left] != string[right]:\n return False\n left += 1\n right -= 1\n return True\n\ndef helper(string):\n if string in cache:\n return c...
<|body_start_0|> if not s: return [] cache = {} def is_pal(string): left, right = (0, len(string) - 1) while left < right: if string[left] != string[right]: return False left += 1 right -= 1 ...
Palindrome
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Palindrome: def partition_palindrome(self, s: str) -> List[List[str]]: """Approach: Recursion with Memoization. :param s: :return:""" <|body_0|> def is_palindrome(self, num: int) -> bool: """Approach: Revert to half :param num: :return:""" <|body_1|> def...
stack_v2_sparse_classes_75kplus_train_065600
3,352
no_license
[ { "docstring": "Approach: Recursion with Memoization. :param s: :return:", "name": "partition_palindrome", "signature": "def partition_palindrome(self, s: str) -> List[List[str]]" }, { "docstring": "Approach: Revert to half :param num: :return:", "name": "is_palindrome", "signature": "de...
3
stack_v2_sparse_classes_30k_train_019398
Implement the Python class `Palindrome` described below. Class description: Implement the Palindrome class. Method signatures and docstrings: - def partition_palindrome(self, s: str) -> List[List[str]]: Approach: Recursion with Memoization. :param s: :return: - def is_palindrome(self, num: int) -> bool: Approach: Rev...
Implement the Python class `Palindrome` described below. Class description: Implement the Palindrome class. Method signatures and docstrings: - def partition_palindrome(self, s: str) -> List[List[str]]: Approach: Recursion with Memoization. :param s: :return: - def is_palindrome(self, num: int) -> bool: Approach: Rev...
65cc78b5afa0db064f9fe8f06597e3e120f7363d
<|skeleton|> class Palindrome: def partition_palindrome(self, s: str) -> List[List[str]]: """Approach: Recursion with Memoization. :param s: :return:""" <|body_0|> def is_palindrome(self, num: int) -> bool: """Approach: Revert to half :param num: :return:""" <|body_1|> def...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Palindrome: def partition_palindrome(self, s: str) -> List[List[str]]: """Approach: Recursion with Memoization. :param s: :return:""" if not s: return [] cache = {} def is_pal(string): left, right = (0, len(string) - 1) while left < right: ...
the_stack_v2_python_sparse
math_and_srings/palindrome.py
Shiv2157k/leet_code
train
1
144ca81cdcb097590c25ac1e088ad6ac3f8040c2
[ "self.validate_parameters(content_type=content_type, accept=accept, customer_id=customer_id, account_id=account_id, body=body)\n_url_path = '/aggregation/v1/customers/{customerId}/accounts/{accountId}/transactions'\n_url_path = APIHelper.append_url_with_template_parameters(_url_path, {'customerId': customer_id, 'ac...
<|body_start_0|> self.validate_parameters(content_type=content_type, accept=accept, customer_id=customer_id, account_id=account_id, body=body) _url_path = '/aggregation/v1/customers/{customerId}/accounts/{accountId}/transactions' _url_path = APIHelper.append_url_with_template_parameters(_url_pat...
A Controller to access Endpoints in the finicityapi API.
TxpushController
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TxpushController: """A Controller to access Endpoints in the finicityapi API.""" def create_txpush_test_transaction(self, content_type, accept, customer_id, account_id, body): """Does a POST request to /aggregation/v1/customers/{customerId}/accounts/{accountId}/transactions. Inject a...
stack_v2_sparse_classes_75kplus_train_065601
11,724
permissive
[ { "docstring": "Does a POST request to /aggregation/v1/customers/{customerId}/accounts/{accountId}/transactions. Inject a transaction into the transaction list for a testing account. This allows an app to trigger TxPush notifications for the account in order to test the app’s TxPush Listener service. This cause...
4
stack_v2_sparse_classes_30k_train_041855
Implement the Python class `TxpushController` described below. Class description: A Controller to access Endpoints in the finicityapi API. Method signatures and docstrings: - def create_txpush_test_transaction(self, content_type, accept, customer_id, account_id, body): Does a POST request to /aggregation/v1/customers...
Implement the Python class `TxpushController` described below. Class description: A Controller to access Endpoints in the finicityapi API. Method signatures and docstrings: - def create_txpush_test_transaction(self, content_type, accept, customer_id, account_id, body): Does a POST request to /aggregation/v1/customers...
b2ab1ded435db75c78d42261f5e4acd2a3061487
<|skeleton|> class TxpushController: """A Controller to access Endpoints in the finicityapi API.""" def create_txpush_test_transaction(self, content_type, accept, customer_id, account_id, body): """Does a POST request to /aggregation/v1/customers/{customerId}/accounts/{accountId}/transactions. Inject a...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TxpushController: """A Controller to access Endpoints in the finicityapi API.""" def create_txpush_test_transaction(self, content_type, accept, customer_id, account_id, body): """Does a POST request to /aggregation/v1/customers/{customerId}/accounts/{accountId}/transactions. Inject a transaction ...
the_stack_v2_python_sparse
finicityapi/controllers/txpush_controller.py
monarchmoney/finicity-python
train
0
2576f7eecb9bc11b1f34bfd7bbc5b63d910e587e
[ "self.beta = None\nself.alpha = alpha\nself.fit_intercept = fit_intercept", "if self.fit_intercept:\n X = np.c_[np.ones(X.shape[0]), X]\nA = self.alpha * np.eye(X.shape[1])\npseudo_inverse = np.dot(np.linalg.inv(X.T @ X + A), X.T)\nself.beta = pseudo_inverse @ y", "if self.fit_intercept:\n X = np.c_[np.on...
<|body_start_0|> self.beta = None self.alpha = alpha self.fit_intercept = fit_intercept <|end_body_0|> <|body_start_1|> if self.fit_intercept: X = np.c_[np.ones(X.shape[0]), X] A = self.alpha * np.eye(X.shape[1]) pseudo_inverse = np.dot(np.linalg.inv(X.T @ X ...
RidgeRegression
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RidgeRegression: def __init__(self, alpha=1, fit_intercept=True): """A ridge regression model fit via the normal equation. Parameters ---------- alpha : float L2 regularization coefficient. Higher values correspond to larger penalty on the L2 norm of the model coefficients. Default is 1....
stack_v2_sparse_classes_75kplus_train_065602
4,831
no_license
[ { "docstring": "A ridge regression model fit via the normal equation. Parameters ---------- alpha : float L2 regularization coefficient. Higher values correspond to larger penalty on the L2 norm of the model coefficients. Default is 1. fit_intercept : bool Whether to fit an additional intercept term in addition...
3
stack_v2_sparse_classes_30k_train_016552
Implement the Python class `RidgeRegression` described below. Class description: Implement the RidgeRegression class. Method signatures and docstrings: - def __init__(self, alpha=1, fit_intercept=True): A ridge regression model fit via the normal equation. Parameters ---------- alpha : float L2 regularization coeffic...
Implement the Python class `RidgeRegression` described below. Class description: Implement the RidgeRegression class. Method signatures and docstrings: - def __init__(self, alpha=1, fit_intercept=True): A ridge regression model fit via the normal equation. Parameters ---------- alpha : float L2 regularization coeffic...
eef451a5d60bd9492fcba51afc7eeedb1094c788
<|skeleton|> class RidgeRegression: def __init__(self, alpha=1, fit_intercept=True): """A ridge regression model fit via the normal equation. Parameters ---------- alpha : float L2 regularization coefficient. Higher values correspond to larger penalty on the L2 norm of the model coefficients. Default is 1....
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RidgeRegression: def __init__(self, alpha=1, fit_intercept=True): """A ridge regression model fit via the normal equation. Parameters ---------- alpha : float L2 regularization coefficient. Higher values correspond to larger penalty on the L2 norm of the model coefficients. Default is 1. fit_intercept...
the_stack_v2_python_sparse
simple_ml/linear/model.py
lizhaoliu-Lec/simple_ml
train
4
e73680494b296e5ea6b7ce88b70562e7757b772f
[ "self._client = _utils.make_client(context)\nself._filter_string = filter_string\nself._descriptors = None", "if self._descriptors is None:\n self._descriptors = self._client.list_resource_descriptors(filter_string=self._filter_string)\nreturn [resource for resource in self._descriptors if fnmatch.fnmatch(reso...
<|body_start_0|> self._client = _utils.make_client(context) self._filter_string = filter_string self._descriptors = None <|end_body_0|> <|body_start_1|> if self._descriptors is None: self._descriptors = self._client.list_resource_descriptors(filter_string=self._filter_string...
ResourceDescriptors object for retrieving the resource descriptors.
ResourceDescriptors
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ResourceDescriptors: """ResourceDescriptors object for retrieving the resource descriptors.""" def __init__(self, filter_string=None, context=None): """Initializes the ResourceDescriptors based on the specified filters. Args: filter_string: An optional filter expression describing th...
stack_v2_sparse_classes_75kplus_train_065603
2,837
permissive
[ { "docstring": "Initializes the ResourceDescriptors based on the specified filters. Args: filter_string: An optional filter expression describing the resource descriptors to be returned. context: An optional Context object to use instead of the global default.", "name": "__init__", "signature": "def __i...
3
stack_v2_sparse_classes_30k_train_015715
Implement the Python class `ResourceDescriptors` described below. Class description: ResourceDescriptors object for retrieving the resource descriptors. Method signatures and docstrings: - def __init__(self, filter_string=None, context=None): Initializes the ResourceDescriptors based on the specified filters. Args: f...
Implement the Python class `ResourceDescriptors` described below. Class description: ResourceDescriptors object for retrieving the resource descriptors. Method signatures and docstrings: - def __init__(self, filter_string=None, context=None): Initializes the ResourceDescriptors based on the specified filters. Args: f...
8bf007da3e43096aa3a3dca158fc56b286ba6f5c
<|skeleton|> class ResourceDescriptors: """ResourceDescriptors object for retrieving the resource descriptors.""" def __init__(self, filter_string=None, context=None): """Initializes the ResourceDescriptors based on the specified filters. Args: filter_string: An optional filter expression describing th...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ResourceDescriptors: """ResourceDescriptors object for retrieving the resource descriptors.""" def __init__(self, filter_string=None, context=None): """Initializes the ResourceDescriptors based on the specified filters. Args: filter_string: An optional filter expression describing the resource de...
the_stack_v2_python_sparse
google/datalab/stackdriver/monitoring/_resource.py
googledatalab/pydatalab
train
200
4ca0fa6376c1d5abb3e9b371d67e3711db1d19cb
[ "login_name = '17880000202'\npassword = '123123456'\nactivebind = ActiveQa()\nactivebind.login(login_name, password)\nres = activebind.bind_player('000075')\njson = res.json\nassert json['Code'] == 0 and res.status_code == 200 and (res.elapsed.seconds <= 3)", "activebind = ActiveQa()\nactivebind.login(login_name,...
<|body_start_0|> login_name = '17880000202' password = '123123456' activebind = ActiveQa() activebind.login(login_name, password) res = activebind.bind_player('000075') json = res.json assert json['Code'] == 0 and res.status_code == 200 and (res.elapsed.seconds <=...
TestBind
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestBind: def test_active_bind_case(self): """王者推荐用户""" <|body_0|> def test_active_bind_list_case(self): """王者推荐列表""" <|body_1|> <|end_skeleton|> <|body_start_0|> login_name = '17880000202' password = '123123456' activebind = ActiveQ...
stack_v2_sparse_classes_75kplus_train_065604
943
no_license
[ { "docstring": "王者推荐用户", "name": "test_active_bind_case", "signature": "def test_active_bind_case(self)" }, { "docstring": "王者推荐列表", "name": "test_active_bind_list_case", "signature": "def test_active_bind_list_case(self)" } ]
2
stack_v2_sparse_classes_30k_test_002578
Implement the Python class `TestBind` described below. Class description: Implement the TestBind class. Method signatures and docstrings: - def test_active_bind_case(self): 王者推荐用户 - def test_active_bind_list_case(self): 王者推荐列表
Implement the Python class `TestBind` described below. Class description: Implement the TestBind class. Method signatures and docstrings: - def test_active_bind_case(self): 王者推荐用户 - def test_active_bind_list_case(self): 王者推荐列表 <|skeleton|> class TestBind: def test_active_bind_case(self): """王者推荐用户""" ...
2a4e94d903d737097949e89dbbaa9650401f6d49
<|skeleton|> class TestBind: def test_active_bind_case(self): """王者推荐用户""" <|body_0|> def test_active_bind_list_case(self): """王者推荐列表""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestBind: def test_active_bind_case(self): """王者推荐用户""" login_name = '17880000202' password = '123123456' activebind = ActiveQa() activebind.login(login_name, password) res = activebind.bind_player('000075') json = res.json assert json['Code'] ==...
the_stack_v2_python_sparse
test_suites/test_broker_active/test_active_answer/test_active_bind.py
wyu0430/tops_pytest
train
0
b2c17416eccf01e21c9eeef7761f4be977a2617a
[ "self.num = n\nself.discount = discount\nself.map = collections.defaultdict(int)\nfor p in range(len(products)):\n self.map[products[p]] = prices[p]\nself.count = 0", "self.count += 1\nb = 0\nfor i in range(len(product)):\n b += self.map[product[i]] * amount[i]\nif self.count % self.num == 0:\n return b ...
<|body_start_0|> self.num = n self.discount = discount self.map = collections.defaultdict(int) for p in range(len(products)): self.map[products[p]] = prices[p] self.count = 0 <|end_body_0|> <|body_start_1|> self.count += 1 b = 0 for i in range...
Cashier
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Cashier: def __init__(self, n, discount, products, prices): """:type n: int :type discount: int :type products: List[int] :type prices: List[int]""" <|body_0|> def getBill(self, product, amount): """:type product: List[int] :type amount: List[int] :rtype: float""" ...
stack_v2_sparse_classes_75kplus_train_065605
1,042
no_license
[ { "docstring": ":type n: int :type discount: int :type products: List[int] :type prices: List[int]", "name": "__init__", "signature": "def __init__(self, n, discount, products, prices)" }, { "docstring": ":type product: List[int] :type amount: List[int] :rtype: float", "name": "getBill", ...
2
stack_v2_sparse_classes_30k_train_018056
Implement the Python class `Cashier` described below. Class description: Implement the Cashier class. Method signatures and docstrings: - def __init__(self, n, discount, products, prices): :type n: int :type discount: int :type products: List[int] :type prices: List[int] - def getBill(self, product, amount): :type pr...
Implement the Python class `Cashier` described below. Class description: Implement the Cashier class. Method signatures and docstrings: - def __init__(self, n, discount, products, prices): :type n: int :type discount: int :type products: List[int] :type prices: List[int] - def getBill(self, product, amount): :type pr...
20623defecf65cbc35b194d8b60d8b211816ee4f
<|skeleton|> class Cashier: def __init__(self, n, discount, products, prices): """:type n: int :type discount: int :type products: List[int] :type prices: List[int]""" <|body_0|> def getBill(self, product, amount): """:type product: List[int] :type amount: List[int] :rtype: float""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Cashier: def __init__(self, n, discount, products, prices): """:type n: int :type discount: int :type products: List[int] :type prices: List[int]""" self.num = n self.discount = discount self.map = collections.defaultdict(int) for p in range(len(products)): ...
the_stack_v2_python_sparse
in_Python/1357 Apply Discount Every n Orders.py
YangLiyli131/Leetcode2020
train
0
d519d1be3d47490f7ebe23655aa2f602962555da
[ "if not isinstance(gate, Gate):\n raise TypeError(f'Expected Gate for gate, got {type(gate)}')\nself.gate = gate", "if not isinstance(target, (UnitaryMatrix, StateVector, StateSystem)):\n raise TypeError('Expected unitary or state, got %s.' % type(target))\ninit_circuit = Circuit(target.num_qudits, target.r...
<|body_start_0|> if not isinstance(gate, Gate): raise TypeError(f'Expected Gate for gate, got {type(gate)}') self.gate = gate <|end_body_0|> <|body_start_1|> if not isinstance(target, (UnitaryMatrix, StateVector, StateSystem)): raise TypeError('Expected unitary or state,...
Layer Generator for search that builds circuits from a single gate.
StairLayerGenerator
[ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StairLayerGenerator: """Layer Generator for search that builds circuits from a single gate.""" def __init__(self, gate: Gate) -> None: """Construct a StairLayerGenerator. Args: gate (Gate): The gate to build from.""" <|body_0|> def gen_initial_layer(self, target: Unitary...
stack_v2_sparse_classes_75kplus_train_065606
2,358
permissive
[ { "docstring": "Construct a StairLayerGenerator. Args: gate (Gate): The gate to build from.", "name": "__init__", "signature": "def __init__(self, gate: Gate) -> None" }, { "docstring": "Generate the initial layer, see LayerGenerator for more. Raises: ValueError: If `target` has a size or radix ...
3
stack_v2_sparse_classes_30k_train_022326
Implement the Python class `StairLayerGenerator` described below. Class description: Layer Generator for search that builds circuits from a single gate. Method signatures and docstrings: - def __init__(self, gate: Gate) -> None: Construct a StairLayerGenerator. Args: gate (Gate): The gate to build from. - def gen_ini...
Implement the Python class `StairLayerGenerator` described below. Class description: Layer Generator for search that builds circuits from a single gate. Method signatures and docstrings: - def __init__(self, gate: Gate) -> None: Construct a StairLayerGenerator. Args: gate (Gate): The gate to build from. - def gen_ini...
c89112d15072e8ffffb68cf1757b184e2aeb3dc8
<|skeleton|> class StairLayerGenerator: """Layer Generator for search that builds circuits from a single gate.""" def __init__(self, gate: Gate) -> None: """Construct a StairLayerGenerator. Args: gate (Gate): The gate to build from.""" <|body_0|> def gen_initial_layer(self, target: Unitary...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class StairLayerGenerator: """Layer Generator for search that builds circuits from a single gate.""" def __init__(self, gate: Gate) -> None: """Construct a StairLayerGenerator. Args: gate (Gate): The gate to build from.""" if not isinstance(gate, Gate): raise TypeError(f'Expected Ga...
the_stack_v2_python_sparse
bqskit/passes/search/generators/stair.py
BQSKit/bqskit
train
54
be1d3bd09743c18c4cd936444994012b2d68197d
[ "self.origin_file = origin_file\nself.new_data_path = new_data_path\nparser = SafeConfigParser()\nparser.read([conf_path])\nsingle_info = parser.get('common', 'single').strip().split(';')\nself.single = []\nfor info in single_info:\n begin_end = info.split('-')\n if len(begin_end) == 2:\n self.single.a...
<|body_start_0|> self.origin_file = origin_file self.new_data_path = new_data_path parser = SafeConfigParser() parser.read([conf_path]) single_info = parser.get('common', 'single').strip().split(';') self.single = [] for info in single_info: begin_end ...
repalce column
ReplaceColumn
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReplaceColumn: """repalce column""" def __init__(self, origin_file, conf_path, new_data_path): """init""" <|body_0|> def read_file(self): """read file to fill content content_bak val_set""" <|body_1|> def shuffle_print(self): """shuffle and p...
stack_v2_sparse_classes_75kplus_train_065607
3,679
permissive
[ { "docstring": "init", "name": "__init__", "signature": "def __init__(self, origin_file, conf_path, new_data_path)" }, { "docstring": "read file to fill content content_bak val_set", "name": "read_file", "signature": "def read_file(self)" }, { "docstring": "shuffle and print to f...
4
stack_v2_sparse_classes_30k_train_035377
Implement the Python class `ReplaceColumn` described below. Class description: repalce column Method signatures and docstrings: - def __init__(self, origin_file, conf_path, new_data_path): init - def read_file(self): read file to fill content content_bak val_set - def shuffle_print(self): shuffle and print to file - ...
Implement the Python class `ReplaceColumn` described below. Class description: repalce column Method signatures and docstrings: - def __init__(self, origin_file, conf_path, new_data_path): init - def read_file(self): read file to fill content content_bak val_set - def shuffle_print(self): shuffle and print to file - ...
b8ec015fa9e16c0a879c619ee1f2aab8a393c7bd
<|skeleton|> class ReplaceColumn: """repalce column""" def __init__(self, origin_file, conf_path, new_data_path): """init""" <|body_0|> def read_file(self): """read file to fill content content_bak val_set""" <|body_1|> def shuffle_print(self): """shuffle and p...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ReplaceColumn: """repalce column""" def __init__(self, origin_file, conf_path, new_data_path): """init""" self.origin_file = origin_file self.new_data_path = new_data_path parser = SafeConfigParser() parser.read([conf_path]) single_info = parser.get('common...
the_stack_v2_python_sparse
ST_DM/KDD2021-MSTPAC/code/MST-PAC/utils/feature_imp/replace_column.py
sserdoubleh/Research
train
10
67ea1d23d9617ff2372b9eb893607f43f0542c93
[ "instrument_list = super(ActiveInstrumentManager, self).get_queryset().filter(instrument_id=instrument_id)\nif len(instrument_list) > 0:\n return instrument_list[0].is_alive\nelse:\n return True", "instrument_list = super(ActiveInstrumentManager, self).get_queryset().filter(instrument_id=instrument_id)\nif ...
<|body_start_0|> instrument_list = super(ActiveInstrumentManager, self).get_queryset().filter(instrument_id=instrument_id) if len(instrument_list) > 0: return instrument_list[0].is_alive else: return True <|end_body_0|> <|body_start_1|> instrument_list = super(Ac...
Table of options for instruments
ActiveInstrumentManager
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ActiveInstrumentManager: """Table of options for instruments""" def is_alive(self, instrument_id): """Returns True if the instrument should be presented as part of the suite of instruments""" <|body_0|> def is_adara(self, instrument_id): """Returns True if the in...
stack_v2_sparse_classes_75kplus_train_065608
4,318
permissive
[ { "docstring": "Returns True if the instrument should be presented as part of the suite of instruments", "name": "is_alive", "signature": "def is_alive(self, instrument_id)" }, { "docstring": "Returns True if the instrument is running ADARA", "name": "is_adara", "signature": "def is_adar...
4
stack_v2_sparse_classes_30k_train_049749
Implement the Python class `ActiveInstrumentManager` described below. Class description: Table of options for instruments Method signatures and docstrings: - def is_alive(self, instrument_id): Returns True if the instrument should be presented as part of the suite of instruments - def is_adara(self, instrument_id): R...
Implement the Python class `ActiveInstrumentManager` described below. Class description: Table of options for instruments Method signatures and docstrings: - def is_alive(self, instrument_id): Returns True if the instrument should be presented as part of the suite of instruments - def is_adara(self, instrument_id): R...
ff55e4e1a0203a6966fc9dab6b49e0d6dd03d18d
<|skeleton|> class ActiveInstrumentManager: """Table of options for instruments""" def is_alive(self, instrument_id): """Returns True if the instrument should be presented as part of the suite of instruments""" <|body_0|> def is_adara(self, instrument_id): """Returns True if the in...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ActiveInstrumentManager: """Table of options for instruments""" def is_alive(self, instrument_id): """Returns True if the instrument should be presented as part of the suite of instruments""" instrument_list = super(ActiveInstrumentManager, self).get_queryset().filter(instrument_id=instru...
the_stack_v2_python_sparse
src/webmon_app/reporting/dasmon/models.py
neutrons/data_workflow
train
4
2e78dfd255a54c23b1e5667bb5794083a8b312ed
[ "reader = csv.reader(data)\nnext(reader)\nenum = []\nfor item in reader:\n name = item[0]\n dscp = item[2]\n rfcs = item[3]\n temp = []\n for rfc in filter(None, re.split('\\\\[|\\\\]', rfcs)):\n if 'RFC' in rfc and re.match('\\\\d+', rfc[3:]):\n temp.append(f'[:rfc:`{rfc[3:]}`]')\n...
<|body_start_0|> reader = csv.reader(data) next(reader) enum = [] for item in reader: name = item[0] dscp = item[2] rfcs = item[3] temp = [] for rfc in filter(None, re.split('\\[|\\]', rfcs)): if 'RFC' in rfc and...
Handover Acknowledge Flags
HandoverACKFlag
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HandoverACKFlag: """Handover Acknowledge Flags""" def process(self, data: 'list[str]') -> 'list[str]': """Process CSV data. Args: data: CSV data. Returns: Enumeration fields and missing fields.""" <|body_0|> def context(self, data: 'list[str]') -> 'str': """Gener...
stack_v2_sparse_classes_75kplus_train_065609
3,921
permissive
[ { "docstring": "Process CSV data. Args: data: CSV data. Returns: Enumeration fields and missing fields.", "name": "process", "signature": "def process(self, data: 'list[str]') -> 'list[str]'" }, { "docstring": "Generate constant context. Args: soup: Parsed HTML source. Returns: Constant context....
2
stack_v2_sparse_classes_30k_train_043165
Implement the Python class `HandoverACKFlag` described below. Class description: Handover Acknowledge Flags Method signatures and docstrings: - def process(self, data: 'list[str]') -> 'list[str]': Process CSV data. Args: data: CSV data. Returns: Enumeration fields and missing fields. - def context(self, data: 'list[s...
Implement the Python class `HandoverACKFlag` described below. Class description: Handover Acknowledge Flags Method signatures and docstrings: - def process(self, data: 'list[str]') -> 'list[str]': Process CSV data. Args: data: CSV data. Returns: Enumeration fields and missing fields. - def context(self, data: 'list[s...
a6fe49ec58f09e105bec5a00fb66d9b3f22730d9
<|skeleton|> class HandoverACKFlag: """Handover Acknowledge Flags""" def process(self, data: 'list[str]') -> 'list[str]': """Process CSV data. Args: data: CSV data. Returns: Enumeration fields and missing fields.""" <|body_0|> def context(self, data: 'list[str]') -> 'str': """Gener...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class HandoverACKFlag: """Handover Acknowledge Flags""" def process(self, data: 'list[str]') -> 'list[str]': """Process CSV data. Args: data: CSV data. Returns: Enumeration fields and missing fields.""" reader = csv.reader(data) next(reader) enum = [] for item in reader:...
the_stack_v2_python_sparse
pcapkit/vendor/mh/handover_ack_flag.py
JarryShaw/PyPCAPKit
train
204
a77803245f8c259a5e3d0643fc4900bc2b4c2c8e
[ "with Net2XS._lock:\n self._check_client()\n return self._client.CurrentUserID", "with Net2XS._lock:\n self._check_client()\n return dir(self._client)" ]
<|body_start_0|> with Net2XS._lock: self._check_client() return self._client.CurrentUserID <|end_body_0|> <|body_start_1|> with Net2XS._lock: self._check_client() return dir(self._client) <|end_body_1|>
Inherited class for additional functionality
MyNet2XS
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyNet2XS: """Inherited class for additional functionality""" def get_current_user_id(self): """Return logged on user id""" <|body_0|> def get_client_members(self): """Return all Net2 client object members using the introspective Python dir function""" <|b...
stack_v2_sparse_classes_75kplus_train_065610
1,370
permissive
[ { "docstring": "Return logged on user id", "name": "get_current_user_id", "signature": "def get_current_user_id(self)" }, { "docstring": "Return all Net2 client object members using the introspective Python dir function", "name": "get_client_members", "signature": "def get_client_members...
2
stack_v2_sparse_classes_30k_train_034567
Implement the Python class `MyNet2XS` described below. Class description: Inherited class for additional functionality Method signatures and docstrings: - def get_current_user_id(self): Return logged on user id - def get_client_members(self): Return all Net2 client object members using the introspective Python dir fu...
Implement the Python class `MyNet2XS` described below. Class description: Inherited class for additional functionality Method signatures and docstrings: - def get_current_user_id(self): Return logged on user id - def get_client_members(self): Return all Net2 client object members using the introspective Python dir fu...
65c4e77a7c88c3d4b88f901225b71710df415ba5
<|skeleton|> class MyNet2XS: """Inherited class for additional functionality""" def get_current_user_id(self): """Return logged on user id""" <|body_0|> def get_client_members(self): """Return all Net2 client object members using the introspective Python dir function""" <|b...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MyNet2XS: """Inherited class for additional functionality""" def get_current_user_id(self): """Return logged on user id""" with Net2XS._lock: self._check_client() return self._client.CurrentUserID def get_client_members(self): """Return all Net2 client...
the_stack_v2_python_sparse
samples/inheritance.py
marcelcorso/Net2Scripting
train
1
741e34689c5f8dac32abf8f5581a9bd53fad98db
[ "send_date = self.cleaned_data['send_date']\nsend_back_date = self.cleaned_data['send_back_date']\nif send_date and send_back_date:\n if send_date > send_back_date:\n raise forms.ValidationError('时间输入错误,请检测!合同寄回时间应大于寄出时间')\nreturn send_back_date", "send_date = self.cleaned_data['send_date']\ntracking_nu...
<|body_start_0|> send_date = self.cleaned_data['send_date'] send_back_date = self.cleaned_data['send_back_date'] if send_date and send_back_date: if send_date > send_back_date: raise forms.ValidationError('时间输入错误,请检测!合同寄回时间应大于寄出时间') return send_back_date <|end...
合同信息表单输入验证
ContractInfoForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ContractInfoForm: """合同信息表单输入验证""" def clean_send_back_date(self): """合同寄回时间应晚于合同寄出时间""" <|body_0|> def clean_tracking_number(self): """邮寄时间填写后限制邮寄单号为必填项""" <|body_1|> def clean_end_date(self): """合同截止日期应晚于起始日期""" <|body_2|> <|end_sk...
stack_v2_sparse_classes_75kplus_train_065611
1,464
no_license
[ { "docstring": "合同寄回时间应晚于合同寄出时间", "name": "clean_send_back_date", "signature": "def clean_send_back_date(self)" }, { "docstring": "邮寄时间填写后限制邮寄单号为必填项", "name": "clean_tracking_number", "signature": "def clean_tracking_number(self)" }, { "docstring": "合同截止日期应晚于起始日期", "name": "c...
3
null
Implement the Python class `ContractInfoForm` described below. Class description: 合同信息表单输入验证 Method signatures and docstrings: - def clean_send_back_date(self): 合同寄回时间应晚于合同寄出时间 - def clean_tracking_number(self): 邮寄时间填写后限制邮寄单号为必填项 - def clean_end_date(self): 合同截止日期应晚于起始日期
Implement the Python class `ContractInfoForm` described below. Class description: 合同信息表单输入验证 Method signatures and docstrings: - def clean_send_back_date(self): 合同寄回时间应晚于合同寄出时间 - def clean_tracking_number(self): 邮寄时间填写后限制邮寄单号为必填项 - def clean_end_date(self): 合同截止日期应晚于起始日期 <|skeleton|> class ContractInfoForm: """合...
6351a7c1606b56c43b2db212445bdb658cfbcbef
<|skeleton|> class ContractInfoForm: """合同信息表单输入验证""" def clean_send_back_date(self): """合同寄回时间应晚于合同寄出时间""" <|body_0|> def clean_tracking_number(self): """邮寄时间填写后限制邮寄单号为必填项""" <|body_1|> def clean_end_date(self): """合同截止日期应晚于起始日期""" <|body_2|> <|end_sk...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ContractInfoForm: """合同信息表单输入验证""" def clean_send_back_date(self): """合同寄回时间应晚于合同寄出时间""" send_date = self.cleaned_data['send_date'] send_back_date = self.cleaned_data['send_back_date'] if send_date and send_back_date: if send_date > send_back_date: ...
the_stack_v2_python_sparse
projects/forms.py
therosemary/bms_colowell-2
train
0
325d102d580b5e043ed917b73104fda51c168ef2
[ "self.capacity = capacity\nself.buffer = list()\nself.index = 0\nstate = env.reset()\nfor _ in range(init_length):\n action = env.action_space.sample() + np.random.normal(0, 0.1, size=env.action_space.shape[0])\n next_state, reward, done, _ = env.step(action)\n transition = [state, action, reward, next_sta...
<|body_start_0|> self.capacity = capacity self.buffer = list() self.index = 0 state = env.reset() for _ in range(init_length): action = env.action_space.sample() + np.random.normal(0, 0.1, size=env.action_space.shape[0]) next_state, reward, done, _ = env.s...
ReplayBuffer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReplayBuffer: def __init__(self, env, init_length=1000, capacity=10000): """Initializes the replay buffer. Parameters ---------- env : gym environment object Object representing the environment. init_length : int, optional Number of transitions to collect at initialization. capacity : in...
stack_v2_sparse_classes_75kplus_train_065612
3,139
no_license
[ { "docstring": "Initializes the replay buffer. Parameters ---------- env : gym environment object Object representing the environment. init_length : int, optional Number of transitions to collect at initialization. capacity : int, optional Maximum size of the replay buffer before the index resets.", "name":...
3
null
Implement the Python class `ReplayBuffer` described below. Class description: Implement the ReplayBuffer class. Method signatures and docstrings: - def __init__(self, env, init_length=1000, capacity=10000): Initializes the replay buffer. Parameters ---------- env : gym environment object Object representing the envir...
Implement the Python class `ReplayBuffer` described below. Class description: Implement the ReplayBuffer class. Method signatures and docstrings: - def __init__(self, env, init_length=1000, capacity=10000): Initializes the replay buffer. Parameters ---------- env : gym environment object Object representing the envir...
e297fcfa223d15121f547f3ab5f0f69e1a72cced
<|skeleton|> class ReplayBuffer: def __init__(self, env, init_length=1000, capacity=10000): """Initializes the replay buffer. Parameters ---------- env : gym environment object Object representing the environment. init_length : int, optional Number of transitions to collect at initialization. capacity : in...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ReplayBuffer: def __init__(self, env, init_length=1000, capacity=10000): """Initializes the replay buffer. Parameters ---------- env : gym environment object Object representing the environment. init_length : int, optional Number of transitions to collect at initialization. capacity : int, optional Ma...
the_stack_v2_python_sparse
old_src/replay_buffer.py
hu-simon/TD3_MACCA
train
1
e8f018f7116bf7a1a4294275c4568613a5469a51
[ "nums1_copy = nums1[:m]\nnums1[:] = []\np1 = p2 = 0\nwhile p1 < m and p2 < n:\n if nums1_copy[p1] < nums2[p2]:\n nums1.append(nums1_copy[p1])\n p1 += 1\n else:\n nums1.append(nums2[p2])\n p2 += 1\nif p1 < m:\n nums1[p1 + p2:] = nums1_copy[p1:]\nif p2 < n:\n nums1[p1 + p2:] = ...
<|body_start_0|> nums1_copy = nums1[:m] nums1[:] = [] p1 = p2 = 0 while p1 < m and p2 < n: if nums1_copy[p1] < nums2[p2]: nums1.append(nums1_copy[p1]) p1 += 1 else: nums1.append(nums2[p2]) p2 += 1 ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def merge1(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """Solution #1: Two pointers, forwards Time: O(m+n) Space O(m): need a copy for nums1""" <|body_0|> def merge2(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: "...
stack_v2_sparse_classes_75kplus_train_065613
1,503
no_license
[ { "docstring": "Solution #1: Two pointers, forwards Time: O(m+n) Space O(m): need a copy for nums1", "name": "merge1", "signature": "def merge1(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None" }, { "docstring": "Solution #2: Three pointers, backwards Time: O(m+n) Space O(1)", ...
2
stack_v2_sparse_classes_30k_train_006291
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def merge1(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: Solution #1: Two pointers, forwards Time: O(m+n) Space O(m): need a copy for nums1 - def merge2(self...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def merge1(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: Solution #1: Two pointers, forwards Time: O(m+n) Space O(m): need a copy for nums1 - def merge2(self...
59c8b144f4245ed4a8b06a458954ca05c0c73aea
<|skeleton|> class Solution: def merge1(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """Solution #1: Two pointers, forwards Time: O(m+n) Space O(m): need a copy for nums1""" <|body_0|> def merge2(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: "...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def merge1(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """Solution #1: Two pointers, forwards Time: O(m+n) Space O(m): need a copy for nums1""" nums1_copy = nums1[:m] nums1[:] = [] p1 = p2 = 0 while p1 < m and p2 < n: if nums...
the_stack_v2_python_sparse
01/merge-sorted-array.py
TrisDing/algorithm010
train
1
eee1594ddc69c04569015c0b58b1f8749e36bea6
[ "self.name = name\nself.dispatch_map = dispatch_map\nsuper().__init__(*args, **kwargs)", "body = message.body\ndata = Objectify(body.get('data', {}))\nevent = body.get('event_name', '')\nmessage_id = body.get('id', '')\ndata.sqs_message_id = message_id\ndispatch = Objectify(self.dispatch_map.get(event, {}))\nif n...
<|body_start_0|> self.name = name self.dispatch_map = dispatch_map super().__init__(*args, **kwargs) <|end_body_0|> <|body_start_1|> body = message.body data = Objectify(body.get('data', {})) event = body.get('event_name', '') message_id = body.get('id', '') ...
Ms.laure queue worker.
Worker
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Worker: """Ms.laure queue worker.""" def __init__(self, *args, name: str, dispatch_map: dict, **kwargs): """Added new parameter to the worker init class.""" <|body_0|> def process_message(self, message: SQSMessage) -> bool: """Process a message retrieved from the...
stack_v2_sparse_classes_75kplus_train_065614
4,814
no_license
[ { "docstring": "Added new parameter to the worker init class.", "name": "__init__", "signature": "def __init__(self, *args, name: str, dispatch_map: dict, **kwargs)" }, { "docstring": "Process a message retrieved from the input_queue. :param message: A message from the queue :returns: Status fro...
2
stack_v2_sparse_classes_30k_train_014523
Implement the Python class `Worker` described below. Class description: Ms.laure queue worker. Method signatures and docstrings: - def __init__(self, *args, name: str, dispatch_map: dict, **kwargs): Added new parameter to the worker init class. - def process_message(self, message: SQSMessage) -> bool: Process a messa...
Implement the Python class `Worker` described below. Class description: Ms.laure queue worker. Method signatures and docstrings: - def __init__(self, *args, name: str, dispatch_map: dict, **kwargs): Added new parameter to the worker init class. - def process_message(self, message: SQSMessage) -> bool: Process a messa...
689d2b6a20c8e4348a040471673fc266eb7d0142
<|skeleton|> class Worker: """Ms.laure queue worker.""" def __init__(self, *args, name: str, dispatch_map: dict, **kwargs): """Added new parameter to the worker init class.""" <|body_0|> def process_message(self, message: SQSMessage) -> bool: """Process a message retrieved from the...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Worker: """Ms.laure queue worker.""" def __init__(self, *args, name: str, dispatch_map: dict, **kwargs): """Added new parameter to the worker init class.""" self.name = name self.dispatch_map = dispatch_map super().__init__(*args, **kwargs) def process_message(self, m...
the_stack_v2_python_sparse
src/briefy/reflex/queue/worker.py
BriefyHQ/briefy.reflex
train
0
0e398b82f786106af78deac08868e7646df69ab5
[ "super().__init__(vm_roll)\nself.sides = 10\nself.difficulty = vm_roll.difficulty", "if not self.result:\n await self.roll()\nmessage = ['```md']\nmessage.append(f'You rolled {self.dice} dice.\\n')\nones = [x for x in self.result if x == 1]\nsuccess = [x for x in self.result if x >= self.difficulty]\nif ones a...
<|body_start_0|> super().__init__(vm_roll) self.sides = 10 self.difficulty = vm_roll.difficulty <|end_body_0|> <|body_start_1|> if not self.result: await self.roll() message = ['```md'] message.append(f'You rolled {self.dice} dice.\n') ones = [x for x...
VMRoll
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VMRoll: def __init__(self, vm_roll): """A roll object for vampire the masquerade. vm_roll: VampireMasqueradeParser object""" <|body_0|> async def format(self): """Formats the roll to be easily readable in discord. If the dice have not yet been rolled, it rolls first....
stack_v2_sparse_classes_75kplus_train_065615
8,545
permissive
[ { "docstring": "A roll object for vampire the masquerade. vm_roll: VampireMasqueradeParser object", "name": "__init__", "signature": "def __init__(self, vm_roll)" }, { "docstring": "Formats the roll to be easily readable in discord. If the dice have not yet been rolled, it rolls first.", "na...
2
stack_v2_sparse_classes_30k_train_005646
Implement the Python class `VMRoll` described below. Class description: Implement the VMRoll class. Method signatures and docstrings: - def __init__(self, vm_roll): A roll object for vampire the masquerade. vm_roll: VampireMasqueradeParser object - async def format(self): Formats the roll to be easily readable in dis...
Implement the Python class `VMRoll` described below. Class description: Implement the VMRoll class. Method signatures and docstrings: - def __init__(self, vm_roll): A roll object for vampire the masquerade. vm_roll: VampireMasqueradeParser object - async def format(self): Formats the roll to be easily readable in dis...
b6947b225e789497eeb5e2375130e24f61c9d60a
<|skeleton|> class VMRoll: def __init__(self, vm_roll): """A roll object for vampire the masquerade. vm_roll: VampireMasqueradeParser object""" <|body_0|> async def format(self): """Formats the roll to be easily readable in discord. If the dice have not yet been rolled, it rolls first....
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class VMRoll: def __init__(self, vm_roll): """A roll object for vampire the masquerade. vm_roll: VampireMasqueradeParser object""" super().__init__(vm_roll) self.sides = 10 self.difficulty = vm_roll.difficulty async def format(self): """Formats the roll to be easily read...
the_stack_v2_python_sparse
utils/rolling/rolls.py
ephreal/rollbot
train
2
d5caa02a5af34e0003eb08a722278baf154abef9
[ "assert api_key != '', 'Must supply a non-empty API key.'\nself.api_key = {'x-api-key': api_key}\nself.api_root = 'https://jsonodds.com/api/'\nself.timeout = timeout\nself._sleep_time = sleep_time", "time.sleep(self._sleep_time)\nfull_uri = self.api_root + path\nresponse = self.session.request(method, full_uri, t...
<|body_start_0|> assert api_key != '', 'Must supply a non-empty API key.' self.api_key = {'x-api-key': api_key} self.api_root = 'https://jsonodds.com/api/' self.timeout = timeout self._sleep_time = sleep_time <|end_body_0|> <|body_start_1|> time.sleep(self._sleep_time) ...
JsonOdds API
API
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class API: """JsonOdds API""" def __init__(self, api_key, timeout=5, sleep_time=1.5): """JsonODDS API Constructor :param api_key: key provided by Sportradar, specific to the sport's API :param timeout: time before quitting on response (seconds) :param sleep_time: time to wait between reque...
stack_v2_sparse_classes_75kplus_train_065616
1,287
no_license
[ { "docstring": "JsonODDS API Constructor :param api_key: key provided by Sportradar, specific to the sport's API :param timeout: time before quitting on response (seconds) :param sleep_time: time to wait between requests, (free min is 1 second)", "name": "__init__", "signature": "def __init__(self, api_...
2
stack_v2_sparse_classes_30k_train_034037
Implement the Python class `API` described below. Class description: JsonOdds API Method signatures and docstrings: - def __init__(self, api_key, timeout=5, sleep_time=1.5): JsonODDS API Constructor :param api_key: key provided by Sportradar, specific to the sport's API :param timeout: time before quitting on respons...
Implement the Python class `API` described below. Class description: JsonOdds API Method signatures and docstrings: - def __init__(self, api_key, timeout=5, sleep_time=1.5): JsonODDS API Constructor :param api_key: key provided by Sportradar, specific to the sport's API :param timeout: time before quitting on respons...
201b22fc5c4c49e371d8d56d06c22834c50de5ba
<|skeleton|> class API: """JsonOdds API""" def __init__(self, api_key, timeout=5, sleep_time=1.5): """JsonODDS API Constructor :param api_key: key provided by Sportradar, specific to the sport's API :param timeout: time before quitting on response (seconds) :param sleep_time: time to wait between reque...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class API: """JsonOdds API""" def __init__(self, api_key, timeout=5, sleep_time=1.5): """JsonODDS API Constructor :param api_key: key provided by Sportradar, specific to the sport's API :param timeout: time before quitting on response (seconds) :param sleep_time: time to wait between requests, (free mi...
the_stack_v2_python_sparse
jsonodds/api.py
jpb8/theBookBKG
train
0
733258dd68b738d1382680ffc0c6a68702823453
[ "sub_devices = []\nstep = 5\nfor index in range(0, self.MAX_SUBDEVICES, step):\n state = {'count': step, 'index': index}\n packet = self._encode(14, state)\n resp = self.send_packet(106, packet)\n e.check_error(resp[34:36])\n resp = self._decode(resp)\n sub_devices.extend(resp['list'])\n if len...
<|body_start_0|> sub_devices = [] step = 5 for index in range(0, self.MAX_SUBDEVICES, step): state = {'count': step, 'index': index} packet = self._encode(14, state) resp = self.send_packet(106, packet) e.check_error(resp[34:36]) resp =...
Controls a Broadlink S3.
s3
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class s3: """Controls a Broadlink S3.""" def get_subdevices(self) -> list: """Return the lit of sub devices.""" <|body_0|> def get_state(self, did: str=None) -> dict: """Return the power state of the device.""" <|body_1|> def set_state(self, did: str=None,...
stack_v2_sparse_classes_75kplus_train_065617
2,541
permissive
[ { "docstring": "Return the lit of sub devices.", "name": "get_subdevices", "signature": "def get_subdevices(self) -> list" }, { "docstring": "Return the power state of the device.", "name": "get_state", "signature": "def get_state(self, did: str=None) -> dict" }, { "docstring": "...
5
null
Implement the Python class `s3` described below. Class description: Controls a Broadlink S3. Method signatures and docstrings: - def get_subdevices(self) -> list: Return the lit of sub devices. - def get_state(self, did: str=None) -> dict: Return the power state of the device. - def set_state(self, did: str=None, pwr...
Implement the Python class `s3` described below. Class description: Controls a Broadlink S3. Method signatures and docstrings: - def get_subdevices(self) -> list: Return the lit of sub devices. - def get_state(self, did: str=None) -> dict: Return the power state of the device. - def set_state(self, did: str=None, pwr...
3c183eaaef6cbaf9c1154b232116bc130cd2113f
<|skeleton|> class s3: """Controls a Broadlink S3.""" def get_subdevices(self) -> list: """Return the lit of sub devices.""" <|body_0|> def get_state(self, did: str=None) -> dict: """Return the power state of the device.""" <|body_1|> def set_state(self, did: str=None,...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class s3: """Controls a Broadlink S3.""" def get_subdevices(self) -> list: """Return the lit of sub devices.""" sub_devices = [] step = 5 for index in range(0, self.MAX_SUBDEVICES, step): state = {'count': step, 'index': index} packet = self._encode(14, s...
the_stack_v2_python_sparse
broadlink/hub.py
mjg59/python-broadlink
train
1,323
46bb0e75a2642b857c6fcf738230900d93dafce1
[ "super().__init__(interval=interval)\nself.atol = atol\nself.rtol = rtol", "if isinstance(field, FieldCollection):\n self._reference = np.array([f.magnitude for f in field])\nelse:\n self._reference = field.magnitude\nreturn super().initialize(field, info)", "if isinstance(field, FieldCollection):\n ma...
<|body_start_0|> super().__init__(interval=interval) self.atol = atol self.rtol = rtol <|end_body_0|> <|body_start_1|> if isinstance(field, FieldCollection): self._reference = np.array([f.magnitude for f in field]) else: self._reference = field.magnitude ...
Tracking interrupting the simulation when material conservation is broken
MaterialConservationTracker
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MaterialConservationTracker: """Tracking interrupting the simulation when material conservation is broken""" def __init__(self, interval: IntervalData=1, atol: float=0.0001, rtol: float=0.0001): """Args: interval: {ARG_TRACKER_INTERVAL} atol (float): Absolute tolerance for amount dev...
stack_v2_sparse_classes_75kplus_train_065618
37,567
permissive
[ { "docstring": "Args: interval: {ARG_TRACKER_INTERVAL} atol (float): Absolute tolerance for amount deviations rtol (float): Relative tolerance for amount deviations", "name": "__init__", "signature": "def __init__(self, interval: IntervalData=1, atol: float=0.0001, rtol: float=0.0001)" }, { "doc...
3
stack_v2_sparse_classes_30k_train_000647
Implement the Python class `MaterialConservationTracker` described below. Class description: Tracking interrupting the simulation when material conservation is broken Method signatures and docstrings: - def __init__(self, interval: IntervalData=1, atol: float=0.0001, rtol: float=0.0001): Args: interval: {ARG_TRACKER_...
Implement the Python class `MaterialConservationTracker` described below. Class description: Tracking interrupting the simulation when material conservation is broken Method signatures and docstrings: - def __init__(self, interval: IntervalData=1, atol: float=0.0001, rtol: float=0.0001): Args: interval: {ARG_TRACKER_...
d9c931a8361eaf27bc3766daba26edc11756b5f5
<|skeleton|> class MaterialConservationTracker: """Tracking interrupting the simulation when material conservation is broken""" def __init__(self, interval: IntervalData=1, atol: float=0.0001, rtol: float=0.0001): """Args: interval: {ARG_TRACKER_INTERVAL} atol (float): Absolute tolerance for amount dev...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MaterialConservationTracker: """Tracking interrupting the simulation when material conservation is broken""" def __init__(self, interval: IntervalData=1, atol: float=0.0001, rtol: float=0.0001): """Args: interval: {ARG_TRACKER_INTERVAL} atol (float): Absolute tolerance for amount deviations rtol ...
the_stack_v2_python_sparse
pde/trackers/trackers.py
zwicker-group/py-pde
train
327
453b128fad660bb8f062b0f67c54eef6f3480b65
[ "self.entity_domain = ENTITY_DOMAIN\nsuper().__init__(config_entry=config_entry, coordinator=coordinator, description=description)\nself._attr_entity_category = EntityCategory.DIAGNOSTIC", "if self.coordinator.data:\n if self.entity_description.state_value:\n if self.entity_description.key:\n ...
<|body_start_0|> self.entity_domain = ENTITY_DOMAIN super().__init__(config_entry=config_entry, coordinator=coordinator, description=description) self._attr_entity_category = EntityCategory.DIAGNOSTIC <|end_body_0|> <|body_start_1|> if self.coordinator.data: if self.entity_d...
Representation of an HDHomeRun sensor.
HDHomerunSensor
[ "Unlicense" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HDHomerunSensor: """Representation of an HDHomeRun sensor.""" def __init__(self, config_entry: ConfigEntry, coordinator: DataUpdateCoordinator, description: HDHomerunSensorEntityDescription) -> None: """Initialise.""" <|body_0|> def native_value(self) -> StateType | date...
stack_v2_sparse_classes_75kplus_train_065619
13,715
permissive
[ { "docstring": "Initialise.", "name": "__init__", "signature": "def __init__(self, config_entry: ConfigEntry, coordinator: DataUpdateCoordinator, description: HDHomerunSensorEntityDescription) -> None" }, { "docstring": "Get the value of the sensor.", "name": "native_value", "signature":...
2
stack_v2_sparse_classes_30k_train_048349
Implement the Python class `HDHomerunSensor` described below. Class description: Representation of an HDHomeRun sensor. Method signatures and docstrings: - def __init__(self, config_entry: ConfigEntry, coordinator: DataUpdateCoordinator, description: HDHomerunSensorEntityDescription) -> None: Initialise. - def native...
Implement the Python class `HDHomerunSensor` described below. Class description: Representation of an HDHomeRun sensor. Method signatures and docstrings: - def __init__(self, config_entry: ConfigEntry, coordinator: DataUpdateCoordinator, description: HDHomerunSensorEntityDescription) -> None: Initialise. - def native...
8548d9999ddd54f13d6a307e013abcb8c897a74e
<|skeleton|> class HDHomerunSensor: """Representation of an HDHomeRun sensor.""" def __init__(self, config_entry: ConfigEntry, coordinator: DataUpdateCoordinator, description: HDHomerunSensorEntityDescription) -> None: """Initialise.""" <|body_0|> def native_value(self) -> StateType | date...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class HDHomerunSensor: """Representation of an HDHomeRun sensor.""" def __init__(self, config_entry: ConfigEntry, coordinator: DataUpdateCoordinator, description: HDHomerunSensorEntityDescription) -> None: """Initialise.""" self.entity_domain = ENTITY_DOMAIN super().__init__(config_entr...
the_stack_v2_python_sparse
custom_components/hdhomerun/sensor.py
bacco007/HomeAssistantConfig
train
98
fea672448a351b160ec1e19f010864edb462cd32
[ "self.activate = False\nself.menu = menu\nself.name = name\nself.profileJoinName = profilePluginFileName + '.& /' + name\nself.profilePluginFileName = profilePluginFileName\nself.radioVar = radioVar\nmenu.add_radiobutton(label=name.replace('_', ' '), command=self.clickRadio, value=self.profileJoinName, variable=sel...
<|body_start_0|> self.activate = False self.menu = menu self.name = name self.profileJoinName = profilePluginFileName + '.& /' + name self.profilePluginFileName = profilePluginFileName self.radioVar = radioVar menu.add_radiobutton(label=name.replace('_', ' '), com...
A class to display a profile menu radio button.
ProfileMenuRadio
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProfileMenuRadio: """A class to display a profile menu radio button.""" def __init__(self, profilePluginFileName, menu, name, radioVar, value): """Create a profile menu radio.""" <|body_0|> def clickRadio(self): """Workaround for Tkinter bug, invoke and set the v...
stack_v2_sparse_classes_75kplus_train_065620
10,948
no_license
[ { "docstring": "Create a profile menu radio.", "name": "__init__", "signature": "def __init__(self, profilePluginFileName, menu, name, radioVar, value)" }, { "docstring": "Workaround for Tkinter bug, invoke and set the value when clicked.", "name": "clickRadio", "signature": "def clickRa...
2
null
Implement the Python class `ProfileMenuRadio` described below. Class description: A class to display a profile menu radio button. Method signatures and docstrings: - def __init__(self, profilePluginFileName, menu, name, radioVar, value): Create a profile menu radio. - def clickRadio(self): Workaround for Tkinter bug,...
Implement the Python class `ProfileMenuRadio` described below. Class description: A class to display a profile menu radio button. Method signatures and docstrings: - def __init__(self, profilePluginFileName, menu, name, radioVar, value): Create a profile menu radio. - def clickRadio(self): Workaround for Tkinter bug,...
fd69d8e856780c826386dc973ceabcc03623f3e8
<|skeleton|> class ProfileMenuRadio: """A class to display a profile menu radio button.""" def __init__(self, profilePluginFileName, menu, name, radioVar, value): """Create a profile menu radio.""" <|body_0|> def clickRadio(self): """Workaround for Tkinter bug, invoke and set the v...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ProfileMenuRadio: """A class to display a profile menu radio button.""" def __init__(self, profilePluginFileName, menu, name, radioVar, value): """Create a profile menu radio.""" self.activate = False self.menu = menu self.name = name self.profileJoinName = profile...
the_stack_v2_python_sparse
skeinforge_tools/profile.py
bmander/skeinforge
train
34
e02f54b55580ff94cbfcd93958c4a4d2e9a4766b
[ "self.Ans = 0\nself.n = n\nself.upperlime = (1 << n) - 1\nself.test(0, 0, 0)\nreturn self.Ans", "if row != self.upperlime:\n pos = self.upperlime & ~(row | ld | rd)\n while pos:\n p = pos & ~pos + 1\n pos = pos - p\n self.test(row | p, (ld | p) << 1, (rd | p) >> 1)\nelse:\n self.Ans ...
<|body_start_0|> self.Ans = 0 self.n = n self.upperlime = (1 << n) - 1 self.test(0, 0, 0) return self.Ans <|end_body_0|> <|body_start_1|> if row != self.upperlime: pos = self.upperlime & ~(row | ld | rd) while pos: p = pos & ~pos +...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def totalNQueens(self, n): """:type n: int :rtype: List[List[str]]""" <|body_0|> def test(self, row, ld, rd): """row代表每一列的禁放位 ld代表左上到右下的 斜向上对角线 禁放位 rd代表右上到左下的 斜向下对角线 禁放位""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.Ans = 0 ...
stack_v2_sparse_classes_75kplus_train_065621
802
no_license
[ { "docstring": ":type n: int :rtype: List[List[str]]", "name": "totalNQueens", "signature": "def totalNQueens(self, n)" }, { "docstring": "row代表每一列的禁放位 ld代表左上到右下的 斜向上对角线 禁放位 rd代表右上到左下的 斜向下对角线 禁放位", "name": "test", "signature": "def test(self, row, ld, rd)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def totalNQueens(self, n): :type n: int :rtype: List[List[str]] - def test(self, row, ld, rd): row代表每一列的禁放位 ld代表左上到右下的 斜向上对角线 禁放位 rd代表右上到左下的 斜向下对角线 禁放位
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def totalNQueens(self, n): :type n: int :rtype: List[List[str]] - def test(self, row, ld, rd): row代表每一列的禁放位 ld代表左上到右下的 斜向上对角线 禁放位 rd代表右上到左下的 斜向下对角线 禁放位 <|skeleton|> class Soluti...
a9c982207d3fc4bcb0513f88b6b5aeaaeb09f554
<|skeleton|> class Solution: def totalNQueens(self, n): """:type n: int :rtype: List[List[str]]""" <|body_0|> def test(self, row, ld, rd): """row代表每一列的禁放位 ld代表左上到右下的 斜向上对角线 禁放位 rd代表右上到左下的 斜向下对角线 禁放位""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def totalNQueens(self, n): """:type n: int :rtype: List[List[str]]""" self.Ans = 0 self.n = n self.upperlime = (1 << n) - 1 self.test(0, 0, 0) return self.Ans def test(self, row, ld, rd): """row代表每一列的禁放位 ld代表左上到右下的 斜向上对角线 禁放位 rd代表右上到左下的 斜向...
the_stack_v2_python_sparse
LeetCode52.py
hzyhzzh/LeetCode
train
0
957b78e29cf69664f62a167ca39a226dfb80fadc
[ "self.M_min = -20\nself.M_max = -18\nself.a_min = -20\nself.a_max = 20\nself.b_min = -20\nself.b_max = 20\nif g_lim != None:\n self.g_min = g_lim[0]\n self.g_max = g_lim[1]", "m = rng.rand()\nM = 1000.0 * rng.rand()\nM = dnest4.wrap(M, self.M_min, self.M_max)\na = 1000.0 * rng.rand()\na = dnest4.wrap(a, sel...
<|body_start_0|> self.M_min = -20 self.M_max = -18 self.a_min = -20 self.a_max = 20 self.b_min = -20 self.b_max = 20 if g_lim != None: self.g_min = g_lim[0] self.g_max = g_lim[1] <|end_body_0|> <|body_start_1|> m = rng.rand() ...
Specify the model in Python.
Model
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Model: """Specify the model in Python.""" def __init__(self, g_lim=None): """Parameter values *are not* stored inside the class""" <|body_0|> def from_prior(self): """Unlike in C++, this must *return* a numpy array of parameters.""" <|body_1|> def pe...
stack_v2_sparse_classes_75kplus_train_065622
13,227
permissive
[ { "docstring": "Parameter values *are not* stored inside the class", "name": "__init__", "signature": "def __init__(self, g_lim=None)" }, { "docstring": "Unlike in C++, this must *return* a numpy array of parameters.", "name": "from_prior", "signature": "def from_prior(self)" }, { ...
4
stack_v2_sparse_classes_30k_train_022307
Implement the Python class `Model` described below. Class description: Specify the model in Python. Method signatures and docstrings: - def __init__(self, g_lim=None): Parameter values *are not* stored inside the class - def from_prior(self): Unlike in C++, this must *return* a numpy array of parameters. - def pertur...
Implement the Python class `Model` described below. Class description: Specify the model in Python. Method signatures and docstrings: - def __init__(self, g_lim=None): Parameter values *are not* stored inside the class - def from_prior(self): Unlike in C++, this must *return* a numpy array of parameters. - def pertur...
c355d18021467cf92546cf2fc9cb1d1abe59b8d8
<|skeleton|> class Model: """Specify the model in Python.""" def __init__(self, g_lim=None): """Parameter values *are not* stored inside the class""" <|body_0|> def from_prior(self): """Unlike in C++, this must *return* a numpy array of parameters.""" <|body_1|> def pe...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Model: """Specify the model in Python.""" def __init__(self, g_lim=None): """Parameter values *are not* stored inside the class""" self.M_min = -20 self.M_max = -18 self.a_min = -20 self.a_max = 20 self.b_min = -20 self.b_max = 20 if g_lim !...
the_stack_v2_python_sparse
zprev versions/Models_py_backup/Models backup/Bfactor.py
lefthandedroo/Cosmodels
train
1
33073a5b7de967b0f0b2ef985a261647bdccb572
[ "try:\n model_name = request.query_params['model_name']\n scheme_electrons = SchemeElectron.objects.filter(model_name=model_name)\n schemes = [scheme_electron.scheme for scheme_electron in scheme_electrons]\n reference_schemes = []\n for scheme in schemes:\n if scheme.is_reference:\n ...
<|body_start_0|> try: model_name = request.query_params['model_name'] scheme_electrons = SchemeElectron.objects.filter(model_name=model_name) schemes = [scheme_electron.scheme for scheme_electron in scheme_electrons] reference_schemes = [] for scheme i...
方案Bom清单
SchemeElectronViewSet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SchemeElectronViewSet: """方案Bom清单""" def scheme_list(self, request, *args, **kwargs): """元器件方案列表(参考设计)""" <|body_0|> def electron_list(self, request, *args, **kwargs): """方案元器件列表""" <|body_1|> <|end_skeleton|> <|body_start_0|> try: m...
stack_v2_sparse_classes_75kplus_train_065623
10,090
no_license
[ { "docstring": "元器件方案列表(参考设计)", "name": "scheme_list", "signature": "def scheme_list(self, request, *args, **kwargs)" }, { "docstring": "方案元器件列表", "name": "electron_list", "signature": "def electron_list(self, request, *args, **kwargs)" } ]
2
stack_v2_sparse_classes_30k_train_029667
Implement the Python class `SchemeElectronViewSet` described below. Class description: 方案Bom清单 Method signatures and docstrings: - def scheme_list(self, request, *args, **kwargs): 元器件方案列表(参考设计) - def electron_list(self, request, *args, **kwargs): 方案元器件列表
Implement the Python class `SchemeElectronViewSet` described below. Class description: 方案Bom清单 Method signatures and docstrings: - def scheme_list(self, request, *args, **kwargs): 元器件方案列表(参考设计) - def electron_list(self, request, *args, **kwargs): 方案元器件列表 <|skeleton|> class SchemeElectronViewSet: """方案Bom清单""" ...
c4d9b124a50e96ce01dfd83073cbe4435cb07266
<|skeleton|> class SchemeElectronViewSet: """方案Bom清单""" def scheme_list(self, request, *args, **kwargs): """元器件方案列表(参考设计)""" <|body_0|> def electron_list(self, request, *args, **kwargs): """方案元器件列表""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SchemeElectronViewSet: """方案Bom清单""" def scheme_list(self, request, *args, **kwargs): """元器件方案列表(参考设计)""" try: model_name = request.query_params['model_name'] scheme_electrons = SchemeElectron.objects.filter(model_name=model_name) schemes = [scheme_elec...
the_stack_v2_python_sparse
apps/scheme/views/views_back.py
wuhaihua1989/magic1
train
0
cc2c825f163c75d6aba81cd1bfae822e20fd95ae
[ "queryset = obj.detalles_entrada.all()\nif self.context['fecha_inicio']:\n queryset = queryset.filter(entrada__fecha__gte=self.context['fecha_inicio'])\nif self.context['fecha_fin']:\n queryset = queryset.filter(entrada__fecha__lte=self.context['fecha_fin'])\nreturn queryset.count()", "queryset = obj.detall...
<|body_start_0|> queryset = obj.detalles_entrada.all() if self.context['fecha_inicio']: queryset = queryset.filter(entrada__fecha__gte=self.context['fecha_inicio']) if self.context['fecha_fin']: queryset = queryset.filter(entrada__fecha__lte=self.context['fecha_fin']) ...
EquipoSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EquipoSerializer: def get_cantidad_entrada(self, obj): """Para obtener la cantidad de :model:`kardex.EntradaDetalle` en el rango de fechas seleccionado. Depende del contexto enviado por la vista, recibe `fecha_inicio` o `fecha_salida` como parámetros opcionales. Returns: TYPE: int""" ...
stack_v2_sparse_classes_75kplus_train_065624
4,844
no_license
[ { "docstring": "Para obtener la cantidad de :model:`kardex.EntradaDetalle` en el rango de fechas seleccionado. Depende del contexto enviado por la vista, recibe `fecha_inicio` o `fecha_salida` como parámetros opcionales. Returns: TYPE: int", "name": "get_cantidad_entrada", "signature": "def get_cantidad...
4
stack_v2_sparse_classes_30k_val_002341
Implement the Python class `EquipoSerializer` described below. Class description: Implement the EquipoSerializer class. Method signatures and docstrings: - def get_cantidad_entrada(self, obj): Para obtener la cantidad de :model:`kardex.EntradaDetalle` en el rango de fechas seleccionado. Depende del contexto enviado p...
Implement the Python class `EquipoSerializer` described below. Class description: Implement the EquipoSerializer class. Method signatures and docstrings: - def get_cantidad_entrada(self, obj): Para obtener la cantidad de :model:`kardex.EntradaDetalle` en el rango de fechas seleccionado. Depende del contexto enviado p...
0e37786d7173abe820fd10b094ffcc2db9593a9c
<|skeleton|> class EquipoSerializer: def get_cantidad_entrada(self, obj): """Para obtener la cantidad de :model:`kardex.EntradaDetalle` en el rango de fechas seleccionado. Depende del contexto enviado por la vista, recibe `fecha_inicio` o `fecha_salida` como parámetros opcionales. Returns: TYPE: int""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EquipoSerializer: def get_cantidad_entrada(self, obj): """Para obtener la cantidad de :model:`kardex.EntradaDetalle` en el rango de fechas seleccionado. Depende del contexto enviado por la vista, recibe `fecha_inicio` o `fecha_salida` como parámetros opcionales. Returns: TYPE: int""" queryset ...
the_stack_v2_python_sparse
src/apps/kardex/serializers.py
jinchuika/app-suni
train
7
4ac01e9db0266170690e0c450adeb2258ce5ce60
[ "super(GeneratorNet, self).__init__()\nself.n_features = 100\nself.n_out = 784\nself.__model_fn()\nself.optimizer = optim.Adam(self.parameters(), lr=0.0002)", "self.hidden0 = nn.Sequential(nn.Linear(self.n_features, 256), nn.LeakyReLU(0.2))\nself.hidden1 = nn.Sequential(nn.Linear(256, 512), nn.LeakyReLU(0.2))\nse...
<|body_start_0|> super(GeneratorNet, self).__init__() self.n_features = 100 self.n_out = 784 self.__model_fn() self.optimizer = optim.Adam(self.parameters(), lr=0.0002) <|end_body_0|> <|body_start_1|> self.hidden0 = nn.Sequential(nn.Linear(self.n_features, 256), nn.Leaky...
Class GeneratorNet.
GeneratorNet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GeneratorNet: """Class GeneratorNet.""" def __init__(self): """Constructor.""" <|body_0|> def __model_fn(self): """Specifies the network.""" <|body_1|> def forward(self, X): """Performs a forward-pass on the data. :param X: network input""" ...
stack_v2_sparse_classes_75kplus_train_065625
11,950
no_license
[ { "docstring": "Constructor.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Specifies the network.", "name": "__model_fn", "signature": "def __model_fn(self)" }, { "docstring": "Performs a forward-pass on the data. :param X: network input", "name":...
3
stack_v2_sparse_classes_30k_train_042317
Implement the Python class `GeneratorNet` described below. Class description: Class GeneratorNet. Method signatures and docstrings: - def __init__(self): Constructor. - def __model_fn(self): Specifies the network. - def forward(self, X): Performs a forward-pass on the data. :param X: network input
Implement the Python class `GeneratorNet` described below. Class description: Class GeneratorNet. Method signatures and docstrings: - def __init__(self): Constructor. - def __model_fn(self): Specifies the network. - def forward(self, X): Performs a forward-pass on the data. :param X: network input <|skeleton|> class...
98b71b76f664d5f6493bd7f90036531d8f6644a7
<|skeleton|> class GeneratorNet: """Class GeneratorNet.""" def __init__(self): """Constructor.""" <|body_0|> def __model_fn(self): """Specifies the network.""" <|body_1|> def forward(self, X): """Performs a forward-pass on the data. :param X: network input""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GeneratorNet: """Class GeneratorNet.""" def __init__(self): """Constructor.""" super(GeneratorNet, self).__init__() self.n_features = 100 self.n_out = 784 self.__model_fn() self.optimizer = optim.Adam(self.parameters(), lr=0.0002) def __model_fn(self):...
the_stack_v2_python_sparse
06_python/misc/gan.py
pfisterer/Applied_ML_Fundamentals
train
0
c8df972ee3f6167ef4a1a3ca7633505f33ae8580
[ "AbstractInitializer.__init__(self, n_in=0, n_out=None, problem=problem)\nself.terminal_list = self._get_terminal_list()\nPopulationOperator.__init__(self, 0, len(self.terminal_list))", "def make_node(func_id):\n new_node = node.Node()\n node.set_id(new_node, func_id)\n return new_node\npopulation = [sol...
<|body_start_0|> AbstractInitializer.__init__(self, n_in=0, n_out=None, problem=problem) self.terminal_list = self._get_terminal_list() PopulationOperator.__init__(self, 0, len(self.terminal_list)) <|end_body_0|> <|body_start_1|> def make_node(func_id): new_node = node.Node(...
Generate all solutions which have an only terminal node.
PopulationTerminalInitializer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PopulationTerminalInitializer: """Generate all solutions which have an only terminal node.""" def __init__(self, problem): """:param k: int. the number of solutions to generate :param problem: problem object. problem to solve""" <|body_0|> def __call__(self): """...
stack_v2_sparse_classes_75kplus_train_065626
5,247
permissive
[ { "docstring": ":param k: int. the number of solutions to generate :param problem: problem object. problem to solve", "name": "__init__", "signature": "def __init__(self, problem)" }, { "docstring": "Generate all solutions which have an only terminal node. :return: list of solution object. list ...
2
stack_v2_sparse_classes_30k_train_013780
Implement the Python class `PopulationTerminalInitializer` described below. Class description: Generate all solutions which have an only terminal node. Method signatures and docstrings: - def __init__(self, problem): :param k: int. the number of solutions to generate :param problem: problem object. problem to solve -...
Implement the Python class `PopulationTerminalInitializer` described below. Class description: Generate all solutions which have an only terminal node. Method signatures and docstrings: - def __init__(self, problem): :param k: int. the number of solutions to generate :param problem: problem object. problem to solve -...
33a2b83bebc61f28449bffa28c87c9013e764ec7
<|skeleton|> class PopulationTerminalInitializer: """Generate all solutions which have an only terminal node.""" def __init__(self, problem): """:param k: int. the number of solutions to generate :param problem: problem object. problem to solve""" <|body_0|> def __call__(self): """...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PopulationTerminalInitializer: """Generate all solutions which have an only terminal node.""" def __init__(self, problem): """:param k: int. the number of solutions to generate :param problem: problem object. problem to solve""" AbstractInitializer.__init__(self, n_in=0, n_out=None, probl...
the_stack_v2_python_sparse
onegpy/operators/initializer.py
hiro-o918/onegpy
train
0
2af56df1745ea9445618617f301e80ec16deaf87
[ "user = request.user\nif not hasattr(user, 'user_profile'):\n return RESPONSE_400_OBJECT_NOT_FOUND\nprofile = user.user_profile\nreturn JsonResponse(profile.to_dict(), status=200)", "user = request.user\nif not hasattr(user, 'user_profile'):\n return RESPONSE_400_OBJECT_NOT_FOUND\nprofile = user.user_profil...
<|body_start_0|> user = request.user if not hasattr(user, 'user_profile'): return RESPONSE_400_OBJECT_NOT_FOUND profile = user.user_profile return JsonResponse(profile.to_dict(), status=200) <|end_body_0|> <|body_start_1|> user = request.user if not hasattr(u...
Class that handles HTTP requests for user_profile model.
UserProfileView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserProfileView: """Class that handles HTTP requests for user_profile model.""" def get(self, request): """Handle the request to retrieve a user_profile object.""" <|body_0|> def put(self, request): """Handle the request to update an existing user_profile object ...
stack_v2_sparse_classes_75kplus_train_065627
3,252
no_license
[ { "docstring": "Handle the request to retrieve a user_profile object.", "name": "get", "signature": "def get(self, request)" }, { "docstring": "Handle the request to update an existing user_profile object with appropriate id.", "name": "put", "signature": "def put(self, request)" } ]
2
stack_v2_sparse_classes_30k_train_018184
Implement the Python class `UserProfileView` described below. Class description: Class that handles HTTP requests for user_profile model. Method signatures and docstrings: - def get(self, request): Handle the request to retrieve a user_profile object. - def put(self, request): Handle the request to update an existing...
Implement the Python class `UserProfileView` described below. Class description: Class that handles HTTP requests for user_profile model. Method signatures and docstrings: - def get(self, request): Handle the request to retrieve a user_profile object. - def put(self, request): Handle the request to update an existing...
c5f533bd049f6939037b14045e2aa2550aaac36a
<|skeleton|> class UserProfileView: """Class that handles HTTP requests for user_profile model.""" def get(self, request): """Handle the request to retrieve a user_profile object.""" <|body_0|> def put(self, request): """Handle the request to update an existing user_profile object ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UserProfileView: """Class that handles HTTP requests for user_profile model.""" def get(self, request): """Handle the request to retrieve a user_profile object.""" user = request.user if not hasattr(user, 'user_profile'): return RESPONSE_400_OBJECT_NOT_FOUND pr...
the_stack_v2_python_sparse
way_to_home/user_profile/views.py
Lv-365python/wayToHome
train
1
e2e1a9346f6aa62136a126aceeccc60576b8fc57
[ "refDir = 'reference_files'\nx1 = x1\ncolor = color\nself.namesRef = namesRef\nLi_files = []\nmag_to_flux_files = []\nself.SNR = SNR\nself.dt_range = dt_range\nself.mag_range = mag_range\nfor name in namesRef:\n self.Li_files = ['{}/Li_{}_{}_{}.npy'.format(refDir, name, x1, color)]\n self.mag_to_flux_files = ...
<|body_start_0|> refDir = 'reference_files' x1 = x1 color = color self.namesRef = namesRef Li_files = [] mag_to_flux_files = [] self.SNR = SNR self.dt_range = dt_range self.mag_range = mag_range for name in namesRef: self.Li_fil...
Summary
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Summary: def __init__(self, x1=-2.0, color=0.2, namesRef=['SNCosmo'], SNR=dict(zip('griz', [30.0, 40.0, 30.0, 20.0])), dt_range=[0.5, 30.0], mag_range=[21.0, 25.5]): """class to load metric data and estimate medians Parameters ---------------- x1: float, opt SN x1 (default: -2.0) color: ...
stack_v2_sparse_classes_75kplus_train_065628
7,601
permissive
[ { "docstring": "class to load metric data and estimate medians Parameters ---------------- x1: float, opt SN x1 (default: -2.0) color: float, opt SN color (default: 0.2) namesRef: list(str) list of reference names for reference LC (default: ['SNCosmo']) SNR: dict, opt SNR cut per band (default: dict(zip('griz',...
3
stack_v2_sparse_classes_30k_train_001362
Implement the Python class `Summary` described below. Class description: Implement the Summary class. Method signatures and docstrings: - def __init__(self, x1=-2.0, color=0.2, namesRef=['SNCosmo'], SNR=dict(zip('griz', [30.0, 40.0, 30.0, 20.0])), dt_range=[0.5, 30.0], mag_range=[21.0, 25.5]): class to load metric da...
Implement the Python class `Summary` described below. Class description: Implement the Summary class. Method signatures and docstrings: - def __init__(self, x1=-2.0, color=0.2, namesRef=['SNCosmo'], SNR=dict(zip('griz', [30.0, 40.0, 30.0, 20.0])), dt_range=[0.5, 30.0], mag_range=[21.0, 25.5]): class to load metric da...
d42c7490ba5ff8c52f62e70a20c922172a6baff1
<|skeleton|> class Summary: def __init__(self, x1=-2.0, color=0.2, namesRef=['SNCosmo'], SNR=dict(zip('griz', [30.0, 40.0, 30.0, 20.0])), dt_range=[0.5, 30.0], mag_range=[21.0, 25.5]): """class to load metric data and estimate medians Parameters ---------------- x1: float, opt SN x1 (default: -2.0) color: ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Summary: def __init__(self, x1=-2.0, color=0.2, namesRef=['SNCosmo'], SNR=dict(zip('griz', [30.0, 40.0, 30.0, 20.0])), dt_range=[0.5, 30.0], mag_range=[21.0, 25.5]): """class to load metric data and estimate medians Parameters ---------------- x1: float, opt SN x1 (default: -2.0) color: float, opt SN ...
the_stack_v2_python_sparse
plot_scripts/metrics/plot_summary.py
LSSTDESC/sn_pipe
train
1
b53e4603b387644eeccbed8a999ac75b4d1f426b
[ "assert da.getDim() == 1\nself.da = da\nself.prob = prob\nself.factor = factor\nself.localX = da.createLocalVec()", "self.da.globalToLocal(X, self.localX)\nx = self.da.getVecArray(self.localX)\nf = self.da.getVecArray(F)\nmx = self.da.getSizes()[0]\nxs, xe = self.da.getRanges()[0]\nfor i in range(xs, xe):\n if...
<|body_start_0|> assert da.getDim() == 1 self.da = da self.prob = prob self.factor = factor self.localX = da.createLocalVec() <|end_body_0|> <|body_start_1|> self.da.globalToLocal(X, self.localX) x = self.da.getVecArray(self.localX) f = self.da.getVecArra...
Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES
Fisher_reaction
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Fisher_reaction: """Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES""" def __init__(self, da, prob, factor): """Initialization routine Args: da: DMDA object prob: problem instance factor: temporal factor (dt*Qd) dx: grid spacing in x direction"...
stack_v2_sparse_classes_75kplus_train_065629
16,584
permissive
[ { "docstring": "Initialization routine Args: da: DMDA object prob: problem instance factor: temporal factor (dt*Qd) dx: grid spacing in x direction", "name": "__init__", "signature": "def __init__(self, da, prob, factor)" }, { "docstring": "Function to evaluate the residual for the Newton solver...
3
stack_v2_sparse_classes_30k_train_006269
Implement the Python class `Fisher_reaction` described below. Class description: Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES Method signatures and docstrings: - def __init__(self, da, prob, factor): Initialization routine Args: da: DMDA object prob: problem instance factor:...
Implement the Python class `Fisher_reaction` described below. Class description: Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES Method signatures and docstrings: - def __init__(self, da, prob, factor): Initialization routine Args: da: DMDA object prob: problem instance factor:...
1a51834bedffd4472e344bed28f4d766614b1537
<|skeleton|> class Fisher_reaction: """Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES""" def __init__(self, da, prob, factor): """Initialization routine Args: da: DMDA object prob: problem instance factor: temporal factor (dt*Qd) dx: grid spacing in x direction"...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Fisher_reaction: """Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES""" def __init__(self, da, prob, factor): """Initialization routine Args: da: DMDA object prob: problem instance factor: temporal factor (dt*Qd) dx: grid spacing in x direction""" as...
the_stack_v2_python_sparse
pySDC/implementations/problem_classes/GeneralizedFisher_1D_PETSc.py
Parallel-in-Time/pySDC
train
30
cba166a52a2f526a8ea80704f7195f84d05c991e
[ "if not os.path.exists(path) or not os.path.isdir(path):\n raise RuntimeError('Path {} does not exist or is not a directory'.format(path))\nf = os.path.join(path, 'description.yaml')\nif not os.path.exists(f) or not os.path.isfile(f):\n raise RuntimeError('Description file {} does not exist or is not a file'....
<|body_start_0|> if not os.path.exists(path) or not os.path.isdir(path): raise RuntimeError('Path {} does not exist or is not a directory'.format(path)) f = os.path.join(path, 'description.yaml') if not os.path.exists(f) or not os.path.isfile(f): raise RuntimeError('Descr...
DynestyResults
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DynestyResults: def __init__(self, path): """Read Results object (in the dynesty.results module) from disk. :param path: Path to the storage location. :type path: str""" <|body_0|> def create(path, parameters, results): """Write a new Results object (in the dynesty.r...
stack_v2_sparse_classes_75kplus_train_065630
26,000
no_license
[ { "docstring": "Read Results object (in the dynesty.results module) from disk. :param path: Path to the storage location. :type path: str", "name": "__init__", "signature": "def __init__(self, path)" }, { "docstring": "Write a new Results object (in the dynesty.results module) to disk. :param pa...
2
stack_v2_sparse_classes_30k_train_029362
Implement the Python class `DynestyResults` described below. Class description: Implement the DynestyResults class. Method signatures and docstrings: - def __init__(self, path): Read Results object (in the dynesty.results module) from disk. :param path: Path to the storage location. :type path: str - def create(path,...
Implement the Python class `DynestyResults` described below. Class description: Implement the DynestyResults class. Method signatures and docstrings: - def __init__(self, path): Read Results object (in the dynesty.results module) from disk. :param path: Path to the storage location. :type path: str - def create(path,...
958db5d493e7b614d2393dbe3605cc0d711a0246
<|skeleton|> class DynestyResults: def __init__(self, path): """Read Results object (in the dynesty.results module) from disk. :param path: Path to the storage location. :type path: str""" <|body_0|> def create(path, parameters, results): """Write a new Results object (in the dynesty.r...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DynestyResults: def __init__(self, path): """Read Results object (in the dynesty.results module) from disk. :param path: Path to the storage location. :type path: str""" if not os.path.exists(path) or not os.path.isdir(path): raise RuntimeError('Path {} does not exist or is not a d...
the_stack_v2_python_sparse
python/eos/data/native.py
eos/eos
train
46
f0bad99e0ba3078c8a58181b37bc0a097170e001
[ "self.modis_id = modis_id\nself.variable_list = variable_list\nself.start_date = start_date\nself.end_date = end_date\nself.daynightboth = daynightboth\nself.grid = grid\nself.grid_fill = grid_fill\nself.use_long_name = use_long_name\nif modis_platform.lower() == 'terra':\n self.modis_platform = 'MOD'\nelif modi...
<|body_start_0|> self.modis_id = modis_id self.variable_list = variable_list self.start_date = start_date self.end_date = end_date self.daynightboth = daynightboth self.grid = grid self.grid_fill = grid_fill self.use_long_name = use_long_name if mo...
Data Fetcher for MODIS data
DataFetcher
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataFetcher: """Data Fetcher for MODIS data""" def __init__(self, ap_paramList, modis_platform, modis_id, variable_list, start_date, end_date, daynightboth='D', grid=None, grid_fill=np.nan, use_long_name=False): """Construct Data Fetcher object @param ap_paramList[lat]: Search latitu...
stack_v2_sparse_classes_75kplus_train_065631
4,630
permissive
[ { "docstring": "Construct Data Fetcher object @param ap_paramList[lat]: Search latitude @param ap_paramList[lon]: Search longitude @param modis_platform: Platform (Either \"Terra\" or \"Aqua\") @param modis_id: Product string (e.g. '06_L2') @param variable_list: List of variables to fetch @param start_date: Sta...
2
stack_v2_sparse_classes_30k_train_003838
Implement the Python class `DataFetcher` described below. Class description: Data Fetcher for MODIS data Method signatures and docstrings: - def __init__(self, ap_paramList, modis_platform, modis_id, variable_list, start_date, end_date, daynightboth='D', grid=None, grid_fill=np.nan, use_long_name=False): Construct Da...
Implement the Python class `DataFetcher` described below. Class description: Data Fetcher for MODIS data Method signatures and docstrings: - def __init__(self, ap_paramList, modis_platform, modis_id, variable_list, start_date, end_date, daynightboth='D', grid=None, grid_fill=np.nan, use_long_name=False): Construct Da...
935bfd54149abd9542fe38e77b7eabab48b1c3a1
<|skeleton|> class DataFetcher: """Data Fetcher for MODIS data""" def __init__(self, ap_paramList, modis_platform, modis_id, variable_list, start_date, end_date, daynightboth='D', grid=None, grid_fill=np.nan, use_long_name=False): """Construct Data Fetcher object @param ap_paramList[lat]: Search latitu...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DataFetcher: """Data Fetcher for MODIS data""" def __init__(self, ap_paramList, modis_platform, modis_id, variable_list, start_date, end_date, daynightboth='D', grid=None, grid_fill=np.nan, use_long_name=False): """Construct Data Fetcher object @param ap_paramList[lat]: Search latitude @param ap_...
the_stack_v2_python_sparse
skdaccess/geo/modis/stream/data_fetcher.py
MITHaystack/scikit-dataaccess
train
41
6b04bb6d719f32a86b1bc83ce357179226385ced
[ "self.num_hypotheses = num_hypotheses\nself.__name__ = 'mhp_loss'\nif avg_weight > 0.25 or avg_weight < 0.0:\n raise RuntimeError('avg_weight must be in [0,0.25]')\nself.avg_weight = avg_weight\nself.min_weight = 1.0 - self.avg_weight\nself.kl_weight = 0.001\nself.loss = keras.losses.get(loss)", "xsum = tf.zer...
<|body_start_0|> self.num_hypotheses = num_hypotheses self.__name__ = 'mhp_loss' if avg_weight > 0.25 or avg_weight < 0.0: raise RuntimeError('avg_weight must be in [0,0.25]') self.avg_weight = avg_weight self.min_weight = 1.0 - self.avg_weight self.kl_weight ...
Defines Christian Rupprecht's multiple-hypothesis loss function. This one operates on multiple hypothesis samples. This version is designed for use with data of one type of output (e.g. an image). ArXiv: https://arxiv.org/pdf/1612.00197.pdf BibTex: @article{rupprecht2016learning, title={Learning in an Uncertain World: ...
MhpLoss
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MhpLoss: """Defines Christian Rupprecht's multiple-hypothesis loss function. This one operates on multiple hypothesis samples. This version is designed for use with data of one type of output (e.g. an image). ArXiv: https://arxiv.org/pdf/1612.00197.pdf BibTex: @article{rupprecht2016learning, titl...
stack_v2_sparse_classes_75kplus_train_065632
7,780
permissive
[ { "docstring": "Set up the MHP loss function. Parameters: ----------- num_hypotheses: number of targets to generate (e.g., predict 8 possible future images). num_outputs: number of output variables per hypothesis (e.g., 64x64x3 for a 64x64 RGB image). Currently deprecated, but may be necessary later on.", "...
2
stack_v2_sparse_classes_30k_train_013466
Implement the Python class `MhpLoss` described below. Class description: Defines Christian Rupprecht's multiple-hypothesis loss function. This one operates on multiple hypothesis samples. This version is designed for use with data of one type of output (e.g. an image). ArXiv: https://arxiv.org/pdf/1612.00197.pdf BibTe...
Implement the Python class `MhpLoss` described below. Class description: Defines Christian Rupprecht's multiple-hypothesis loss function. This one operates on multiple hypothesis samples. This version is designed for use with data of one type of output (e.g. an image). ArXiv: https://arxiv.org/pdf/1612.00197.pdf BibTe...
be5c12f9d0e9d7078e6a5c283d3be059e7f3d040
<|skeleton|> class MhpLoss: """Defines Christian Rupprecht's multiple-hypothesis loss function. This one operates on multiple hypothesis samples. This version is designed for use with data of one type of output (e.g. an image). ArXiv: https://arxiv.org/pdf/1612.00197.pdf BibTex: @article{rupprecht2016learning, titl...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MhpLoss: """Defines Christian Rupprecht's multiple-hypothesis loss function. This one operates on multiple hypothesis samples. This version is designed for use with data of one type of output (e.g. an image). ArXiv: https://arxiv.org/pdf/1612.00197.pdf BibTex: @article{rupprecht2016learning, title={Learning i...
the_stack_v2_python_sparse
costar_models/python/costar_models/mhp_loss.py
lk-greenbird/costar_plan
train
0
635ad4768cf13bec200f6106ce658b5a27427f5a
[ "self.log = _logging.create_logger(self.__class__.__name__)\nif not isinstance(fs, FileSystem):\n raise Exception('Parameter is no Filesystem.')\nself.fs = fs", "fuse_log = _logging.create_logger('pyfuse3', self.fs.debug)\nfuse_options = set(pyfuse3.default_options)\nfuse_options.add('fsname=' + self.fs.__clas...
<|body_start_0|> self.log = _logging.create_logger(self.__class__.__name__) if not isinstance(fs, FileSystem): raise Exception('Parameter is no Filesystem.') self.fs = fs <|end_body_0|> <|body_start_1|> fuse_log = _logging.create_logger('pyfuse3', self.fs.debug) fuse...
FileSystemStarter starts a class inheriting FileSystem with trio. ... Attributes ---------- fs : iotfs.filesystem.fs.FileSystem a filesystem object inheriting from FileSystem Methods ------- start() starts a pyfuse3 filesystem with different options Raises ------ Exception If fs is no instance of FileSystem, this error...
FileSystemStarter
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FileSystemStarter: """FileSystemStarter starts a class inheriting FileSystem with trio. ... Attributes ---------- fs : iotfs.filesystem.fs.FileSystem a filesystem object inheriting from FileSystem Methods ------- start() starts a pyfuse3 filesystem with different options Raises ------ Exception I...
stack_v2_sparse_classes_75kplus_train_065633
4,037
permissive
[ { "docstring": "Parameters ---------- fs : iotfs.filesystem.fs.FileSystem a filesystem object inheriting from FileSystem", "name": "__init__", "signature": "def __init__(self, fs)" }, { "docstring": "Starts a pyfuse3 filesystem with different options. Raises ------ FUSEError If a FUSEError occur...
2
stack_v2_sparse_classes_30k_train_049008
Implement the Python class `FileSystemStarter` described below. Class description: FileSystemStarter starts a class inheriting FileSystem with trio. ... Attributes ---------- fs : iotfs.filesystem.fs.FileSystem a filesystem object inheriting from FileSystem Methods ------- start() starts a pyfuse3 filesystem with diff...
Implement the Python class `FileSystemStarter` described below. Class description: FileSystemStarter starts a class inheriting FileSystem with trio. ... Attributes ---------- fs : iotfs.filesystem.fs.FileSystem a filesystem object inheriting from FileSystem Methods ------- start() starts a pyfuse3 filesystem with diff...
e25f91d2fa49a251e7c1f7d7263357962afbe09e
<|skeleton|> class FileSystemStarter: """FileSystemStarter starts a class inheriting FileSystem with trio. ... Attributes ---------- fs : iotfs.filesystem.fs.FileSystem a filesystem object inheriting from FileSystem Methods ------- start() starts a pyfuse3 filesystem with different options Raises ------ Exception I...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FileSystemStarter: """FileSystemStarter starts a class inheriting FileSystem with trio. ... Attributes ---------- fs : iotfs.filesystem.fs.FileSystem a filesystem object inheriting from FileSystem Methods ------- start() starts a pyfuse3 filesystem with different options Raises ------ Exception If fs is no in...
the_stack_v2_python_sparse
iotfs/filesystem/fs.py
Th-Os/IoTFS
train
3
c32c09686ac1c33045eb45e481382250bc925336
[ "try:\n enc = binascii.b2a_base64(pickle.dumps(raw, -1))\n if settings.ENABLE_INTERNAL_ENCRYPTION:\n iv = binascii.b2a_hex(os.urandom(8))\n cipher = AES.new(key, AES.MODE_CBC, iv)\n enc = binascii.b2a_base64(cipher.encrypt(pad(enc)))\n return '%s/%s' % (iv.decode('utf-8'), enc.deco...
<|body_start_0|> try: enc = binascii.b2a_base64(pickle.dumps(raw, -1)) if settings.ENABLE_INTERNAL_ENCRYPTION: iv = binascii.b2a_hex(os.urandom(8)) cipher = AES.new(key, AES.MODE_CBC, iv) enc = binascii.b2a_base64(cipher.encrypt(pad(enc))) ...
AES encryption backend
AESEncryption
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AESEncryption: """AES encryption backend""" def encrypt_to_b64(raw): """encrypt and b64-encode data""" <|body_0|> def decrypt_from_b64(enc): """decrypt b64-encoded data""" <|body_1|> <|end_skeleton|> <|body_start_0|> try: enc = binas...
stack_v2_sparse_classes_75kplus_train_065634
2,178
permissive
[ { "docstring": "encrypt and b64-encode data", "name": "encrypt_to_b64", "signature": "def encrypt_to_b64(raw)" }, { "docstring": "decrypt b64-encoded data", "name": "decrypt_from_b64", "signature": "def decrypt_from_b64(enc)" } ]
2
stack_v2_sparse_classes_30k_train_015913
Implement the Python class `AESEncryption` described below. Class description: AES encryption backend Method signatures and docstrings: - def encrypt_to_b64(raw): encrypt and b64-encode data - def decrypt_from_b64(enc): decrypt b64-encoded data
Implement the Python class `AESEncryption` described below. Class description: AES encryption backend Method signatures and docstrings: - def encrypt_to_b64(raw): encrypt and b64-encode data - def decrypt_from_b64(enc): decrypt b64-encoded data <|skeleton|> class AESEncryption: """AES encryption backend""" ...
27a23ce47e3ec11b94f3355c2d2ee94c1958679c
<|skeleton|> class AESEncryption: """AES encryption backend""" def encrypt_to_b64(raw): """encrypt and b64-encode data""" <|body_0|> def decrypt_from_b64(enc): """decrypt b64-encoded data""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AESEncryption: """AES encryption backend""" def encrypt_to_b64(raw): """encrypt and b64-encode data""" try: enc = binascii.b2a_base64(pickle.dumps(raw, -1)) if settings.ENABLE_INTERNAL_ENCRYPTION: iv = binascii.b2a_hex(os.urandom(8)) ...
the_stack_v2_python_sparse
will/backends/encryption/aes.py
skoczen/will
train
359
ae6021b612bae973f4595fac665cb6c06530f859
[ "self = self.filter(cancelled=False, end_datetime__gt=timezone.now())\nif current_term_only:\n self = self.filter(term=Term.objects.get_current_term())\nreturn self", "user_level = Event.get_user_restriction_level(user)\nvisible_levels = list(Event.VISIBLE_TO_EVERYONE)\nif user_level >= Event.MEMBER:\n visi...
<|body_start_0|> self = self.filter(cancelled=False, end_datetime__gt=timezone.now()) if current_term_only: self = self.filter(term=Term.objects.get_current_term()) return self <|end_body_0|> <|body_start_1|> user_level = Event.get_user_restriction_level(user) visibl...
EventQuerySet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EventQuerySet: def get_upcoming(self, current_term_only=True): """Return events that haven't been cancelled and haven't yet ended. If current_term_only is True, the method returns only upcoming events in the current term. Otherwise, the method returns upcoming events from all terms.""" ...
stack_v2_sparse_classes_75kplus_train_065635
16,435
no_license
[ { "docstring": "Return events that haven't been cancelled and haven't yet ended. If current_term_only is True, the method returns only upcoming events in the current term. Otherwise, the method returns upcoming events from all terms.", "name": "get_upcoming", "signature": "def get_upcoming(self, current...
2
null
Implement the Python class `EventQuerySet` described below. Class description: Implement the EventQuerySet class. Method signatures and docstrings: - def get_upcoming(self, current_term_only=True): Return events that haven't been cancelled and haven't yet ended. If current_term_only is True, the method returns only u...
Implement the Python class `EventQuerySet` described below. Class description: Implement the EventQuerySet class. Method signatures and docstrings: - def get_upcoming(self, current_term_only=True): Return events that haven't been cancelled and haven't yet ended. If current_term_only is True, the method returns only u...
1dfccb7d79c7be23e2982906fa968243709a95cd
<|skeleton|> class EventQuerySet: def get_upcoming(self, current_term_only=True): """Return events that haven't been cancelled and haven't yet ended. If current_term_only is True, the method returns only upcoming events in the current term. Otherwise, the method returns upcoming events from all terms.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EventQuerySet: def get_upcoming(self, current_term_only=True): """Return events that haven't been cancelled and haven't yet ended. If current_term_only is True, the method returns only upcoming events in the current term. Otherwise, the method returns upcoming events from all terms.""" self = ...
the_stack_v2_python_sparse
events/models.py
TBP-IT/tbpweb
train
3
6a929c41716787a2e354326a60154e1c5e25975e
[ "conn, cursor = get_db_cursor()\nbuild = 'toy_build'\ndatabase = 'scratch/toy.db'\ntalon.get_counters(database)\ninit_refs.make_temp_novel_gene_table(cursor, build)\ninit_refs.make_temp_monoexonic_transcript_table(cursor, build)\nedge_dict = init_refs.make_edge_dict(cursor)\nlocation_dict = init_refs.make_location_...
<|body_start_0|> conn, cursor = get_db_cursor() build = 'toy_build' database = 'scratch/toy.db' talon.get_counters(database) init_refs.make_temp_novel_gene_table(cursor, build) init_refs.make_temp_monoexonic_transcript_table(cursor, build) edge_dict = init_refs.ma...
TestIdentifyMonoexonic
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestIdentifyMonoexonic: def test_match(self): """Example where the transcript is a monoexonic match.""" <|body_0|> def test_partial_match(self): """Example where the transcript overlaps a single-exon transcript, but is shorter. In the past, the start would be assigne...
stack_v2_sparse_classes_75kplus_train_065636
9,789
permissive
[ { "docstring": "Example where the transcript is a monoexonic match.", "name": "test_match", "signature": "def test_match(self)" }, { "docstring": "Example where the transcript overlaps a single-exon transcript, but is shorter. In the past, the start would be assigned to the annotated start, and ...
3
null
Implement the Python class `TestIdentifyMonoexonic` described below. Class description: Implement the TestIdentifyMonoexonic class. Method signatures and docstrings: - def test_match(self): Example where the transcript is a monoexonic match. - def test_partial_match(self): Example where the transcript overlaps a sing...
Implement the Python class `TestIdentifyMonoexonic` described below. Class description: Implement the TestIdentifyMonoexonic class. Method signatures and docstrings: - def test_match(self): Example where the transcript is a monoexonic match. - def test_partial_match(self): Example where the transcript overlaps a sing...
8014faed5f982e5e106ec05239e47d65878e76c3
<|skeleton|> class TestIdentifyMonoexonic: def test_match(self): """Example where the transcript is a monoexonic match.""" <|body_0|> def test_partial_match(self): """Example where the transcript overlaps a single-exon transcript, but is shorter. In the past, the start would be assigne...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestIdentifyMonoexonic: def test_match(self): """Example where the transcript is a monoexonic match.""" conn, cursor = get_db_cursor() build = 'toy_build' database = 'scratch/toy.db' talon.get_counters(database) init_refs.make_temp_novel_gene_table(cursor, build...
the_stack_v2_python_sparse
testing_suite/test_monoexonic.py
kopardev/TALON
train
0
11fb5c875972a220de7a8c96c598ebb8c1cf0976
[ "with self.subTest('both custom columns'), TemporaryDirectory() as tmpdir:\n convert(self.path / 'wrapped.fasta', Path(tmpdir) / 'unwrapped.csv', colmap={'sequence_id': 'SeqID', 'sequence': 'Seq'})\n self.assertTxtsMatch(self.path / 'unwrapped.csv', Path(tmpdir) / 'unwrapped.csv')\nwith self.subTest('one cust...
<|body_start_0|> with self.subTest('both custom columns'), TemporaryDirectory() as tmpdir: convert(self.path / 'wrapped.fasta', Path(tmpdir) / 'unwrapped.csv', colmap={'sequence_id': 'SeqID', 'sequence': 'Seq'}) self.assertTxtsMatch(self.path / 'unwrapped.csv', Path(tmpdir) / 'unwrapped....
Test that convert(..., colmap=...) can customize column names used.
TestConvertCustomCols
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestConvertCustomCols: """Test that convert(..., colmap=...) can customize column names used.""" def test_convert_fa_csv(self): """Test converting fasta to csv. There should be three columns of output, (sequence IDs, sequences, and sequence descriptions) with custom column names as g...
stack_v2_sparse_classes_75kplus_train_065637
17,106
no_license
[ { "docstring": "Test converting fasta to csv. There should be three columns of output, (sequence IDs, sequences, and sequence descriptions) with custom column names as given.", "name": "test_convert_fa_csv", "signature": "def test_convert_fa_csv(self)" }, { "docstring": "Test converting fasta to...
5
null
Implement the Python class `TestConvertCustomCols` described below. Class description: Test that convert(..., colmap=...) can customize column names used. Method signatures and docstrings: - def test_convert_fa_csv(self): Test converting fasta to csv. There should be three columns of output, (sequence IDs, sequences,...
Implement the Python class `TestConvertCustomCols` described below. Class description: Test that convert(..., colmap=...) can customize column names used. Method signatures and docstrings: - def test_convert_fa_csv(self): Test converting fasta to csv. There should be three columns of output, (sequence IDs, sequences,...
539868dab2041b7694c0d53e8e74cf1b5b033653
<|skeleton|> class TestConvertCustomCols: """Test that convert(..., colmap=...) can customize column names used.""" def test_convert_fa_csv(self): """Test converting fasta to csv. There should be three columns of output, (sequence IDs, sequences, and sequence descriptions) with custom column names as g...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestConvertCustomCols: """Test that convert(..., colmap=...) can customize column names used.""" def test_convert_fa_csv(self): """Test converting fasta to csv. There should be three columns of output, (sequence IDs, sequences, and sequence descriptions) with custom column names as given.""" ...
the_stack_v2_python_sparse
test_igseq/test_convert.py
ShawHahnLab/igseq
train
1
808d252ab54980d4d84b93b442782fc2eff4377d
[ "base, regression = build_function(idx, exdir)\nbase.write_simulation()\nif regression is not None:\n if isinstance(regression, flopy.mf6.MFSimulation):\n regression.write_simulation()\n else:\n regression.write_input()", "sim.set_model(sim.name if workspace is None else workspace, testModel=F...
<|body_start_0|> base, regression = build_function(idx, exdir) base.write_simulation() if regression is not None: if isinstance(regression, flopy.mf6.MFSimulation): regression.write_simulation() else: regression.write_input() <|end_body_0|>...
TestFramework
[ "LicenseRef-scancode-warranty-disclaimer", "CC0-1.0", "LicenseRef-scancode-public-domain" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestFramework: def build(self, build_function, idx, exdir): """Build base and regression MODFLOW 6 models Parameters ---------- build_function : function user defined function that builds a base model and optionally builds a regression model. If a regression model is not built then None ...
stack_v2_sparse_classes_75kplus_train_065638
1,742
permissive
[ { "docstring": "Build base and regression MODFLOW 6 models Parameters ---------- build_function : function user defined function that builds a base model and optionally builds a regression model. If a regression model is not built then None must be returned from the function for the regression model. idx : int ...
2
stack_v2_sparse_classes_30k_train_051554
Implement the Python class `TestFramework` described below. Class description: Implement the TestFramework class. Method signatures and docstrings: - def build(self, build_function, idx, exdir): Build base and regression MODFLOW 6 models Parameters ---------- build_function : function user defined function that build...
Implement the Python class `TestFramework` described below. Class description: Implement the TestFramework class. Method signatures and docstrings: - def build(self, build_function, idx, exdir): Build base and regression MODFLOW 6 models Parameters ---------- build_function : function user defined function that build...
43f6198125867c487eedc64b17e9adaceb73f5ab
<|skeleton|> class TestFramework: def build(self, build_function, idx, exdir): """Build base and regression MODFLOW 6 models Parameters ---------- build_function : function user defined function that builds a base model and optionally builds a regression model. If a regression model is not built then None ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestFramework: def build(self, build_function, idx, exdir): """Build base and regression MODFLOW 6 models Parameters ---------- build_function : function user defined function that builds a base model and optionally builds a regression model. If a regression model is not built then None must be return...
the_stack_v2_python_sparse
autotest/framework.py
MODFLOW-USGS/modflow6
train
158
33202def949b6f0c4f47c192c311bcf208bb4293
[ "super().__init__(coordinator)\nself.entity_description = description\nself.coordinator = coordinator\nself._entry_id = entry_id\nself._attrs: dict[str, Any] = {}\n_id = coordinator.data.iata\nself._attr_name = f'{_id} {description.name}'\nself._attr_unique_id = f'{_id}_{description.key}'", "sensor_type = self.en...
<|body_start_0|> super().__init__(coordinator) self.entity_description = description self.coordinator = coordinator self._entry_id = entry_id self._attrs: dict[str, Any] = {} _id = coordinator.data.iata self._attr_name = f'{_id} {description.name}' self._a...
Define a binary sensor for FAA Delays.
FAABinarySensor
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FAABinarySensor: """Define a binary sensor for FAA Delays.""" def __init__(self, coordinator, entry_id, description: BinarySensorEntityDescription) -> None: """Initialize the sensor.""" <|body_0|> def is_on(self): """Return the status of the sensor.""" <|...
stack_v2_sparse_classes_75kplus_train_065639
3,718
permissive
[ { "docstring": "Initialize the sensor.", "name": "__init__", "signature": "def __init__(self, coordinator, entry_id, description: BinarySensorEntityDescription) -> None" }, { "docstring": "Return the status of the sensor.", "name": "is_on", "signature": "def is_on(self)" }, { "do...
3
stack_v2_sparse_classes_30k_train_006169
Implement the Python class `FAABinarySensor` described below. Class description: Define a binary sensor for FAA Delays. Method signatures and docstrings: - def __init__(self, coordinator, entry_id, description: BinarySensorEntityDescription) -> None: Initialize the sensor. - def is_on(self): Return the status of the ...
Implement the Python class `FAABinarySensor` described below. Class description: Define a binary sensor for FAA Delays. Method signatures and docstrings: - def __init__(self, coordinator, entry_id, description: BinarySensorEntityDescription) -> None: Initialize the sensor. - def is_on(self): Return the status of the ...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class FAABinarySensor: """Define a binary sensor for FAA Delays.""" def __init__(self, coordinator, entry_id, description: BinarySensorEntityDescription) -> None: """Initialize the sensor.""" <|body_0|> def is_on(self): """Return the status of the sensor.""" <|...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FAABinarySensor: """Define a binary sensor for FAA Delays.""" def __init__(self, coordinator, entry_id, description: BinarySensorEntityDescription) -> None: """Initialize the sensor.""" super().__init__(coordinator) self.entity_description = description self.coordinator = ...
the_stack_v2_python_sparse
homeassistant/components/faa_delays/binary_sensor.py
home-assistant/core
train
35,501
e10bda90efa0a61cb2cf5c5821a1e72daa27f713
[ "for row in matrix:\n for el in row:\n print(str(el).rjust(2), end=' ')\n print()", "if m == 1 or n == 1:\n return 1\nreturn self.unique_paths(m - 1, n) + self.unique_paths(m, n - 1)", "results = [[1] * n for i in range(m)]\nfor i in range(1, m):\n for j in range(1, n):\n results[i][j]...
<|body_start_0|> for row in matrix: for el in row: print(str(el).rjust(2), end=' ') print() <|end_body_0|> <|body_start_1|> if m == 1 or n == 1: return 1 return self.unique_paths(m - 1, n) + self.unique_paths(m, n - 1) <|end_body_1|> <|body_s...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def display(self, matrix): """Prints out 2D array.""" <|body_0|> def unique_paths_rec(self, m, n): """Recursive solution. Exponential running time, not efficient.""" <|body_1|> def unique_paths_dp(self, m, n): """Dynamic programming sol...
stack_v2_sparse_classes_75kplus_train_065640
2,386
no_license
[ { "docstring": "Prints out 2D array.", "name": "display", "signature": "def display(self, matrix)" }, { "docstring": "Recursive solution. Exponential running time, not efficient.", "name": "unique_paths_rec", "signature": "def unique_paths_rec(self, m, n)" }, { "docstring": "Dyna...
4
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def display(self, matrix): Prints out 2D array. - def unique_paths_rec(self, m, n): Recursive solution. Exponential running time, not efficient. - def unique_paths_dp(self, m, n)...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def display(self, matrix): Prints out 2D array. - def unique_paths_rec(self, m, n): Recursive solution. Exponential running time, not efficient. - def unique_paths_dp(self, m, n)...
71b722ddfe8da04572e527b055cf8723d5c87bbf
<|skeleton|> class Solution: def display(self, matrix): """Prints out 2D array.""" <|body_0|> def unique_paths_rec(self, m, n): """Recursive solution. Exponential running time, not efficient.""" <|body_1|> def unique_paths_dp(self, m, n): """Dynamic programming sol...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def display(self, matrix): """Prints out 2D array.""" for row in matrix: for el in row: print(str(el).rjust(2), end=' ') print() def unique_paths_rec(self, m, n): """Recursive solution. Exponential running time, not efficient.""" ...
the_stack_v2_python_sparse
Dynamic_programming/unique_paths.py
vladn90/Algorithms
train
0
63b0f1dbd63763c55f9ef85e0e234148d8b29108
[ "self.env = env\nself.LOCATION = loc\nself.RECHARGE_SPEED = 0.01", "maxDistance = simTime / 60 * 35 * 2\ndistCovered = 0\nrechargeStations = [RechargeStation(env, 0)]\nwhile distCovered < maxDistance:\n nextStation = np.random.randint(80, 140)\n distCovered += nextStation\n rechargeStations.append(Rechar...
<|body_start_0|> self.env = env self.LOCATION = loc self.RECHARGE_SPEED = 0.01 <|end_body_0|> <|body_start_1|> maxDistance = simTime / 60 * 35 * 2 distCovered = 0 rechargeStations = [RechargeStation(env, 0)] while distCovered < maxDistance: nextStatio...
定义充电站的类
RechargeStation
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RechargeStation: """定义充电站的类""" def __init__(self, env, loc): """主函数 @param env -- 环境 变量 @param loc -- 充电站的位置""" <|body_0|> def generateRechargeStations(simTime): """沿途随机放置充电站,距离范围 80 ~ 140英里 @param simTime -- 模拟时间""" <|body_1|> <|end_skeleton|> <|body_s...
stack_v2_sparse_classes_75kplus_train_065641
7,580
no_license
[ { "docstring": "主函数 @param env -- 环境 变量 @param loc -- 充电站的位置", "name": "__init__", "signature": "def __init__(self, env, loc)" }, { "docstring": "沿途随机放置充电站,距离范围 80 ~ 140英里 @param simTime -- 模拟时间", "name": "generateRechargeStations", "signature": "def generateRechargeStations(simTime)" ...
2
stack_v2_sparse_classes_30k_train_041048
Implement the Python class `RechargeStation` described below. Class description: 定义充电站的类 Method signatures and docstrings: - def __init__(self, env, loc): 主函数 @param env -- 环境 变量 @param loc -- 充电站的位置 - def generateRechargeStations(simTime): 沿途随机放置充电站,距离范围 80 ~ 140英里 @param simTime -- 模拟时间
Implement the Python class `RechargeStation` described below. Class description: 定义充电站的类 Method signatures and docstrings: - def __init__(self, env, loc): 主函数 @param env -- 环境 变量 @param loc -- 充电站的位置 - def generateRechargeStations(simTime): 沿途随机放置充电站,距离范围 80 ~ 140英里 @param simTime -- 模拟时间 <|skeleton|> class Recharge...
cc30938f4e5e51041de414fa26fbbe1a545959d8
<|skeleton|> class RechargeStation: """定义充电站的类""" def __init__(self, env, loc): """主函数 @param env -- 环境 变量 @param loc -- 充电站的位置""" <|body_0|> def generateRechargeStations(simTime): """沿途随机放置充电站,距离范围 80 ~ 140英里 @param simTime -- 模拟时间""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RechargeStation: """定义充电站的类""" def __init__(self, env, loc): """主函数 @param env -- 环境 变量 @param loc -- 充电站的位置""" self.env = env self.LOCATION = loc self.RECHARGE_SPEED = 0.01 def generateRechargeStations(simTime): """沿途随机放置充电站,距离范围 80 ~ 140英里 @param simTime -- ...
the_stack_v2_python_sparse
数据分析与机器学习/数据分析实战/模拟/模拟电动车耗尽电量的最大行驶里程.py
Cedric-Chan/Script_of_Data_Analysis
train
3
f6a2d4ef95c0345b2b75a984cfd91cf6ad9c2d3b
[ "length_a = len(A)\nlength_b = len(B)\nif length_a >= length_b:\n repeat = 1\nelse:\n repeat = int(length_b / length_a)\nmax_repeat = len(B) / len(A) + 3\ns = A * repeat\nwhile repeat < max_repeat:\n if s.find(B) >= 0:\n return repeat\n s += A\n repeat += 1\nreturn -1", "if not B or A.find(B...
<|body_start_0|> length_a = len(A) length_b = len(B) if length_a >= length_b: repeat = 1 else: repeat = int(length_b / length_a) max_repeat = len(B) / len(A) + 3 s = A * repeat while repeat < max_repeat: if s.find(B) >= 0: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def repeatedStringMatch1(self, A, B): """:type A: str :type B: str :rtype: int""" <|body_0|> def repeatedStringMatch(self, A, B): """:type A: str :type B: str :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> length_a = len(A) ...
stack_v2_sparse_classes_75kplus_train_065642
1,356
no_license
[ { "docstring": ":type A: str :type B: str :rtype: int", "name": "repeatedStringMatch1", "signature": "def repeatedStringMatch1(self, A, B)" }, { "docstring": ":type A: str :type B: str :rtype: int", "name": "repeatedStringMatch", "signature": "def repeatedStringMatch(self, A, B)" } ]
2
stack_v2_sparse_classes_30k_train_010455
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def repeatedStringMatch1(self, A, B): :type A: str :type B: str :rtype: int - def repeatedStringMatch(self, A, B): :type A: str :type B: str :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def repeatedStringMatch1(self, A, B): :type A: str :type B: str :rtype: int - def repeatedStringMatch(self, A, B): :type A: str :type B: str :rtype: int <|skeleton|> class Solut...
70bdd75b6af2e1811c1beab22050c01d28d7373e
<|skeleton|> class Solution: def repeatedStringMatch1(self, A, B): """:type A: str :type B: str :rtype: int""" <|body_0|> def repeatedStringMatch(self, A, B): """:type A: str :type B: str :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def repeatedStringMatch1(self, A, B): """:type A: str :type B: str :rtype: int""" length_a = len(A) length_b = len(B) if length_a >= length_b: repeat = 1 else: repeat = int(length_b / length_a) max_repeat = len(B) / len(A) + 3 ...
the_stack_v2_python_sparse
python/leetcode_bak/686_Repeated_String_Match.py
bobcaoge/my-code
train
0
e0938ab0e8efea66f7cba7e4fd1d826450c2609d
[ "super().__init__(parameter_dictionary)\nself.model_string = 'jimenez'\nmodel_dictionary = parameter_dictionary[self.model_string]\nself.ad = float(model_dictionary['ad'])\nself.kd = float(model_dictionary['kd'])\nself.bd = float(model_dictionary['bd'])", "xi_init = cosd(turbine.yaw_angle) * sind(turbine.yaw_angl...
<|body_start_0|> super().__init__(parameter_dictionary) self.model_string = 'jimenez' model_dictionary = parameter_dictionary[self.model_string] self.ad = float(model_dictionary['ad']) self.kd = float(model_dictionary['kd']) self.bd = float(model_dictionary['bd']) <|end_b...
Subclass of the :py:class:`floris.simulation.wake_deflection.WakeDeflection` object class. Parameters required for Jimenez wake model: - ad: #TODO What is this parameter for? - kd: #TODO What is this parameter for? - bd: #TODO What is this parameter for?
Jimenez
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Jimenez: """Subclass of the :py:class:`floris.simulation.wake_deflection.WakeDeflection` object class. Parameters required for Jimenez wake model: - ad: #TODO What is this parameter for? - kd: #TODO What is this parameter for? - bd: #TODO What is this parameter for?""" def __init__(self, par...
stack_v2_sparse_classes_75kplus_train_065643
10,947
permissive
[ { "docstring": "Instantiate Jimenez object and pass function paramter values. Args: parameter_dictionary (dict): input dictionary with the following key-value pairs: { \"kd\": 0.05, \"ad\": 0.0, \"bd\": 0.0 }", "name": "__init__", "signature": "def __init__(self, parameter_dictionary)" }, { "doc...
2
stack_v2_sparse_classes_30k_train_052473
Implement the Python class `Jimenez` described below. Class description: Subclass of the :py:class:`floris.simulation.wake_deflection.WakeDeflection` object class. Parameters required for Jimenez wake model: - ad: #TODO What is this parameter for? - kd: #TODO What is this parameter for? - bd: #TODO What is this parame...
Implement the Python class `Jimenez` described below. Class description: Subclass of the :py:class:`floris.simulation.wake_deflection.WakeDeflection` object class. Parameters required for Jimenez wake model: - ad: #TODO What is this parameter for? - kd: #TODO What is this parameter for? - bd: #TODO What is this parame...
85f2a56fa0ab7c2237d308690a554c6101dbcd34
<|skeleton|> class Jimenez: """Subclass of the :py:class:`floris.simulation.wake_deflection.WakeDeflection` object class. Parameters required for Jimenez wake model: - ad: #TODO What is this parameter for? - kd: #TODO What is this parameter for? - bd: #TODO What is this parameter for?""" def __init__(self, par...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Jimenez: """Subclass of the :py:class:`floris.simulation.wake_deflection.WakeDeflection` object class. Parameters required for Jimenez wake model: - ad: #TODO What is this parameter for? - kd: #TODO What is this parameter for? - bd: #TODO What is this parameter for?""" def __init__(self, parameter_dictio...
the_stack_v2_python_sparse
floris/simulation/wake_deflection.py
PStanfel/floris
train
3
fedbe2bccf489f778cba98d6ebc58fa8915e9ab3
[ "if not points:\n return 0\npoints.sort()\nres = 1\nl, r = points[0]\nfor i in range(1, len(points)):\n ll, rr = points[i]\n if ll > r:\n res += 1\n r = rr\n else:\n r = min(r, rr)\nreturn res", "if not points:\n return 0\npoints.sort(key=lambda x: x[1])\nres = 1\nl, r = points...
<|body_start_0|> if not points: return 0 points.sort() res = 1 l, r = points[0] for i in range(1, len(points)): ll, rr = points[i] if ll > r: res += 1 r = rr else: r = min(r, rr) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findMinArrowShots(self, points: List[List[int]]) -> int: """思路:贪心算法 1. 按照起点从小到大排序,如果新的区间的起点ll小于当前区间的终点r,就缩小区间r = min(r, rr),令r等于当前区间和新区间终点的最小值 2. 如果新区间的起点ll大于当前区间的终点,则需要新的箭,res+1,同时设置新的区间的终点r @param points: @return:""" <|body_0|> def findMinArrowShots2(self, po...
stack_v2_sparse_classes_75kplus_train_065644
2,714
no_license
[ { "docstring": "思路:贪心算法 1. 按照起点从小到大排序,如果新的区间的起点ll小于当前区间的终点r,就缩小区间r = min(r, rr),令r等于当前区间和新区间终点的最小值 2. 如果新区间的起点ll大于当前区间的终点,则需要新的箭,res+1,同时设置新的区间的终点r @param points: @return:", "name": "findMinArrowShots", "signature": "def findMinArrowShots(self, points: List[List[int]]) -> int" }, { "docstring": ...
2
stack_v2_sparse_classes_30k_train_045327
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findMinArrowShots(self, points: List[List[int]]) -> int: 思路:贪心算法 1. 按照起点从小到大排序,如果新的区间的起点ll小于当前区间的终点r,就缩小区间r = min(r, rr),令r等于当前区间和新区间终点的最小值 2. 如果新区间的起点ll大于当前区间的终点,则需要新的箭,res+...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findMinArrowShots(self, points: List[List[int]]) -> int: 思路:贪心算法 1. 按照起点从小到大排序,如果新的区间的起点ll小于当前区间的终点r,就缩小区间r = min(r, rr),令r等于当前区间和新区间终点的最小值 2. 如果新区间的起点ll大于当前区间的终点,则需要新的箭,res+...
e43ee86c5a8cdb808da09b4b6138e10275abadb5
<|skeleton|> class Solution: def findMinArrowShots(self, points: List[List[int]]) -> int: """思路:贪心算法 1. 按照起点从小到大排序,如果新的区间的起点ll小于当前区间的终点r,就缩小区间r = min(r, rr),令r等于当前区间和新区间终点的最小值 2. 如果新区间的起点ll大于当前区间的终点,则需要新的箭,res+1,同时设置新的区间的终点r @param points: @return:""" <|body_0|> def findMinArrowShots2(self, po...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def findMinArrowShots(self, points: List[List[int]]) -> int: """思路:贪心算法 1. 按照起点从小到大排序,如果新的区间的起点ll小于当前区间的终点r,就缩小区间r = min(r, rr),令r等于当前区间和新区间终点的最小值 2. 如果新区间的起点ll大于当前区间的终点,则需要新的箭,res+1,同时设置新的区间的终点r @param points: @return:""" if not points: return 0 points.sort() ...
the_stack_v2_python_sparse
LeetCode/贪心算法/452. 用最少数量的箭引爆气球.py
yiming1012/MyLeetCode
train
2
21e8d5a6898928e2152dbd0ef0a141912c4d703d
[ "if self.action in ['create', 'list']:\n permission_classes = [permissions.IsUserFromUnitReferralRequesters | permissions.IsRequestReferralLinkedUser | permissions.IsRequestReferralLinkedUnitMember]\nelif self.action in ['retrieve']:\n permission_classes = [permissions.IsLinkedReferralLinkedUser | permissions...
<|body_start_0|> if self.action in ['create', 'list']: permission_classes = [permissions.IsUserFromUnitReferralRequesters | permissions.IsRequestReferralLinkedUser | permissions.IsRequestReferralLinkedUnitMember] elif self.action in ['retrieve']: permission_classes = [permissions...
API endpoints for referral messages.
ReferralMessageViewSet
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReferralMessageViewSet: """API endpoints for referral messages.""" def get_permissions(self): """Manage permissions for default methods separately, delegating to @action defined permissions for other actions.""" <|body_0|> def create(self, request, *args, **kwargs): ...
stack_v2_sparse_classes_75kplus_train_065645
4,228
permissive
[ { "docstring": "Manage permissions for default methods separately, delegating to @action defined permissions for other actions.", "name": "get_permissions", "signature": "def get_permissions(self)" }, { "docstring": "Create a new referral message as the client issues a POST on the referralmessag...
3
stack_v2_sparse_classes_30k_train_041574
Implement the Python class `ReferralMessageViewSet` described below. Class description: API endpoints for referral messages. Method signatures and docstrings: - def get_permissions(self): Manage permissions for default methods separately, delegating to @action defined permissions for other actions. - def create(self,...
Implement the Python class `ReferralMessageViewSet` described below. Class description: API endpoints for referral messages. Method signatures and docstrings: - def get_permissions(self): Manage permissions for default methods separately, delegating to @action defined permissions for other actions. - def create(self,...
22e4afa728a851bb4c2479fbb6f5944a75984b9b
<|skeleton|> class ReferralMessageViewSet: """API endpoints for referral messages.""" def get_permissions(self): """Manage permissions for default methods separately, delegating to @action defined permissions for other actions.""" <|body_0|> def create(self, request, *args, **kwargs): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ReferralMessageViewSet: """API endpoints for referral messages.""" def get_permissions(self): """Manage permissions for default methods separately, delegating to @action defined permissions for other actions.""" if self.action in ['create', 'list']: permission_classes = [permi...
the_stack_v2_python_sparse
src/backend/partaj/core/api/referral_message.py
MTES-MCT/partaj
train
4
d277cc6819383f75eb9462fb8f06f3b66478069b
[ "self.client = Client()\nself.test_user = User.objects.create_user('testuser', 'blah@blah.com', 'testpassword')\nself.test_user.is_superuser = True\nself.test_user.is_active = True\nself.test_user.save()\nself.assertEqual(self.test_user.is_superuser, True)\nlogin = self.client.login(username='testuser', password='t...
<|body_start_0|> self.client = Client() self.test_user = User.objects.create_user('testuser', 'blah@blah.com', 'testpassword') self.test_user.is_superuser = True self.test_user.is_active = True self.test_user.save() self.assertEqual(self.test_user.is_superuser, True) ...
This class tests the views for the base :mod:`~mousedb.veterinary` app.
VeterinaryViewTests
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VeterinaryViewTests: """This class tests the views for the base :mod:`~mousedb.veterinary` app.""" def setUp(self): """Instantiate the test client. Creates a test user.""" <|body_0|> def tearDown(self): """Depopulate created model instances from test database."""...
stack_v2_sparse_classes_75kplus_train_065646
26,324
permissive
[ { "docstring": "Instantiate the test client. Creates a test user.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Depopulate created model instances from test database.", "name": "tearDown", "signature": "def tearDown(self)" }, { "docstring": "This tests the ...
3
null
Implement the Python class `VeterinaryViewTests` described below. Class description: This class tests the views for the base :mod:`~mousedb.veterinary` app. Method signatures and docstrings: - def setUp(self): Instantiate the test client. Creates a test user. - def tearDown(self): Depopulate created model instances f...
Implement the Python class `VeterinaryViewTests` described below. Class description: This class tests the views for the base :mod:`~mousedb.veterinary` app. Method signatures and docstrings: - def setUp(self): Instantiate the test client. Creates a test user. - def tearDown(self): Depopulate created model instances f...
7e423991f72c89468010c99865e3c70c22044df3
<|skeleton|> class VeterinaryViewTests: """This class tests the views for the base :mod:`~mousedb.veterinary` app.""" def setUp(self): """Instantiate the test client. Creates a test user.""" <|body_0|> def tearDown(self): """Depopulate created model instances from test database."""...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class VeterinaryViewTests: """This class tests the views for the base :mod:`~mousedb.veterinary` app.""" def setUp(self): """Instantiate the test client. Creates a test user.""" self.client = Client() self.test_user = User.objects.create_user('testuser', 'blah@blah.com', 'testpassword')...
the_stack_v2_python_sparse
mousedb/veterinary/tests.py
BridgesLab/mousedb
train
0
3338cfa066d7ca47732a75ba755f41233ef3d05a
[ "mcafee_mar = importlib.import_module('McAfee-MAR')\nd = {'key1': 'value1', 'key2': 'value2'}\ntranslator = {'key1': 'key1', 'key2': 'key2'}\nexpected = {'key1': 'value1', 'key2': 'value2'}\nself.assertEqual(mcafee_mar.translate_dict(d, translator), expected)", "mcafee_mar = importlib.import_module('McAfee-MAR')\...
<|body_start_0|> mcafee_mar = importlib.import_module('McAfee-MAR') d = {'key1': 'value1', 'key2': 'value2'} translator = {'key1': 'key1', 'key2': 'key2'} expected = {'key1': 'value1', 'key2': 'value2'} self.assertEqual(mcafee_mar.translate_dict(d, translator), expected) <|end_bo...
Test cases for the translate_dict function.
TestTranslateDict
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestTranslateDict: """Test cases for the translate_dict function.""" def test_translate_dict_no_translation_needed(self): """Test the scenario where no translation is needed.""" <|body_0|> def test_translate_dict_translation_needed(self): """Test the scenario whe...
stack_v2_sparse_classes_75kplus_train_065647
6,205
permissive
[ { "docstring": "Test the scenario where no translation is needed.", "name": "test_translate_dict_no_translation_needed", "signature": "def test_translate_dict_no_translation_needed(self)" }, { "docstring": "Test the scenario where every key in the dictionary needs to be translated.", "name":...
4
stack_v2_sparse_classes_30k_train_039452
Implement the Python class `TestTranslateDict` described below. Class description: Test cases for the translate_dict function. Method signatures and docstrings: - def test_translate_dict_no_translation_needed(self): Test the scenario where no translation is needed. - def test_translate_dict_translation_needed(self): ...
Implement the Python class `TestTranslateDict` described below. Class description: Test cases for the translate_dict function. Method signatures and docstrings: - def test_translate_dict_no_translation_needed(self): Test the scenario where no translation is needed. - def test_translate_dict_translation_needed(self): ...
890def5a0e0ae8d6eaa538148249ddbc851dbb6b
<|skeleton|> class TestTranslateDict: """Test cases for the translate_dict function.""" def test_translate_dict_no_translation_needed(self): """Test the scenario where no translation is needed.""" <|body_0|> def test_translate_dict_translation_needed(self): """Test the scenario whe...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestTranslateDict: """Test cases for the translate_dict function.""" def test_translate_dict_no_translation_needed(self): """Test the scenario where no translation is needed.""" mcafee_mar = importlib.import_module('McAfee-MAR') d = {'key1': 'value1', 'key2': 'value2'} tra...
the_stack_v2_python_sparse
Packs/McAfee-MAR/Integrations/McAfee-MAR/McAfee-MAR_test.py
demisto/content
train
1,023
8e3c11968b8fde08e4b383e303fcad0f51215fc1
[ "modules = self.import_modules(path, use_superpkg)\nmodule_dicts = []\nfor module in modules:\n mod_dict = dict()\n for field in dir(module):\n if field.find('__') != 0:\n mod_dict[field] = getattr(module, field)\n module_dicts.append(mod_dict)\nreturn module_dicts", "if not os.path.isd...
<|body_start_0|> modules = self.import_modules(path, use_superpkg) module_dicts = [] for module in modules: mod_dict = dict() for field in dir(module): if field.find('__') != 0: mod_dict[field] = getattr(module, field) modul...
Class to help load python file based dictionaries
PythonLoader
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PythonLoader: """Class to help load python file based dictionaries""" def read_dict(self, path, use_superpkg=False): """Reads all python modules at the given path and constructs a dict list This function assumes that path is a directory containing many python module files. Each modul...
stack_v2_sparse_classes_75kplus_train_065648
4,890
permissive
[ { "docstring": "Reads all python modules at the given path and constructs a dict list This function assumes that path is a directory containing many python module files. Each module file has several fields with associated values. This function reads each file and constructs a dictionary using the fields and the...
2
stack_v2_sparse_classes_30k_train_054405
Implement the Python class `PythonLoader` described below. Class description: Class to help load python file based dictionaries Method signatures and docstrings: - def read_dict(self, path, use_superpkg=False): Reads all python modules at the given path and constructs a dict list This function assumes that path is a ...
Implement the Python class `PythonLoader` described below. Class description: Class to help load python file based dictionaries Method signatures and docstrings: - def read_dict(self, path, use_superpkg=False): Reads all python modules at the given path and constructs a dict list This function assumes that path is a ...
aa663303327587146390dde67b83b9bf4e916d54
<|skeleton|> class PythonLoader: """Class to help load python file based dictionaries""" def read_dict(self, path, use_superpkg=False): """Reads all python modules at the given path and constructs a dict list This function assumes that path is a directory containing many python module files. Each modul...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PythonLoader: """Class to help load python file based dictionaries""" def read_dict(self, path, use_superpkg=False): """Reads all python modules at the given path and constructs a dict list This function assumes that path is a directory containing many python module files. Each module file has se...
the_stack_v2_python_sparse
Gds/src/fprime_gds/common/loaders/python_loader.py
suriyaa/fprime
train
1
928817a860114ede9a62f2d3d7a698a7c957ed14
[ "if os.path.exists('testReadFasta.fas'):\n os.remove('testReadFasta.fas')\nsequenceToWrite = [['ACGT', 'ACGTAATTA']]\nexpectedSequence = ['ACGT', 'ACGTAATTA']\nio().writeFastaFile(sequenceToWrite, 'testReadFasta.fas')\nreadSequence = io().readFastaFile('testReadFasta.fas', multipleSequenceAlignment=False)\nself....
<|body_start_0|> if os.path.exists('testReadFasta.fas'): os.remove('testReadFasta.fas') sequenceToWrite = [['ACGT', 'ACGTAATTA']] expectedSequence = ['ACGT', 'ACGTAATTA'] io().writeFastaFile(sequenceToWrite, 'testReadFasta.fas') readSequence = io().readFastaFile('test...
Test class to check the correctness of the methods in IOHelper.
IOHelperTestClass
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IOHelperTestClass: """Test class to check the correctness of the methods in IOHelper.""" def test_readFastaFile(self): """Test method to test the correct reading of a fasta file.""" <|body_0|> def test_writeFastaFile(self): """Test method to test the correct writ...
stack_v2_sparse_classes_75kplus_train_065649
3,044
no_license
[ { "docstring": "Test method to test the correct reading of a fasta file.", "name": "test_readFastaFile", "signature": "def test_readFastaFile(self)" }, { "docstring": "Test method to test the correct writing of a fasta file.", "name": "test_writeFastaFile", "signature": "def test_writeFa...
2
stack_v2_sparse_classes_30k_train_012467
Implement the Python class `IOHelperTestClass` described below. Class description: Test class to check the correctness of the methods in IOHelper. Method signatures and docstrings: - def test_readFastaFile(self): Test method to test the correct reading of a fasta file. - def test_writeFastaFile(self): Test method to ...
Implement the Python class `IOHelperTestClass` described below. Class description: Test class to check the correctness of the methods in IOHelper. Method signatures and docstrings: - def test_readFastaFile(self): Test method to test the correct reading of a fasta file. - def test_writeFastaFile(self): Test method to ...
20d8df6172906337f81583dabb841d66b8f31857
<|skeleton|> class IOHelperTestClass: """Test class to check the correctness of the methods in IOHelper.""" def test_readFastaFile(self): """Test method to test the correct reading of a fasta file.""" <|body_0|> def test_writeFastaFile(self): """Test method to test the correct writ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class IOHelperTestClass: """Test class to check the correctness of the methods in IOHelper.""" def test_readFastaFile(self): """Test method to test the correct reading of a fasta file.""" if os.path.exists('testReadFasta.fas'): os.remove('testReadFasta.fas') sequenceToWrite ...
the_stack_v2_python_sparse
new_algs/Sequence+algorithms/Needleman-Wunsch+algorithm/IOHelperTest.py
coolsnake/JupyterNotebook
train
0
27677e239cb418a4aeb4b8285fbaf6b28ba5a899
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn PhoneAuthenticationMethod()", "from .authentication_method import AuthenticationMethod\nfrom .authentication_method_sign_in_state import AuthenticationMethodSignInState\nfrom .authentication_phone_type import AuthenticationPhoneType\nf...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return PhoneAuthenticationMethod() <|end_body_0|> <|body_start_1|> from .authentication_method import AuthenticationMethod from .authentication_method_sign_in_state import AuthenticationMethodS...
PhoneAuthenticationMethod
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PhoneAuthenticationMethod: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PhoneAuthenticationMethod: """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...
stack_v2_sparse_classes_75kplus_train_065650
3,706
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: PhoneAuthenticationMethod", "name": "create_from_discriminator_value", "signature": "def create_from_discrim...
3
null
Implement the Python class `PhoneAuthenticationMethod` described below. Class description: Implement the PhoneAuthenticationMethod class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PhoneAuthenticationMethod: Creates a new instance of the appropriat...
Implement the Python class `PhoneAuthenticationMethod` described below. Class description: Implement the PhoneAuthenticationMethod class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PhoneAuthenticationMethod: Creates a new instance of the appropriat...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class PhoneAuthenticationMethod: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PhoneAuthenticationMethod: """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...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PhoneAuthenticationMethod: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PhoneAuthenticationMethod: """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...
the_stack_v2_python_sparse
msgraph/generated/models/phone_authentication_method.py
microsoftgraph/msgraph-sdk-python
train
135
f6e69661f699f5aa0ea96aa261221e98a2893a11
[ "if not nums:\n return []\nn = len(nums)\nres = []\nfor i in range(n - k + 1):\n res.append(max(nums[i:i + k]))\nreturn res", "if not nums:\n return []\nqueue = collections.deque(nums[:k])\nres = []\nres.append(max(queue))\nn = len(nums)\nfor i in range(k, n):\n queue.popleft()\n queue.append(nums[...
<|body_start_0|> if not nums: return [] n = len(nums) res = [] for i in range(n - k + 1): res.append(max(nums[i:i + k])) return res <|end_body_0|> <|body_start_1|> if not nums: return [] queue = collections.deque(nums[:k]) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxSlidingWindow(self, nums, k): """:type nums: List[int] :type k: int :rtype: List[int] 先想到一个简单粗暴的方法""" <|body_0|> def maxSlidingWindow1(self, nums, k): """:param nums: :param k: :return: 看了提示,用deque来做, 不过时间复杂度并不是O(n)""" <|body_1|> def max...
stack_v2_sparse_classes_75kplus_train_065651
2,134
no_license
[ { "docstring": ":type nums: List[int] :type k: int :rtype: List[int] 先想到一个简单粗暴的方法", "name": "maxSlidingWindow", "signature": "def maxSlidingWindow(self, nums, k)" }, { "docstring": ":param nums: :param k: :return: 看了提示,用deque来做, 不过时间复杂度并不是O(n)", "name": "maxSlidingWindow1", "signature": ...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxSlidingWindow(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int] 先想到一个简单粗暴的方法 - def maxSlidingWindow1(self, nums, k): :param nums: :param k: :return: 看了提...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxSlidingWindow(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int] 先想到一个简单粗暴的方法 - def maxSlidingWindow1(self, nums, k): :param nums: :param k: :return: 看了提...
11ad9d3841de09c0b4dc3a667e7e63c3558656a5
<|skeleton|> class Solution: def maxSlidingWindow(self, nums, k): """:type nums: List[int] :type k: int :rtype: List[int] 先想到一个简单粗暴的方法""" <|body_0|> def maxSlidingWindow1(self, nums, k): """:param nums: :param k: :return: 看了提示,用deque来做, 不过时间复杂度并不是O(n)""" <|body_1|> def max...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def maxSlidingWindow(self, nums, k): """:type nums: List[int] :type k: int :rtype: List[int] 先想到一个简单粗暴的方法""" if not nums: return [] n = len(nums) res = [] for i in range(n - k + 1): res.append(max(nums[i:i + k])) return res ...
the_stack_v2_python_sparse
sliding-window-maximum.py
ganlanshu/leetcode
train
0
5b7b3d50893ab342c41ff10a0035f30dbb31c5aa
[ "self.done = False\nself.flight = Flight(failure_modes=[[A_err, B, C, D], [A, B_err, C, D]])\nself.possibilities = self.flight.possibilities\nself.observation = [0, 0]\nself.past_err = []\nself.observation_space = spaces.Box(-np.inf, np.inf, shape=(3,), dtype=np.float32)\nself.action_space = spaces.Box(low=np.array...
<|body_start_0|> self.done = False self.flight = Flight(failure_modes=[[A_err, B, C, D], [A, B_err, C, D]]) self.possibilities = self.flight.possibilities self.observation = [0, 0] self.past_err = [] self.observation_space = spaces.Box(-np.inf, np.inf, shape=(3,), dtype=n...
FailureMode10
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FailureMode10: def __init__(self): """Initialize the enviroment""" <|body_0|> def step(self, action): """Handles the io of the environment Args: action (list, ndarray, tensor): The action taken be the control model Returns: tuple: Returns the state following the acti...
stack_v2_sparse_classes_75kplus_train_065652
3,490
no_license
[ { "docstring": "Initialize the enviroment", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Handles the io of the environment Args: action (list, ndarray, tensor): The action taken be the control model Returns: tuple: Returns the state following the action, the reward, w...
5
null
Implement the Python class `FailureMode10` described below. Class description: Implement the FailureMode10 class. Method signatures and docstrings: - def __init__(self): Initialize the enviroment - def step(self, action): Handles the io of the environment Args: action (list, ndarray, tensor): The action taken be the ...
Implement the Python class `FailureMode10` described below. Class description: Implement the FailureMode10 class. Method signatures and docstrings: - def __init__(self): Initialize the enviroment - def step(self, action): Handles the io of the environment Args: action (list, ndarray, tensor): The action taken be the ...
3b3771fc4337407b1cdf78a6a4ca3ad61726724a
<|skeleton|> class FailureMode10: def __init__(self): """Initialize the enviroment""" <|body_0|> def step(self, action): """Handles the io of the environment Args: action (list, ndarray, tensor): The action taken be the control model Returns: tuple: Returns the state following the acti...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FailureMode10: def __init__(self): """Initialize the enviroment""" self.done = False self.flight = Flight(failure_modes=[[A_err, B, C, D], [A, B_err, C, D]]) self.possibilities = self.flight.possibilities self.observation = [0, 0] self.past_err = [] self...
the_stack_v2_python_sparse
Enviroment/gym-Boeing/gym_Boeing/envs/AB_wrong_train.py
fotinosk/masters_project
train
0
c435a4ea1075a96aed42b42e561f662cfa810b99
[ "self._check_locations(locations)\ni, k, info_input = self._filter_indices([0], k)\nlocations_p = self._apply2allelements(locations, k)\nlocations_p = self._filter_output(locations_p, info_input)\nreturn locations_p", "self._check_locations(locations)\ni, k, info_input = self._filter_indices(i, k)\nlocations_p = ...
<|body_start_0|> self._check_locations(locations) i, k, info_input = self._filter_indices([0], k) locations_p = self._apply2allelements(locations, k) locations_p = self._filter_output(locations_p, info_input) return locations_p <|end_body_0|> <|body_start_1|> self._check...
Reindice perturbation for the whole locations.
PermutationPerturbationLocations
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PermutationPerturbationLocations: """Reindice perturbation for the whole locations.""" def apply2locations(self, locations, k=None): """Apply perturbation to locations. Parameters ---------- locations: np.ndarray the spatial information to be perturbed. k: int (default=None) the pert...
stack_v2_sparse_classes_75kplus_train_065653
32,949
permissive
[ { "docstring": "Apply perturbation to locations. Parameters ---------- locations: np.ndarray the spatial information to be perturbed. k: int (default=None) the perturbation indices. Returns ------- locations: np.ndarray the spatial information perturbated.", "name": "apply2locations", "signature": "def ...
2
null
Implement the Python class `PermutationPerturbationLocations` described below. Class description: Reindice perturbation for the whole locations. Method signatures and docstrings: - def apply2locations(self, locations, k=None): Apply perturbation to locations. Parameters ---------- locations: np.ndarray the spatial in...
Implement the Python class `PermutationPerturbationLocations` described below. Class description: Reindice perturbation for the whole locations. Method signatures and docstrings: - def apply2locations(self, locations, k=None): Apply perturbation to locations. Parameters ---------- locations: np.ndarray the spatial in...
6f2e5ba3be67a48d3cd5cf72dcabfae04cfa7afe
<|skeleton|> class PermutationPerturbationLocations: """Reindice perturbation for the whole locations.""" def apply2locations(self, locations, k=None): """Apply perturbation to locations. Parameters ---------- locations: np.ndarray the spatial information to be perturbed. k: int (default=None) the pert...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PermutationPerturbationLocations: """Reindice perturbation for the whole locations.""" def apply2locations(self, locations, k=None): """Apply perturbation to locations. Parameters ---------- locations: np.ndarray the spatial information to be perturbed. k: int (default=None) the perturbation indi...
the_stack_v2_python_sparse
pythonUtils/Perturbations/perturbations.py
tgquintela/pythonUtils
train
1
12dcd5f7096e4684a91a188a73df5dbe52febc66
[ "self.name = name\nself.desired_species = desired_species\nself.feared_species = feared_species", "adopter_score = float(adoption_center.get_number_of_species(self.desired_species))\nnum_feared = float(adoption_center.get_number_of_species(self.feared_species))\nresult = adopter_score - 0.3 * num_feared\nif resul...
<|body_start_0|> self.name = name self.desired_species = desired_species self.feared_species = feared_species <|end_body_0|> <|body_start_1|> adopter_score = float(adoption_center.get_number_of_species(self.desired_species)) num_feared = float(adoption_center.get_number_of_speci...
A FearfulAdopter is afraid of a particular species of animal. If the adoption center has one or more of those animals in it, they will be a bit more reluctant to go there due to the presence of the feared species. Their score should be 1x number of desired species - .3x the number of feared species
FearfulAdopter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FearfulAdopter: """A FearfulAdopter is afraid of a particular species of animal. If the adoption center has one or more of those animals in it, they will be a bit more reluctant to go there due to the presence of the feared species. Their score should be 1x number of desired species - .3x the num...
stack_v2_sparse_classes_75kplus_train_065654
4,359
no_license
[ { "docstring": "Initializes FearfulAdopter, a subclass of Adopter object class feared_species - a string that is the name of the feared species. All of the inputs are the same as the Adopter", "name": "__init__", "signature": "def __init__(self, name, desired_species, feared_species)" }, { "docs...
2
stack_v2_sparse_classes_30k_train_005127
Implement the Python class `FearfulAdopter` described below. Class description: A FearfulAdopter is afraid of a particular species of animal. If the adoption center has one or more of those animals in it, they will be a bit more reluctant to go there due to the presence of the feared species. Their score should be 1x ...
Implement the Python class `FearfulAdopter` described below. Class description: A FearfulAdopter is afraid of a particular species of animal. If the adoption center has one or more of those animals in it, they will be a bit more reluctant to go there due to the presence of the feared species. Their score should be 1x ...
d8750a5d78f042477f6577af67cc46d584f4aede
<|skeleton|> class FearfulAdopter: """A FearfulAdopter is afraid of a particular species of animal. If the adoption center has one or more of those animals in it, they will be a bit more reluctant to go there due to the presence of the feared species. Their score should be 1x number of desired species - .3x the num...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FearfulAdopter: """A FearfulAdopter is afraid of a particular species of animal. If the adoption center has one or more of those animals in it, they will be a bit more reluctant to go there due to the presence of the feared species. Their score should be 1x number of desired species - .3x the number of feared...
the_stack_v2_python_sparse
ProblemSets/ProblemSet07c.py
Greatdane/MITx-6.00.1x
train
0
1ab142181d161c216e433b506476f7f4d4352fe3
[ "json_response = {}\nif not contact_id:\n contacts = Contact.get_by_user_id(request.user.id)\n json_response['response'] = [contact.to_dict() for contact in contacts]\n return JsonResponse(json_response, status=200)\ncontact = Contact.get_by_id(contact_id)\nif not contact:\n json_response['error'] = 'Co...
<|body_start_0|> json_response = {} if not contact_id: contacts = Contact.get_by_user_id(request.user.id) json_response['response'] = [contact.to_dict() for contact in contacts] return JsonResponse(json_response, status=200) contact = Contact.get_by_id(contact...
Contact view handles GET, POST, PUT, DELETE requests.
ContactView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ContactView: """Contact view handles GET, POST, PUT, DELETE requests.""" def get(self, request, contact_id=None): """Handles GET request. If contact_id is None, return json response with all contacts, otherwise contact with given id. If contact with specified id was not found return ...
stack_v2_sparse_classes_75kplus_train_065655
6,227
no_license
[ { "docstring": "Handles GET request. If contact_id is None, return json response with all contacts, otherwise contact with given id. If contact with specified id was not found return error. :param contact_id: int - contact id :return: JsonResponse: { response: <list of contacts> or error: <error message> }", ...
5
null
Implement the Python class `ContactView` described below. Class description: Contact view handles GET, POST, PUT, DELETE requests. Method signatures and docstrings: - def get(self, request, contact_id=None): Handles GET request. If contact_id is None, return json response with all contacts, otherwise contact with giv...
Implement the Python class `ContactView` described below. Class description: Contact view handles GET, POST, PUT, DELETE requests. Method signatures and docstrings: - def get(self, request, contact_id=None): Handles GET request. If contact_id is None, return json response with all contacts, otherwise contact with giv...
83f5acb57862c1766748e7bed92335a3e9c71957
<|skeleton|> class ContactView: """Contact view handles GET, POST, PUT, DELETE requests.""" def get(self, request, contact_id=None): """Handles GET request. If contact_id is None, return json response with all contacts, otherwise contact with given id. If contact with specified id was not found return ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ContactView: """Contact view handles GET, POST, PUT, DELETE requests.""" def get(self, request, contact_id=None): """Handles GET request. If contact_id is None, return json response with all contacts, otherwise contact with given id. If contact with specified id was not found return error. :param...
the_stack_v2_python_sparse
moninag/contact/views.py
Lv-219-Python/MoniNag
train
4
50108bb4abdbde0a4433781c7ec232b9b8204af7
[ "m3 = dstrip(self.beads.m3)\nfor i in range(self.nsteps_o):\n self.thermostat.step()\n p = dstrip(self.beads.p)\n self.ensemble.eens += np.dot(p.flatten(), (p / m3).flatten()) * 0.5\n self.proj_cotangent()\n p = dstrip(self.beads.p).copy()\n self.ensemble.eens -= np.dot(p.flatten(), (p / m3).flatt...
<|body_start_0|> m3 = dstrip(self.beads.m3) for i in range(self.nsteps_o): self.thermostat.step() p = dstrip(self.beads.p) self.ensemble.eens += np.dot(p.flatten(), (p / m3).flatten()) * 0.5 self.proj_cotangent() p = dstrip(self.beads.p).copy()...
Constrained integrator object for constant temperature simulations. Has the relevant conserved quantity for the constant temperature ensemble. Contains a thermostat object that keeps the temperature constant. Implementation details: B. Leimkuhler, C. Matthews Proc. R. Soc. A 472, 20160138, (2016) Attributes: thermostat...
NVTConstrainedIntegrator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NVTConstrainedIntegrator: """Constrained integrator object for constant temperature simulations. Has the relevant conserved quantity for the constant temperature ensemble. Contains a thermostat object that keeps the temperature constant. Implementation details: B. Leimkuhler, C. Matthews Proc. R....
stack_v2_sparse_classes_75kplus_train_065656
19,035
no_license
[ { "docstring": "Constrained stochastic propagation. We solve the problem that the thermostat and the projective step do not necessarily commute (e.g. in GLE) by doing a MTS splitting scheme", "name": "step_Oc", "signature": "def step_Oc(self)" }, { "docstring": "Does one simulation time step.", ...
2
stack_v2_sparse_classes_30k_train_052797
Implement the Python class `NVTConstrainedIntegrator` described below. Class description: Constrained integrator object for constant temperature simulations. Has the relevant conserved quantity for the constant temperature ensemble. Contains a thermostat object that keeps the temperature constant. Implementation detai...
Implement the Python class `NVTConstrainedIntegrator` described below. Class description: Constrained integrator object for constant temperature simulations. Has the relevant conserved quantity for the constant temperature ensemble. Contains a thermostat object that keeps the temperature constant. Implementation detai...
57f255266d4668bafef0881d1e7cbf8a27270ddd
<|skeleton|> class NVTConstrainedIntegrator: """Constrained integrator object for constant temperature simulations. Has the relevant conserved quantity for the constant temperature ensemble. Contains a thermostat object that keeps the temperature constant. Implementation details: B. Leimkuhler, C. Matthews Proc. R....
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NVTConstrainedIntegrator: """Constrained integrator object for constant temperature simulations. Has the relevant conserved quantity for the constant temperature ensemble. Contains a thermostat object that keeps the temperature constant. Implementation details: B. Leimkuhler, C. Matthews Proc. R. Soc. A 472, ...
the_stack_v2_python_sparse
ipi/engine/motion/constrained_dynamics.py
i-pi/i-pi
train
170
9dd649ea9d7f22706db7ea61ddfd5651dd30b3bb
[ "host = _test_base.ftp_host_factory(session_factory=TimeShiftMockSession)\nrounded_time_shift = host._FTPHost__rounded_time_shift\ntest_data = [(0, 0), (0.1, 0), (-0.1, 0), (1500, 0), (-1500, 0), (1800, 3600), (-1800, -3600), (2000, 3600), (-2000, -3600), (5 * 3600 - 100, 5 * 3600), (-5 * 3600 + 100, -5 * 3600)]\nf...
<|body_start_0|> host = _test_base.ftp_host_factory(session_factory=TimeShiftMockSession) rounded_time_shift = host._FTPHost__rounded_time_shift test_data = [(0, 0), (0.1, 0), (-0.1, 0), (1500, 0), (-1500, 0), (1800, 3600), (-1800, -3600), (2000, 3600), (-2000, -3600), (5 * 3600 - 100, 5 * 3600)...
TestTimeShift
[ "BSD-3-Clause", "LicenseRef-scancode-public-domain" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestTimeShift: def test_rounded_time_shift(self): """Test if time shift is rounded correctly.""" <|body_0|> def test_assert_valid_time_shift(self): """Test time shift sanity checks.""" <|body_1|> def test_synchronize_times(self): """Test time syn...
stack_v2_sparse_classes_75kplus_train_065657
21,191
permissive
[ { "docstring": "Test if time shift is rounded correctly.", "name": "test_rounded_time_shift", "signature": "def test_rounded_time_shift(self)" }, { "docstring": "Test time shift sanity checks.", "name": "test_assert_valid_time_shift", "signature": "def test_assert_valid_time_shift(self)"...
3
stack_v2_sparse_classes_30k_train_017178
Implement the Python class `TestTimeShift` described below. Class description: Implement the TestTimeShift class. Method signatures and docstrings: - def test_rounded_time_shift(self): Test if time shift is rounded correctly. - def test_assert_valid_time_shift(self): Test time shift sanity checks. - def test_synchron...
Implement the Python class `TestTimeShift` described below. Class description: Implement the TestTimeShift class. Method signatures and docstrings: - def test_rounded_time_shift(self): Test if time shift is rounded correctly. - def test_assert_valid_time_shift(self): Test time shift sanity checks. - def test_synchron...
c1164ba7c5a35ce5aef43fdffbebaab6ccc21597
<|skeleton|> class TestTimeShift: def test_rounded_time_shift(self): """Test if time shift is rounded correctly.""" <|body_0|> def test_assert_valid_time_shift(self): """Test time shift sanity checks.""" <|body_1|> def test_synchronize_times(self): """Test time syn...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestTimeShift: def test_rounded_time_shift(self): """Test if time shift is rounded correctly.""" host = _test_base.ftp_host_factory(session_factory=TimeShiftMockSession) rounded_time_shift = host._FTPHost__rounded_time_shift test_data = [(0, 0), (0.1, 0), (-0.1, 0), (1500, 0), ...
the_stack_v2_python_sparse
python examples/software/ftputil-2.2.3/_test_ftputil.py
gansell/python
train
0
1c275a28c3f069b29d5d97c7be91b0c180829058
[ "self.sess = tf.Session()\nself.saver = tf.train.import_meta_graph(meta)\nself.saver.restore(self.sess, ckpt)\nself.graph = tf.get_default_graph()\nself.names = sorted([t.name for t in self.graph.as_graph_def().node])\nself.images = self.graph.get_tensor_by_name('images:0')\nself.conv26 = self.graph.get_tensor_by_n...
<|body_start_0|> self.sess = tf.Session() self.saver = tf.train.import_meta_graph(meta) self.saver.restore(self.sess, ckpt) self.graph = tf.get_default_graph() self.names = sorted([t.name for t in self.graph.as_graph_def().node]) self.images = self.graph.get_tensor_by_nam...
Test
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Test: def __init__(self, meta, ckpt): """This is how you can load a model in TF without reconstructing it. :-)""" <|body_0|> def _process(self, img): """We also need to process it in a similar way, unfortunately.""" <|body_1|> def _resize(self, arr): ...
stack_v2_sparse_classes_75kplus_train_065658
5,322
no_license
[ { "docstring": "This is how you can load a model in TF without reconstructing it. :-)", "name": "__init__", "signature": "def __init__(self, meta, ckpt)" }, { "docstring": "We also need to process it in a similar way, unfortunately.", "name": "_process", "signature": "def _process(self, ...
4
stack_v2_sparse_classes_30k_train_037272
Implement the Python class `Test` described below. Class description: Implement the Test class. Method signatures and docstrings: - def __init__(self, meta, ckpt): This is how you can load a model in TF without reconstructing it. :-) - def _process(self, img): We also need to process it in a similar way, unfortunatel...
Implement the Python class `Test` described below. Class description: Implement the Test class. Method signatures and docstrings: - def __init__(self, meta, ckpt): This is how you can load a model in TF without reconstructing it. :-) - def _process(self, img): We also need to process it in a similar way, unfortunatel...
98907194ae996291f326d8199229415900653a9a
<|skeleton|> class Test: def __init__(self, meta, ckpt): """This is how you can load a model in TF without reconstructing it. :-)""" <|body_0|> def _process(self, img): """We also need to process it in a similar way, unfortunately.""" <|body_1|> def _resize(self, arr): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Test: def __init__(self, meta, ckpt): """This is how you can load a model in TF without reconstructing it. :-)""" self.sess = tf.Session() self.saver = tf.train.import_meta_graph(meta) self.saver.restore(self.sess, ckpt) self.graph = tf.get_default_graph() self....
the_stack_v2_python_sparse
main/example_load_network_easier.py
DanielTakeshi/IL_ROS_HSR
train
12
535c2dc2307757aeb3f418df9ce0ea2dd4dbd8e9
[ "super(CombinedModelMaskRCNN, self).__init__()\nself.maskrcnn_extractor = MaskRCNNExtractor()\nself.img_model = ProcessMaskRCNNFeats()\nself.use = use\nif self.use:\n self.text_model = ToyText(hidden_size)\nelse:\n self.text_model = ToyRNNLSTM(hidden_size, embedding_length)", "img = self.maskrcnn_extractor(...
<|body_start_0|> super(CombinedModelMaskRCNN, self).__init__() self.maskrcnn_extractor = MaskRCNNExtractor() self.img_model = ProcessMaskRCNNFeats() self.use = use if self.use: self.text_model = ToyText(hidden_size) else: self.text_model = ToyRNNLS...
CombinedModelMaskRCNN
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CombinedModelMaskRCNN: def __init__(self, hidden_size, use=True, embedding_length=None): """Creates an instance for the model that perform image-text matching task Args: hidden_size (int): dimensionality of the latent space use (bool): whether to use Universal Sentence Encoder (USE) to e...
stack_v2_sparse_classes_75kplus_train_065659
3,137
permissive
[ { "docstring": "Creates an instance for the model that perform image-text matching task Args: hidden_size (int): dimensionality of the latent space use (bool): whether to use Universal Sentence Encoder (USE) to embed text embedding_length: Size of word embedding vector (used only for Glove and Fasttext) Returns...
2
stack_v2_sparse_classes_30k_test_002719
Implement the Python class `CombinedModelMaskRCNN` described below. Class description: Implement the CombinedModelMaskRCNN class. Method signatures and docstrings: - def __init__(self, hidden_size, use=True, embedding_length=None): Creates an instance for the model that perform image-text matching task Args: hidden_s...
Implement the Python class `CombinedModelMaskRCNN` described below. Class description: Implement the CombinedModelMaskRCNN class. Method signatures and docstrings: - def __init__(self, hidden_size, use=True, embedding_length=None): Creates an instance for the model that perform image-text matching task Args: hidden_s...
2185ee4d217d5982f5b2112b7efbde33a206ca0b
<|skeleton|> class CombinedModelMaskRCNN: def __init__(self, hidden_size, use=True, embedding_length=None): """Creates an instance for the model that perform image-text matching task Args: hidden_size (int): dimensionality of the latent space use (bool): whether to use Universal Sentence Encoder (USE) to e...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CombinedModelMaskRCNN: def __init__(self, hidden_size, use=True, embedding_length=None): """Creates an instance for the model that perform image-text matching task Args: hidden_size (int): dimensionality of the latent space use (bool): whether to use Universal Sentence Encoder (USE) to embed text embe...
the_stack_v2_python_sparse
model_archs/models.py
nathanbegbie/COSMOS
train
0
3cc5403cd5148eae09133929907407a10e1f5a80
[ "if obj is None:\n ans = ['service', 'start_date', 'end_date']\nelse:\n ans = ['service', 'start_date', 'end_date', 'exported_file']\nreturn ans", "fields = super(RangedExportAdmin, self).get_readonly_fields(request=request, obj=obj)\nif not self.has_save_permission(request):\n return fields\nif obj:\n ...
<|body_start_0|> if obj is None: ans = ['service', 'start_date', 'end_date'] else: ans = ['service', 'start_date', 'end_date', 'exported_file'] return ans <|end_body_0|> <|body_start_1|> fields = super(RangedExportAdmin, self).get_readonly_fields(request=request,...
RangedExportAdmin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RangedExportAdmin: def get_fields(self, request, obj=None): """Si estamos modificando un enrollment mostramos un link al estudiante. Si es nuevo permitimos al usuario que seleccine un estudiante por id. Mostramos el servicio al que esta asociado. Si es un enrollment nuevo permitimos fact...
stack_v2_sparse_classes_75kplus_train_065660
2,066
no_license
[ { "docstring": "Si estamos modificando un enrollment mostramos un link al estudiante. Si es nuevo permitimos al usuario que seleccine un estudiante por id. Mostramos el servicio al que esta asociado. Si es un enrollment nuevo permitimos facturar el examen medico automaticamente, caso contrario mostramos la fech...
2
null
Implement the Python class `RangedExportAdmin` described below. Class description: Implement the RangedExportAdmin class. Method signatures and docstrings: - def get_fields(self, request, obj=None): Si estamos modificando un enrollment mostramos un link al estudiante. Si es nuevo permitimos al usuario que seleccine u...
Implement the Python class `RangedExportAdmin` described below. Class description: Implement the RangedExportAdmin class. Method signatures and docstrings: - def get_fields(self, request, obj=None): Si estamos modificando un enrollment mostramos un link al estudiante. Si es nuevo permitimos al usuario que seleccine u...
e534dc2f1214a249625dc69f910b37914a5f11d1
<|skeleton|> class RangedExportAdmin: def get_fields(self, request, obj=None): """Si estamos modificando un enrollment mostramos un link al estudiante. Si es nuevo permitimos al usuario que seleccine un estudiante por id. Mostramos el servicio al que esta asociado. Si es un enrollment nuevo permitimos fact...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RangedExportAdmin: def get_fields(self, request, obj=None): """Si estamos modificando un enrollment mostramos un link al estudiante. Si es nuevo permitimos al usuario que seleccine un estudiante por id. Mostramos el servicio al que esta asociado. Si es un enrollment nuevo permitimos facturar el examen...
the_stack_v2_python_sparse
informacion/admin/RangedExportAdmin.py
CEITBA-Scheduler/Facturacion
train
0
ae3bed2bfe8a94a8d283677f7ff01af2d76f45f5
[ "super(StudentUserLogic, self).__init__(auth, sid)\nif isinstance(stid, PracticeStudentUser):\n self.studentuser = sid\nelse:\n self.studentuser = self.get_studentuser_model(stid)", "if not stid:\n return None\nstudentuser = PracticeStudentUser.objects.get_once(stid)\nif not studentuser:\n raise Pract...
<|body_start_0|> super(StudentUserLogic, self).__init__(auth, sid) if isinstance(stid, PracticeStudentUser): self.studentuser = sid else: self.studentuser = self.get_studentuser_model(stid) <|end_body_0|> <|body_start_1|> if not stid: return None ...
StudentUserLogic
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StudentUserLogic: def __init__(self, auth, sid, stid=''): """INIT :param auth: :param sid: :param stid:""" <|body_0|> def get_studentuser_model(self, stid): """获取学生model :param stid: :return:""" <|body_1|> def get_studentuser_info(self): """获取学生信...
stack_v2_sparse_classes_75kplus_train_065661
3,709
no_license
[ { "docstring": "INIT :param auth: :param sid: :param stid:", "name": "__init__", "signature": "def __init__(self, auth, sid, stid='')" }, { "docstring": "获取学生model :param stid: :return:", "name": "get_studentuser_model", "signature": "def get_studentuser_model(self, stid)" }, { "...
4
stack_v2_sparse_classes_30k_train_002337
Implement the Python class `StudentUserLogic` described below. Class description: Implement the StudentUserLogic class. Method signatures and docstrings: - def __init__(self, auth, sid, stid=''): INIT :param auth: :param sid: :param stid: - def get_studentuser_model(self, stid): 获取学生model :param stid: :return: - def ...
Implement the Python class `StudentUserLogic` described below. Class description: Implement the StudentUserLogic class. Method signatures and docstrings: - def __init__(self, auth, sid, stid=''): INIT :param auth: :param sid: :param stid: - def get_studentuser_model(self, stid): 获取学生model :param stid: :return: - def ...
7467cd66e1fc91f0b3a264f8fc9b93f22f09fe7b
<|skeleton|> class StudentUserLogic: def __init__(self, auth, sid, stid=''): """INIT :param auth: :param sid: :param stid:""" <|body_0|> def get_studentuser_model(self, stid): """获取学生model :param stid: :return:""" <|body_1|> def get_studentuser_info(self): """获取学生信...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class StudentUserLogic: def __init__(self, auth, sid, stid=''): """INIT :param auth: :param sid: :param stid:""" super(StudentUserLogic, self).__init__(auth, sid) if isinstance(stid, PracticeStudentUser): self.studentuser = sid else: self.studentuser = self.ge...
the_stack_v2_python_sparse
FireHydrant/server/practice/logics/student.py
shoogoome/FireHydrant
train
4
5bc6f4417408f9a9f92a5b02a93fff8b114103be
[ "self.ans = []\nif root is None:\n return self.ans\n\ndef dfs(root, path):\n if root.left is None and root.right is None:\n self.ans += (path,)\n if root.left:\n dfs(root.left, path + '->' + str(root.left.val))\n if root.right:\n dfs(root.right, path + '->' + str(root.right.val))\nd...
<|body_start_0|> self.ans = [] if root is None: return self.ans def dfs(root, path): if root.left is None and root.right is None: self.ans += (path,) if root.left: dfs(root.left, path + '->' + str(root.left.val)) if...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def binaryTreePaths(self, root): """dfs :type root: TreeNode :rtype: List[str]""" <|body_0|> def binary_tree_paths(self, root): """pythonic dfs :param root: :return:""" <|body_1|> def binary_tree_paths_bfs(self, root): """bfs :param roo...
stack_v2_sparse_classes_75kplus_train_065662
2,358
no_license
[ { "docstring": "dfs :type root: TreeNode :rtype: List[str]", "name": "binaryTreePaths", "signature": "def binaryTreePaths(self, root)" }, { "docstring": "pythonic dfs :param root: :return:", "name": "binary_tree_paths", "signature": "def binary_tree_paths(self, root)" }, { "docst...
3
stack_v2_sparse_classes_30k_train_037360
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def binaryTreePaths(self, root): dfs :type root: TreeNode :rtype: List[str] - def binary_tree_paths(self, root): pythonic dfs :param root: :return: - def binary_tree_paths_bfs(se...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def binaryTreePaths(self, root): dfs :type root: TreeNode :rtype: List[str] - def binary_tree_paths(self, root): pythonic dfs :param root: :return: - def binary_tree_paths_bfs(se...
215d513b3564a7a76db3d2b29e4acc341a68e8ee
<|skeleton|> class Solution: def binaryTreePaths(self, root): """dfs :type root: TreeNode :rtype: List[str]""" <|body_0|> def binary_tree_paths(self, root): """pythonic dfs :param root: :return:""" <|body_1|> def binary_tree_paths_bfs(self, root): """bfs :param roo...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def binaryTreePaths(self, root): """dfs :type root: TreeNode :rtype: List[str]""" self.ans = [] if root is None: return self.ans def dfs(root, path): if root.left is None and root.right is None: self.ans += (path,) ...
the_stack_v2_python_sparse
python/dfs/binary-tree-paths.py
euxuoh/leetcode
train
0
0a906177891985b00fc2db38ea3eb1a64acea453
[ "self.s3 = AwsClient().connect('s3', region_name)\nself.s3_resource = AwsResource().connect('s3', region_name)\ntry:\n self.s3.list_buckets()\nexcept EndpointConnectionError:\n print('s3 resource is not available in this aws region')\n return", "for s3_bucket in self.list_buckets(older_than_seconds):\n ...
<|body_start_0|> self.s3 = AwsClient().connect('s3', region_name) self.s3_resource = AwsResource().connect('s3', region_name) try: self.s3.list_buckets() except EndpointConnectionError: print('s3 resource is not available in this aws region') return <|...
Abstract s3 nuke in a class.
NukeS3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NukeS3: """Abstract s3 nuke in a class.""" def __init__(self, region_name=None) -> None: """Initialize s3 nuke.""" <|body_0|> def nuke(self, older_than_seconds: float) -> None: """S3 bucket deleting function. Deleting all s3 buckets with a timestamp greater than ...
stack_v2_sparse_classes_75kplus_train_065663
2,283
permissive
[ { "docstring": "Initialize s3 nuke.", "name": "__init__", "signature": "def __init__(self, region_name=None) -> None" }, { "docstring": "S3 bucket deleting function. Deleting all s3 buckets with a timestamp greater than older_than_seconds. :param int older_than_seconds: The timestamp in seconds ...
3
stack_v2_sparse_classes_30k_train_002787
Implement the Python class `NukeS3` described below. Class description: Abstract s3 nuke in a class. Method signatures and docstrings: - def __init__(self, region_name=None) -> None: Initialize s3 nuke. - def nuke(self, older_than_seconds: float) -> None: S3 bucket deleting function. Deleting all s3 buckets with a ti...
Implement the Python class `NukeS3` described below. Class description: Abstract s3 nuke in a class. Method signatures and docstrings: - def __init__(self, region_name=None) -> None: Initialize s3 nuke. - def nuke(self, older_than_seconds: float) -> None: S3 bucket deleting function. Deleting all s3 buckets with a ti...
25c4159e71935a9903a41540c168992586c5ba0c
<|skeleton|> class NukeS3: """Abstract s3 nuke in a class.""" def __init__(self, region_name=None) -> None: """Initialize s3 nuke.""" <|body_0|> def nuke(self, older_than_seconds: float) -> None: """S3 bucket deleting function. Deleting all s3 buckets with a timestamp greater than ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NukeS3: """Abstract s3 nuke in a class.""" def __init__(self, region_name=None) -> None: """Initialize s3 nuke.""" self.s3 = AwsClient().connect('s3', region_name) self.s3_resource = AwsResource().connect('s3', region_name) try: self.s3.list_buckets() e...
the_stack_v2_python_sparse
package/nuke/storage/s3.py
diodonfrost/terraform-aws-lambda-nuke
train
20
2e75b1dfa79a3d7e52dbc65e4ace1a241ffe6ecb
[ "self.url = url\nself.query = query\nself.make_request = make_request\nself.use_get = use_get", "if rows:\n self.query['rows'] = rows\nif 'rows' not in self.query:\n self.query['rows'] = 10\nself.query['start'] = 0\nend = False\ndocs_retrieved = 0\nwhile not end:\n if self.use_get:\n http_response...
<|body_start_0|> self.url = url self.query = query self.make_request = make_request self.use_get = use_get <|end_body_0|> <|body_start_1|> if rows: self.query['rows'] = rows if 'rows' not in self.query: self.query['rows'] = 10 self.query['...
Implements the concept of cursor in relational databases
Cursor
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Cursor: """Implements the concept of cursor in relational databases""" def __init__(self, url, query, make_request=requests, use_get=False): """Cursor initialization""" <|body_0|> def fetch(self, rows=None): """Generator method that grabs all the documents in bul...
stack_v2_sparse_classes_75kplus_train_065664
47,807
no_license
[ { "docstring": "Cursor initialization", "name": "__init__", "signature": "def __init__(self, url, query, make_request=requests, use_get=False)" }, { "docstring": "Generator method that grabs all the documents in bulk sets of 'rows' documents :param rows: number of rows for each request", "na...
2
stack_v2_sparse_classes_30k_train_030988
Implement the Python class `Cursor` described below. Class description: Implements the concept of cursor in relational databases Method signatures and docstrings: - def __init__(self, url, query, make_request=requests, use_get=False): Cursor initialization - def fetch(self, rows=None): Generator method that grabs all...
Implement the Python class `Cursor` described below. Class description: Implements the concept of cursor in relational databases Method signatures and docstrings: - def __init__(self, url, query, make_request=requests, use_get=False): Cursor initialization - def fetch(self, rows=None): Generator method that grabs all...
0ac6653219c2701c13c508c5c4fc9bc3437eea06
<|skeleton|> class Cursor: """Implements the concept of cursor in relational databases""" def __init__(self, url, query, make_request=requests, use_get=False): """Cursor initialization""" <|body_0|> def fetch(self, rows=None): """Generator method that grabs all the documents in bul...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Cursor: """Implements the concept of cursor in relational databases""" def __init__(self, url, query, make_request=requests, use_get=False): """Cursor initialization""" self.url = url self.query = query self.make_request = make_request self.use_get = use_get d...
the_stack_v2_python_sparse
repoData/RedTuna-mysolr/allPythonContent.py
aCoffeeYin/pyreco
train
0
3f02536bd75accef055111f5c147811187cba969
[ "Log().log_print().info('init Operate_Redis...')\nself.obj_clinet = redis.StrictRedis(str_host, int_port)\nself.list_authors = Operate_MySQL().mysql_all_authors_id()", "Log().log_print().info('redis_subscribe...')\nobj_subscribe = self.obj_clinet.pubsub()\nobj_subscribe.subscribe(self.list_authors)\nself.redis_sh...
<|body_start_0|> Log().log_print().info('init Operate_Redis...') self.obj_clinet = redis.StrictRedis(str_host, int_port) self.list_authors = Operate_MySQL().mysql_all_authors_id() <|end_body_0|> <|body_start_1|> Log().log_print().info('redis_subscribe...') obj_subscribe = self.o...
Operate_Redis
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Operate_Redis: def __init__(self, str_host='127.0.0.1', int_port=6379): """【初始化】""" <|body_0|> def redis_subscribe(self): """【订阅文章】""" <|body_1|> def redis_show(self, str_name, obj_subscribe): """【显示订阅】""" <|body_2|> <|end_skeleton|> <|...
stack_v2_sparse_classes_75kplus_train_065665
2,259
no_license
[ { "docstring": "【初始化】", "name": "__init__", "signature": "def __init__(self, str_host='127.0.0.1', int_port=6379)" }, { "docstring": "【订阅文章】", "name": "redis_subscribe", "signature": "def redis_subscribe(self)" }, { "docstring": "【显示订阅】", "name": "redis_show", "signature"...
3
null
Implement the Python class `Operate_Redis` described below. Class description: Implement the Operate_Redis class. Method signatures and docstrings: - def __init__(self, str_host='127.0.0.1', int_port=6379): 【初始化】 - def redis_subscribe(self): 【订阅文章】 - def redis_show(self, str_name, obj_subscribe): 【显示订阅】
Implement the Python class `Operate_Redis` described below. Class description: Implement the Operate_Redis class. Method signatures and docstrings: - def __init__(self, str_host='127.0.0.1', int_port=6379): 【初始化】 - def redis_subscribe(self): 【订阅文章】 - def redis_show(self, str_name, obj_subscribe): 【显示订阅】 <|skeleton|>...
bd7152899dcb04aa76ed9f65b36e6a8ccc0affd0
<|skeleton|> class Operate_Redis: def __init__(self, str_host='127.0.0.1', int_port=6379): """【初始化】""" <|body_0|> def redis_subscribe(self): """【订阅文章】""" <|body_1|> def redis_show(self, str_name, obj_subscribe): """【显示订阅】""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Operate_Redis: def __init__(self, str_host='127.0.0.1', int_port=6379): """【初始化】""" Log().log_print().info('init Operate_Redis...') self.obj_clinet = redis.StrictRedis(str_host, int_port) self.list_authors = Operate_MySQL().mysql_all_authors_id() def redis_subscribe(self):...
the_stack_v2_python_sparse
part04/week05/redis_client.py
tea8336/test
train
0
386c9aaf00ae82ba0a7c179a86bd60bc3331f53d
[ "CardToken = get_model('pinpayments', 'CardToken')\ncustomer.cards.exclude(pk=primary_card.pk).filter(primary=True).update(primary=False)\nif data:\n CardToken.objects.update_card_from_data(primary_card, data, commit=False)\nprimary_card.primary = True\nprimary_card.save()\nreturn True", "payload = {}\npayload...
<|body_start_0|> CardToken = get_model('pinpayments', 'CardToken') customer.cards.exclude(pk=primary_card.pk).filter(primary=True).update(primary=False) if data: CardToken.objects.update_card_from_data(primary_card, data, commit=False) primary_card.primary = True prim...
Manager class for CustomerToken, separates API calls and model logic away from the Model's class impl for sanity and separation of concern reasons. Variables and parameter semantics: because the actual model names in this app are a little confusing with the API parameters: CustomerToken instances -> customer CardToken ...
CustomerTokenManager
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CustomerTokenManager: """Manager class for CustomerToken, separates API calls and model logic away from the Model's class impl for sanity and separation of concern reasons. Variables and parameter semantics: because the actual model names in this app are a little confusing with the API parameters...
stack_v2_sparse_classes_75kplus_train_065666
6,056
permissive
[ { "docstring": "Handles keeping the primary CardTokens of cards on CustomerTokens in sync.", "name": "set_primary_card_models", "signature": "def set_primary_card_models(self, customer, primary_card, data={})" }, { "docstring": "Sets the primary CardToken for a given CustomerToken.", "name":...
5
stack_v2_sparse_classes_30k_train_042844
Implement the Python class `CustomerTokenManager` described below. Class description: Manager class for CustomerToken, separates API calls and model logic away from the Model's class impl for sanity and separation of concern reasons. Variables and parameter semantics: because the actual model names in this app are a l...
Implement the Python class `CustomerTokenManager` described below. Class description: Manager class for CustomerToken, separates API calls and model logic away from the Model's class impl for sanity and separation of concern reasons. Variables and parameter semantics: because the actual model names in this app are a l...
b17d4bf78a679c22f5b6f3fba777eb1f94ba9a67
<|skeleton|> class CustomerTokenManager: """Manager class for CustomerToken, separates API calls and model logic away from the Model's class impl for sanity and separation of concern reasons. Variables and parameter semantics: because the actual model names in this app are a little confusing with the API parameters...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CustomerTokenManager: """Manager class for CustomerToken, separates API calls and model logic away from the Model's class impl for sanity and separation of concern reasons. Variables and parameter semantics: because the actual model names in this app are a little confusing with the API parameters: CustomerTok...
the_stack_v2_python_sparse
pinpayments/managers.py
ionata/django-pinpayments
train
0
088288bc3e0ec0b22e983d0bbf31ac0248d838dd
[ "probOfClickOne = super(SGDFMClassification, self).predict_proba(X_test)\nresultingProb = []\nfor item in probOfClickOne:\n click1prob = item\n click0prob = 1 - item\n resultingProb.append([click0prob, click1prob])\npredictedProb = np.array(resultingProb)\nreturn predictedProb", "probOfClickOne = super(S...
<|body_start_0|> probOfClickOne = super(SGDFMClassification, self).predict_proba(X_test) resultingProb = [] for item in probOfClickOne: click1prob = item click0prob = 1 - item resultingProb.append([click0prob, click1prob]) predictedProb = np.array(resu...
SGDFMClassification
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SGDFMClassification: def predict_proba(self, X_test): """Override predict_proba as its original output is not in line with Scikit-Learn's general conventions. :param X_test: :return:""" <|body_0|> def predict(self, X_test, threshold=0.5): """Override to allow manual ...
stack_v2_sparse_classes_75kplus_train_065667
1,413
no_license
[ { "docstring": "Override predict_proba as its original output is not in line with Scikit-Learn's general conventions. :param X_test: :return:", "name": "predict_proba", "signature": "def predict_proba(self, X_test)" }, { "docstring": "Override to allow manual setting of threshold instead of the ...
2
null
Implement the Python class `SGDFMClassification` described below. Class description: Implement the SGDFMClassification class. Method signatures and docstrings: - def predict_proba(self, X_test): Override predict_proba as its original output is not in line with Scikit-Learn's general conventions. :param X_test: :retur...
Implement the Python class `SGDFMClassification` described below. Class description: Implement the SGDFMClassification class. Method signatures and docstrings: - def predict_proba(self, X_test): Override predict_proba as its original output is not in line with Scikit-Learn's general conventions. :param X_test: :retur...
f256ef7859d26ec0ca169cf58c1e3d1e90dc0575
<|skeleton|> class SGDFMClassification: def predict_proba(self, X_test): """Override predict_proba as its original output is not in line with Scikit-Learn's general conventions. :param X_test: :return:""" <|body_0|> def predict(self, X_test, threshold=0.5): """Override to allow manual ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SGDFMClassification: def predict_proba(self, X_test): """Override predict_proba as its original output is not in line with Scikit-Learn's general conventions. :param X_test: :return:""" probOfClickOne = super(SGDFMClassification, self).predict_proba(X_test) resultingProb = [] f...
the_stack_v2_python_sparse
sgdFMClassification.py
jax79sg/webecon2017
train
2
93740725b09204d79f4480f80d94dd9b217aea8a
[ "self.vsm = vsm\nself.key_field = key_field\nself.emb_field = emb_field\nif isinstance(vsm, KeyedVectors):\n vector_size = vsm.syn0.shape[1]\n np.random.seed(9)\n self.root = np.random.uniform(-0.25, 0.25, (vector_size,)).astype('float32')\n np.random.seed()\n self.zero = np.zeros((vector_size,)).ast...
<|body_start_0|> self.vsm = vsm self.key_field = key_field self.emb_field = emb_field if isinstance(vsm, KeyedVectors): vector_size = vsm.syn0.shape[1] np.random.seed(9) self.root = np.random.uniform(-0.25, 0.25, (vector_size,)).astype('float32') ...
NLPEmbedding
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NLPEmbedding: def __init__(self, vsm, key_field, emb_field): """:param vsm: the vector space model in either the form of Word2Vec or FastText. :type vsm: Union[KeyedVectors, WordVectorModel] :param key_field: the field in NLPNode (e.g., word, pos) used as the key to retrieve the emb_matr...
stack_v2_sparse_classes_75kplus_train_065668
3,300
permissive
[ { "docstring": ":param vsm: the vector space model in either the form of Word2Vec or FastText. :type vsm: Union[KeyedVectors, WordVectorModel] :param key_field: the field in NLPNode (e.g., word, pos) used as the key to retrieve the emb_matrix from vsm. :type key_field: str :param emb_field: where the emb_matrix...
2
stack_v2_sparse_classes_30k_test_001541
Implement the Python class `NLPEmbedding` described below. Class description: Implement the NLPEmbedding class. Method signatures and docstrings: - def __init__(self, vsm, key_field, emb_field): :param vsm: the vector space model in either the form of Word2Vec or FastText. :type vsm: Union[KeyedVectors, WordVectorMod...
Implement the Python class `NLPEmbedding` described below. Class description: Implement the NLPEmbedding class. Method signatures and docstrings: - def __init__(self, vsm, key_field, emb_field): :param vsm: the vector space model in either the form of Word2Vec or FastText. :type vsm: Union[KeyedVectors, WordVectorMod...
622b4438ea73c0f235fd1a79b13ee9e6850bfdc9
<|skeleton|> class NLPEmbedding: def __init__(self, vsm, key_field, emb_field): """:param vsm: the vector space model in either the form of Word2Vec or FastText. :type vsm: Union[KeyedVectors, WordVectorModel] :param key_field: the field in NLPNode (e.g., word, pos) used as the key to retrieve the emb_matr...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NLPEmbedding: def __init__(self, vsm, key_field, emb_field): """:param vsm: the vector space model in either the form of Word2Vec or FastText. :type vsm: Union[KeyedVectors, WordVectorModel] :param key_field: the field in NLPNode (e.g., word, pos) used as the key to retrieve the emb_matrix from vsm. :...
the_stack_v2_python_sparse
elit/dev/template/lexicon.py
hankcs/elit
train
0
9007d7bb2d213ebcca64a38448d8c789a906bd3c
[ "self.positions = positions\nself.position_vals = []\nself.num_trials = num_trials\ntry:\n self.num_trials = int(num_trials)\nexcept:\n raise TypeError\nelse:\n if self.num_trials <= 0:\n raise ValueError\n for i in self.positions:\n self.position_vals.append(int(i) / 1000)", "num_shares...
<|body_start_0|> self.positions = positions self.position_vals = [] self.num_trials = num_trials try: self.num_trials = int(num_trials) except: raise TypeError else: if self.num_trials <= 0: raise ValueError ...
this class includes the functions and initialization method for the list of positions and number of simulations that will be input by the user
Investment
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Investment: """this class includes the functions and initialization method for the list of positions and number of simulations that will be input by the user""" def __init__(self, positions, num_trials): """Initializes the position list and number of simulations""" <|body_0|>...
stack_v2_sparse_classes_75kplus_train_065669
1,888
no_license
[ { "docstring": "Initializes the position list and number of simulations", "name": "__init__", "signature": "def __init__(self, positions, num_trials)" }, { "docstring": "generates the outcome of betting a total of $1000, given a position value ie. if the position value is 1, it generates the out...
3
stack_v2_sparse_classes_30k_train_016265
Implement the Python class `Investment` described below. Class description: this class includes the functions and initialization method for the list of positions and number of simulations that will be input by the user Method signatures and docstrings: - def __init__(self, positions, num_trials): Initializes the posi...
Implement the Python class `Investment` described below. Class description: this class includes the functions and initialization method for the list of positions and number of simulations that will be input by the user Method signatures and docstrings: - def __init__(self, positions, num_trials): Initializes the posi...
068db95cef0c693ad833fcfe968aa0b5db2162cd
<|skeleton|> class Investment: """this class includes the functions and initialization method for the list of positions and number of simulations that will be input by the user""" def __init__(self, positions, num_trials): """Initializes the position list and number of simulations""" <|body_0|>...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Investment: """this class includes the functions and initialization method for the list of positions and number of simulations that will be input by the user""" def __init__(self, positions, num_trials): """Initializes the position list and number of simulations""" self.positions = positi...
the_stack_v2_python_sparse
neb330/Investment.py
whirlkick/assignment8
train
0
3ba8924bc5fa0e3a1ba10f25fedf647ea08db318
[ "self._subword_vocab = subword_vocab\nself._subword_tokenizer = subword_tokenizer\nself._slot_vocab = slot_vocab\nself._cased = cased\nself._slot_pad_id = self._slot_vocab['O']", "subword_ids = []\nsubword_mask = []\nselected = []\npadded_tag_ids = []\nintent_label = intent_ids[0]\nptr = 0\nfor token, tag in zip(...
<|body_start_0|> self._subword_vocab = subword_vocab self._subword_tokenizer = subword_tokenizer self._slot_vocab = slot_vocab self._cased = cased self._slot_pad_id = self._slot_vocab['O'] <|end_body_0|> <|body_start_1|> subword_ids = [] subword_mask = [] ...
Transform the word_tokens/tags by the subword tokenizer
IDSLSubwordTransform
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IDSLSubwordTransform: """Transform the word_tokens/tags by the subword tokenizer""" def __init__(self, subword_vocab, subword_tokenizer, slot_vocab, cased=False): """Parameters ---------- subword_vocab : Vocab subword_tokenizer : Tokenizer cased : bool Whether to convert all characte...
stack_v2_sparse_classes_75kplus_train_065670
20,404
permissive
[ { "docstring": "Parameters ---------- subword_vocab : Vocab subword_tokenizer : Tokenizer cased : bool Whether to convert all characters to lower", "name": "__init__", "signature": "def __init__(self, subword_vocab, subword_tokenizer, slot_vocab, cased=False)" }, { "docstring": "Transform the wo...
2
stack_v2_sparse_classes_30k_train_015631
Implement the Python class `IDSLSubwordTransform` described below. Class description: Transform the word_tokens/tags by the subword tokenizer Method signatures and docstrings: - def __init__(self, subword_vocab, subword_tokenizer, slot_vocab, cased=False): Parameters ---------- subword_vocab : Vocab subword_tokenizer...
Implement the Python class `IDSLSubwordTransform` described below. Class description: Transform the word_tokens/tags by the subword tokenizer Method signatures and docstrings: - def __init__(self, subword_vocab, subword_tokenizer, slot_vocab, cased=False): Parameters ---------- subword_vocab : Vocab subword_tokenizer...
ffff7237d2bb73a8a66addc04dee94824976aae0
<|skeleton|> class IDSLSubwordTransform: """Transform the word_tokens/tags by the subword tokenizer""" def __init__(self, subword_vocab, subword_tokenizer, slot_vocab, cased=False): """Parameters ---------- subword_vocab : Vocab subword_tokenizer : Tokenizer cased : bool Whether to convert all characte...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class IDSLSubwordTransform: """Transform the word_tokens/tags by the subword tokenizer""" def __init__(self, subword_vocab, subword_tokenizer, slot_vocab, cased=False): """Parameters ---------- subword_vocab : Vocab subword_tokenizer : Tokenizer cased : bool Whether to convert all characters to lower""...
the_stack_v2_python_sparse
intent_classification_and_slot_labelling/finetune_icsl.py
eric-haibin-lin/nlp-notebooks
train
22
6004cb9716f10f718ab738b767b2e5863451d6be
[ "parser = lldp_parsers.LLDPBasicMgmtParser(node_info)\nfor tlv_type, tlv_value in tlvs:\n try:\n data = bytearray(binascii.a2b_hex(tlv_value))\n except TypeError as e:\n LOG.warning('TLV value for TLV type %(tlv_type)d not in correct format, value must be in hexadecimal: %(msg)s', {'tlv_type': t...
<|body_start_0|> parser = lldp_parsers.LLDPBasicMgmtParser(node_info) for tlv_type, tlv_value in tlvs: try: data = bytearray(binascii.a2b_hex(tlv_value)) except TypeError as e: LOG.warning('TLV value for TLV type %(tlv_type)d not in correct format,...
Process mandatory and optional LLDP packet fields Loop through raw LLDP TLVs and parse those from the basic management, 802.1, and 802.3 TLV sets. Store parsed data back to the ironic-inspector database.
LLDPBasicProcessingHook
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LLDPBasicProcessingHook: """Process mandatory and optional LLDP packet fields Loop through raw LLDP TLVs and parse those from the basic management, 802.1, and 802.3 TLV sets. Store parsed data back to the ironic-inspector database.""" def _parse_lldp_tlvs(self, tlvs, node_info): """P...
stack_v2_sparse_classes_75kplus_train_065671
3,235
permissive
[ { "docstring": "Parse LLDP TLVs into dictionary of name/value pairs :param tlvs: list of raw TLVs :param node_info: node being introspected :returns nv: dictionary of name/value pairs. The LLDP user-friendly names, e.g. \"switch_port_id\" are the keys", "name": "_parse_lldp_tlvs", "signature": "def _par...
2
stack_v2_sparse_classes_30k_val_000448
Implement the Python class `LLDPBasicProcessingHook` described below. Class description: Process mandatory and optional LLDP packet fields Loop through raw LLDP TLVs and parse those from the basic management, 802.1, and 802.3 TLV sets. Store parsed data back to the ironic-inspector database. Method signatures and doc...
Implement the Python class `LLDPBasicProcessingHook` described below. Class description: Process mandatory and optional LLDP packet fields Loop through raw LLDP TLVs and parse those from the basic management, 802.1, and 802.3 TLV sets. Store parsed data back to the ironic-inspector database. Method signatures and doc...
4a6bdaaf4bdd14ce9dc479cde83176b4c1100f42
<|skeleton|> class LLDPBasicProcessingHook: """Process mandatory and optional LLDP packet fields Loop through raw LLDP TLVs and parse those from the basic management, 802.1, and 802.3 TLV sets. Store parsed data back to the ironic-inspector database.""" def _parse_lldp_tlvs(self, tlvs, node_info): """P...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LLDPBasicProcessingHook: """Process mandatory and optional LLDP packet fields Loop through raw LLDP TLVs and parse those from the basic management, 802.1, and 802.3 TLV sets. Store parsed data back to the ironic-inspector database.""" def _parse_lldp_tlvs(self, tlvs, node_info): """Parse LLDP TLV...
the_stack_v2_python_sparse
ironic_inspector/plugins/lldp_basic.py
openstack/ironic-inspector
train
34
e1df69aab2d6e0e83f93ce2889e4194e952fd4ba
[ "if fileName not in self.header:\n return None\ninfo = self.header[fileName]\nlogger.debug('found: %s', info)\nif isinstance(info, str):\n logger.debug('redirect!')\n data = self.manager.get_item(info)\nelse:\n seek, size = info\n self.fh.seek(4 + self.header_size + seek)\n data = self.fh.read(siz...
<|body_start_0|> if fileName not in self.header: return None info = self.header[fileName] logger.debug('found: %s', info) if isinstance(info, str): logger.debug('redirect!') data = self.manager.get_item(info) else: seek, size = info...
Common functionality for a block.
Bloque
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Bloque: """Common functionality for a block.""" def get_item(self, fileName): """Return the item if present, else None.""" <|body_0|> def close(self): """Cleanup.""" <|body_1|> <|end_skeleton|> <|body_start_0|> if fileName not in self.header: ...
stack_v2_sparse_classes_75kplus_train_065672
13,483
no_license
[ { "docstring": "Return the item if present, else None.", "name": "get_item", "signature": "def get_item(self, fileName)" }, { "docstring": "Cleanup.", "name": "close", "signature": "def close(self)" } ]
2
null
Implement the Python class `Bloque` described below. Class description: Common functionality for a block. Method signatures and docstrings: - def get_item(self, fileName): Return the item if present, else None. - def close(self): Cleanup.
Implement the Python class `Bloque` described below. Class description: Common functionality for a block. Method signatures and docstrings: - def get_item(self, fileName): Return the item if present, else None. - def close(self): Cleanup. <|skeleton|> class Bloque: """Common functionality for a block.""" de...
76f1ae18621c914f9a2d585ae7ebb543ba4e9485
<|skeleton|> class Bloque: """Common functionality for a block.""" def get_item(self, fileName): """Return the item if present, else None.""" <|body_0|> def close(self): """Cleanup.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Bloque: """Common functionality for a block.""" def get_item(self, fileName): """Return the item if present, else None.""" if fileName not in self.header: return None info = self.header[fileName] logger.debug('found: %s', info) if isinstance(info, str):...
the_stack_v2_python_sparse
src/armado/compresor.py
PyAr/CDPedia
train
38
1ca4406cb1e89827421dbbc75cb67129c45a324b
[ "self.tableid = tableid\nself.min_intersect = min_intersect\nself.max_intersect = max_intersect", "image = dict(creator='MOL/com.google.earthengine.examples.mol.CountPolygonIntersect', args=[dict(type='FeatureCollection', table_id=self.tableid)])\nquery = dict(image=simplejson.dumps(image), bands='intersectionCou...
<|body_start_0|> self.tableid = tableid self.min_intersect = min_intersect self.max_intersect = max_intersect <|end_body_0|> <|body_start_1|> image = dict(creator='MOL/com.google.earthengine.examples.mol.CountPolygonIntersect', args=[dict(type='FeatureCollection', table_id=self.tableid)...
This class encapsulates a /mapid request to Earth Engine. When executed, this request returns a mapid and token that can be used to create tile URLs for tiling a Fusion Table table on a Google Map.
MapIdRequest
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MapIdRequest: """This class encapsulates a /mapid request to Earth Engine. When executed, this request returns a mapid and token that can be used to create tile URLs for tiling a Fusion Table table on a Google Map.""" def __init__(self, tableid, min_intersect=1, max_intersect=32): ""...
stack_v2_sparse_classes_75kplus_train_065673
13,900
permissive
[ { "docstring": "Creates a new MapIdRequest object. Args: tableid - The Fusion Table table id. min_intersect - The min number of polygons to intersect. max_intersect - The max number of polygons to intersect.", "name": "__init__", "signature": "def __init__(self, tableid, min_intersect=1, max_intersect=3...
2
stack_v2_sparse_classes_30k_train_006133
Implement the Python class `MapIdRequest` described below. Class description: This class encapsulates a /mapid request to Earth Engine. When executed, this request returns a mapid and token that can be used to create tile URLs for tiling a Fusion Table table on a Google Map. Method signatures and docstrings: - def __...
Implement the Python class `MapIdRequest` described below. Class description: This class encapsulates a /mapid request to Earth Engine. When executed, this request returns a mapid and token that can be used to create tile URLs for tiling a Fusion Table table on a Google Map. Method signatures and docstrings: - def __...
e3c50ee4ec8364c61cfff3ea68ece1098674f4d6
<|skeleton|> class MapIdRequest: """This class encapsulates a /mapid request to Earth Engine. When executed, this request returns a mapid and token that can be used to create tile URLs for tiling a Fusion Table table on a Google Map.""" def __init__(self, tableid, min_intersect=1, max_intersect=32): ""...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MapIdRequest: """This class encapsulates a /mapid request to Earth Engine. When executed, this request returns a mapid and token that can be used to create tile URLs for tiling a Fusion Table table on a Google Map.""" def __init__(self, tableid, min_intersect=1, max_intersect=32): """Creates a ne...
the_stack_v2_python_sparse
earthengine/frontend.py
MapofLife/MOL
train
19
ab0b2817d91e8ea431fccd36a61ee1267dc9f696
[ "self.driver.get(buy_car_url)\nself.driver.find_element(BuyCarLocator.CAR_LIST_INFO).click()\nself.driver.switch_to_window()\nbrand_name = self.driver.find_element(BuyCarLocator.CAR_DETAIL_INFO).text\nprint('进入车源:{brand_name} 的详情页'.format(brand_name=brand_name))\ncity_name = self.driver.find_element(BuyCarLocator.C...
<|body_start_0|> self.driver.get(buy_car_url) self.driver.find_element(BuyCarLocator.CAR_LIST_INFO).click() self.driver.switch_to_window() brand_name = self.driver.find_element(BuyCarLocator.CAR_DETAIL_INFO).text print('进入车源:{brand_name} 的详情页'.format(brand_name=brand_name)) ...
Detail
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Detail: def test_car_info(self): """验证详情页车源基本信息与选中的车源是否一致@author:fangyu""" <|body_0|> def test_addCollect(self): """验证详情页车源的收藏功能@author:gaoxinling""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.driver.get(buy_car_url) self.driver.find_...
stack_v2_sparse_classes_75kplus_train_065674
2,979
no_license
[ { "docstring": "验证详情页车源基本信息与选中的车源是否一致@author:fangyu", "name": "test_car_info", "signature": "def test_car_info(self)" }, { "docstring": "验证详情页车源的收藏功能@author:gaoxinling", "name": "test_addCollect", "signature": "def test_addCollect(self)" } ]
2
null
Implement the Python class `Detail` described below. Class description: Implement the Detail class. Method signatures and docstrings: - def test_car_info(self): 验证详情页车源基本信息与选中的车源是否一致@author:fangyu - def test_addCollect(self): 验证详情页车源的收藏功能@author:gaoxinling
Implement the Python class `Detail` described below. Class description: Implement the Detail class. Method signatures and docstrings: - def test_car_info(self): 验证详情页车源基本信息与选中的车源是否一致@author:fangyu - def test_addCollect(self): 验证详情页车源的收藏功能@author:gaoxinling <|skeleton|> class Detail: def test_car_info(self): ...
204856bd33c06d25f2970eba13799db75d4fd4fe
<|skeleton|> class Detail: def test_car_info(self): """验证详情页车源基本信息与选中的车源是否一致@author:fangyu""" <|body_0|> def test_addCollect(self): """验证详情页车源的收藏功能@author:gaoxinling""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Detail: def test_car_info(self): """验证详情页车源基本信息与选中的车源是否一致@author:fangyu""" self.driver.get(buy_car_url) self.driver.find_element(BuyCarLocator.CAR_LIST_INFO).click() self.driver.switch_to_window() brand_name = self.driver.find_element(BuyCarLocator.CAR_DETAIL_INFO).text...
the_stack_v2_python_sparse
mc/taochePC/test_buycar/test_detail.py
boeai/mc
train
0
108c001b67d1f95a8159d91317472625ab7b1d01
[ "self.current_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nself.config_path = os.path.join(self.current_path, 'study_配置文件')\nself.g_config_path = os.path.join(self.config_path, 'config.ini')\nself.db_config_path = os.path.join(self.config_path, 'db_config.ini')\nself.v_config_path = os.path.j...
<|body_start_0|> self.current_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) self.config_path = os.path.join(self.current_path, 'study_配置文件') self.g_config_path = os.path.join(self.config_path, 'config.ini') self.db_config_path = os.path.join(self.config_path, 'db_con...
Config
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Config: def __init__(self): """初始化配置 -- 简化使用""" <|body_0|> def get_variable_config(self, variable_name, section_name='Global_Variable'): """返回全局变量的值 :param variable_name:变量名 :param section_name: 变量名所在的section :return:""" <|body_1|> def set_variable_confi...
stack_v2_sparse_classes_75kplus_train_065675
2,327
no_license
[ { "docstring": "初始化配置 -- 简化使用", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "返回全局变量的值 :param variable_name:变量名 :param section_name: 变量名所在的section :return:", "name": "get_variable_config", "signature": "def get_variable_config(self, variable_name, section_name=...
3
null
Implement the Python class `Config` described below. Class description: Implement the Config class. Method signatures and docstrings: - def __init__(self): 初始化配置 -- 简化使用 - def get_variable_config(self, variable_name, section_name='Global_Variable'): 返回全局变量的值 :param variable_name:变量名 :param section_name: 变量名所在的section...
Implement the Python class `Config` described below. Class description: Implement the Config class. Method signatures and docstrings: - def __init__(self): 初始化配置 -- 简化使用 - def get_variable_config(self, variable_name, section_name='Global_Variable'): 返回全局变量的值 :param variable_name:变量名 :param section_name: 变量名所在的section...
d885b520757097c1d984d1cdda5d242ee5c6a5d6
<|skeleton|> class Config: def __init__(self): """初始化配置 -- 简化使用""" <|body_0|> def get_variable_config(self, variable_name, section_name='Global_Variable'): """返回全局变量的值 :param variable_name:变量名 :param section_name: 变量名所在的section :return:""" <|body_1|> def set_variable_confi...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Config: def __init__(self): """初始化配置 -- 简化使用""" self.current_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) self.config_path = os.path.join(self.current_path, 'study_配置文件') self.g_config_path = os.path.join(self.config_path, 'config.ini') self.db_con...
the_stack_v2_python_sparse
module_study/study_配置文件/config.py
yolotester/learngit
train
0
d772b59a4cc8f4982c85157a6b1ab99829814f71
[ "User = get_user_model()\ntry:\n user = User.objects.get(username=username)\n return user\nexcept User.DoesNotExist:\n return None", "User = get_user_model()\ntry:\n return User.objects.get(pk=user_id)\nexcept User.DoesNotExist:\n return None" ]
<|body_start_0|> User = get_user_model() try: user = User.objects.get(username=username) return user except User.DoesNotExist: return None <|end_body_0|> <|body_start_1|> User = get_user_model() try: return User.objects.get(pk=user...
Define authentication and get user functions for custom authentication.
CustomAuthentication
[ "LicenseRef-scancode-public-domain", "CC0-1.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CustomAuthentication: """Define authentication and get user functions for custom authentication.""" def authenticate(self, username=None): """Authenticate user with the request and username.""" <|body_0|> def get_user(self, user_id): """Get user by the user id.""...
stack_v2_sparse_classes_75kplus_train_065676
797
permissive
[ { "docstring": "Authenticate user with the request and username.", "name": "authenticate", "signature": "def authenticate(self, username=None)" }, { "docstring": "Get user by the user id.", "name": "get_user", "signature": "def get_user(self, user_id)" } ]
2
stack_v2_sparse_classes_30k_train_006509
Implement the Python class `CustomAuthentication` described below. Class description: Define authentication and get user functions for custom authentication. Method signatures and docstrings: - def authenticate(self, username=None): Authenticate user with the request and username. - def get_user(self, user_id): Get u...
Implement the Python class `CustomAuthentication` described below. Class description: Define authentication and get user functions for custom authentication. Method signatures and docstrings: - def authenticate(self, username=None): Authenticate user with the request and username. - def get_user(self, user_id): Get u...
1d61e8691175f243cca988bbef4d617b0460f4be
<|skeleton|> class CustomAuthentication: """Define authentication and get user functions for custom authentication.""" def authenticate(self, username=None): """Authenticate user with the request and username.""" <|body_0|> def get_user(self, user_id): """Get user by the user id.""...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CustomAuthentication: """Define authentication and get user functions for custom authentication.""" def authenticate(self, username=None): """Authenticate user with the request and username.""" User = get_user_model() try: user = User.objects.get(username=username) ...
the_stack_v2_python_sparse
tdrs-backend/tdpservice/users/authentication.py
reitermb/TANF-app
train
0
74fd649a193af6e4e65f00f72397e4f240669700
[ "self.learning_rate = learning_rate\nself.params = []\nfor p in model.params:\n self.params.append(theano.shared(p.get_value()))\nself.timestamp = 0\nself.clients = clients\nself.pending_grads = {}", "unblock = False\nself.pending_grads[client] = grads\nif len(self.pending_grads) == self.clients:\n stalenes...
<|body_start_0|> self.learning_rate = learning_rate self.params = [] for p in model.params: self.params.append(theano.shared(p.get_value())) self.timestamp = 0 self.clients = clients self.pending_grads = {} <|end_body_0|> <|body_start_1|> unblock = Fa...
Completely synchronous gradient descent with N clients and batch size B. This should give exactly the same convergence as normal SGD with batch size B*N.
HardSyncServer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HardSyncServer: """Completely synchronous gradient descent with N clients and batch size B. This should give exactly the same convergence as normal SGD with batch size B*N.""" def __init__(self, model, clients, learning_rate=0.13): """Give server a copy of the model params.""" ...
stack_v2_sparse_classes_75kplus_train_065677
6,454
no_license
[ { "docstring": "Give server a copy of the model params.", "name": "__init__", "signature": "def __init__(self, model, clients, learning_rate=0.13)" }, { "docstring": "Takes in a single gradient update and optionally applies it to the parameters.", "name": "apply_update", "signature": "de...
2
stack_v2_sparse_classes_30k_train_025837
Implement the Python class `HardSyncServer` described below. Class description: Completely synchronous gradient descent with N clients and batch size B. This should give exactly the same convergence as normal SGD with batch size B*N. Method signatures and docstrings: - def __init__(self, model, clients, learning_rate...
Implement the Python class `HardSyncServer` described below. Class description: Completely synchronous gradient descent with N clients and batch size B. This should give exactly the same convergence as normal SGD with batch size B*N. Method signatures and docstrings: - def __init__(self, model, clients, learning_rate...
3ffeaad287896ab9aa8b2f6a2b64114bc250ce75
<|skeleton|> class HardSyncServer: """Completely synchronous gradient descent with N clients and batch size B. This should give exactly the same convergence as normal SGD with batch size B*N.""" def __init__(self, model, clients, learning_rate=0.13): """Give server a copy of the model params.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class HardSyncServer: """Completely synchronous gradient descent with N clients and batch size B. This should give exactly the same convergence as normal SGD with batch size B*N.""" def __init__(self, model, clients, learning_rate=0.13): """Give server a copy of the model params.""" self.learni...
the_stack_v2_python_sparse
code/servers.py
FrederickBizzardo/fred
train
0
f3473d56926548839dae99a736e4d01e32c1db6f
[ "super().__init__(name=name)\nif not isinstance(event, Event):\n raise TypeError('Use the Event enum!')\nself._event = event\nif event_freq <= 0:\n raise ValueError(f'CounterCallback: event_freq cannot be <= 0. Received event_freq = {event_freq}')\nself._event_freq = event_freq\nself._fn = fn\nself._event_cou...
<|body_start_0|> super().__init__(name=name) if not isinstance(event, Event): raise TypeError('Use the Event enum!') self._event = event if event_freq <= 0: raise ValueError(f'CounterCallback: event_freq cannot be <= 0. Received event_freq = {event_freq}') ...
Count events of a specific type. Calls fn passing the context every event_freq. Useful for logging or for measuring performance. If you want to implement a callback defining a certain behaviour every n_events you can just inherit from CounterCallback.
CounterCallback
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CounterCallback: """Count events of a specific type. Calls fn passing the context every event_freq. Useful for logging or for measuring performance. If you want to implement a callback defining a certain behaviour every n_events you can just inherit from CounterCallback.""" def __init__(self...
stack_v2_sparse_classes_75kplus_train_065678
2,914
permissive
[ { "docstring": "Initialize the CounterCallback. Args: event (:py:class:`ashpy.events.Event`): event to count. fn (:py:class:`Callable`): function to call every `event_freq` events. event_freq (int): event frequency. name (str): name of the Callback. Raises: ValueError: if `event_freq` is not valid.", "name"...
2
null
Implement the Python class `CounterCallback` described below. Class description: Count events of a specific type. Calls fn passing the context every event_freq. Useful for logging or for measuring performance. If you want to implement a callback defining a certain behaviour every n_events you can just inherit from Cou...
Implement the Python class `CounterCallback` described below. Class description: Count events of a specific type. Calls fn passing the context every event_freq. Useful for logging or for measuring performance. If you want to implement a callback defining a certain behaviour every n_events you can just inherit from Cou...
92ac86fb0c962854e0d80c44165e0e7ff126b3c1
<|skeleton|> class CounterCallback: """Count events of a specific type. Calls fn passing the context every event_freq. Useful for logging or for measuring performance. If you want to implement a callback defining a certain behaviour every n_events you can just inherit from CounterCallback.""" def __init__(self...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CounterCallback: """Count events of a specific type. Calls fn passing the context every event_freq. Useful for logging or for measuring performance. If you want to implement a callback defining a certain behaviour every n_events you can just inherit from CounterCallback.""" def __init__(self, event: Even...
the_stack_v2_python_sparse
src/ashpy/callbacks/counter_callback.py
zurutech/ashpy
train
89
e2086e6f4c1827f8687740c7cc1e0cf64d1b6c6f
[ "def helper(left, right):\n if left < right:\n s[left], s[right] = (s[right], s[left])\n helper(left + 1, right - 1)\nhelper(0, len(s) - 1)\nreturn s", "left, right = (0, len(s) - 1)\nwhile left < right:\n s[left], s[right] = (s[right], s[left])\n left, right = (left + 1, right - 1)\nreturn...
<|body_start_0|> def helper(left, right): if left < right: s[left], s[right] = (s[right], s[left]) helper(left + 1, right - 1) helper(0, len(s) - 1) return s <|end_body_0|> <|body_start_1|> left, right = (0, len(s) - 1) while left < ri...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def reverseString_1(self, s: List[str]) -> None: """方法一:双指针(递归) 时间复杂度:O(N)。执行了 N/2 次的交换。 空间复杂度:O(N),递归过程中使用的堆栈空间 N/2 。 Do not return anything, modify s in-place instead.""" <|body_0|> def reverseString_2(self, s): """方法二:双指针法(迭代) 时间复杂度:O(N)。执行了 N/2 次的交换。 空间...
stack_v2_sparse_classes_75kplus_train_065679
1,783
no_license
[ { "docstring": "方法一:双指针(递归) 时间复杂度:O(N)。执行了 N/2 次的交换。 空间复杂度:O(N),递归过程中使用的堆栈空间 N/2 。 Do not return anything, modify s in-place instead.", "name": "reverseString_1", "signature": "def reverseString_1(self, s: List[str]) -> None" }, { "docstring": "方法二:双指针法(迭代) 时间复杂度:O(N)。执行了 N/2 次的交换。 空间复杂度:O(1),只使...
2
stack_v2_sparse_classes_30k_train_041958
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseString_1(self, s: List[str]) -> None: 方法一:双指针(递归) 时间复杂度:O(N)。执行了 N/2 次的交换。 空间复杂度:O(N),递归过程中使用的堆栈空间 N/2 。 Do not return anything, modify s in-place instead. - def rever...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseString_1(self, s: List[str]) -> None: 方法一:双指针(递归) 时间复杂度:O(N)。执行了 N/2 次的交换。 空间复杂度:O(N),递归过程中使用的堆栈空间 N/2 。 Do not return anything, modify s in-place instead. - def rever...
62419b49000e79962bcdc99cd98afd2fb82ea345
<|skeleton|> class Solution: def reverseString_1(self, s: List[str]) -> None: """方法一:双指针(递归) 时间复杂度:O(N)。执行了 N/2 次的交换。 空间复杂度:O(N),递归过程中使用的堆栈空间 N/2 。 Do not return anything, modify s in-place instead.""" <|body_0|> def reverseString_2(self, s): """方法二:双指针法(迭代) 时间复杂度:O(N)。执行了 N/2 次的交换。 空间...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def reverseString_1(self, s: List[str]) -> None: """方法一:双指针(递归) 时间复杂度:O(N)。执行了 N/2 次的交换。 空间复杂度:O(N),递归过程中使用的堆栈空间 N/2 。 Do not return anything, modify s in-place instead.""" def helper(left, right): if left < right: s[left], s[right] = (s[right], s[left]) ...
the_stack_v2_python_sparse
软件开发岗刷题(华为笔试准备)/递归/reverseString.py
MaoningGuan/LeetCode
train
3
034b92b1e5caa2de4d4956e9849ba3439745074e
[ "super(SepConv, self).__init__()\nself.conv = nn.Sequential(nn.Conv(in_channels, in_channels * depth_multiplier, kernel_size, groups=in_channels), nn.Conv(in_channels * depth_multiplier, out_channels, 1, bias=not with_bn))\nself.activation = activation\nself.bn = nn.BatchNorm(out_channels, momentum=0.9) if with_bn ...
<|body_start_0|> super(SepConv, self).__init__() self.conv = nn.Sequential(nn.Conv(in_channels, in_channels * depth_multiplier, kernel_size, groups=in_channels), nn.Conv(in_channels * depth_multiplier, out_channels, 1, bias=not with_bn)) self.activation = activation self.bn = nn.BatchNor...
Depthwise separable convolution with optional activation and batch normalization
SepConv
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SepConv: """Depthwise separable convolution with optional activation and batch normalization""" def __init__(self, in_channels: int, out_channels: int, kernel_size: Union[int, Tuple[int, int]], depth_multiplier=1, with_bn=True, activation=nn.ReLU()) -> None: """:param in_channels: Le...
stack_v2_sparse_classes_75kplus_train_065680
18,458
no_license
[ { "docstring": ":param in_channels: Length of input featuers (first dimension). :param out_channels: Length of output features (first dimension). :param kernel_size: Size of convolutional kernel. :depth_multiplier: Depth multiplier for middle part of separable convolution. :param with_bn: Whether or not to appl...
2
null
Implement the Python class `SepConv` described below. Class description: Depthwise separable convolution with optional activation and batch normalization Method signatures and docstrings: - def __init__(self, in_channels: int, out_channels: int, kernel_size: Union[int, Tuple[int, int]], depth_multiplier=1, with_bn=Tr...
Implement the Python class `SepConv` described below. Class description: Depthwise separable convolution with optional activation and batch normalization Method signatures and docstrings: - def __init__(self, in_channels: int, out_channels: int, kernel_size: Union[int, Tuple[int, int]], depth_multiplier=1, with_bn=Tr...
c0018e21ee1a93c0d9df2dde25144585d6e3ab49
<|skeleton|> class SepConv: """Depthwise separable convolution with optional activation and batch normalization""" def __init__(self, in_channels: int, out_channels: int, kernel_size: Union[int, Tuple[int, int]], depth_multiplier=1, with_bn=True, activation=nn.ReLU()) -> None: """:param in_channels: Le...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SepConv: """Depthwise separable convolution with optional activation and batch normalization""" def __init__(self, in_channels: int, out_channels: int, kernel_size: Union[int, Tuple[int, int]], depth_multiplier=1, with_bn=True, activation=nn.ReLU()) -> None: """:param in_channels: Length of input...
the_stack_v2_python_sparse
ops/layers.py
xiaoxTM/jittor-pcl
train
0
fced14c5b2e955582adc849d7c06ea7e5dc014d8
[ "if Singleton.__instance == None:\n Singleton()\nreturn Singleton.__instance", "if Singleton.__instance != None:\n raise Exception('This class is a singleton!')\nelse:\n Singleton.__instance = self\n embeddingFile = '/home/owner/PhD/dr.norbert/dataset/shorttext/glove.42B.300d/glove.42B.300d.txt'\n ...
<|body_start_0|> if Singleton.__instance == None: Singleton() return Singleton.__instance <|end_body_0|> <|body_start_1|> if Singleton.__instance != None: raise Exception('This class is a singleton!') else: Singleton.__instance = self embe...
Singleton
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Singleton: def getInstance(): """Static access method.""" <|body_0|> def __init__(self): """Virtually private constructor.""" <|body_1|> <|end_skeleton|> <|body_start_0|> if Singleton.__instance == None: Singleton() return Single...
stack_v2_sparse_classes_75kplus_train_065681
1,386
no_license
[ { "docstring": "Static access method.", "name": "getInstance", "signature": "def getInstance()" }, { "docstring": "Virtually private constructor.", "name": "__init__", "signature": "def __init__(self)" } ]
2
stack_v2_sparse_classes_30k_val_002279
Implement the Python class `Singleton` described below. Class description: Implement the Singleton class. Method signatures and docstrings: - def getInstance(): Static access method. - def __init__(self): Virtually private constructor.
Implement the Python class `Singleton` described below. Class description: Implement the Singleton class. Method signatures and docstrings: - def getInstance(): Static access method. - def __init__(self): Virtually private constructor. <|skeleton|> class Singleton: def getInstance(): """Static access me...
f7600a3501064000ddfd849653c7b36f5cc742f7
<|skeleton|> class Singleton: def getInstance(): """Static access method.""" <|body_0|> def __init__(self): """Virtually private constructor.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Singleton: def getInstance(): """Static access method.""" if Singleton.__instance == None: Singleton() return Singleton.__instance def __init__(self): """Virtually private constructor.""" if Singleton.__instance != None: raise Exception('Thi...
the_stack_v2_python_sparse
BatchClustering/CacheEmbeddings.py
rashadulrakib/short-text-stream-clustering
train
7
e3c0f00413c6c57f413b6f5b3b5b15944f4889a8
[ "params = {'verb': 'ListRecords', 'metadataPrefix': 'pmc'}\nif date_from:\n params['from'] = date_from.strftime(self.date_fmt)\nif date_until:\n params['until'] = date_until.strftime(self.date_fmt)\ndocs = []\nxml = self.query(**params)\nxml_parse = BS(xml)\nyield xml_parse.findAll('record')\ntoken = xml_pars...
<|body_start_0|> params = {'verb': 'ListRecords', 'metadataPrefix': 'pmc'} if date_from: params['from'] = date_from.strftime(self.date_fmt) if date_until: params['until'] = date_until.strftime(self.date_fmt) docs = [] xml = self.query(**params) xml...
Fetcher class designed to fetch data from OAI
OAIFetcher
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OAIFetcher: """Fetcher class designed to fetch data from OAI""" def fetch_batch(self, date_from=None, date_until=None): """Fetch and return a batch of documents. args: date_from : datetime - start date of batch request date_until : datetime - stop date of batch request returns: docs ...
stack_v2_sparse_classes_75kplus_train_065682
2,105
permissive
[ { "docstring": "Fetch and return a batch of documents. args: date_from : datetime - start date of batch request date_until : datetime - stop date of batch request returns: docs : a generator of raw documents in xml", "name": "fetch_batch", "signature": "def fetch_batch(self, date_from=None, date_until=N...
2
stack_v2_sparse_classes_30k_val_000515
Implement the Python class `OAIFetcher` described below. Class description: Fetcher class designed to fetch data from OAI Method signatures and docstrings: - def fetch_batch(self, date_from=None, date_until=None): Fetch and return a batch of documents. args: date_from : datetime - start date of batch request date_unt...
Implement the Python class `OAIFetcher` described below. Class description: Fetcher class designed to fetch data from OAI Method signatures and docstrings: - def fetch_batch(self, date_from=None, date_until=None): Fetch and return a batch of documents. args: date_from : datetime - start date of batch request date_unt...
3679ef4a1746a287061186078ce4b9144afe9083
<|skeleton|> class OAIFetcher: """Fetcher class designed to fetch data from OAI""" def fetch_batch(self, date_from=None, date_until=None): """Fetch and return a batch of documents. args: date_from : datetime - start date of batch request date_until : datetime - stop date of batch request returns: docs ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class OAIFetcher: """Fetcher class designed to fetch data from OAI""" def fetch_batch(self, date_from=None, date_until=None): """Fetch and return a batch of documents. args: date_from : datetime - start date of batch request date_until : datetime - stop date of batch request returns: docs : a generator...
the_stack_v2_python_sparse
collectors/fetchers/OAIFetcher.py
irhawks/citations
train
0
ce0c938c7657ddf2557e6ee790985ecf607aadc9
[ "groups = list(set(targets))\nzipped = list(zip(targets, features))\ndata = {a: np.array([b[1] for b in zipped if b[0] == a]) for a in groups}\nfeatures, targets = ([], [])\nself.group_means = {}\nfor group in data:\n mean = np.mean(data[group], axis=0)\n features.append(mean)\n targets.append(group)\n ...
<|body_start_0|> groups = list(set(targets)) zipped = list(zip(targets, features)) data = {a: np.array([b[1] for b in zipped if b[0] == a]) for a in groups} features, targets = ([], []) self.group_means = {} for group in data: mean = np.mean(data[group], axis=...
K-nearest neighbours algorithm used for classification. :param samples_per_class: Number of training examples that will be saved by the model. If None, all examples will be kept :param k: Number of neighbours to use for prediction
KNNClassifier
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KNNClassifier: """K-nearest neighbours algorithm used for classification. :param samples_per_class: Number of training examples that will be saved by the model. If None, all examples will be kept :param k: Number of neighbours to use for prediction""" def fit(self, features, targets): ...
stack_v2_sparse_classes_75kplus_train_065683
4,776
permissive
[ { "docstring": "Trains the algorithm on the given dataset. For each class, the algorithm calculates a center that is the mean of all examples of the class. It only saves self.samples_per_class values for each class. :param features: An array-like object of shape (nb_samples, nb_features) :param targets: An arra...
2
null
Implement the Python class `KNNClassifier` described below. Class description: K-nearest neighbours algorithm used for classification. :param samples_per_class: Number of training examples that will be saved by the model. If None, all examples will be kept :param k: Number of neighbours to use for prediction Method s...
Implement the Python class `KNNClassifier` described below. Class description: K-nearest neighbours algorithm used for classification. :param samples_per_class: Number of training examples that will be saved by the model. If None, all examples will be kept :param k: Number of neighbours to use for prediction Method s...
7a329136d9a8aed938db910d54f6e6aa3a1d9842
<|skeleton|> class KNNClassifier: """K-nearest neighbours algorithm used for classification. :param samples_per_class: Number of training examples that will be saved by the model. If None, all examples will be kept :param k: Number of neighbours to use for prediction""" def fit(self, features, targets): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class KNNClassifier: """K-nearest neighbours algorithm used for classification. :param samples_per_class: Number of training examples that will be saved by the model. If None, all examples will be kept :param k: Number of neighbours to use for prediction""" def fit(self, features, targets): """Trains t...
the_stack_v2_python_sparse
pylearning/neighbours/neighbours.py
Schmetzler/pylearning
train
0
05d51fd3daaca91089765c54e62bad2b07146d57
[ "self.wordHash = {}\nfor i in range(len(words)):\n if words[i] not in self.wordHash:\n self.wordHash[words[i]] = [i]\n else:\n self.wordHash[words[i]].append(i)", "word1Index = self.wordHash[word1]\nword2Index = self.wordHash[word2]\nres = float('inf')\ni = j = 0\nm, n = (len(word1Index), len(...
<|body_start_0|> self.wordHash = {} for i in range(len(words)): if words[i] not in self.wordHash: self.wordHash[words[i]] = [i] else: self.wordHash[words[i]].append(i) <|end_body_0|> <|body_start_1|> word1Index = self.wordHash[word1] ...
WordDistance
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WordDistance: def __init__(self, words): """:type words: List[str]""" <|body_0|> def shortest(self, word1, word2): """:type word1: str :type word2: str :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.wordHash = {} for i in r...
stack_v2_sparse_classes_75kplus_train_065684
1,968
no_license
[ { "docstring": ":type words: List[str]", "name": "__init__", "signature": "def __init__(self, words)" }, { "docstring": ":type word1: str :type word2: str :rtype: int", "name": "shortest", "signature": "def shortest(self, word1, word2)" } ]
2
stack_v2_sparse_classes_30k_train_036444
Implement the Python class `WordDistance` described below. Class description: Implement the WordDistance class. Method signatures and docstrings: - def __init__(self, words): :type words: List[str] - def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int
Implement the Python class `WordDistance` described below. Class description: Implement the WordDistance class. Method signatures and docstrings: - def __init__(self, words): :type words: List[str] - def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int <|skeleton|> class WordDistance: ...
604efd2c53c369fb262f42f7f7f31997ea4d029b
<|skeleton|> class WordDistance: def __init__(self, words): """:type words: List[str]""" <|body_0|> def shortest(self, word1, word2): """:type word1: str :type word2: str :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class WordDistance: def __init__(self, words): """:type words: List[str]""" self.wordHash = {} for i in range(len(words)): if words[i] not in self.wordHash: self.wordHash[words[i]] = [i] else: self.wordHash[words[i]].append(i) def ...
the_stack_v2_python_sparse
244_Shortest_Word_Distance_II.py
fxy1018/Leetcode
train
1
b952de2dbb8f70bb29b1f30c7fc9d5965059c45c
[ "super().__init__()\nself.hidden_dim = hidden_dim\nself.embedding_dim = embedding_dim\nself.length = length\nself.conv = nn.Sequential(nn.Dropout(p=cnn_dropout), nn.Conv2d(1024, self.hidden_dim, 3, padding=1), nn.ELU(), nn.Dropout(p=cnn_dropout), nn.Conv2d(self.hidden_dim, self.hidden_dim, 3, padding=1), nn.ELU())\...
<|body_start_0|> super().__init__() self.hidden_dim = hidden_dim self.embedding_dim = embedding_dim self.length = length self.conv = nn.Sequential(nn.Dropout(p=cnn_dropout), nn.Conv2d(1024, self.hidden_dim, 3, padding=1), nn.ELU(), nn.Dropout(p=cnn_dropout), nn.Conv2d(self.hidden...
Implementation of a MAC network, including question and image stem modules.
OriginalMACNetwork
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OriginalMACNetwork: """Implementation of a MAC network, including question and image stem modules.""" def __init__(self, hidden_dim: int=512, length: int=12, vocab_size: int=90, embedding_dim: int=300, cnn_dropout: float=0.18, bilstm_dropout: float=0.08): """Initialise a `MACNetwork`...
stack_v2_sparse_classes_75kplus_train_065685
11,830
no_license
[ { "docstring": "Initialise a `MACNetwork` instance.", "name": "__init__", "signature": "def __init__(self, hidden_dim: int=512, length: int=12, vocab_size: int=90, embedding_dim: int=300, cnn_dropout: float=0.18, bilstm_dropout: float=0.08)" }, { "docstring": "Reset the network's parameters.", ...
3
stack_v2_sparse_classes_30k_train_013489
Implement the Python class `OriginalMACNetwork` described below. Class description: Implementation of a MAC network, including question and image stem modules. Method signatures and docstrings: - def __init__(self, hidden_dim: int=512, length: int=12, vocab_size: int=90, embedding_dim: int=300, cnn_dropout: float=0.1...
Implement the Python class `OriginalMACNetwork` described below. Class description: Implementation of a MAC network, including question and image stem modules. Method signatures and docstrings: - def __init__(self, hidden_dim: int=512, length: int=12, vocab_size: int=90, embedding_dim: int=300, cnn_dropout: float=0.1...
78c479f8d0b3209ece9f9ccbbf63810802293f61
<|skeleton|> class OriginalMACNetwork: """Implementation of a MAC network, including question and image stem modules.""" def __init__(self, hidden_dim: int=512, length: int=12, vocab_size: int=90, embedding_dim: int=300, cnn_dropout: float=0.18, bilstm_dropout: float=0.08): """Initialise a `MACNetwork`...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class OriginalMACNetwork: """Implementation of a MAC network, including question and image stem modules.""" def __init__(self, hidden_dim: int=512, length: int=12, vocab_size: int=90, embedding_dim: int=300, cnn_dropout: float=0.18, bilstm_dropout: float=0.08): """Initialise a `MACNetwork` instance."""...
the_stack_v2_python_sparse
gat_vqa/modules/reasoning/mac/network.py
alexmirrington/gat-vqa
train
4
43cfe435a36d76f893a96942fed63dd9ac824617
[ "labels = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8])\npreds = torch.tensor([1.0, 2.1, 3.0, 4, 5.2, 6, 8, 8])\naccuracy = metrics.accuracy(labels, preds)\nself.assertEqual(accuracy, 0.625)", "pos_preds = torch.tensor([1, 1, 0, 0, 0])\nneg_preds = torch.tensor([1, 1, 0, 0, 0])\naccuracy = metrics.binary_clas_accuracy(p...
<|body_start_0|> labels = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8]) preds = torch.tensor([1.0, 2.1, 3.0, 4, 5.2, 6, 8, 8]) accuracy = metrics.accuracy(labels, preds) self.assertEqual(accuracy, 0.625) <|end_body_0|> <|body_start_1|> pos_preds = torch.tensor([1, 1, 0, 0, 0]) ...
Tests metrics.
MetricsTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MetricsTest: """Tests metrics.""" def test_accuracy(self): """Tests :meth:`~texar.torch.evals.accuracy`.""" <|body_0|> def test_binary_clas_accuracy(self): """Tests :meth:`~texar.torch.evals.binary_clas_accuracy""" <|body_1|> <|end_skeleton|> <|body_sta...
stack_v2_sparse_classes_75kplus_train_065686
1,779
permissive
[ { "docstring": "Tests :meth:`~texar.torch.evals.accuracy`.", "name": "test_accuracy", "signature": "def test_accuracy(self)" }, { "docstring": "Tests :meth:`~texar.torch.evals.binary_clas_accuracy", "name": "test_binary_clas_accuracy", "signature": "def test_binary_clas_accuracy(self)" ...
2
null
Implement the Python class `MetricsTest` described below. Class description: Tests metrics. Method signatures and docstrings: - def test_accuracy(self): Tests :meth:`~texar.torch.evals.accuracy`. - def test_binary_clas_accuracy(self): Tests :meth:`~texar.torch.evals.binary_clas_accuracy
Implement the Python class `MetricsTest` described below. Class description: Tests metrics. Method signatures and docstrings: - def test_accuracy(self): Tests :meth:`~texar.torch.evals.accuracy`. - def test_binary_clas_accuracy(self): Tests :meth:`~texar.torch.evals.binary_clas_accuracy <|skeleton|> class MetricsTes...
931ead9222ca90bfc75c3045dc79fb118de340c9
<|skeleton|> class MetricsTest: """Tests metrics.""" def test_accuracy(self): """Tests :meth:`~texar.torch.evals.accuracy`.""" <|body_0|> def test_binary_clas_accuracy(self): """Tests :meth:`~texar.torch.evals.binary_clas_accuracy""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MetricsTest: """Tests metrics.""" def test_accuracy(self): """Tests :meth:`~texar.torch.evals.accuracy`.""" labels = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8]) preds = torch.tensor([1.0, 2.1, 3.0, 4, 5.2, 6, 8, 8]) accuracy = metrics.accuracy(labels, preds) self.assert...
the_stack_v2_python_sparse
texar/torch/evals/metrics_test.py
panaali/texar-pytorch
train
1
1caa34bbc6c112da13ea9762e522e358bdcda853
[ "slower = head\nfaster = head\nwhile True:\n if faster == None or faster.next == None:\n return None\n slower = slower.next\n faster = faster.next.next\n if slower == faster:\n break\nslower = head\nwhile True:\n if slower == faster:\n return slower\n else:\n slower = s...
<|body_start_0|> slower = head faster = head while True: if faster == None or faster.next == None: return None slower = slower.next faster = faster.next.next if slower == faster: break slower = head w...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def detectCycle(self, head): """:type head: ListNode :rtype: ListNode""" <|body_0|> def detectCycle_self(self, head): """:type head: ListNode :rtype: ListNode""" <|body_1|> <|end_skeleton|> <|body_start_0|> slower = head faster = h...
stack_v2_sparse_classes_75kplus_train_065687
1,255
no_license
[ { "docstring": ":type head: ListNode :rtype: ListNode", "name": "detectCycle", "signature": "def detectCycle(self, head)" }, { "docstring": ":type head: ListNode :rtype: ListNode", "name": "detectCycle_self", "signature": "def detectCycle_self(self, head)" } ]
2
stack_v2_sparse_classes_30k_train_027810
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def detectCycle(self, head): :type head: ListNode :rtype: ListNode - def detectCycle_self(self, head): :type head: ListNode :rtype: ListNode
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def detectCycle(self, head): :type head: ListNode :rtype: ListNode - def detectCycle_self(self, head): :type head: ListNode :rtype: ListNode <|skeleton|> class Solution: de...
ea492ec864b50547214ecbbb2cdeeac21e70229b
<|skeleton|> class Solution: def detectCycle(self, head): """:type head: ListNode :rtype: ListNode""" <|body_0|> def detectCycle_self(self, head): """:type head: ListNode :rtype: ListNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def detectCycle(self, head): """:type head: ListNode :rtype: ListNode""" slower = head faster = head while True: if faster == None or faster.next == None: return None slower = slower.next faster = faster.next.next ...
the_stack_v2_python_sparse
142_linked_list_cycle_2/sol.py
lianke123321/leetcode_sol
train
0
6cc688877efaa7f979bedf374faea98d19e20ee4
[ "self.decknames = decknames\nself.p = pvalues\nself.matchups = self.matchupGen(matchups)", "sub = {}\nfor i in range(len(self.decknames)):\n name = self.decknames[i]\n sub[name] = {'': {}}\n for j in range(len(self.decknames)):\n name2 = self.decknames[j]\n mp = matchups[i][j]\n sub[...
<|body_start_0|> self.decknames = decknames self.p = pvalues self.matchups = self.matchupGen(matchups) <|end_body_0|> <|body_start_1|> sub = {} for i in range(len(self.decknames)): name = self.decknames[i] sub[name] = {'': {}} for j in range(l...
An object that can instantiate Metagames, based on some configuration.
MetaFactory
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MetaFactory: """An object that can instantiate Metagames, based on some configuration.""" def __init__(self, decknames, pvalues, matchups): """Create a MetaFactory, which can create Metagames. decknames: A list of archetype names. pvalues: A list of proportions, each corresponding to...
stack_v2_sparse_classes_75kplus_train_065688
15,382
no_license
[ { "docstring": "Create a MetaFactory, which can create Metagames. decknames: A list of archetype names. pvalues: A list of proportions, each corresponding to the appropriate deck in decknames. Should sum to 1. matchups: A 2D array of matchups, ordered in the same way, e.g. (1vs1, 1vs2, 1vs3), (2vs1, 2vs2, 2vs3)...
5
null
Implement the Python class `MetaFactory` described below. Class description: An object that can instantiate Metagames, based on some configuration. Method signatures and docstrings: - def __init__(self, decknames, pvalues, matchups): Create a MetaFactory, which can create Metagames. decknames: A list of archetype nam...
Implement the Python class `MetaFactory` described below. Class description: An object that can instantiate Metagames, based on some configuration. Method signatures and docstrings: - def __init__(self, decknames, pvalues, matchups): Create a MetaFactory, which can create Metagames. decknames: A list of archetype nam...
21587e869017024268adc3e7bf429b38a1494fb7
<|skeleton|> class MetaFactory: """An object that can instantiate Metagames, based on some configuration.""" def __init__(self, decknames, pvalues, matchups): """Create a MetaFactory, which can create Metagames. decknames: A list of archetype names. pvalues: A list of proportions, each corresponding to...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MetaFactory: """An object that can instantiate Metagames, based on some configuration.""" def __init__(self, decknames, pvalues, matchups): """Create a MetaFactory, which can create Metagames. decknames: A list of archetype names. pvalues: A list of proportions, each corresponding to the appropri...
the_stack_v2_python_sparse
metatools/meta.py
jessehatfield/tmi-metatools
train
0
a363da7a4ee66f19b99eade321a5148db2b03678
[ "port = self._client.create(network_id=network['id'])\nif check:\n self.check_presence(port)\nreturn port", "self._client.delete(port['id'])\nif check:\n self.check_presence(port, must_present=False)", "def _check_port_presence():\n is_present = bool(self._client.find_all(id=port['id']))\n return wa...
<|body_start_0|> port = self._client.create(network_id=network['id']) if check: self.check_presence(port) return port <|end_body_0|> <|body_start_1|> self._client.delete(port['id']) if check: self.check_presence(port, must_present=False) <|end_body_1|> <...
Port steps.
PortSteps
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PortSteps: """Port steps.""" def create(self, network, check=True): """Step to create port. Args: network (dict): network to create port on check (bool): flag whether to check step or not Returns: dict: port""" <|body_0|> def delete(self, port, check=True): """St...
stack_v2_sparse_classes_75kplus_train_065689
2,253
no_license
[ { "docstring": "Step to create port. Args: network (dict): network to create port on check (bool): flag whether to check step or not Returns: dict: port", "name": "create", "signature": "def create(self, network, check=True)" }, { "docstring": "Step to create port. Args: port (dict): port to del...
3
stack_v2_sparse_classes_30k_train_050540
Implement the Python class `PortSteps` described below. Class description: Port steps. Method signatures and docstrings: - def create(self, network, check=True): Step to create port. Args: network (dict): network to create port on check (bool): flag whether to check step or not Returns: dict: port - def delete(self, ...
Implement the Python class `PortSteps` described below. Class description: Port steps. Method signatures and docstrings: - def create(self, network, check=True): Step to create port. Args: network (dict): network to create port on check (bool): flag whether to check step or not Returns: dict: port - def delete(self, ...
2d85917ed9a35ee434d636fbbab60726d44af3a1
<|skeleton|> class PortSteps: """Port steps.""" def create(self, network, check=True): """Step to create port. Args: network (dict): network to create port on check (bool): flag whether to check step or not Returns: dict: port""" <|body_0|> def delete(self, port, check=True): """St...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PortSteps: """Port steps.""" def create(self, network, check=True): """Step to create port. Args: network (dict): network to create port on check (bool): flag whether to check step or not Returns: dict: port""" port = self._client.create(network_id=network['id']) if check: ...
the_stack_v2_python_sparse
stepler/neutron/steps/ports.py
Mirantis/stepler-draft
train
0
faaabaeb71d1e73aed74372579eb77123fce9c8d
[ "startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('bohorqux_peterg04_rocksdan_yfchen', 'bohorqux_peterg04_rocksdan_yfchen')\nurl = 'http://datamechanics.io/data/eileenli_yidingou/Restaurant.json'\nresponse = urllib.request.urlopen(url).read().decode('utf...
<|body_start_0|> startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('bohorqux_peterg04_rocksdan_yfchen', 'bohorqux_peterg04_rocksdan_yfchen') url = 'http://datamechanics.io/data/eileenli_yidingou/Restaurant.json' re...
getRestaurants
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class getRestaurants: def execute(trial=False): """Retrieve some data sets (not using the API here for the sake of simplicity).""" <|body_0|> def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): """Create the provenance document describing everythin...
stack_v2_sparse_classes_75kplus_train_065690
4,123
no_license
[ { "docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).", "name": "execute", "signature": "def execute(trial=False)" }, { "docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d...
2
stack_v2_sparse_classes_30k_train_008681
Implement the Python class `getRestaurants` described below. Class description: Implement the getRestaurants class. Method signatures and docstrings: - def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity). - def provenance(doc=prov.model.ProvDocument(), startTime=None,...
Implement the Python class `getRestaurants` described below. Class description: Implement the getRestaurants class. Method signatures and docstrings: - def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity). - def provenance(doc=prov.model.ProvDocument(), startTime=None,...
97e72731ffadbeae57d7a332decd58706e7c08de
<|skeleton|> class getRestaurants: def execute(trial=False): """Retrieve some data sets (not using the API here for the sake of simplicity).""" <|body_0|> def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): """Create the provenance document describing everythin...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class getRestaurants: def execute(trial=False): """Retrieve some data sets (not using the API here for the sake of simplicity).""" startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('bohorqux_peterg04_rocksdan_yfchen', ...
the_stack_v2_python_sparse
bohorqux_peterg04_rocksdan_yfchen/getRestaurants.py
ROODAY/course-2017-fal-proj
train
3
cdcbf9ed979fae17399af6fd681a6a5c618dc419
[ "super(AutoSpatialPath, self).__init__()\nsplit_arch = arch.split('_')\nself.base_channels = int(split_arch[0])\narch = [[int(a) for a in x] for x in split_arch[1].split('-')]\nself.conv1 = ConvBnRelu(3, self.base_channels, 3, 2, 1, norm_layer=norm_layer, **kwargs)\nself.arch = arch\nself.stride = stride\nself.laye...
<|body_start_0|> super(AutoSpatialPath, self).__init__() split_arch = arch.split('_') self.base_channels = int(split_arch[0]) arch = [[int(a) for a in x] for x in split_arch[1].split('-')] self.conv1 = ConvBnRelu(3, self.base_channels, 3, 2, 1, norm_layer=norm_layer, **kwargs) ...
Build spatial path from code string.
AutoSpatialPath
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AutoSpatialPath: """Build spatial path from code string.""" def __init__(self, layer, arch, norm_layer='BN', Conv2d=nn.Conv2d, stride=[1, 2, 2, 1], **kwargs): """Build spatial path. :param layer: layers of spatial path :param arch: code of model :param norm_layer: type of norm layer....
stack_v2_sparse_classes_75kplus_train_065691
10,354
permissive
[ { "docstring": "Build spatial path. :param layer: layers of spatial path :param arch: code of model :param norm_layer: type of norm layer. :param Conv2d: type of conv layer. :param stride: stride of the convolution :param **kwargs: other keywords. :return: output tensor", "name": "__init__", "signature"...
3
stack_v2_sparse_classes_30k_train_030493
Implement the Python class `AutoSpatialPath` described below. Class description: Build spatial path from code string. Method signatures and docstrings: - def __init__(self, layer, arch, norm_layer='BN', Conv2d=nn.Conv2d, stride=[1, 2, 2, 1], **kwargs): Build spatial path. :param layer: layers of spatial path :param a...
Implement the Python class `AutoSpatialPath` described below. Class description: Build spatial path from code string. Method signatures and docstrings: - def __init__(self, layer, arch, norm_layer='BN', Conv2d=nn.Conv2d, stride=[1, 2, 2, 1], **kwargs): Build spatial path. :param layer: layers of spatial path :param a...
e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04
<|skeleton|> class AutoSpatialPath: """Build spatial path from code string.""" def __init__(self, layer, arch, norm_layer='BN', Conv2d=nn.Conv2d, stride=[1, 2, 2, 1], **kwargs): """Build spatial path. :param layer: layers of spatial path :param arch: code of model :param norm_layer: type of norm layer....
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AutoSpatialPath: """Build spatial path from code string.""" def __init__(self, layer, arch, norm_layer='BN', Conv2d=nn.Conv2d, stride=[1, 2, 2, 1], **kwargs): """Build spatial path. :param layer: layers of spatial path :param arch: code of model :param norm_layer: type of norm layer. :param Conv2...
the_stack_v2_python_sparse
zeus/networks/pytorch/customs/segmentation/evolveresnet.py
huawei-noah/xingtian
train
308
85d49deaac9df33918e09e248a7b376d38744110
[ "super().__init__(reduction=reduction)\nif babilim.is_backend(babilim.PYTORCH_BACKEND):\n from torch.nn import SmoothL1Loss\n self.loss_fun = SmoothL1Loss(reduction='none')\nelse:\n from tensorflow.keras.losses import huber\n self.loss_fun = huber\n self.delta = 1.0", "if babilim.is_backend(babilim...
<|body_start_0|> super().__init__(reduction=reduction) if babilim.is_backend(babilim.PYTORCH_BACKEND): from torch.nn import SmoothL1Loss self.loss_fun = SmoothL1Loss(reduction='none') else: from tensorflow.keras.losses import huber self.loss_fun = ...
SmoothL1Loss
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SmoothL1Loss: def __init__(self, reduction: str='mean'): """Compute a binary cross entropy. This means that the preds are logits and the targets are a binary (1 or 0) tensor of same shape as logits. :param reduction: Specifies the reduction to apply to the output: `'none'` | `'mean'` | `...
stack_v2_sparse_classes_75kplus_train_065692
18,625
permissive
[ { "docstring": "Compute a binary cross entropy. This means that the preds are logits and the targets are a binary (1 or 0) tensor of same shape as logits. :param reduction: Specifies the reduction to apply to the output: `'none'` | `'mean'` | `'sum'`. `'none'`: no reduction will be applied, `'mean'`: the sum of...
2
stack_v2_sparse_classes_30k_train_042147
Implement the Python class `SmoothL1Loss` described below. Class description: Implement the SmoothL1Loss class. Method signatures and docstrings: - def __init__(self, reduction: str='mean'): Compute a binary cross entropy. This means that the preds are logits and the targets are a binary (1 or 0) tensor of same shape...
Implement the Python class `SmoothL1Loss` described below. Class description: Implement the SmoothL1Loss class. Method signatures and docstrings: - def __init__(self, reduction: str='mean'): Compute a binary cross entropy. This means that the preds are logits and the targets are a binary (1 or 0) tensor of same shape...
d3b1dd7c38a9de8f1e553cc5c0b2dfa62fe25c27
<|skeleton|> class SmoothL1Loss: def __init__(self, reduction: str='mean'): """Compute a binary cross entropy. This means that the preds are logits and the targets are a binary (1 or 0) tensor of same shape as logits. :param reduction: Specifies the reduction to apply to the output: `'none'` | `'mean'` | `...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SmoothL1Loss: def __init__(self, reduction: str='mean'): """Compute a binary cross entropy. This means that the preds are logits and the targets are a binary (1 or 0) tensor of same shape as logits. :param reduction: Specifies the reduction to apply to the output: `'none'` | `'mean'` | `'sum'`. `'none...
the_stack_v2_python_sparse
babilim/training/losses.py
penguinmenac3/babilim
train
1
52123965c47ba4877da0a9fa569e27fa68087227
[ "self.max_num_data_points = max_num_data_points\nself.data_dim = data_dim\nself.max_k = max_k\ntarget_dim = 1 + data_dim + int(data_dim * (data_dim + 1) / 2)\nself.tfmr = transformer.EncoderDecoderTransformer.partial(target_dim=target_dim, max_input_length=max_num_data_points, max_target_length=max_k, num_heads=num...
<|body_start_0|> self.max_num_data_points = max_num_data_points self.data_dim = data_dim self.max_k = max_k target_dim = 1 + data_dim + int(data_dim * (data_dim + 1) / 2) self.tfmr = transformer.EncoderDecoderTransformer.partial(target_dim=target_dim, max_input_length=max_num_dat...
MeanScaleWeightInferenceMachine
[ "Apache-2.0", "CC-BY-4.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MeanScaleWeightInferenceMachine: def __init__(self, data_dim=2, max_k=2, max_num_data_points=25, num_heads=8, num_encoders=6, num_decoders=6, qkv_dim=512, activation_fn=flax.deprecated.nn.relu, weight_init=jax.nn.initializers.xavier_uniform()): """Creates the model. Args: data_dim: The d...
stack_v2_sparse_classes_75kplus_train_065693
18,989
permissive
[ { "docstring": "Creates the model. Args: data_dim: The dimensionality of the data points to be fed in. max_k: The maximum number of clusters that could occur in the data. max_num_data_points: The maximum number of data points that could be fed in at one time. num_heads: The number of heads to use in the transfo...
5
null
Implement the Python class `MeanScaleWeightInferenceMachine` described below. Class description: Implement the MeanScaleWeightInferenceMachine class. Method signatures and docstrings: - def __init__(self, data_dim=2, max_k=2, max_num_data_points=25, num_heads=8, num_encoders=6, num_decoders=6, qkv_dim=512, activation...
Implement the Python class `MeanScaleWeightInferenceMachine` described below. Class description: Implement the MeanScaleWeightInferenceMachine class. Method signatures and docstrings: - def __init__(self, data_dim=2, max_k=2, max_num_data_points=25, num_heads=8, num_encoders=6, num_decoders=6, qkv_dim=512, activation...
5573d9c5822f4e866b6692769963ae819cb3f10d
<|skeleton|> class MeanScaleWeightInferenceMachine: def __init__(self, data_dim=2, max_k=2, max_num_data_points=25, num_heads=8, num_encoders=6, num_decoders=6, qkv_dim=512, activation_fn=flax.deprecated.nn.relu, weight_init=jax.nn.initializers.xavier_uniform()): """Creates the model. Args: data_dim: The d...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MeanScaleWeightInferenceMachine: def __init__(self, data_dim=2, max_k=2, max_num_data_points=25, num_heads=8, num_encoders=6, num_decoders=6, qkv_dim=512, activation_fn=flax.deprecated.nn.relu, weight_init=jax.nn.initializers.xavier_uniform()): """Creates the model. Args: data_dim: The dimensionality ...
the_stack_v2_python_sparse
learn_to_infer/gmm_models.py
Jimmy-INL/google-research
train
1
c7e8906553914cb951cb023b1af42c20752c8be1
[ "assert_pycocotools_installed('PyCOCOWrapper')\nCOCO.__init__(self, annotation_file=None)\nself._eval_type = 'box'\nif gt_dataset:\n self.dataset = gt_dataset\n self.createIndex()", "res = COCO()\nres.dataset['images'] = copy.deepcopy(self.dataset['images'])\nres.dataset['categories'] = copy.deepcopy(self.d...
<|body_start_0|> assert_pycocotools_installed('PyCOCOWrapper') COCO.__init__(self, annotation_file=None) self._eval_type = 'box' if gt_dataset: self.dataset = gt_dataset self.createIndex() <|end_body_0|> <|body_start_1|> res = COCO() res.dataset['...
COCO wrapper class. This class wraps COCO API object, which provides the following additional functionalities: 1. Support string type image id. 2. Support loading the groundtruth dataset using the external annotation dictionary. 3. Support loading the prediction results using the external annotation dictionary.
PyCOCOWrapper
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PyCOCOWrapper: """COCO wrapper class. This class wraps COCO API object, which provides the following additional functionalities: 1. Support string type image id. 2. Support loading the groundtruth dataset using the external annotation dictionary. 3. Support loading the prediction results using th...
stack_v2_sparse_classes_75kplus_train_065694
8,149
permissive
[ { "docstring": "Instantiates a COCO-style API object. Args: eval_type: either 'box' or 'mask'. annotation_file: a JSON file that stores annotations of the eval dataset. This is required if `gt_dataset` is not provided. gt_dataset: the groundtruth eval dataset in COCO API format.", "name": "__init__", "s...
2
stack_v2_sparse_classes_30k_train_028019
Implement the Python class `PyCOCOWrapper` described below. Class description: COCO wrapper class. This class wraps COCO API object, which provides the following additional functionalities: 1. Support string type image id. 2. Support loading the groundtruth dataset using the external annotation dictionary. 3. Support ...
Implement the Python class `PyCOCOWrapper` described below. Class description: COCO wrapper class. This class wraps COCO API object, which provides the following additional functionalities: 1. Support string type image id. 2. Support loading the groundtruth dataset using the external annotation dictionary. 3. Support ...
e83f229f1b7b847cd712d5cd4810097d3e06d14e
<|skeleton|> class PyCOCOWrapper: """COCO wrapper class. This class wraps COCO API object, which provides the following additional functionalities: 1. Support string type image id. 2. Support loading the groundtruth dataset using the external annotation dictionary. 3. Support loading the prediction results using th...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PyCOCOWrapper: """COCO wrapper class. This class wraps COCO API object, which provides the following additional functionalities: 1. Support string type image id. 2. Support loading the groundtruth dataset using the external annotation dictionary. 3. Support loading the prediction results using the external an...
the_stack_v2_python_sparse
keras_cv/metrics/coco/pycoco_wrapper.py
keras-team/keras-cv
train
818
781d002e5ce2177595aeae5056758074f2b49f07
[ "self.quota_policy = quota_policy\nself.sid = sid\nself.unix_uid = unix_uid", "if dictionary is None:\n return None\nquota_policy = cohesity_management_sdk.models.quota_policy.QuotaPolicy.from_dictionary(dictionary.get('quotaPolicy')) if dictionary.get('quotaPolicy') else None\nsid = dictionary.get('sid')\nuni...
<|body_start_0|> self.quota_policy = quota_policy self.sid = sid self.unix_uid = unix_uid <|end_body_0|> <|body_start_1|> if dictionary is None: return None quota_policy = cohesity_management_sdk.models.quota_policy.QuotaPolicy.from_dictionary(dictionary.get('quotaPo...
Implementation of the 'UserQuota' model. Specifies the quota policy applied to a user. Attributes: quota_policy (QuotaPolicy): User quota policy applied to this user. sid (string): If interested in a user via smb_client, include SID. Otherwise, If a valid unix-id to SID mappings are available (i.e., when mixed mode is ...
UserQuota
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserQuota: """Implementation of the 'UserQuota' model. Specifies the quota policy applied to a user. Attributes: quota_policy (QuotaPolicy): User quota policy applied to this user. sid (string): If interested in a user via smb_client, include SID. Otherwise, If a valid unix-id to SID mappings are...
stack_v2_sparse_classes_75kplus_train_065695
2,632
permissive
[ { "docstring": "Constructor for the UserQuota class", "name": "__init__", "signature": "def __init__(self, quota_policy=None, sid=None, unix_uid=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object ...
2
stack_v2_sparse_classes_30k_train_043105
Implement the Python class `UserQuota` described below. Class description: Implementation of the 'UserQuota' model. Specifies the quota policy applied to a user. Attributes: quota_policy (QuotaPolicy): User quota policy applied to this user. sid (string): If interested in a user via smb_client, include SID. Otherwise,...
Implement the Python class `UserQuota` described below. Class description: Implementation of the 'UserQuota' model. Specifies the quota policy applied to a user. Attributes: quota_policy (QuotaPolicy): User quota policy applied to this user. sid (string): If interested in a user via smb_client, include SID. Otherwise,...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class UserQuota: """Implementation of the 'UserQuota' model. Specifies the quota policy applied to a user. Attributes: quota_policy (QuotaPolicy): User quota policy applied to this user. sid (string): If interested in a user via smb_client, include SID. Otherwise, If a valid unix-id to SID mappings are...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UserQuota: """Implementation of the 'UserQuota' model. Specifies the quota policy applied to a user. Attributes: quota_policy (QuotaPolicy): User quota policy applied to this user. sid (string): If interested in a user via smb_client, include SID. Otherwise, If a valid unix-id to SID mappings are available (i...
the_stack_v2_python_sparse
cohesity_management_sdk/models/user_quota.py
cohesity/management-sdk-python
train
24
41f0d0ad5e971b2d4f0352278ab517ecbcf7767c
[ "shots = 100\ncircuits = ref_measure.measure_circuits_deterministic(allow_sampling=True)\ntargets = ref_measure.measure_counts_deterministic(shots)\nqobj = assemble(circuits, self.SIMULATOR, shots=shots)\nresult = self.SIMULATOR.run(qobj, backend_options=self.BACKEND_OPTS).result()\nself.is_completed(result)\nself....
<|body_start_0|> shots = 100 circuits = ref_measure.measure_circuits_deterministic(allow_sampling=True) targets = ref_measure.measure_counts_deterministic(shots) qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run(qobj, backend_options=self.BACKEND_...
QasmSimulator measure tests.
QasmMeasureTests
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QasmMeasureTests: """QasmSimulator measure tests.""" def test_measure_deterministic_with_sampling(self): """Test QasmSimulator measure with deterministic counts with sampling""" <|body_0|> def test_measure_deterministic_without_sampling(self): """Test QasmSimulat...
stack_v2_sparse_classes_75kplus_train_065696
10,352
permissive
[ { "docstring": "Test QasmSimulator measure with deterministic counts with sampling", "name": "test_measure_deterministic_with_sampling", "signature": "def test_measure_deterministic_with_sampling(self)" }, { "docstring": "Test QasmSimulator measure with deterministic counts without sampling", ...
6
stack_v2_sparse_classes_30k_train_001428
Implement the Python class `QasmMeasureTests` described below. Class description: QasmSimulator measure tests. Method signatures and docstrings: - def test_measure_deterministic_with_sampling(self): Test QasmSimulator measure with deterministic counts with sampling - def test_measure_deterministic_without_sampling(se...
Implement the Python class `QasmMeasureTests` described below. Class description: QasmSimulator measure tests. Method signatures and docstrings: - def test_measure_deterministic_with_sampling(self): Test QasmSimulator measure with deterministic counts with sampling - def test_measure_deterministic_without_sampling(se...
0c1c805fd5dfce465a8955ee3faf81037023a23e
<|skeleton|> class QasmMeasureTests: """QasmSimulator measure tests.""" def test_measure_deterministic_with_sampling(self): """Test QasmSimulator measure with deterministic counts with sampling""" <|body_0|> def test_measure_deterministic_without_sampling(self): """Test QasmSimulat...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class QasmMeasureTests: """QasmSimulator measure tests.""" def test_measure_deterministic_with_sampling(self): """Test QasmSimulator measure with deterministic counts with sampling""" shots = 100 circuits = ref_measure.measure_circuits_deterministic(allow_sampling=True) targets ...
the_stack_v2_python_sparse
artifacts/old_dataset_versions/original_commits_backup/qiskit-aer/qiskit-aer#322/before/qasm_measure.py
MattePalte/Bugs-Quantum-Computing-Platforms
train
4
52f949b2ab0f69fb243625c573715e9c238cc200
[ "super(RNNDecoder, self).__init__()\nself.embedding = tf.keras.layers.Embedding(input_dim=vocab, output_dim=embedding)\nself.gru = tf.keras.layers.GRU(units=units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform')\nself.F = tf.keras.layers.Dense(vocab)", "context, _ = SelfAttention...
<|body_start_0|> super(RNNDecoder, self).__init__() self.embedding = tf.keras.layers.Embedding(input_dim=vocab, output_dim=embedding) self.gru = tf.keras.layers.GRU(units=units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform') self.F = tf.keras.layers.Den...
Class representation of a decoder for machine translation
RNNDecoder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RNNDecoder: """Class representation of a decoder for machine translation""" def __init__(self, vocab, embedding, units, batch): """vocab: integer representing the size of the output vocabulary embedding: integer representing the dimensionality of the embedding vector units: integer r...
stack_v2_sparse_classes_75kplus_train_065697
2,342
no_license
[ { "docstring": "vocab: integer representing the size of the output vocabulary embedding: integer representing the dimensionality of the embedding vector units: integer representing the number of hidden units in the RNN cell batch: integer representing the batch size", "name": "__init__", "signature": "d...
2
stack_v2_sparse_classes_30k_train_041758
Implement the Python class `RNNDecoder` described below. Class description: Class representation of a decoder for machine translation Method signatures and docstrings: - def __init__(self, vocab, embedding, units, batch): vocab: integer representing the size of the output vocabulary embedding: integer representing th...
Implement the Python class `RNNDecoder` described below. Class description: Class representation of a decoder for machine translation Method signatures and docstrings: - def __init__(self, vocab, embedding, units, batch): vocab: integer representing the size of the output vocabulary embedding: integer representing th...
2757c8526290197d45a4de33cda71e686ddcbf1c
<|skeleton|> class RNNDecoder: """Class representation of a decoder for machine translation""" def __init__(self, vocab, embedding, units, batch): """vocab: integer representing the size of the output vocabulary embedding: integer representing the dimensionality of the embedding vector units: integer r...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RNNDecoder: """Class representation of a decoder for machine translation""" def __init__(self, vocab, embedding, units, batch): """vocab: integer representing the size of the output vocabulary embedding: integer representing the dimensionality of the embedding vector units: integer representing t...
the_stack_v2_python_sparse
supervised_learning/0x11-attention/2-rnn_decoder.py
95ktsmith/holbertonschool-machine_learning
train
0
036ced2c0800b972a8e3c10523501538ff1f5496
[ "if not name in self:\n self[name] = instance\nelse:\n raise RepeatError('The repeat name \"%s\" already exists! ' % name + 'If you are creating a new repeat, please use a different ' + 'name. If you are updating the repeat, please use ' + 'repeat.find(\"%s\").' % name)", "try:\n del self[name]\nexcept K...
<|body_start_0|> if not name in self: self[name] = instance else: raise RepeatError('The repeat name "%s" already exists! ' % name + 'If you are creating a new repeat, please use a different ' + 'name. If you are updating the repeat, please use ' + 'repeat.find("%s").' % name) <|...
Dictionary object that contains all repeat instances. The keys of the dictionary are the repeat names and the Repeat() instances are the values of the keys.
RepeatContainer
[ "Artistic-1.0", "LicenseRef-scancode-public-domain" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RepeatContainer: """Dictionary object that contains all repeat instances. The keys of the dictionary are the repeat names and the Repeat() instances are the values of the keys.""" def add(self, name, instance): """Adds a repeat instance by name to the dictionary.""" <|body_0|...
stack_v2_sparse_classes_75kplus_train_065698
14,534
permissive
[ { "docstring": "Adds a repeat instance by name to the dictionary.", "name": "add", "signature": "def add(self, name, instance)" }, { "docstring": "Deletes a repeat instance by name from the container.", "name": "delete", "signature": "def delete(self, name)" } ]
2
stack_v2_sparse_classes_30k_train_001262
Implement the Python class `RepeatContainer` described below. Class description: Dictionary object that contains all repeat instances. The keys of the dictionary are the repeat names and the Repeat() instances are the values of the keys. Method signatures and docstrings: - def add(self, name, instance): Adds a repeat...
Implement the Python class `RepeatContainer` described below. Class description: Dictionary object that contains all repeat instances. The keys of the dictionary are the repeat names and the Repeat() instances are the values of the keys. Method signatures and docstrings: - def add(self, name, instance): Adds a repeat...
ebf4624626266f552189a32612b8d09cd5b4c5a3
<|skeleton|> class RepeatContainer: """Dictionary object that contains all repeat instances. The keys of the dictionary are the repeat names and the Repeat() instances are the values of the keys.""" def add(self, name, instance): """Adds a repeat instance by name to the dictionary.""" <|body_0|...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RepeatContainer: """Dictionary object that contains all repeat instances. The keys of the dictionary are the repeat names and the Repeat() instances are the values of the keys.""" def add(self, name, instance): """Adds a repeat instance by name to the dictionary.""" if not name in self: ...
the_stack_v2_python_sparse
cstrike/addons/eventscripts/gungame51/core/repeat/repeat.py
GunGame-Dev-Team/GunGame51
train
0
8ca31fb871a7994a8b7e812be61dc55ea9bb1b36
[ "m = {}\nfor row in matrix:\n key = tuple(row)\n if m.get(key, 0) != 0:\n m[key] += 1\n else:\n key = tuple((1 - x for x in row))\n if m.get(key, 0) != 0:\n m[key] += 1\n else:\n m[key] = 1\nreturn max((x for _, x in m.items()))", "ret = 0\nfor i in range...
<|body_start_0|> m = {} for row in matrix: key = tuple(row) if m.get(key, 0) != 0: m[key] += 1 else: key = tuple((1 - x for x in row)) if m.get(key, 0) != 0: m[key] += 1 else: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxEqualRowsAfterFlips(self, matrix): """:type matrix: List[List[int]] :rtype: int""" <|body_0|> def maxEqualRowsAfterFlips1(self, matrix): """:type matrix: List[List[int]] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> m ...
stack_v2_sparse_classes_75kplus_train_065699
1,192
no_license
[ { "docstring": ":type matrix: List[List[int]] :rtype: int", "name": "maxEqualRowsAfterFlips", "signature": "def maxEqualRowsAfterFlips(self, matrix)" }, { "docstring": ":type matrix: List[List[int]] :rtype: int", "name": "maxEqualRowsAfterFlips1", "signature": "def maxEqualRowsAfterFlips...
2
stack_v2_sparse_classes_30k_train_016030
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxEqualRowsAfterFlips(self, matrix): :type matrix: List[List[int]] :rtype: int - def maxEqualRowsAfterFlips1(self, matrix): :type matrix: List[List[int]] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxEqualRowsAfterFlips(self, matrix): :type matrix: List[List[int]] :rtype: int - def maxEqualRowsAfterFlips1(self, matrix): :type matrix: List[List[int]] :rtype: int <|skel...
70bdd75b6af2e1811c1beab22050c01d28d7373e
<|skeleton|> class Solution: def maxEqualRowsAfterFlips(self, matrix): """:type matrix: List[List[int]] :rtype: int""" <|body_0|> def maxEqualRowsAfterFlips1(self, matrix): """:type matrix: List[List[int]] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def maxEqualRowsAfterFlips(self, matrix): """:type matrix: List[List[int]] :rtype: int""" m = {} for row in matrix: key = tuple(row) if m.get(key, 0) != 0: m[key] += 1 else: key = tuple((1 - x for x in row)) ...
the_stack_v2_python_sparse
python/leetcode/1072_Flip_Columns_For_Maximum_Number_of_Equal_Rows.py
bobcaoge/my-code
train
0