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 467 8.64k | id stringlengths 40 40 | length_bytes int64 515 49.7k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 160 3.93k | prompted_full_text stringlengths 681 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.09k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 331 8.3k | source stringclasses 1
value | source_path stringlengths 5 177 | source_repo stringlengths 6 88 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aec4e05b567dd771e14544f27f007cdf08280014 | [
"np.random.seed(106)\nself.params = dict()\nself.params['W1'] = weight_init_std * np.random.randn(input_size, hidden_size)\nself.params['b1'] = np.zeros(hidden_size)\nself.params['W2'] = weight_init_std * np.random.randn(hidden_size, output_size)\nself.params['b2'] = np.zeros(output_size)\nself.layers = OrderedDict... | <|body_start_0|>
np.random.seed(106)
self.params = dict()
self.params['W1'] = weight_init_std * np.random.randn(input_size, hidden_size)
self.params['b1'] = np.zeros(hidden_size)
self.params['W2'] = weight_init_std * np.random.randn(hidden_size, output_size)
self.params['... | TwoLayerNetwork | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwoLayerNetwork:
def __init__(self, input_size, hidden_size, output_size, weight_init_std=0.01):
"""신경망의 구조 결정"""
<|body_0|>
def predict(self, x):
"""input x를 받아 Forwrd Propagation을 통해 예측된 output Y1 = self.layer['affine1].forward(x) Y2 = self.layer['relu].forward(Y1)... | stack_v2_sparse_classes_10k_train_000500 | 7,910 | no_license | [
{
"docstring": "신경망의 구조 결정",
"name": "__init__",
"signature": "def __init__(self, input_size, hidden_size, output_size, weight_init_std=0.01)"
},
{
"docstring": "input x를 받아 Forwrd Propagation을 통해 예측된 output Y1 = self.layer['affine1].forward(x) Y2 = self.layer['relu].forward(Y1) Y3 = self.layer[... | 5 | stack_v2_sparse_classes_30k_train_002554 | Implement the Python class `TwoLayerNetwork` described below.
Class description:
Implement the TwoLayerNetwork class.
Method signatures and docstrings:
- def __init__(self, input_size, hidden_size, output_size, weight_init_std=0.01): 신경망의 구조 결정
- def predict(self, x): input x를 받아 Forwrd Propagation을 통해 예측된 output Y1 ... | Implement the Python class `TwoLayerNetwork` described below.
Class description:
Implement the TwoLayerNetwork class.
Method signatures and docstrings:
- def __init__(self, input_size, hidden_size, output_size, weight_init_std=0.01): 신경망의 구조 결정
- def predict(self, x): input x를 받아 Forwrd Propagation을 통해 예측된 output Y1 ... | 99ddcadec0c93bd42113f6b5fbecd9171c030f8b | <|skeleton|>
class TwoLayerNetwork:
def __init__(self, input_size, hidden_size, output_size, weight_init_std=0.01):
"""신경망의 구조 결정"""
<|body_0|>
def predict(self, x):
"""input x를 받아 Forwrd Propagation을 통해 예측된 output Y1 = self.layer['affine1].forward(x) Y2 = self.layer['relu].forward(Y1)... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TwoLayerNetwork:
def __init__(self, input_size, hidden_size, output_size, weight_init_std=0.01):
"""신경망의 구조 결정"""
np.random.seed(106)
self.params = dict()
self.params['W1'] = weight_init_std * np.random.randn(input_size, hidden_size)
self.params['b1'] = np.zeros(hidden_... | the_stack_v2_python_sparse | ch05_Back_Propagation/ex10_MNIST_Two_Layer_NN_Propagation.py | handaeho/lab_dl | train | 0 | |
94602e1fb02942065bb21bcd3ac0801c77000f83 | [
"if not settings.REGISTER_ENABLED:\n raise BadRequest(_('Public register is disabled.'))\nserializer = RegisterSerializer(data=request.data)\nif not serializer.is_valid():\n raise RequestValidationError(serializer.errors)\ndata = serializer.data\nregister(**data)\nreturn Response(data, status=status.HTTP_201_... | <|body_start_0|>
if not settings.REGISTER_ENABLED:
raise BadRequest(_('Public register is disabled.'))
serializer = RegisterSerializer(data=request.data)
if not serializer.is_valid():
raise RequestValidationError(serializer.errors)
data = serializer.data
r... | AuthViewSet | [
"MIT",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthViewSet:
def register(self, request, **kwargs):
"""Register for a new user. --- parameters: - name: first_name description: user first name required: true type: string paramType: form - name: last_name description: user last name required: true type: string paramType: form - name: em... | stack_v2_sparse_classes_10k_train_000501 | 6,297 | permissive | [
{
"docstring": "Register for a new user. --- parameters: - name: first_name description: user first name required: true type: string paramType: form - name: last_name description: user last name required: true type: string paramType: form - name: email description: user email required: true type: string paramTy... | 6 | stack_v2_sparse_classes_30k_train_004644 | Implement the Python class `AuthViewSet` described below.
Class description:
Implement the AuthViewSet class.
Method signatures and docstrings:
- def register(self, request, **kwargs): Register for a new user. --- parameters: - name: first_name description: user first name required: true type: string paramType: form ... | Implement the Python class `AuthViewSet` described below.
Class description:
Implement the AuthViewSet class.
Method signatures and docstrings:
- def register(self, request, **kwargs): Register for a new user. --- parameters: - name: first_name description: user first name required: true type: string paramType: form ... | 665de9832e8a262f9051f4075572f5aed0553f6e | <|skeleton|>
class AuthViewSet:
def register(self, request, **kwargs):
"""Register for a new user. --- parameters: - name: first_name description: user first name required: true type: string paramType: form - name: last_name description: user last name required: true type: string paramType: form - name: em... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AuthViewSet:
def register(self, request, **kwargs):
"""Register for a new user. --- parameters: - name: first_name description: user first name required: true type: string paramType: form - name: last_name description: user last name required: true type: string paramType: form - name: email descriptio... | the_stack_v2_python_sparse | app/auth/api.py | sololuz/cibb-web | train | 0 | |
00f5220631f275b3e3dd0d3a1fd27482110ddf65 | [
"if '_xml_ns' in kwargs:\n self._xml_ns = kwargs['_xml_ns']\nif '_xml_ns_key' in kwargs:\n self._xml_ns_key = kwargs['_xml_ns_key']\nself.AzSF = AzSF\nself.KazPoly = KazPoly\nsuper(RgAzCompType, self).__init__(**kwargs)",
"look = SCPCOA.look\naz_sf = -look * numpy.sin(numpy.deg2rad(SCPCOA.DopplerConeAng)) /... | <|body_start_0|>
if '_xml_ns' in kwargs:
self._xml_ns = kwargs['_xml_ns']
if '_xml_ns_key' in kwargs:
self._xml_ns_key = kwargs['_xml_ns_key']
self.AzSF = AzSF
self.KazPoly = KazPoly
super(RgAzCompType, self).__init__(**kwargs)
<|end_body_0|>
<|body_start... | Parameters included for a Range, Doppler image. | RgAzCompType | [
"MIT",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RgAzCompType:
"""Parameters included for a Range, Doppler image."""
def __init__(self, AzSF: float=None, KazPoly: Union[Poly1DType, numpy.ndarray, list, tuple]=None, **kwargs):
"""Parameters ---------- AzSF : float KazPoly : Poly1DType|numpy.ndarray|list|tuple kwargs"""
<|bod... | stack_v2_sparse_classes_10k_train_000502 | 3,652 | permissive | [
{
"docstring": "Parameters ---------- AzSF : float KazPoly : Poly1DType|numpy.ndarray|list|tuple kwargs",
"name": "__init__",
"signature": "def __init__(self, AzSF: float=None, KazPoly: Union[Poly1DType, numpy.ndarray, list, tuple]=None, **kwargs)"
},
{
"docstring": "Expected to be called by the... | 2 | stack_v2_sparse_classes_30k_val_000178 | Implement the Python class `RgAzCompType` described below.
Class description:
Parameters included for a Range, Doppler image.
Method signatures and docstrings:
- def __init__(self, AzSF: float=None, KazPoly: Union[Poly1DType, numpy.ndarray, list, tuple]=None, **kwargs): Parameters ---------- AzSF : float KazPoly : Po... | Implement the Python class `RgAzCompType` described below.
Class description:
Parameters included for a Range, Doppler image.
Method signatures and docstrings:
- def __init__(self, AzSF: float=None, KazPoly: Union[Poly1DType, numpy.ndarray, list, tuple]=None, **kwargs): Parameters ---------- AzSF : float KazPoly : Po... | de1b1886f161a83b6c89aadc7a2c7cfc4892ef81 | <|skeleton|>
class RgAzCompType:
"""Parameters included for a Range, Doppler image."""
def __init__(self, AzSF: float=None, KazPoly: Union[Poly1DType, numpy.ndarray, list, tuple]=None, **kwargs):
"""Parameters ---------- AzSF : float KazPoly : Poly1DType|numpy.ndarray|list|tuple kwargs"""
<|bod... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RgAzCompType:
"""Parameters included for a Range, Doppler image."""
def __init__(self, AzSF: float=None, KazPoly: Union[Poly1DType, numpy.ndarray, list, tuple]=None, **kwargs):
"""Parameters ---------- AzSF : float KazPoly : Poly1DType|numpy.ndarray|list|tuple kwargs"""
if '_xml_ns' in kw... | the_stack_v2_python_sparse | sarpy/io/complex/sicd_elements/RgAzComp.py | ngageoint/sarpy | train | 192 |
d01e533c15be3ffa5d7717e6909ec649a258309c | [
"self.__ops = ops\nself.__nops = len(ops)\nfor iop in range(self.__nops):\n if not isinstance(self.__ops[iop], operator):\n raise Exception('Elements of ops list must be of type operator')\nif self.__nops != len(dims):\n raise Exception('Number of dimensions (%d) must equal number of operators (%d)' % ... | <|body_start_0|>
self.__ops = ops
self.__nops = len(ops)
for iop in range(self.__nops):
if not isinstance(self.__ops[iop], operator):
raise Exception('Elements of ops list must be of type operator')
if self.__nops != len(dims):
raise Exception('Num... | A diagonal operator | diagop | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class diagop:
"""A diagonal operator"""
def __init__(self, ops, dims, epss=None):
"""diagop constructor Parameters ops - a list of operators used to form the row operator dims - a list of dictionaries that contain the dimensions of the inputs and outputs of the arrays For example dims = [{... | stack_v2_sparse_classes_10k_train_000503 | 13,837 | no_license | [
{
"docstring": "diagop constructor Parameters ops - a list of operators used to form the row operator dims - a list of dictionaries that contain the dimensions of the inputs and outputs of the arrays For example dims = [{'nrows': 10, 'ncols': 10},...] epss - a list of scalar values to be applied to the output o... | 4 | stack_v2_sparse_classes_30k_train_004227 | Implement the Python class `diagop` described below.
Class description:
A diagonal operator
Method signatures and docstrings:
- def __init__(self, ops, dims, epss=None): diagop constructor Parameters ops - a list of operators used to form the row operator dims - a list of dictionaries that contain the dimensions of t... | Implement the Python class `diagop` described below.
Class description:
A diagonal operator
Method signatures and docstrings:
- def __init__(self, ops, dims, epss=None): diagop constructor Parameters ops - a list of operators used to form the row operator dims - a list of dictionaries that contain the dimensions of t... | 32a303eddd13385d8778b8bb3b4fbbfbe78bea51 | <|skeleton|>
class diagop:
"""A diagonal operator"""
def __init__(self, ops, dims, epss=None):
"""diagop constructor Parameters ops - a list of operators used to form the row operator dims - a list of dictionaries that contain the dimensions of the inputs and outputs of the arrays For example dims = [{... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class diagop:
"""A diagonal operator"""
def __init__(self, ops, dims, epss=None):
"""diagop constructor Parameters ops - a list of operators used to form the row operator dims - a list of dictionaries that contain the dimensions of the inputs and outputs of the arrays For example dims = [{'nrows': 10, ... | the_stack_v2_python_sparse | opt/linopt/combops.py | ke0m/scaas | train | 2 |
9bd90dfa9cf9a776224647c536872ff986a7d894 | [
"if self.orbit:\n return 1 + self.orbit.orbit_count()\nreturn 0",
"total = 0\norbit_hops = {}\norbit = self.orbit\nwhile orbit:\n orbit_hops[orbit.name] = total\n orbit = orbit.orbit\n total += 1\nreturn orbit_hops"
] | <|body_start_0|>
if self.orbit:
return 1 + self.orbit.orbit_count()
return 0
<|end_body_0|>
<|body_start_1|>
total = 0
orbit_hops = {}
orbit = self.orbit
while orbit:
orbit_hops[orbit.name] = total
orbit = orbit.orbit
total... | Keep track of ObjectMass orbit / orbitters | ObjectMass | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectMass:
"""Keep track of ObjectMass orbit / orbitters"""
def orbit_count(self) -> int:
"""counts total number of objects this object is orbitings (directly and indirectly) Returns: int -- total orbit count"""
<|body_0|>
def get_orbit_hops(self) -> Dict[str, int]:
... | stack_v2_sparse_classes_10k_train_000504 | 2,844 | no_license | [
{
"docstring": "counts total number of objects this object is orbitings (directly and indirectly) Returns: int -- total orbit count",
"name": "orbit_count",
"signature": "def orbit_count(self) -> int"
},
{
"docstring": "return a dict with total \"hop\" count to each orbit Returns: Dict[str, int]... | 2 | stack_v2_sparse_classes_30k_train_005538 | Implement the Python class `ObjectMass` described below.
Class description:
Keep track of ObjectMass orbit / orbitters
Method signatures and docstrings:
- def orbit_count(self) -> int: counts total number of objects this object is orbitings (directly and indirectly) Returns: int -- total orbit count
- def get_orbit_h... | Implement the Python class `ObjectMass` described below.
Class description:
Keep track of ObjectMass orbit / orbitters
Method signatures and docstrings:
- def orbit_count(self) -> int: counts total number of objects this object is orbitings (directly and indirectly) Returns: int -- total orbit count
- def get_orbit_h... | 942449d25b9fbcead090a526799cb0e3dca7ecf3 | <|skeleton|>
class ObjectMass:
"""Keep track of ObjectMass orbit / orbitters"""
def orbit_count(self) -> int:
"""counts total number of objects this object is orbitings (directly and indirectly) Returns: int -- total orbit count"""
<|body_0|>
def get_orbit_hops(self) -> Dict[str, int]:
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ObjectMass:
"""Keep track of ObjectMass orbit / orbitters"""
def orbit_count(self) -> int:
"""counts total number of objects this object is orbitings (directly and indirectly) Returns: int -- total orbit count"""
if self.orbit:
return 1 + self.orbit.orbit_count()
retur... | the_stack_v2_python_sparse | advent_of_code/day_06/orbit.py | WildStriker/advent_of_code_2019 | train | 0 |
cb9c469d1df50f59a1b1673c45f39db7aaf992f0 | [
"self.all = False\nself.coverage = False\nsuper(test, self).initialize_options()",
"if self.all:\n cmd = self.apply_options(self.test_all_cmd)\n self.call_and_exit(cmd)\nelse:\n cmds = (self.apply_options(self.unit_test_cmd, ('coverage',)),)\n if self.coverage:\n cmds += (self.apply_options(sel... | <|body_start_0|>
self.all = False
self.coverage = False
super(test, self).initialize_options()
<|end_body_0|>
<|body_start_1|>
if self.all:
cmd = self.apply_options(self.test_all_cmd)
self.call_and_exit(cmd)
else:
cmds = (self.apply_options(se... | Run the test suites for this project. | test | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test:
"""Run the test suites for this project."""
def initialize_options(self):
"""Set the default options."""
<|body_0|>
def run(self):
"""Run the test suites."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.all = False
self.covera... | stack_v2_sparse_classes_10k_train_000505 | 3,851 | permissive | [
{
"docstring": "Set the default options.",
"name": "initialize_options",
"signature": "def initialize_options(self)"
},
{
"docstring": "Run the test suites.",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005232 | Implement the Python class `test` described below.
Class description:
Run the test suites for this project.
Method signatures and docstrings:
- def initialize_options(self): Set the default options.
- def run(self): Run the test suites. | Implement the Python class `test` described below.
Class description:
Run the test suites for this project.
Method signatures and docstrings:
- def initialize_options(self): Set the default options.
- def run(self): Run the test suites.
<|skeleton|>
class test:
"""Run the test suites for this project."""
de... | 4e2c417f68bc07c72b508e107431569b0783c4ef | <|skeleton|>
class test:
"""Run the test suites for this project."""
def initialize_options(self):
"""Set the default options."""
<|body_0|>
def run(self):
"""Run the test suites."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class test:
"""Run the test suites for this project."""
def initialize_options(self):
"""Set the default options."""
self.all = False
self.coverage = False
super(test, self).initialize_options()
def run(self):
"""Run the test suites."""
if self.all:
... | the_stack_v2_python_sparse | tasks.py | dbcli/cli_helpers | train | 102 |
ecc70807d73a849065a0fbdc707c63126b3cbaea | [
"self.semaphoreKey = semaphoreKey\nif context is None:\n self.logger = logging\nelse:\n self.logger = context.logger\nself.obj = obj",
"assert payload\ncached = memcache.get(self.semaphoreKey)\nif cached:\n if cached != payload:\n self.logger.critical('Run-once semaphore memcache payload write err... | <|body_start_0|>
self.semaphoreKey = semaphoreKey
if context is None:
self.logger = logging
else:
self.logger = context.logger
self.obj = obj
<|end_body_0|>
<|body_start_1|>
assert payload
cached = memcache.get(self.semaphoreKey)
if cached... | A object used to enforce run-once semantics | RunOnceSemaphore | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RunOnceSemaphore:
"""A object used to enforce run-once semantics"""
def __init__(self, semaphoreKey, context, obj=None):
"""ctor @param logger: a logging module or object"""
<|body_0|>
def writeRunOnceSemaphore(self, payload=None, transactional=True):
"""Writes t... | stack_v2_sparse_classes_10k_train_000506 | 8,985 | no_license | [
{
"docstring": "ctor @param logger: a logging module or object",
"name": "__init__",
"signature": "def __init__(self, semaphoreKey, context, obj=None)"
},
{
"docstring": "Writes the semaphore @return: a tuple of (bool, obj) where the first arg is True if the semaphore was created and work can co... | 3 | stack_v2_sparse_classes_30k_train_001822 | Implement the Python class `RunOnceSemaphore` described below.
Class description:
A object used to enforce run-once semantics
Method signatures and docstrings:
- def __init__(self, semaphoreKey, context, obj=None): ctor @param logger: a logging module or object
- def writeRunOnceSemaphore(self, payload=None, transact... | Implement the Python class `RunOnceSemaphore` described below.
Class description:
A object used to enforce run-once semantics
Method signatures and docstrings:
- def __init__(self, semaphoreKey, context, obj=None): ctor @param logger: a logging module or object
- def writeRunOnceSemaphore(self, payload=None, transact... | 0227b9621c7b0d5103ee483cebd2f9e5275dbd0f | <|skeleton|>
class RunOnceSemaphore:
"""A object used to enforce run-once semantics"""
def __init__(self, semaphoreKey, context, obj=None):
"""ctor @param logger: a logging module or object"""
<|body_0|>
def writeRunOnceSemaphore(self, payload=None, transactional=True):
"""Writes t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RunOnceSemaphore:
"""A object used to enforce run-once semantics"""
def __init__(self, semaphoreKey, context, obj=None):
"""ctor @param logger: a logging module or object"""
self.semaphoreKey = semaphoreKey
if context is None:
self.logger = logging
else:
... | the_stack_v2_python_sparse | fantasm/lock.py | awolf/Foojal | train | 1 |
bc5961805e73c9597574886d68e362772364fe45 | [
"self.kv_table = create_kv_table(capacity=capacity, value_len=value_len, key_type=np.int64, value_type=np.float32, kwargs=kwargs, solver=solver)\nself.wait_get_id = None\nself.wait_add_id = None\nself.value = Tensor([1], np.float32)\nself.grad = Tensor([1], np.float32)",
"assert isinstance(key, Tensor)\nassert is... | <|body_start_0|>
self.kv_table = create_kv_table(capacity=capacity, value_len=value_len, key_type=np.int64, value_type=np.float32, kwargs=kwargs, solver=solver)
self.wait_get_id = None
self.wait_add_id = None
self.value = Tensor([1], np.float32)
self.grad = Tensor([1], np.float32... | The embedding model param manager, which is used for managing and synchronizing the variables in sparse embedding. | Embedding | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Embedding:
"""The embedding model param manager, which is used for managing and synchronizing the variables in sparse embedding."""
def __init__(self, capacity, value_len, kwargs={}, solver='adam'):
"""The constructor of Embedding"""
<|body_0|>
def get(self, key, next_ke... | stack_v2_sparse_classes_10k_train_000507 | 2,349 | permissive | [
{
"docstring": "The constructor of Embedding",
"name": "__init__",
"signature": "def __init__(self, capacity, value_len, kwargs={}, solver='adam')"
},
{
"docstring": "get current key's value and pre-get the next key. Parameters ---------- key: The current iteration id key, which is Tensor instan... | 3 | stack_v2_sparse_classes_30k_train_007182 | Implement the Python class `Embedding` described below.
Class description:
The embedding model param manager, which is used for managing and synchronizing the variables in sparse embedding.
Method signatures and docstrings:
- def __init__(self, capacity, value_len, kwargs={}, solver='adam'): The constructor of Embedd... | Implement the Python class `Embedding` described below.
Class description:
The embedding model param manager, which is used for managing and synchronizing the variables in sparse embedding.
Method signatures and docstrings:
- def __init__(self, capacity, value_len, kwargs={}, solver='adam'): The constructor of Embedd... | 3333a669c59ce2e525945f814a54784dafc6191b | <|skeleton|>
class Embedding:
"""The embedding model param manager, which is used for managing and synchronizing the variables in sparse embedding."""
def __init__(self, capacity, value_len, kwargs={}, solver='adam'):
"""The constructor of Embedding"""
<|body_0|>
def get(self, key, next_ke... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Embedding:
"""The embedding model param manager, which is used for managing and synchronizing the variables in sparse embedding."""
def __init__(self, capacity, value_len, kwargs={}, solver='adam'):
"""The constructor of Embedding"""
self.kv_table = create_kv_table(capacity=capacity, valu... | the_stack_v2_python_sparse | binding/python/ddls/topi/embedding.py | kiminh/ddls | train | 0 |
0b0b05d98513cba036357a1f8a10a764d96b92b5 | [
"frozen_graph_name = {'alex_lin': 'net-lin_alex_v0.1_27.pb', 'alex': 'net_alex_v0.1_27.pb', 'vgg_lin': 'net-lin_vgg_v0.1_27.pb', 'vgg': 'net_vgg_v0.1_27.pb'}\nfrozen_graph_path = osp.join(frozen_graphs_parent_dir, frozen_graph_name[net])\ninputs = ['0:0', '1:0']\noutputs = {'alex_lin': 'Reshape_10:0', 'alex': 'Add_... | <|body_start_0|>
frozen_graph_name = {'alex_lin': 'net-lin_alex_v0.1_27.pb', 'alex': 'net_alex_v0.1_27.pb', 'vgg_lin': 'net-lin_vgg_v0.1_27.pb', 'vgg': 'net_vgg_v0.1_27.pb'}
frozen_graph_path = osp.join(frozen_graphs_parent_dir, frozen_graph_name[net])
inputs = ['0:0', '1:0']
outputs = {... | LPIPS | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LPIPS:
def __init__(self, net='alex_lin', frozen_graphs_parent_dir='/vulcanscratch/mmeshry/third_party/lpips'):
"""Frozen graphs can be downloaded from the following link: http://rail.eecs.berkeley.edu/models/lpips"""
<|body_0|>
def __call__(self, x, y, axis=None):
"... | stack_v2_sparse_classes_10k_train_000508 | 7,391 | permissive | [
{
"docstring": "Frozen graphs can be downloaded from the following link: http://rail.eecs.berkeley.edu/models/lpips",
"name": "__init__",
"signature": "def __init__(self, net='alex_lin', frozen_graphs_parent_dir='/vulcanscratch/mmeshry/third_party/lpips')"
},
{
"docstring": "Computes LPIPS loss ... | 2 | stack_v2_sparse_classes_30k_train_003186 | Implement the Python class `LPIPS` described below.
Class description:
Implement the LPIPS class.
Method signatures and docstrings:
- def __init__(self, net='alex_lin', frozen_graphs_parent_dir='/vulcanscratch/mmeshry/third_party/lpips'): Frozen graphs can be downloaded from the following link: http://rail.eecs.berke... | Implement the Python class `LPIPS` described below.
Class description:
Implement the LPIPS class.
Method signatures and docstrings:
- def __init__(self, net='alex_lin', frozen_graphs_parent_dir='/vulcanscratch/mmeshry/third_party/lpips'): Frozen graphs can be downloaded from the following link: http://rail.eecs.berke... | a9a6643968a7b6b29cab3b53b73ab80d14fb32b7 | <|skeleton|>
class LPIPS:
def __init__(self, net='alex_lin', frozen_graphs_parent_dir='/vulcanscratch/mmeshry/third_party/lpips'):
"""Frozen graphs can be downloaded from the following link: http://rail.eecs.berkeley.edu/models/lpips"""
<|body_0|>
def __call__(self, x, y, axis=None):
"... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LPIPS:
def __init__(self, net='alex_lin', frozen_graphs_parent_dir='/vulcanscratch/mmeshry/third_party/lpips'):
"""Frozen graphs can be downloaded from the following link: http://rail.eecs.berkeley.edu/models/lpips"""
frozen_graph_name = {'alex_lin': 'net-lin_alex_v0.1_27.pb', 'alex': 'net_ale... | the_stack_v2_python_sparse | losses/losses.py | czero69/lsr | train | 0 | |
edb73ac1fb6f4b75d99e624b56a68a0560c4425a | [
"try:\n logger.info('Starting model version %s for project %s', model_version, project_name)\n lookoutvision_client.start_model(ProjectName=project_name, ModelVersion=model_version, MinInferenceUnits=min_inference_units)\n print('Starting hosting...')\n status = ''\n finished = False\n while finis... | <|body_start_0|>
try:
logger.info('Starting model version %s for project %s', model_version, project_name)
lookoutvision_client.start_model(ProjectName=project_name, ModelVersion=model_version, MinInferenceUnits=min_inference_units)
print('Starting hosting...')
st... | Shows how to start and stop a Lookout for Vision Model. Also shows how to list the models that are currently running. | Hosting | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Hosting:
"""Shows how to start and stop a Lookout for Vision Model. Also shows how to list the models that are currently running."""
def start_model(lookoutvision_client, project_name, model_version, min_inference_units):
"""Starts the hosting of a Lookout for Vision model. :param lo... | stack_v2_sparse_classes_10k_train_000509 | 6,335 | permissive | [
{
"docstring": "Starts the hosting of a Lookout for Vision model. :param lookoutvision_client: A Boto3 Lookout for Vision client. :param project_name: The name of the project that contains the version of the model that you want to start hosting. :param model_version: The version of the model that you want to st... | 3 | null | Implement the Python class `Hosting` described below.
Class description:
Shows how to start and stop a Lookout for Vision Model. Also shows how to list the models that are currently running.
Method signatures and docstrings:
- def start_model(lookoutvision_client, project_name, model_version, min_inference_units): St... | Implement the Python class `Hosting` described below.
Class description:
Shows how to start and stop a Lookout for Vision Model. Also shows how to list the models that are currently running.
Method signatures and docstrings:
- def start_model(lookoutvision_client, project_name, model_version, min_inference_units): St... | dec41fb589043ac9d8667aac36fb88a53c3abe50 | <|skeleton|>
class Hosting:
"""Shows how to start and stop a Lookout for Vision Model. Also shows how to list the models that are currently running."""
def start_model(lookoutvision_client, project_name, model_version, min_inference_units):
"""Starts the hosting of a Lookout for Vision model. :param lo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Hosting:
"""Shows how to start and stop a Lookout for Vision Model. Also shows how to list the models that are currently running."""
def start_model(lookoutvision_client, project_name, model_version, min_inference_units):
"""Starts the hosting of a Lookout for Vision model. :param lookoutvision_c... | the_stack_v2_python_sparse | python/example_code/lookoutvision/hosting.py | awsdocs/aws-doc-sdk-examples | train | 8,240 |
892cbc07a1524f47caaf9eddeb1e1485bb79c915 | [
"data = form.cleaned_data\nself.success_url = reverse('level_result', kwargs={'level': int(data['level'])})\nreturn super().form_valid(form)",
"context = super().get_context_data(**kwargs)\ncontext['title_text'] = 'Choose Level Result To Display'\ncontext['detail_text'] = 'Please select the <strong>Level/Session\... | <|body_start_0|>
data = form.cleaned_data
self.success_url = reverse('level_result', kwargs={'level': int(data['level'])})
return super().form_valid(form)
<|end_body_0|>
<|body_start_1|>
context = super().get_context_data(**kwargs)
context['title_text'] = 'Choose Level Result To... | View for choosing which level/session result to display. Check that the user's account is still active. Redirects to level_result view on form valid. | ShowLevelResultView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShowLevelResultView:
"""View for choosing which level/session result to display. Check that the user's account is still active. Redirects to level_result view on form valid."""
def form_valid(self, form):
"""Compute the success URL and call super.form_valid()"""
<|body_0|>
... | stack_v2_sparse_classes_10k_train_000510 | 29,759 | no_license | [
{
"docstring": "Compute the success URL and call super.form_valid()",
"name": "form_valid",
"signature": "def form_valid(self, form)"
},
{
"docstring": "Return the data used in the templates rendering.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
... | 2 | stack_v2_sparse_classes_30k_train_000700 | Implement the Python class `ShowLevelResultView` described below.
Class description:
View for choosing which level/session result to display. Check that the user's account is still active. Redirects to level_result view on form valid.
Method signatures and docstrings:
- def form_valid(self, form): Compute the success... | Implement the Python class `ShowLevelResultView` described below.
Class description:
View for choosing which level/session result to display. Check that the user's account is still active. Redirects to level_result view on form valid.
Method signatures and docstrings:
- def form_valid(self, form): Compute the success... | 06bc577d01d3dbf6c425e03dcb903977a38e377c | <|skeleton|>
class ShowLevelResultView:
"""View for choosing which level/session result to display. Check that the user's account is still active. Redirects to level_result view on form valid."""
def form_valid(self, form):
"""Compute the success URL and call super.form_valid()"""
<|body_0|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ShowLevelResultView:
"""View for choosing which level/session result to display. Check that the user's account is still active. Redirects to level_result view on form valid."""
def form_valid(self, form):
"""Compute the success URL and call super.form_valid()"""
data = form.cleaned_data
... | the_stack_v2_python_sparse | cbt/views.py | Festusali/CBTest | train | 6 |
b9525f829e0324496d34ec2212aacc74ad04f55d | [
"self.size = size or cpu_count()\nself.timeout = timeout\nself.pool = []\nself._counter = 1\nself._q = Queue()",
"while True:\n if len(it) and len(self.pool) < self.size:\n arg = it.pop(0)\n self._start_process(func, (arg,))\n continue\n if len(self.pool) == len(it) == 0:\n break... | <|body_start_0|>
self.size = size or cpu_count()
self.timeout = timeout
self.pool = []
self._counter = 1
self._q = Queue()
<|end_body_0|>
<|body_start_1|>
while True:
if len(it) and len(self.pool) < self.size:
arg = it.pop(0)
s... | Very basic process pool with timeout. | Pool | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pool:
"""Very basic process pool with timeout."""
def __init__(self, size=None, timeout=15):
"""Create new `Pool` of `size` concurrent processes. Args: size (int): Number of concurrent processes. Defaults to no. of processors. timeout (int, optional): Number of seconds to wait before... | stack_v2_sparse_classes_10k_train_000511 | 3,824 | no_license | [
{
"docstring": "Create new `Pool` of `size` concurrent processes. Args: size (int): Number of concurrent processes. Defaults to no. of processors. timeout (int, optional): Number of seconds to wait before killing the process.",
"name": "__init__",
"signature": "def __init__(self, size=None, timeout=15)"... | 3 | null | Implement the Python class `Pool` described below.
Class description:
Very basic process pool with timeout.
Method signatures and docstrings:
- def __init__(self, size=None, timeout=15): Create new `Pool` of `size` concurrent processes. Args: size (int): Number of concurrent processes. Defaults to no. of processors. ... | Implement the Python class `Pool` described below.
Class description:
Very basic process pool with timeout.
Method signatures and docstrings:
- def __init__(self, size=None, timeout=15): Create new `Pool` of `size` concurrent processes. Args: size (int): Number of concurrent processes. Defaults to no. of processors. ... | c7301fb7983edbe3492e7d78d531ba2f427d2f3e | <|skeleton|>
class Pool:
"""Very basic process pool with timeout."""
def __init__(self, size=None, timeout=15):
"""Create new `Pool` of `size` concurrent processes. Args: size (int): Number of concurrent processes. Defaults to no. of processors. timeout (int, optional): Number of seconds to wait before... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Pool:
"""Very basic process pool with timeout."""
def __init__(self, size=None, timeout=15):
"""Create new `Pool` of `size` concurrent processes. Args: size (int): Number of concurrent processes. Defaults to no. of processors. timeout (int, optional): Number of seconds to wait before killing the ... | the_stack_v2_python_sparse | Multiprocessing/consumer_producer_pool.py | Silentsoul04/PythonCode | train | 0 |
3d0c8af1ebfe88c84ea3b13cda8ae5505f594ead | [
"payment_method = self.data.get('req_payment_method')\nif payment_method == 'card':\n card_type = self.data.get('req_card_type')\n card_type_description = CARD_TYPES.get(card_type, '')\n card_number = self.data.get('req_card_number', '')\n return f'{card_type_description} | {card_number}'\nelif payment_... | <|body_start_0|>
payment_method = self.data.get('req_payment_method')
if payment_method == 'card':
card_type = self.data.get('req_card_type')
card_type_description = CARD_TYPES.get(card_type, '')
card_number = self.data.get('req_card_number', '')
return f'... | The contents of the message from CyberSource about an Order fulfillment or cancellation | Receipt | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Receipt:
"""The contents of the message from CyberSource about an Order fulfillment or cancellation"""
def payment_method(self):
"""Try to guess the payment source based on the Cybersource receipt"""
<|body_0|>
def __str__(self):
"""Description of Receipt"""
... | stack_v2_sparse_classes_10k_train_000512 | 6,187 | permissive | [
{
"docstring": "Try to guess the payment source based on the Cybersource receipt",
"name": "payment_method",
"signature": "def payment_method(self)"
},
{
"docstring": "Description of Receipt",
"name": "__str__",
"signature": "def __str__(self)"
}
] | 2 | null | Implement the Python class `Receipt` described below.
Class description:
The contents of the message from CyberSource about an Order fulfillment or cancellation
Method signatures and docstrings:
- def payment_method(self): Try to guess the payment source based on the Cybersource receipt
- def __str__(self): Descripti... | Implement the Python class `Receipt` described below.
Class description:
The contents of the message from CyberSource about an Order fulfillment or cancellation
Method signatures and docstrings:
- def payment_method(self): Try to guess the payment source based on the Cybersource receipt
- def __str__(self): Descripti... | 339c67b84b661a37ffe32580da72383d95666c5c | <|skeleton|>
class Receipt:
"""The contents of the message from CyberSource about an Order fulfillment or cancellation"""
def payment_method(self):
"""Try to guess the payment source based on the Cybersource receipt"""
<|body_0|>
def __str__(self):
"""Description of Receipt"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Receipt:
"""The contents of the message from CyberSource about an Order fulfillment or cancellation"""
def payment_method(self):
"""Try to guess the payment source based on the Cybersource receipt"""
payment_method = self.data.get('req_payment_method')
if payment_method == 'card':... | the_stack_v2_python_sparse | ecommerce/models.py | mitodl/bootcamp-ecommerce | train | 6 |
6edb0cb8f34a40d8ff576e6d6bc42983ff81abe8 | [
"if isinstance(schema, dict):\n schema = vol.Schema(schema)\nself._schema = schema\nself._allow_empty = allow_empty",
"@wraps(method)\nasync def wrapper(view: _HassViewT, request: web.Request, *args: _P.args, **kwargs: _P.kwargs) -> web.Response:\n \"\"\"Wrap a request handler with data validation.\"\"\"\n ... | <|body_start_0|>
if isinstance(schema, dict):
schema = vol.Schema(schema)
self._schema = schema
self._allow_empty = allow_empty
<|end_body_0|>
<|body_start_1|>
@wraps(method)
async def wrapper(view: _HassViewT, request: web.Request, *args: _P.args, **kwargs: _P.kwarg... | Decorator that will validate the incoming data. Takes in a voluptuous schema and adds 'data' as keyword argument to the function call. Will return a 400 if no JSON provided or doesn't match schema. | RequestDataValidator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RequestDataValidator:
"""Decorator that will validate the incoming data. Takes in a voluptuous schema and adds 'data' as keyword argument to the function call. Will return a 400 if no JSON provided or doesn't match schema."""
def __init__(self, schema: vol.Schema, allow_empty: bool=False) ->... | stack_v2_sparse_classes_10k_train_000513 | 2,410 | permissive | [
{
"docstring": "Initialize the decorator.",
"name": "__init__",
"signature": "def __init__(self, schema: vol.Schema, allow_empty: bool=False) -> None"
},
{
"docstring": "Decorate a function.",
"name": "__call__",
"signature": "def __call__(self, method: Callable[Concatenate[_HassViewT, w... | 2 | null | Implement the Python class `RequestDataValidator` described below.
Class description:
Decorator that will validate the incoming data. Takes in a voluptuous schema and adds 'data' as keyword argument to the function call. Will return a 400 if no JSON provided or doesn't match schema.
Method signatures and docstrings:
... | Implement the Python class `RequestDataValidator` described below.
Class description:
Decorator that will validate the incoming data. Takes in a voluptuous schema and adds 'data' as keyword argument to the function call. Will return a 400 if no JSON provided or doesn't match schema.
Method signatures and docstrings:
... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class RequestDataValidator:
"""Decorator that will validate the incoming data. Takes in a voluptuous schema and adds 'data' as keyword argument to the function call. Will return a 400 if no JSON provided or doesn't match schema."""
def __init__(self, schema: vol.Schema, allow_empty: bool=False) ->... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RequestDataValidator:
"""Decorator that will validate the incoming data. Takes in a voluptuous schema and adds 'data' as keyword argument to the function call. Will return a 400 if no JSON provided or doesn't match schema."""
def __init__(self, schema: vol.Schema, allow_empty: bool=False) -> None:
... | the_stack_v2_python_sparse | homeassistant/components/http/data_validator.py | home-assistant/core | train | 35,501 |
9ac820e719879ea9a506e07561ee38ed360dc004 | [
"game_object: GameObject = CommonObjectUtils.get_root_parent(game_object)\nslot_component = cls.get_slot_component(game_object)\nif slot_component is None:\n return tuple()\ncontainment_slot_list: List[CommonObjectContainmentSlot] = list()\nfor slot_hash, slot_types in tuple(slot_component.get_containment_slot_i... | <|body_start_0|>
game_object: GameObject = CommonObjectUtils.get_root_parent(game_object)
slot_component = cls.get_slot_component(game_object)
if slot_component is None:
return tuple()
containment_slot_list: List[CommonObjectContainmentSlot] = list()
for slot_hash, sl... | Utilities for manipulating object slots. | CommonObjectSlotUtils | [
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommonObjectSlotUtils:
"""Utilities for manipulating object slots."""
def get_containment_slots(cls, game_object: GameObject) -> Tuple[CommonObjectContainmentSlot]:
"""get_containment_slots(game_object) Retrieve the containment slots of an object. :param game_object: An instance of a... | stack_v2_sparse_classes_10k_train_000514 | 9,030 | permissive | [
{
"docstring": "get_containment_slots(game_object) Retrieve the containment slots of an object. :param game_object: An instance of an Object. :type game_object: GameObject :return: A collection of containment slots on the specified object. :rtype: Tuple[CommonObjectContainmentSlot]",
"name": "get_containmen... | 6 | stack_v2_sparse_classes_30k_val_000035 | Implement the Python class `CommonObjectSlotUtils` described below.
Class description:
Utilities for manipulating object slots.
Method signatures and docstrings:
- def get_containment_slots(cls, game_object: GameObject) -> Tuple[CommonObjectContainmentSlot]: get_containment_slots(game_object) Retrieve the containment... | Implement the Python class `CommonObjectSlotUtils` described below.
Class description:
Utilities for manipulating object slots.
Method signatures and docstrings:
- def get_containment_slots(cls, game_object: GameObject) -> Tuple[CommonObjectContainmentSlot]: get_containment_slots(game_object) Retrieve the containment... | 58e7beb30b9c818b294d35abd2436a0192cd3e82 | <|skeleton|>
class CommonObjectSlotUtils:
"""Utilities for manipulating object slots."""
def get_containment_slots(cls, game_object: GameObject) -> Tuple[CommonObjectContainmentSlot]:
"""get_containment_slots(game_object) Retrieve the containment slots of an object. :param game_object: An instance of a... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CommonObjectSlotUtils:
"""Utilities for manipulating object slots."""
def get_containment_slots(cls, game_object: GameObject) -> Tuple[CommonObjectContainmentSlot]:
"""get_containment_slots(game_object) Retrieve the containment slots of an object. :param game_object: An instance of an Object. :ty... | the_stack_v2_python_sparse | Scripts/sims4communitylib/utils/objects/common_object_slot_utils.py | ColonolNutty/Sims4CommunityLibrary | train | 183 |
9abe9eecfb320f6d312aaaca915ccbd59a96ba47 | [
"try:\n if self.pool != self.pool.check_signaling():\n self.env.reset()\n self = self.env()[self._name]\n log_depth = None if _logger.isEnabledFor(logging.DEBUG) else 1\n odoo.netsvc.log(_logger, logging.DEBUG, 'cron.object.execute', (self._cr.dbname, self._uid, '*', cron_name, server_action_... | <|body_start_0|>
try:
if self.pool != self.pool.check_signaling():
self.env.reset()
self = self.env()[self._name]
log_depth = None if _logger.isEnabledFor(logging.DEBUG) else 1
odoo.netsvc.log(_logger, logging.DEBUG, 'cron.object.execute', (sel... | 扩展添加用户数据 | IrCronExtend | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IrCronExtend:
"""扩展添加用户数据"""
def _callback(self, cron_name, server_action_id, job_id, job_data=None):
"""Run the method associated to a given job. It takes care of logging and exception handling. Note that the user running the server action is the user calling this method."""
... | stack_v2_sparse_classes_10k_train_000515 | 4,343 | no_license | [
{
"docstring": "Run the method associated to a given job. It takes care of logging and exception handling. Note that the user running the server action is the user calling this method.",
"name": "_callback",
"signature": "def _callback(self, cron_name, server_action_id, job_id, job_data=None)"
},
{
... | 2 | null | Implement the Python class `IrCronExtend` described below.
Class description:
扩展添加用户数据
Method signatures and docstrings:
- def _callback(self, cron_name, server_action_id, job_id, job_data=None): Run the method associated to a given job. It takes care of logging and exception handling. Note that the user running the ... | Implement the Python class `IrCronExtend` described below.
Class description:
扩展添加用户数据
Method signatures and docstrings:
- def _callback(self, cron_name, server_action_id, job_id, job_data=None): Run the method associated to a given job. It takes care of logging and exception handling. Note that the user running the ... | 13b428a5c4ade6278e3e5e996ef10d9fb0fea4b9 | <|skeleton|>
class IrCronExtend:
"""扩展添加用户数据"""
def _callback(self, cron_name, server_action_id, job_id, job_data=None):
"""Run the method associated to a given job. It takes care of logging and exception handling. Note that the user running the server action is the user calling this method."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class IrCronExtend:
"""扩展添加用户数据"""
def _callback(self, cron_name, server_action_id, job_id, job_data=None):
"""Run the method associated to a given job. It takes care of logging and exception handling. Note that the user running the server action is the user calling this method."""
try:
... | the_stack_v2_python_sparse | mdias_addons/funenc_theme/models/funenc_extend_cron.py | rezaghanimi/main_mdias | train | 0 |
a00d5ddef611e1319e745dbe5ae4f910280cd417 | [
"super(PointNetVanillaClassifier, self).__init__()\nself.encoder = VanillaEncoder(momentum)\nself.classifier = ClassificationHead(num_classes=num_classes, momentum=momentum, dropout_rate=dropout_rate)",
"features = self.encoder(points, training)\nlogits = self.classifier(features, training)\nreturn logits",
"cr... | <|body_start_0|>
super(PointNetVanillaClassifier, self).__init__()
self.encoder = VanillaEncoder(momentum)
self.classifier = ClassificationHead(num_classes=num_classes, momentum=momentum, dropout_rate=dropout_rate)
<|end_body_0|>
<|body_start_1|>
features = self.encoder(points, training... | The PointNet 'Vanilla' classifier (i.e. without spatial transformer). | PointNetVanillaClassifier | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PointNetVanillaClassifier:
"""The PointNet 'Vanilla' classifier (i.e. without spatial transformer)."""
def __init__(self, num_classes: int=40, momentum: float=0.5, dropout_rate: float=0.3):
"""Constructor. Args: num_classes: the number of classes to classify. momentum: the momentum u... | stack_v2_sparse_classes_10k_train_000516 | 9,332 | permissive | [
{
"docstring": "Constructor. Args: num_classes: the number of classes to classify. momentum: the momentum used for the batch normalization layer. dropout_rate: the dropout rate for the classification head.",
"name": "__init__",
"signature": "def __init__(self, num_classes: int=40, momentum: float=0.5, d... | 3 | stack_v2_sparse_classes_30k_train_004166 | Implement the Python class `PointNetVanillaClassifier` described below.
Class description:
The PointNet 'Vanilla' classifier (i.e. without spatial transformer).
Method signatures and docstrings:
- def __init__(self, num_classes: int=40, momentum: float=0.5, dropout_rate: float=0.3): Constructor. Args: num_classes: th... | Implement the Python class `PointNetVanillaClassifier` described below.
Class description:
The PointNet 'Vanilla' classifier (i.e. without spatial transformer).
Method signatures and docstrings:
- def __init__(self, num_classes: int=40, momentum: float=0.5, dropout_rate: float=0.3): Constructor. Args: num_classes: th... | 1b0203eb538f2b6a1013ec7736d0d548416f059a | <|skeleton|>
class PointNetVanillaClassifier:
"""The PointNet 'Vanilla' classifier (i.e. without spatial transformer)."""
def __init__(self, num_classes: int=40, momentum: float=0.5, dropout_rate: float=0.3):
"""Constructor. Args: num_classes: the number of classes to classify. momentum: the momentum u... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PointNetVanillaClassifier:
"""The PointNet 'Vanilla' classifier (i.e. without spatial transformer)."""
def __init__(self, num_classes: int=40, momentum: float=0.5, dropout_rate: float=0.3):
"""Constructor. Args: num_classes: the number of classes to classify. momentum: the momentum used for the b... | the_stack_v2_python_sparse | tensorflow_graphics/nn/layer/pointnet.py | tensorflow/graphics | train | 2,920 |
4aa971659c2a1e41a019c6a96b4c7ce4af10ec42 | [
"obj = context.active_object\nif obj is None:\n return False\nreturn obj is not None and obj.type == 'MESH' and (obj.mode == 'EDIT')",
"pg = context.scene.pdt_pg\npg.command = f'intall'\nreturn {'FINISHED'}"
] | <|body_start_0|>
obj = context.active_object
if obj is None:
return False
return obj is not None and obj.type == 'MESH' and (obj.mode == 'EDIT')
<|end_body_0|>
<|body_start_1|>
pg = context.scene.pdt_pg
pg.command = f'intall'
return {'FINISHED'}
<|end_body_1|... | Cut Selected Edges at All Intersections | PDT_OT_IntersectAllEdges | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PDT_OT_IntersectAllEdges:
"""Cut Selected Edges at All Intersections"""
def poll(cls, context):
"""Check to see object is in correct condition. Args: context: Blender bpy.context instance. Returns: Boolean"""
<|body_0|>
def execute(self, context):
"""Computes All... | stack_v2_sparse_classes_10k_train_000517 | 7,448 | permissive | [
{
"docstring": "Check to see object is in correct condition. Args: context: Blender bpy.context instance. Returns: Boolean",
"name": "poll",
"signature": "def poll(cls, context)"
},
{
"docstring": "Computes All intersections with Crossing Geometry. Note: Deletes original edges and replaces with ... | 2 | null | Implement the Python class `PDT_OT_IntersectAllEdges` described below.
Class description:
Cut Selected Edges at All Intersections
Method signatures and docstrings:
- def poll(cls, context): Check to see object is in correct condition. Args: context: Blender bpy.context instance. Returns: Boolean
- def execute(self, c... | Implement the Python class `PDT_OT_IntersectAllEdges` described below.
Class description:
Cut Selected Edges at All Intersections
Method signatures and docstrings:
- def poll(cls, context): Check to see object is in correct condition. Args: context: Blender bpy.context instance. Returns: Boolean
- def execute(self, c... | 4d5c304878c1e0018d97c1b07bcaa3981632265a | <|skeleton|>
class PDT_OT_IntersectAllEdges:
"""Cut Selected Edges at All Intersections"""
def poll(cls, context):
"""Check to see object is in correct condition. Args: context: Blender bpy.context instance. Returns: Boolean"""
<|body_0|>
def execute(self, context):
"""Computes All... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PDT_OT_IntersectAllEdges:
"""Cut Selected Edges at All Intersections"""
def poll(cls, context):
"""Check to see object is in correct condition. Args: context: Blender bpy.context instance. Returns: Boolean"""
obj = context.active_object
if obj is None:
return False
... | the_stack_v2_python_sparse | src/bpy/3.6/scripts/addons/precision_drawing_tools/pdt_xall.py | RnoB/3DVisualSwarm | train | 0 |
73dfd60aae18ce455bdc3908d8c3c58fa22f1d19 | [
"path = self.SUB_BASEURL + '/' + account + '/' + name\nurl = build_url(choice(self.list_hosts), path=path)\nif retroactive:\n raise NotImplementedError('Retroactive mode is not implemented')\nif filter_ and (not isinstance(filter_, dict)):\n raise TypeError('filter should be a dict')\nif replication_rules and... | <|body_start_0|>
path = self.SUB_BASEURL + '/' + account + '/' + name
url = build_url(choice(self.list_hosts), path=path)
if retroactive:
raise NotImplementedError('Retroactive mode is not implemented')
if filter_ and (not isinstance(filter_, dict)):
raise TypeErr... | SubscriptionClient class for working with subscriptions | SubscriptionClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubscriptionClient:
"""SubscriptionClient class for working with subscriptions"""
def add_subscription(self, name, account, filter_, replication_rules, comments, lifetime, retroactive, dry_run, priority=3):
"""Adds a new subscription which will be verified against every new added fil... | stack_v2_sparse_classes_10k_train_000518 | 7,980 | permissive | [
{
"docstring": "Adds a new subscription which will be verified against every new added file and dataset :param name: Name of the subscription :type: String :param account: Account identifier :type account: String :param filter_: Dictionary of attributes by which the input data should be filtered **Example**: ``... | 4 | null | Implement the Python class `SubscriptionClient` described below.
Class description:
SubscriptionClient class for working with subscriptions
Method signatures and docstrings:
- def add_subscription(self, name, account, filter_, replication_rules, comments, lifetime, retroactive, dry_run, priority=3): Adds a new subscr... | Implement the Python class `SubscriptionClient` described below.
Class description:
SubscriptionClient class for working with subscriptions
Method signatures and docstrings:
- def add_subscription(self, name, account, filter_, replication_rules, comments, lifetime, retroactive, dry_run, priority=3): Adds a new subscr... | 7f0d229ac0b3bc7dec12c6e158bea2b82d414a3b | <|skeleton|>
class SubscriptionClient:
"""SubscriptionClient class for working with subscriptions"""
def add_subscription(self, name, account, filter_, replication_rules, comments, lifetime, retroactive, dry_run, priority=3):
"""Adds a new subscription which will be verified against every new added fil... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SubscriptionClient:
"""SubscriptionClient class for working with subscriptions"""
def add_subscription(self, name, account, filter_, replication_rules, comments, lifetime, retroactive, dry_run, priority=3):
"""Adds a new subscription which will be verified against every new added file and dataset... | the_stack_v2_python_sparse | lib/rucio/client/subscriptionclient.py | rucio/rucio | train | 232 |
31f0bdede4f123023f5250218d6d075da9db54e6 | [
"super().__init__(**kwargs)\nself._context = weakref.ref(context)\nself._inbound_message = inbound_message\nself._send = send_outbound",
"context = self._context()\nif not context:\n raise RuntimeError('weakref to context has expired')\nif isinstance(message, AgentMessage) and context.settings.get('timing.enab... | <|body_start_0|>
super().__init__(**kwargs)
self._context = weakref.ref(context)
self._inbound_message = inbound_message
self._send = send_outbound
<|end_body_0|>
<|body_start_1|>
context = self._context()
if not context:
raise RuntimeError('weakref to contex... | Handle outgoing messages from message handlers. | DispatcherResponder | [
"LicenseRef-scancode-dco-1.1",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DispatcherResponder:
"""Handle outgoing messages from message handlers."""
def __init__(self, context: RequestContext, inbound_message: InboundMessage, send_outbound: Coroutine, **kwargs):
"""Initialize an instance of `DispatcherResponder`. Args: context: The request context of the i... | stack_v2_sparse_classes_10k_train_000519 | 15,803 | permissive | [
{
"docstring": "Initialize an instance of `DispatcherResponder`. Args: context: The request context of the incoming message inbound_message: The inbound message triggering this handler send_outbound: Async function to send outbound message",
"name": "__init__",
"signature": "def __init__(self, context: ... | 4 | null | Implement the Python class `DispatcherResponder` described below.
Class description:
Handle outgoing messages from message handlers.
Method signatures and docstrings:
- def __init__(self, context: RequestContext, inbound_message: InboundMessage, send_outbound: Coroutine, **kwargs): Initialize an instance of `Dispatch... | Implement the Python class `DispatcherResponder` described below.
Class description:
Handle outgoing messages from message handlers.
Method signatures and docstrings:
- def __init__(self, context: RequestContext, inbound_message: InboundMessage, send_outbound: Coroutine, **kwargs): Initialize an instance of `Dispatch... | 39cac36d8937ce84a9307ce100aaefb8bc05ec04 | <|skeleton|>
class DispatcherResponder:
"""Handle outgoing messages from message handlers."""
def __init__(self, context: RequestContext, inbound_message: InboundMessage, send_outbound: Coroutine, **kwargs):
"""Initialize an instance of `DispatcherResponder`. Args: context: The request context of the i... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DispatcherResponder:
"""Handle outgoing messages from message handlers."""
def __init__(self, context: RequestContext, inbound_message: InboundMessage, send_outbound: Coroutine, **kwargs):
"""Initialize an instance of `DispatcherResponder`. Args: context: The request context of the incoming messa... | the_stack_v2_python_sparse | aries_cloudagent/core/dispatcher.py | hyperledger/aries-cloudagent-python | train | 370 |
232b0ab35c39ae33779d8d46f496162e61b53517 | [
"for rec in self:\n base_url = rec.get_base_url()\n share_url = rec._get_share_url(redirect=True, signup_partner=True)\n url = base_url + share_url\n return url",
"for rec in self:\n templated_id = self.env.ref('sale_whatsapp_connector.sale_order_status', raise_if_not_found=False)\n whatsapp_log... | <|body_start_0|>
for rec in self:
base_url = rec.get_base_url()
share_url = rec._get_share_url(redirect=True, signup_partner=True)
url = base_url + share_url
return url
<|end_body_0|>
<|body_start_1|>
for rec in self:
templated_id = self.env.r... | Inherit Sale Order. | SaleOrder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SaleOrder:
"""Inherit Sale Order."""
def get_link(self):
"""Method to genrate the share Link."""
<|body_0|>
def send_order_status(self):
"""Send Message to Customer."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for rec in self:
ba... | stack_v2_sparse_classes_10k_train_000520 | 3,182 | no_license | [
{
"docstring": "Method to genrate the share Link.",
"name": "get_link",
"signature": "def get_link(self)"
},
{
"docstring": "Send Message to Customer.",
"name": "send_order_status",
"signature": "def send_order_status(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006178 | Implement the Python class `SaleOrder` described below.
Class description:
Inherit Sale Order.
Method signatures and docstrings:
- def get_link(self): Method to genrate the share Link.
- def send_order_status(self): Send Message to Customer. | Implement the Python class `SaleOrder` described below.
Class description:
Inherit Sale Order.
Method signatures and docstrings:
- def get_link(self): Method to genrate the share Link.
- def send_order_status(self): Send Message to Customer.
<|skeleton|>
class SaleOrder:
"""Inherit Sale Order."""
def get_li... | e5c27a9201d27f6a1dfabbc73a92cc62d25c9702 | <|skeleton|>
class SaleOrder:
"""Inherit Sale Order."""
def get_link(self):
"""Method to genrate the share Link."""
<|body_0|>
def send_order_status(self):
"""Send Message to Customer."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SaleOrder:
"""Inherit Sale Order."""
def get_link(self):
"""Method to genrate the share Link."""
for rec in self:
base_url = rec.get_base_url()
share_url = rec._get_share_url(redirect=True, signup_partner=True)
url = base_url + share_url
ret... | the_stack_v2_python_sparse | sale_whatsapp_connector/models/sale_order.py | Raniani-lab/dxm | train | 0 |
3e21061207c8af6753ebbaa3da10e0d0d988afc1 | [
"lti = LTI(request_type='any', role_type='any')\ntry:\n lti.verify(request)\nexcept LTIException:\n return render(request, 'lti_failure.html')\nif not request.user.is_authenticated:\n try:\n lti_user = login_existing_user(request)\n except EmailAddress.DoesNotExist:\n lti_email = request.P... | <|body_start_0|>
lti = LTI(request_type='any', role_type='any')
try:
lti.verify(request)
except LTIException:
return render(request, 'lti_failure.html')
if not request.user.is_authenticated:
try:
lti_user = login_existing_user(request)
... | LtiInitializerView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LtiInitializerView:
def dispatch(self, request, *args, **kwargs):
"""Handle LTI verification and user authentication"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Handle the POST coming directly from Canvas"""
<|body_1|>
def create_lti_user(... | stack_v2_sparse_classes_10k_train_000521 | 4,866 | permissive | [
{
"docstring": "Handle LTI verification and user authentication",
"name": "dispatch",
"signature": "def dispatch(self, request, *args, **kwargs)"
},
{
"docstring": "Handle the POST coming directly from Canvas",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
},
... | 6 | stack_v2_sparse_classes_30k_train_005903 | Implement the Python class `LtiInitializerView` described below.
Class description:
Implement the LtiInitializerView class.
Method signatures and docstrings:
- def dispatch(self, request, *args, **kwargs): Handle LTI verification and user authentication
- def post(self, request, *args, **kwargs): Handle the POST comi... | Implement the Python class `LtiInitializerView` described below.
Class description:
Implement the LtiInitializerView class.
Method signatures and docstrings:
- def dispatch(self, request, *args, **kwargs): Handle LTI verification and user authentication
- def post(self, request, *args, **kwargs): Handle the POST comi... | f44773bcf7695f4f73f0cd71daed7767902bcfd4 | <|skeleton|>
class LtiInitializerView:
def dispatch(self, request, *args, **kwargs):
"""Handle LTI verification and user authentication"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Handle the POST coming directly from Canvas"""
<|body_1|>
def create_lti_user(... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LtiInitializerView:
def dispatch(self, request, *args, **kwargs):
"""Handle LTI verification and user authentication"""
lti = LTI(request_type='any', role_type='any')
try:
lti.verify(request)
except LTIException:
return render(request, 'lti_failure.html'... | the_stack_v2_python_sparse | lti/views.py | Hedera-Lang-Learn/hedera | train | 9 | |
2cde86e769029d77c3c23aaa75748afd5bd16409 | [
"bots = []\nwhitelist = ndb.Key('BotWhitelist', WHITELIST_KEY).get()\nif whitelist:\n bots = whitelist.bots\nself.RenderHtml('bot_whitelist.html', {'bot_whitelist': '\\n'.join(bots)})",
"bots = []\nwhitelist_text = self.request.get('bot_whitelist', '')\nif whitelist_text:\n bots = whitelist_text.strip().spl... | <|body_start_0|>
bots = []
whitelist = ndb.Key('BotWhitelist', WHITELIST_KEY).get()
if whitelist:
bots = whitelist.bots
self.RenderHtml('bot_whitelist.html', {'bot_whitelist': '\n'.join(bots)})
<|end_body_0|>
<|body_start_1|>
bots = []
whitelist_text = self.r... | URL endpoint to view/edit the external Bot whitelist for /add_point. | BotWhitelistHandler | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BotWhitelistHandler:
"""URL endpoint to view/edit the external Bot whitelist for /add_point."""
def get(self):
"""Lists the Bots in the whitelist."""
<|body_0|>
def post(self):
"""Updates the Bot names in the whitelist."""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_10k_train_000522 | 1,383 | permissive | [
{
"docstring": "Lists the Bots in the whitelist.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Updates the Bot names in the whitelist.",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005910 | Implement the Python class `BotWhitelistHandler` described below.
Class description:
URL endpoint to view/edit the external Bot whitelist for /add_point.
Method signatures and docstrings:
- def get(self): Lists the Bots in the whitelist.
- def post(self): Updates the Bot names in the whitelist. | Implement the Python class `BotWhitelistHandler` described below.
Class description:
URL endpoint to view/edit the external Bot whitelist for /add_point.
Method signatures and docstrings:
- def get(self): Lists the Bots in the whitelist.
- def post(self): Updates the Bot names in the whitelist.
<|skeleton|>
class Bo... | e71f21b9b4b9b839f5093301974a45545dad2691 | <|skeleton|>
class BotWhitelistHandler:
"""URL endpoint to view/edit the external Bot whitelist for /add_point."""
def get(self):
"""Lists the Bots in the whitelist."""
<|body_0|>
def post(self):
"""Updates the Bot names in the whitelist."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BotWhitelistHandler:
"""URL endpoint to view/edit the external Bot whitelist for /add_point."""
def get(self):
"""Lists the Bots in the whitelist."""
bots = []
whitelist = ndb.Key('BotWhitelist', WHITELIST_KEY).get()
if whitelist:
bots = whitelist.bots
... | the_stack_v2_python_sparse | third_party/catapult/dashboard/dashboard/bot_whitelist.py | zenoalbisser/chromium | train | 0 |
44eafb8c193c6c5ba65faf9c6863a6951af3361c | [
"def back_track(string='', left=0, right=0):\n if len(string) == 2 * num:\n combinations.append(string)\n if left < num:\n back_track(string + '(', left + 1, right)\n if right < left:\n back_track(string + ')', left, right + 1)\nif num == 0:\n return ['']\ncombinations = []\nback_tr... | <|body_start_0|>
def back_track(string='', left=0, right=0):
if len(string) == 2 * num:
combinations.append(string)
if left < num:
back_track(string + '(', left + 1, right)
if right < left:
back_track(string + ')', left, right +... | Parenthesis | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Parenthesis:
def generate_combinations(self, num: int) -> List[str]:
"""Approach: Back tracking Time Complexity: O(4^n / sqrt(n)) Space Complexity: O(4^n / sqrt(n)) :param num: :return:"""
<|body_0|>
def generate_combinations_(self, num: int) -> List[str]:
"""Approac... | stack_v2_sparse_classes_10k_train_000523 | 1,434 | no_license | [
{
"docstring": "Approach: Back tracking Time Complexity: O(4^n / sqrt(n)) Space Complexity: O(4^n / sqrt(n)) :param num: :return:",
"name": "generate_combinations",
"signature": "def generate_combinations(self, num: int) -> List[str]"
},
{
"docstring": "Approach: Closure Number Time Complexity: ... | 2 | stack_v2_sparse_classes_30k_train_002120 | Implement the Python class `Parenthesis` described below.
Class description:
Implement the Parenthesis class.
Method signatures and docstrings:
- def generate_combinations(self, num: int) -> List[str]: Approach: Back tracking Time Complexity: O(4^n / sqrt(n)) Space Complexity: O(4^n / sqrt(n)) :param num: :return:
- ... | Implement the Python class `Parenthesis` described below.
Class description:
Implement the Parenthesis class.
Method signatures and docstrings:
- def generate_combinations(self, num: int) -> List[str]: Approach: Back tracking Time Complexity: O(4^n / sqrt(n)) Space Complexity: O(4^n / sqrt(n)) :param num: :return:
- ... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Parenthesis:
def generate_combinations(self, num: int) -> List[str]:
"""Approach: Back tracking Time Complexity: O(4^n / sqrt(n)) Space Complexity: O(4^n / sqrt(n)) :param num: :return:"""
<|body_0|>
def generate_combinations_(self, num: int) -> List[str]:
"""Approac... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Parenthesis:
def generate_combinations(self, num: int) -> List[str]:
"""Approach: Back tracking Time Complexity: O(4^n / sqrt(n)) Space Complexity: O(4^n / sqrt(n)) :param num: :return:"""
def back_track(string='', left=0, right=0):
if len(string) == 2 * num:
combin... | the_stack_v2_python_sparse | math_and_srings/paranthesis.py | Shiv2157k/leet_code | train | 1 | |
1df3f1004f5ead7a853c0db30af098fb1ca64e8b | [
"self.persistence_factory = PersistenceMechanismFactory(bucket_base=bucket_base, key_base=key_base, object_type=object_type, logger=logger)\nself.object_type = object_type\nself.reference_pruner = reference_pruner\nself.dictionary_converter = dictionary_converter\nself.fallback = SerializationFormats.JSON\nself.log... | <|body_start_0|>
self.persistence_factory = PersistenceMechanismFactory(bucket_base=bucket_base, key_base=key_base, object_type=object_type, logger=logger)
self.object_type = object_type
self.reference_pruner = reference_pruner
self.dictionary_converter = dictionary_converter
sel... | Factory class for Persistence implementations. Given: 1. a string specifying PersistenceMechanism type 2. a "persist_dir" passed from the caller (which often is experiment name) 3. a "persist_file" passed from the caller (i.e. file name) ... the create_persistence() method will dish out the correct persistence implemen... | PersistenceFactory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PersistenceFactory:
"""Factory class for Persistence implementations. Given: 1. a string specifying PersistenceMechanism type 2. a "persist_dir" passed from the caller (which often is experiment name) 3. a "persist_file" passed from the caller (i.e. file name) ... the create_persistence() method ... | stack_v2_sparse_classes_10k_train_000524 | 9,147 | no_license | [
{
"docstring": "Constructor. :param bucket_base: The bucket base for S3 storage :param key_base: The key (folder) base for S3 storage :param object_type: A string describing what kind of object is to be persisted. :param reference_pruner: A ReferencePruner implementation to prevent persisting reference data twi... | 5 | stack_v2_sparse_classes_30k_train_005769 | Implement the Python class `PersistenceFactory` described below.
Class description:
Factory class for Persistence implementations. Given: 1. a string specifying PersistenceMechanism type 2. a "persist_dir" passed from the caller (which often is experiment name) 3. a "persist_file" passed from the caller (i.e. file nam... | Implement the Python class `PersistenceFactory` described below.
Class description:
Factory class for Persistence implementations. Given: 1. a string specifying PersistenceMechanism type 2. a "persist_dir" passed from the caller (which often is experiment name) 3. a "persist_file" passed from the caller (i.e. file nam... | 99c2f401d6c4b203ee439ed607985a918d0c3c7e | <|skeleton|>
class PersistenceFactory:
"""Factory class for Persistence implementations. Given: 1. a string specifying PersistenceMechanism type 2. a "persist_dir" passed from the caller (which often is experiment name) 3. a "persist_file" passed from the caller (i.e. file name) ... the create_persistence() method ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PersistenceFactory:
"""Factory class for Persistence implementations. Given: 1. a string specifying PersistenceMechanism type 2. a "persist_dir" passed from the caller (which often is experiment name) 3. a "persist_file" passed from the caller (i.e. file name) ... the create_persistence() method will dish out... | the_stack_v2_python_sparse | servicecommon/persistence/factory/persistence_factory.py | Cognizant-CDB-AIA-BAI-AI-OI/LEAF-ENN-Training-V2 | train | 0 |
03bd4ffbbe35eebeffc6257a761aa7d5fb7d13a7 | [
"self.fields[name] = typ(label='', required=False)\nif value is not None:\n self.fields[name].initial = value\nif pos:\n order = list(self.fields.keys())\n order.remove(name)\n order.insert(pos, name)\n self.fields = OrderedDict(((key, self.fields[key]) for key in order))",
"expr = re.compile('%s_\... | <|body_start_0|>
self.fields[name] = typ(label='', required=False)
if value is not None:
self.fields[name].initial = value
if pos:
order = list(self.fields.keys())
order.remove(name)
order.insert(pos, name)
self.fields = OrderedDict(((k... | A form which accepts dynamic fields. We consider a field to be dynamic when it can appear multiple times within the same request. | DynamicForm | [
"ISC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DynamicForm:
"""A form which accepts dynamic fields. We consider a field to be dynamic when it can appear multiple times within the same request."""
def _create_field(self, typ, name, value=None, pos=None):
"""Create a new form field."""
<|body_0|>
def _load_from_qdict(s... | stack_v2_sparse_classes_10k_train_000525 | 11,908 | permissive | [
{
"docstring": "Create a new form field.",
"name": "_create_field",
"signature": "def _create_field(self, typ, name, value=None, pos=None)"
},
{
"docstring": "Load all instances of a field from a ``QueryDict`` object. :param ``QueryDict`` qdict: a QueryDict object :param string pattern: pattern ... | 2 | null | Implement the Python class `DynamicForm` described below.
Class description:
A form which accepts dynamic fields. We consider a field to be dynamic when it can appear multiple times within the same request.
Method signatures and docstrings:
- def _create_field(self, typ, name, value=None, pos=None): Create a new form... | Implement the Python class `DynamicForm` described below.
Class description:
A form which accepts dynamic fields. We consider a field to be dynamic when it can appear multiple times within the same request.
Method signatures and docstrings:
- def _create_field(self, typ, name, value=None, pos=None): Create a new form... | df699aab0799ec1725b6b89be38e56285821c889 | <|skeleton|>
class DynamicForm:
"""A form which accepts dynamic fields. We consider a field to be dynamic when it can appear multiple times within the same request."""
def _create_field(self, typ, name, value=None, pos=None):
"""Create a new form field."""
<|body_0|>
def _load_from_qdict(s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DynamicForm:
"""A form which accepts dynamic fields. We consider a field to be dynamic when it can appear multiple times within the same request."""
def _create_field(self, typ, name, value=None, pos=None):
"""Create a new form field."""
self.fields[name] = typ(label='', required=False)
... | the_stack_v2_python_sparse | modoboa/lib/form_utils.py | modoboa/modoboa | train | 2,201 |
0cb2f3f2c585b665afa1daad007282903caa93a1 | [
"tk.Canvas.__init__(self, parent, **kwargs)\nself._color1 = color1\nself._color2 = color2\nself.bind('<Configure>', self._draw_gradient)\nself.config(relief='flat', highlightthickness=0)",
"self.delete('gradient')\nwidth = self.winfo_width()\nheight = self.winfo_height()\nlimit = width\nr1, g1, b1 = self.winfo_rg... | <|body_start_0|>
tk.Canvas.__init__(self, parent, **kwargs)
self._color1 = color1
self._color2 = color2
self.bind('<Configure>', self._draw_gradient)
self.config(relief='flat', highlightthickness=0)
<|end_body_0|>
<|body_start_1|>
self.delete('gradient')
width = ... | from Bryan Oakley on (https://stackoverflow.com/questions/26178869/ is-it-possible-to-apply-gradient-colours- to-bg-of-tkinter-python-widgets) A gradient frame which uses a canvas to draw the background parent: color11: 渐变颜色1 color22: 渐变颜色2 | GradientCanvas | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GradientCanvas:
"""from Bryan Oakley on (https://stackoverflow.com/questions/26178869/ is-it-possible-to-apply-gradient-colours- to-bg-of-tkinter-python-widgets) A gradient frame which uses a canvas to draw the background parent: color11: 渐变颜色1 color22: 渐变颜色2"""
def __init__(self, parent, co... | stack_v2_sparse_classes_10k_train_000526 | 19,682 | no_license | [
{
"docstring": "default gradient color: red to black",
"name": "__init__",
"signature": "def __init__(self, parent, color1='#ffc851', color2='#808000', **kwargs)"
},
{
"docstring": "Draw the gradient",
"name": "_draw_gradient",
"signature": "def _draw_gradient(self, event=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003624 | Implement the Python class `GradientCanvas` described below.
Class description:
from Bryan Oakley on (https://stackoverflow.com/questions/26178869/ is-it-possible-to-apply-gradient-colours- to-bg-of-tkinter-python-widgets) A gradient frame which uses a canvas to draw the background parent: color11: 渐变颜色1 color22: 渐变颜色... | Implement the Python class `GradientCanvas` described below.
Class description:
from Bryan Oakley on (https://stackoverflow.com/questions/26178869/ is-it-possible-to-apply-gradient-colours- to-bg-of-tkinter-python-widgets) A gradient frame which uses a canvas to draw the background parent: color11: 渐变颜色1 color22: 渐变颜色... | 440d168fd84bd98d2d9f2bc27b34ac9d7816a4e1 | <|skeleton|>
class GradientCanvas:
"""from Bryan Oakley on (https://stackoverflow.com/questions/26178869/ is-it-possible-to-apply-gradient-colours- to-bg-of-tkinter-python-widgets) A gradient frame which uses a canvas to draw the background parent: color11: 渐变颜色1 color22: 渐变颜色2"""
def __init__(self, parent, co... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GradientCanvas:
"""from Bryan Oakley on (https://stackoverflow.com/questions/26178869/ is-it-possible-to-apply-gradient-colours- to-bg-of-tkinter-python-widgets) A gradient frame which uses a canvas to draw the background parent: color11: 渐变颜色1 color22: 渐变颜色2"""
def __init__(self, parent, color1='#ffc851... | the_stack_v2_python_sparse | Lib/gpconfig/newGUI.py | hygnic/Gispot | train | 0 |
4323a234d087b27a709e67ed7091db42f8b1705e | [
"if not head:\n return None\nif not head.next:\n return TreeNode(head.val)\nmidPre = self.midPreOfLists(head)\nmid = midPre.next\nright = midPre.next.next\nmidPre.next = None\nmid.next = None\nroot = TreeNode(mid.val)\nroot.left = self.sortedListToBST(head)\nroot.right = self.sortedListToBST(right)\nreturn ro... | <|body_start_0|>
if not head:
return None
if not head.next:
return TreeNode(head.val)
midPre = self.midPreOfLists(head)
mid = midPre.next
right = midPre.next.next
midPre.next = None
mid.next = None
root = TreeNode(mid.val)
r... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortedListToBST(self, head):
""":type head: ListNode :rtype: TreeNode"""
<|body_0|>
def midPreOfLists(self, head):
"""qiu中间节点的前一个节点 :param head: :return:"""
<|body_1|>
def sortedArrayToBST(self, array):
"""排序数组-->BST :param array: :... | stack_v2_sparse_classes_10k_train_000527 | 2,216 | permissive | [
{
"docstring": ":type head: ListNode :rtype: TreeNode",
"name": "sortedListToBST",
"signature": "def sortedListToBST(self, head)"
},
{
"docstring": "qiu中间节点的前一个节点 :param head: :return:",
"name": "midPreOfLists",
"signature": "def midPreOfLists(self, head)"
},
{
"docstring": "排序数组... | 4 | stack_v2_sparse_classes_30k_train_002993 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortedListToBST(self, head): :type head: ListNode :rtype: TreeNode
- def midPreOfLists(self, head): qiu中间节点的前一个节点 :param head: :return:
- def sortedArrayToBST(self, array): 排... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortedListToBST(self, head): :type head: ListNode :rtype: TreeNode
- def midPreOfLists(self, head): qiu中间节点的前一个节点 :param head: :return:
- def sortedArrayToBST(self, array): 排... | f5e1c94c99628e7fb04ba158f686a55a8093e933 | <|skeleton|>
class Solution:
def sortedListToBST(self, head):
""":type head: ListNode :rtype: TreeNode"""
<|body_0|>
def midPreOfLists(self, head):
"""qiu中间节点的前一个节点 :param head: :return:"""
<|body_1|>
def sortedArrayToBST(self, array):
"""排序数组-->BST :param array: :... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def sortedListToBST(self, head):
""":type head: ListNode :rtype: TreeNode"""
if not head:
return None
if not head.next:
return TreeNode(head.val)
midPre = self.midPreOfLists(head)
mid = midPre.next
right = midPre.next.next
... | the_stack_v2_python_sparse | 03LinkedList/109ConvertSortedListtoBinarySearchTree.py | zhaoxinlu/leetcode-algorithms | train | 0 | |
33520546e08f4c4dc928d33015c257ecdab23ba1 | [
"if not nums:\n return []\nresults = []\nnums.sort()\nfor i in range(len(nums) - 3):\n if i > 0 and nums[i] == nums[i - 1]:\n continue\n threeSum = self.threeSum(nums, i + 1, target - nums[i])\n results += [[nums[i]] + t for t in threeSum]\nreturn results",
"if not nums or startInd >= len(nums)... | <|body_start_0|>
if not nums:
return []
results = []
nums.sort()
for i in range(len(nums) - 3):
if i > 0 and nums[i] == nums[i - 1]:
continue
threeSum = self.threeSum(nums, i + 1, target - nums[i])
results += [[nums[i]] + t ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def fourSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]]"""
<|body_0|>
def threeSum(self, nums, startInd, target):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_10k_train_000528 | 1,610 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[List[int]]",
"name": "fourSum",
"signature": "def fourSum(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum",
"signature": "def threeSum(self, nums, startInd, targ... | 2 | stack_v2_sparse_classes_30k_train_005457 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fourSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[List[int]]
- def threeSum(self, nums, startInd, target): :type nums: List[int] :rtype: List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fourSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[List[int]]
- def threeSum(self, nums, startInd, target): :type nums: List[int] :rtype: List[... | e2837f3d6c23f012148a2d1f9d0ef6d34d4e6912 | <|skeleton|>
class Solution:
def fourSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]]"""
<|body_0|>
def threeSum(self, nums, startInd, target):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def fourSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]]"""
if not nums:
return []
results = []
nums.sort()
for i in range(len(nums) - 3):
if i > 0 and nums[i] == nums[i - 1]:
c... | the_stack_v2_python_sparse | TwoPointers/4sum.py | wttttt-wang/leetcode_withTopics | train | 0 | |
cfde457675af576c03951a39725249b17164802d | [
"vel_x = set_up_xy_velocity_cube('advection_velocity_x')\nvel_y = set_up_xy_velocity_cube('advection_velocity_y')\nplugin = AdvectField(vel_x, vel_y)\nself.assertEqual(plugin.x_coord.name(), 'projection_x_coordinate')\nself.assertIsInstance(plugin.vel_y, iris.cube.Cube)",
"vel_x = set_up_xy_velocity_cube('advecti... | <|body_start_0|>
vel_x = set_up_xy_velocity_cube('advection_velocity_x')
vel_y = set_up_xy_velocity_cube('advection_velocity_y')
plugin = AdvectField(vel_x, vel_y)
self.assertEqual(plugin.x_coord.name(), 'projection_x_coordinate')
self.assertIsInstance(plugin.vel_y, iris.cube.Cub... | Test class initialisation | Test__init__ | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test__init__:
"""Test class initialisation"""
def test_basic(self):
"""Test for cubes and coordinates in class instance"""
<|body_0|>
def test_units(self):
"""Test velocity fields are converted to m/s"""
<|body_1|>
def test_raises_grid_mismatch_error... | stack_v2_sparse_classes_10k_train_000529 | 22,262 | permissive | [
{
"docstring": "Test for cubes and coordinates in class instance",
"name": "test_basic",
"signature": "def test_basic(self)"
},
{
"docstring": "Test velocity fields are converted to m/s",
"name": "test_units",
"signature": "def test_units(self)"
},
{
"docstring": "Test error is r... | 3 | null | Implement the Python class `Test__init__` described below.
Class description:
Test class initialisation
Method signatures and docstrings:
- def test_basic(self): Test for cubes and coordinates in class instance
- def test_units(self): Test velocity fields are converted to m/s
- def test_raises_grid_mismatch_error(sel... | Implement the Python class `Test__init__` described below.
Class description:
Test class initialisation
Method signatures and docstrings:
- def test_basic(self): Test for cubes and coordinates in class instance
- def test_units(self): Test velocity fields are converted to m/s
- def test_raises_grid_mismatch_error(sel... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test__init__:
"""Test class initialisation"""
def test_basic(self):
"""Test for cubes and coordinates in class instance"""
<|body_0|>
def test_units(self):
"""Test velocity fields are converted to m/s"""
<|body_1|>
def test_raises_grid_mismatch_error... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Test__init__:
"""Test class initialisation"""
def test_basic(self):
"""Test for cubes and coordinates in class instance"""
vel_x = set_up_xy_velocity_cube('advection_velocity_x')
vel_y = set_up_xy_velocity_cube('advection_velocity_y')
plugin = AdvectField(vel_x, vel_y)
... | the_stack_v2_python_sparse | improver_tests/nowcasting/forecasting/test_AdvectField.py | metoppv/improver | train | 101 |
5aff9dcca0dfbba27d8c2bd168a82c44f8dbace3 | [
"self.width = width - 1\nself.height = height - 1\nself.food = deque(food)\nself.snake = deque([[0, 0]])",
"i, j = self.snake[0]\nif direction == 'U':\n i -= 1\nelif direction == 'R':\n j += 1\nelif direction == 'L':\n j -= 1\nelif direction == 'D':\n i += 1\nif i < 0 or i > self.height or j < 0 or (j... | <|body_start_0|>
self.width = width - 1
self.height = height - 1
self.food = deque(food)
self.snake = deque([[0, 0]])
<|end_body_0|>
<|body_start_1|>
i, j = self.snake[0]
if direction == 'U':
i -= 1
elif direction == 'R':
j += 1
el... | 스네이크 게임을 디자인한다. 화면 크기 = 너비 x 높이의 장치에서 플레이한다. 뱀은 처음에 길이 = 1 인 상태로, 왼쪽 상단 모서리에 위치한다. 음식의 위치 목록을 행-열 순서대로 받는다. 뱀이 음식을 먹으면 길이와 게임의 점수가 모두 1씩 증가한다. 각각의 음식이 화면에 하나씩 나타난다. 첫 번째 음식을 뱀이 먹으면 두 번째 음식이 나타난다. 화면에 음식이 나타날 때, 뱀이 점유한 블록에는 음식이 나타나지 않는다. | SnakeGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
"""스네이크 게임을 디자인한다. 화면 크기 = 너비 x 높이의 장치에서 플레이한다. 뱀은 처음에 길이 = 1 인 상태로, 왼쪽 상단 모서리에 위치한다. 음식의 위치 목록을 행-열 순서대로 받는다. 뱀이 음식을 먹으면 길이와 게임의 점수가 모두 1씩 증가한다. 각각의 음식이 화면에 하나씩 나타난다. 첫 번째 음식을 뱀이 먹으면 두 번째 음식이 나타난다. 화면에 음식이 나타날 때, 뱀이 점유한 블록에는 음식이 나타나지 않는다."""
def __init__(self, width: int, height:... | stack_v2_sparse_classes_10k_train_000530 | 3,893 | no_license | [
{
"docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].",
"name": "__init__",
"signature": "def __init__(self, widt... | 2 | stack_v2_sparse_classes_30k_train_006510 | Implement the Python class `SnakeGame` described below.
Class description:
스네이크 게임을 디자인한다. 화면 크기 = 너비 x 높이의 장치에서 플레이한다. 뱀은 처음에 길이 = 1 인 상태로, 왼쪽 상단 모서리에 위치한다. 음식의 위치 목록을 행-열 순서대로 받는다. 뱀이 음식을 먹으면 길이와 게임의 점수가 모두 1씩 증가한다. 각각의 음식이 화면에 하나씩 나타난다. 첫 번째 음식을 뱀이 먹으면 두 번째 음식이 나타난다. 화면에 음식이 나타날 때, 뱀이 점유한 블록에는 음식이 나타나지 않는다.
Method... | Implement the Python class `SnakeGame` described below.
Class description:
스네이크 게임을 디자인한다. 화면 크기 = 너비 x 높이의 장치에서 플레이한다. 뱀은 처음에 길이 = 1 인 상태로, 왼쪽 상단 모서리에 위치한다. 음식의 위치 목록을 행-열 순서대로 받는다. 뱀이 음식을 먹으면 길이와 게임의 점수가 모두 1씩 증가한다. 각각의 음식이 화면에 하나씩 나타난다. 첫 번째 음식을 뱀이 먹으면 두 번째 음식이 나타난다. 화면에 음식이 나타날 때, 뱀이 점유한 블록에는 음식이 나타나지 않는다.
Method... | 1c9528e26752b723e1d128b020f6c5291ed5ca19 | <|skeleton|>
class SnakeGame:
"""스네이크 게임을 디자인한다. 화면 크기 = 너비 x 높이의 장치에서 플레이한다. 뱀은 처음에 길이 = 1 인 상태로, 왼쪽 상단 모서리에 위치한다. 음식의 위치 목록을 행-열 순서대로 받는다. 뱀이 음식을 먹으면 길이와 게임의 점수가 모두 1씩 증가한다. 각각의 음식이 화면에 하나씩 나타난다. 첫 번째 음식을 뱀이 먹으면 두 번째 음식이 나타난다. 화면에 음식이 나타날 때, 뱀이 점유한 블록에는 음식이 나타나지 않는다."""
def __init__(self, width: int, height:... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SnakeGame:
"""스네이크 게임을 디자인한다. 화면 크기 = 너비 x 높이의 장치에서 플레이한다. 뱀은 처음에 길이 = 1 인 상태로, 왼쪽 상단 모서리에 위치한다. 음식의 위치 목록을 행-열 순서대로 받는다. 뱀이 음식을 먹으면 길이와 게임의 점수가 모두 1씩 증가한다. 각각의 음식이 화면에 하나씩 나타난다. 첫 번째 음식을 뱀이 먹으면 두 번째 음식이 나타난다. 화면에 음식이 나타날 때, 뱀이 점유한 블록에는 음식이 나타나지 않는다."""
def __init__(self, width: int, height: int, food: L... | the_stack_v2_python_sparse | system_design/353_design_snake_game.py | eunjungchoi/algorithm | train | 1 |
5f3e797d27a35f3f3047f3069842179bf35eebc9 | [
"self.model_name = model_name\nself.ckpt_path = ckpt_path\nself.params = hparams_config.get_detection_config(model_name).as_dict()\nif model_params:\n self.params.update(model_params)\nself.params.update(dict(is_training_bn=False))\nself.label_map = self.params.get('label_map', None)",
"params = copy.deepcopy(... | <|body_start_0|>
self.model_name = model_name
self.ckpt_path = ckpt_path
self.params = hparams_config.get_detection_config(model_name).as_dict()
if model_params:
self.params.update(model_params)
self.params.update(dict(is_training_bn=False))
self.label_map = s... | A driver for doing batch inference. Example usage: driver = inference.InferenceDriver('efficientdet-d0', '/tmp/efficientdet-d0') driver.inference('/tmp/*.jpg', '/tmp/outputdir') | InferenceDriver | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InferenceDriver:
"""A driver for doing batch inference. Example usage: driver = inference.InferenceDriver('efficientdet-d0', '/tmp/efficientdet-d0') driver.inference('/tmp/*.jpg', '/tmp/outputdir')"""
def __init__(self, model_name: Text, ckpt_path: Text, model_params: Dict[Text, Any]=None):
... | stack_v2_sparse_classes_10k_train_000531 | 26,168 | permissive | [
{
"docstring": "Initialize the inference driver. Args: model_name: target model name, such as efficientdet-d0. ckpt_path: checkpoint path, such as /tmp/efficientdet-d0/. model_params: model parameters for overriding the config.",
"name": "__init__",
"signature": "def __init__(self, model_name: Text, ckp... | 2 | stack_v2_sparse_classes_30k_train_001840 | Implement the Python class `InferenceDriver` described below.
Class description:
A driver for doing batch inference. Example usage: driver = inference.InferenceDriver('efficientdet-d0', '/tmp/efficientdet-d0') driver.inference('/tmp/*.jpg', '/tmp/outputdir')
Method signatures and docstrings:
- def __init__(self, mode... | Implement the Python class `InferenceDriver` described below.
Class description:
A driver for doing batch inference. Example usage: driver = inference.InferenceDriver('efficientdet-d0', '/tmp/efficientdet-d0') driver.inference('/tmp/*.jpg', '/tmp/outputdir')
Method signatures and docstrings:
- def __init__(self, mode... | c7392f2bab3165244d1c565b66409fa11fa82367 | <|skeleton|>
class InferenceDriver:
"""A driver for doing batch inference. Example usage: driver = inference.InferenceDriver('efficientdet-d0', '/tmp/efficientdet-d0') driver.inference('/tmp/*.jpg', '/tmp/outputdir')"""
def __init__(self, model_name: Text, ckpt_path: Text, model_params: Dict[Text, Any]=None):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class InferenceDriver:
"""A driver for doing batch inference. Example usage: driver = inference.InferenceDriver('efficientdet-d0', '/tmp/efficientdet-d0') driver.inference('/tmp/*.jpg', '/tmp/outputdir')"""
def __init__(self, model_name: Text, ckpt_path: Text, model_params: Dict[Text, Any]=None):
"""In... | the_stack_v2_python_sparse | efficientdet/inference.py | google/automl | train | 6,415 |
24c0eca60e4b90b60e8991bbd27f5d587f97dfc2 | [
"pc = DotDict()\nf2jd = copy.deepcopy(cannonical_json_dump)\npc.upload_file_minidump_flash2 = DotDict()\npc.upload_file_minidump_flash2.json_dump = f2jd\npc.upload_file_minidump_flash2.json_dump['threads'][0]['frames'][1]['function'] = 'NtUserPeekMessage'\npc.upload_file_minidump_flash2.json_dump['threads'][0]['fra... | <|body_start_0|>
pc = DotDict()
f2jd = copy.deepcopy(cannonical_json_dump)
pc.upload_file_minidump_flash2 = DotDict()
pc.upload_file_minidump_flash2.json_dump = f2jd
pc.upload_file_minidump_flash2.json_dump['threads'][0]['frames'][1]['function'] = 'NtUserPeekMessage'
pc.u... | TestBug812318 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestBug812318:
def test_action_case_1(self):
"""success - both targets found in top 5 frames of stack"""
<|body_0|>
def test_action_case_2(self):
"""success - only 1st target found in top 5 frames of stack"""
<|body_1|>
def test_action_case_3(self):
... | stack_v2_sparse_classes_10k_train_000532 | 27,276 | no_license | [
{
"docstring": "success - both targets found in top 5 frames of stack",
"name": "test_action_case_1",
"signature": "def test_action_case_1(self)"
},
{
"docstring": "success - only 1st target found in top 5 frames of stack",
"name": "test_action_case_2",
"signature": "def test_action_case... | 3 | stack_v2_sparse_classes_30k_train_001594 | Implement the Python class `TestBug812318` described below.
Class description:
Implement the TestBug812318 class.
Method signatures and docstrings:
- def test_action_case_1(self): success - both targets found in top 5 frames of stack
- def test_action_case_2(self): success - only 1st target found in top 5 frames of s... | Implement the Python class `TestBug812318` described below.
Class description:
Implement the TestBug812318 class.
Method signatures and docstrings:
- def test_action_case_1(self): success - both targets found in top 5 frames of stack
- def test_action_case_2(self): success - only 1st target found in top 5 frames of s... | 9c9b7701d7ddf9f3cbba1a4d0aa65758e8b49528 | <|skeleton|>
class TestBug812318:
def test_action_case_1(self):
"""success - both targets found in top 5 frames of stack"""
<|body_0|>
def test_action_case_2(self):
"""success - only 1st target found in top 5 frames of stack"""
<|body_1|>
def test_action_case_3(self):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestBug812318:
def test_action_case_1(self):
"""success - both targets found in top 5 frames of stack"""
pc = DotDict()
f2jd = copy.deepcopy(cannonical_json_dump)
pc.upload_file_minidump_flash2 = DotDict()
pc.upload_file_minidump_flash2.json_dump = f2jd
pc.uploa... | the_stack_v2_python_sparse | socorro/unittest/processor/test_skunk_classifiers.py | v1ka5/socorro | train | 0 | |
0983b5ad2a06663f2ec3763ea09f3581fe003e2b | [
"if n == 2 or n == 3:\n return True\nif n % 6 != 1 and n % 6 != 5:\n return False\nsqrt_n = int(math.sqrt(n)) + 1\nindex = 5\nwhile index < sqrt_n:\n if n % index == 0 or n % (index + 2) == 0:\n return False\n index += 6\nreturn True",
"sqrt_n = int(math.sqrt(n)) + 1\nfor i in range(2, sqrt_n):... | <|body_start_0|>
if n == 2 or n == 3:
return True
if n % 6 != 1 and n % 6 != 5:
return False
sqrt_n = int(math.sqrt(n)) + 1
index = 5
while index < sqrt_n:
if n % index == 0 or n % (index + 2) == 0:
return False
inde... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _is_prime_bad2(self, n):
"""# Better than _is_prime_bad1 but still bad. # Reference: [判断一个数是否为质数/素数——从普通判断算法到高效判断算法思路](blog.csdn.net/huang_miao_xin/article/details/51331710) 令x≥1,将大于等于5的自然数表示如下: 6x-1, 6x, 6x+1, 6x+2, 6x+3, 6x+4, 6x+5, 6(x+1), 6(x+1)+1 ··· 可以看到,不在6的倍数两侧,即6x两... | stack_v2_sparse_classes_10k_train_000533 | 2,539 | no_license | [
{
"docstring": "# Better than _is_prime_bad1 but still bad. # Reference: [判断一个数是否为质数/素数——从普通判断算法到高效判断算法思路](blog.csdn.net/huang_miao_xin/article/details/51331710) 令x≥1,将大于等于5的自然数表示如下: 6x-1, 6x, 6x+1, 6x+2, 6x+3, 6x+4, 6x+5, 6(x+1), 6(x+1)+1 ··· 可以看到,不在6的倍数两侧,即6x两侧的数为6x+2,6x+3,6x+4,由于2(3x+1),3(2x+1),2(3x+2),所以它们一... | 4 | stack_v2_sparse_classes_30k_train_006762 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _is_prime_bad2(self, n): # Better than _is_prime_bad1 but still bad. # Reference: [判断一个数是否为质数/素数——从普通判断算法到高效判断算法思路](blog.csdn.net/huang_miao_xin/article/details/51331710) 令x≥... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _is_prime_bad2(self, n): # Better than _is_prime_bad1 but still bad. # Reference: [判断一个数是否为质数/素数——从普通判断算法到高效判断算法思路](blog.csdn.net/huang_miao_xin/article/details/51331710) 令x≥... | 3c9e54680cefd51c8f56fa12eb27276787de3a2a | <|skeleton|>
class Solution:
def _is_prime_bad2(self, n):
"""# Better than _is_prime_bad1 but still bad. # Reference: [判断一个数是否为质数/素数——从普通判断算法到高效判断算法思路](blog.csdn.net/huang_miao_xin/article/details/51331710) 令x≥1,将大于等于5的自然数表示如下: 6x-1, 6x, 6x+1, 6x+2, 6x+3, 6x+4, 6x+5, 6(x+1), 6(x+1)+1 ··· 可以看到,不在6的倍数两侧,即6x两... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def _is_prime_bad2(self, n):
"""# Better than _is_prime_bad1 but still bad. # Reference: [判断一个数是否为质数/素数——从普通判断算法到高效判断算法思路](blog.csdn.net/huang_miao_xin/article/details/51331710) 令x≥1,将大于等于5的自然数表示如下: 6x-1, 6x, 6x+1, 6x+2, 6x+3, 6x+4, 6x+5, 6(x+1), 6(x+1)+1 ··· 可以看到,不在6的倍数两侧,即6x两侧的数为6x+2,6x+3,... | the_stack_v2_python_sparse | lxw/num204/num204.py | We-Hack/LeetCode | train | 3 | |
d97408bd1a9da1afde336964e916ee3dc933bf7b | [
"self.vocab = vocab\npunct = '[:punct:]' + '\"\\'ˊ"〃ײ᳓″״‶˶ʺ“”˝'\nnum_like = '\\\\d+(?:[.,]\\\\d(?![.,]?[0-9])|(?![.,]?[0-9]))?'\nsep = f\"\\\\d{punct}'\\\\n[:space:]\"\ndefault = f\"[^{sep}]+(?:['ˊ](?=[[:alpha:]]|$))?\"\nexceptions = '|'.join(TOKENIZER_EXCEPTIONS)\nacronym = '[A-Z][A-Z0-9]*[.](?=[A-Z0-9])'\nself.wo... | <|body_start_0|>
self.vocab = vocab
punct = '[:punct:]' + '"\'ˊ"〃ײ᳓″״‶˶ʺ“”˝'
num_like = '\\d+(?:[.,]\\d(?![.,]?[0-9])|(?![.,]?[0-9]))?'
sep = f"\\d{punct}'\\n[:space:]"
default = f"[^{sep}]+(?:['ˊ](?=[[:alpha:]]|$))?"
exceptions = '|'.join(TOKENIZER_EXCEPTIONS)
ac... | EDSTokenizer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EDSTokenizer:
def __init__(self, vocab: Vocab) -> None:
"""Tokenizer class for French clinical documents. It better handles tokenization around: - numbers: "ACR5" -> ["ACR", "5"] instead of ["ACR5"] - newlines: " " -> [" ", " ", " "] instead of [" "] and should be around 5-6 times faster... | stack_v2_sparse_classes_10k_train_000534 | 3,908 | permissive | [
{
"docstring": "Tokenizer class for French clinical documents. It better handles tokenization around: - numbers: \"ACR5\" -> [\"ACR\", \"5\"] instead of [\"ACR5\"] - newlines: \" \" -> [\" \", \" \", \" \"] instead of [\" \"] and should be around 5-6 times faster than its standard French counterpart. Parameters... | 2 | stack_v2_sparse_classes_30k_train_000297 | Implement the Python class `EDSTokenizer` described below.
Class description:
Implement the EDSTokenizer class.
Method signatures and docstrings:
- def __init__(self, vocab: Vocab) -> None: Tokenizer class for French clinical documents. It better handles tokenization around: - numbers: "ACR5" -> ["ACR", "5"] instead ... | Implement the Python class `EDSTokenizer` described below.
Class description:
Implement the EDSTokenizer class.
Method signatures and docstrings:
- def __init__(self, vocab: Vocab) -> None: Tokenizer class for French clinical documents. It better handles tokenization around: - numbers: "ACR5" -> ["ACR", "5"] instead ... | 57e86002735097342b16c8f3edb770a231f4d526 | <|skeleton|>
class EDSTokenizer:
def __init__(self, vocab: Vocab) -> None:
"""Tokenizer class for French clinical documents. It better handles tokenization around: - numbers: "ACR5" -> ["ACR", "5"] instead of ["ACR5"] - newlines: " " -> [" ", " ", " "] instead of [" "] and should be around 5-6 times faster... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EDSTokenizer:
def __init__(self, vocab: Vocab) -> None:
"""Tokenizer class for French clinical documents. It better handles tokenization around: - numbers: "ACR5" -> ["ACR", "5"] instead of ["ACR5"] - newlines: " " -> [" ", " ", " "] instead of [" "] and should be around 5-6 times faster than its stan... | the_stack_v2_python_sparse | edsnlp/language.py | aphp/edsnlp | train | 98 | |
8df120006538e72e8e7e248f5befec826cb4d276 | [
"self.application_parameters = application_parameters\nself.excluded_disks = excluded_disks\nself.vm_credentials = vm_credentials",
"if dictionary is None:\n return None\napplication_parameters = cohesity_management_sdk.models.application_parameters.ApplicationParameters.from_dictionary(dictionary.get('applica... | <|body_start_0|>
self.application_parameters = application_parameters
self.excluded_disks = excluded_disks
self.vm_credentials = vm_credentials
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
application_parameters = cohesity_management_sdk.models.... | Implementation of the 'VmwareSpecialParameters' model. Specifies additional special settings applicable for a Protection Source of 'kVMware' type in a Protection Job. Attributes: application_parameters (ApplicationParameters): Specifies parameters that are related to applications running on the Protection Source. exclu... | VmwareSpecialParameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VmwareSpecialParameters:
"""Implementation of the 'VmwareSpecialParameters' model. Specifies additional special settings applicable for a Protection Source of 'kVMware' type in a Protection Job. Attributes: application_parameters (ApplicationParameters): Specifies parameters that are related to a... | stack_v2_sparse_classes_10k_train_000535 | 3,395 | permissive | [
{
"docstring": "Constructor for the VmwareSpecialParameters class",
"name": "__init__",
"signature": "def __init__(self, application_parameters=None, excluded_disks=None, vm_credentials=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A... | 2 | null | Implement the Python class `VmwareSpecialParameters` described below.
Class description:
Implementation of the 'VmwareSpecialParameters' model. Specifies additional special settings applicable for a Protection Source of 'kVMware' type in a Protection Job. Attributes: application_parameters (ApplicationParameters): Spe... | Implement the Python class `VmwareSpecialParameters` described below.
Class description:
Implementation of the 'VmwareSpecialParameters' model. Specifies additional special settings applicable for a Protection Source of 'kVMware' type in a Protection Job. Attributes: application_parameters (ApplicationParameters): Spe... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class VmwareSpecialParameters:
"""Implementation of the 'VmwareSpecialParameters' model. Specifies additional special settings applicable for a Protection Source of 'kVMware' type in a Protection Job. Attributes: application_parameters (ApplicationParameters): Specifies parameters that are related to a... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class VmwareSpecialParameters:
"""Implementation of the 'VmwareSpecialParameters' model. Specifies additional special settings applicable for a Protection Source of 'kVMware' type in a Protection Job. Attributes: application_parameters (ApplicationParameters): Specifies parameters that are related to applications r... | the_stack_v2_python_sparse | cohesity_management_sdk/models/vmware_special_parameters.py | cohesity/management-sdk-python | train | 24 |
f275d28d27451e829fb50a700cf3b122f2a2a66e | [
"try:\n self._fromfile()\nexcept:\n self._fromdatabase()\n self._tofile()",
"from datasource import DataSource\nfrom astropy.coordinates import SkyCoord\nfrom astropy import units as u\nself.wifsip = DataSource(database=config.dbname, user=config.dbuser, host=config.dbhost)\nself.stars = []\ncolumns = se... | <|body_start_0|>
try:
self._fromfile()
except:
self._fromdatabase()
self._tofile()
<|end_body_0|>
<|body_start_1|>
from datasource import DataSource
from astropy.coordinates import SkyCoord
from astropy import units as u
self.wifsip = ... | NGC6633Table | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NGC6633Table:
def __init__(self):
"""Constructor"""
<|body_0|>
def _fromdatabase(self):
"""import the table from a database"""
<|body_1|>
def _fromfile(self, filename=None):
"""unpickle the data from a file"""
<|body_2|>
def _tofile(... | stack_v2_sparse_classes_10k_train_000536 | 2,628 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "import the table from a database",
"name": "_fromdatabase",
"signature": "def _fromdatabase(self)"
},
{
"docstring": "unpickle the data from a file",
"name": "_fromfile",
... | 4 | stack_v2_sparse_classes_30k_train_002364 | Implement the Python class `NGC6633Table` described below.
Class description:
Implement the NGC6633Table class.
Method signatures and docstrings:
- def __init__(self): Constructor
- def _fromdatabase(self): import the table from a database
- def _fromfile(self, filename=None): unpickle the data from a file
- def _tof... | Implement the Python class `NGC6633Table` described below.
Class description:
Implement the NGC6633Table class.
Method signatures and docstrings:
- def __init__(self): Constructor
- def _fromdatabase(self): import the table from a database
- def _fromfile(self, filename=None): unpickle the data from a file
- def _tof... | c2df6b5de8e94c3935768a8fb40b4f046c21afb4 | <|skeleton|>
class NGC6633Table:
def __init__(self):
"""Constructor"""
<|body_0|>
def _fromdatabase(self):
"""import the table from a database"""
<|body_1|>
def _fromfile(self, filename=None):
"""unpickle the data from a file"""
<|body_2|>
def _tofile(... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NGC6633Table:
def __init__(self):
"""Constructor"""
try:
self._fromfile()
except:
self._fromdatabase()
self._tofile()
def _fromdatabase(self):
"""import the table from a database"""
from datasource import DataSource
from ... | the_stack_v2_python_sparse | src/ngc6633/ngc6633table.py | weingrill/SOCS | train | 0 | |
1a0e931f67807b0ddaf8571551ebb87418accd08 | [
"ret = []\nself.walk(root, defaultdict(int), ret)\nreturn ret",
"if not cur:\n return 'None'\ncur_key = ','.join([self.walk(cur.left, counter, ret), self.walk(cur.right, counter, ret), str(cur.val)])\nif counter[cur_key] == 1:\n ret.append(cur)\ncounter[cur_key] += 1\nreturn cur_key"
] | <|body_start_0|>
ret = []
self.walk(root, defaultdict(int), ret)
return ret
<|end_body_0|>
<|body_start_1|>
if not cur:
return 'None'
cur_key = ','.join([self.walk(cur.left, counter, ret), self.walk(cur.right, counter, ret), str(cur.val)])
if counter[cur_key]... | Solution2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution2:
def findDuplicateSubtrees(self, root: TreeNode) -> List[TreeNode]:
"""Only need to return the root"""
<|body_0|>
def walk(self, cur, counter, ret) -> str:
"""serialize the subtrees and check existence Needs to have a unique representation for the key, cann... | stack_v2_sparse_classes_10k_train_000537 | 2,915 | no_license | [
{
"docstring": "Only need to return the root",
"name": "findDuplicateSubtrees",
"signature": "def findDuplicateSubtrees(self, root: TreeNode) -> List[TreeNode]"
},
{
"docstring": "serialize the subtrees and check existence Needs to have a unique representation for the key, cannot but cur.val in ... | 2 | null | Implement the Python class `Solution2` described below.
Class description:
Implement the Solution2 class.
Method signatures and docstrings:
- def findDuplicateSubtrees(self, root: TreeNode) -> List[TreeNode]: Only need to return the root
- def walk(self, cur, counter, ret) -> str: serialize the subtrees and check exi... | Implement the Python class `Solution2` described below.
Class description:
Implement the Solution2 class.
Method signatures and docstrings:
- def findDuplicateSubtrees(self, root: TreeNode) -> List[TreeNode]: Only need to return the root
- def walk(self, cur, counter, ret) -> str: serialize the subtrees and check exi... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class Solution2:
def findDuplicateSubtrees(self, root: TreeNode) -> List[TreeNode]:
"""Only need to return the root"""
<|body_0|>
def walk(self, cur, counter, ret) -> str:
"""serialize the subtrees and check existence Needs to have a unique representation for the key, cann... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution2:
def findDuplicateSubtrees(self, root: TreeNode) -> List[TreeNode]:
"""Only need to return the root"""
ret = []
self.walk(root, defaultdict(int), ret)
return ret
def walk(self, cur, counter, ret) -> str:
"""serialize the subtrees and check existence Needs... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/LeetCode/652 Find Duplicate Subtrees.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
2cfa8547dac6c6967dd79611594fcf86e15eaa82 | [
"super().__init__(coordinator)\nself.entity_description = description\nself._attr_unique_id = f'{device_id}_{description.key}'\nself._attr_device_info = device\nself.utility_account_id = utility_account_id",
"if self.coordinator.data is not None:\n return self.entity_description.value_fn(self.coordinator.data[... | <|body_start_0|>
super().__init__(coordinator)
self.entity_description = description
self._attr_unique_id = f'{device_id}_{description.key}'
self._attr_device_info = device
self.utility_account_id = utility_account_id
<|end_body_0|>
<|body_start_1|>
if self.coordinator.d... | Representation of an Opower sensor. | OpowerSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpowerSensor:
"""Representation of an Opower sensor."""
def __init__(self, coordinator: OpowerCoordinator, description: OpowerEntityDescription, utility_account_id: str, device: DeviceInfo, device_id: str) -> None:
"""Initialize the sensor."""
<|body_0|>
def native_value... | stack_v2_sparse_classes_10k_train_000538 | 8,626 | permissive | [
{
"docstring": "Initialize the sensor.",
"name": "__init__",
"signature": "def __init__(self, coordinator: OpowerCoordinator, description: OpowerEntityDescription, utility_account_id: str, device: DeviceInfo, device_id: str) -> None"
},
{
"docstring": "Return the state.",
"name": "native_val... | 2 | stack_v2_sparse_classes_30k_train_000954 | Implement the Python class `OpowerSensor` described below.
Class description:
Representation of an Opower sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: OpowerCoordinator, description: OpowerEntityDescription, utility_account_id: str, device: DeviceInfo, device_id: str) -> None: Initializ... | Implement the Python class `OpowerSensor` described below.
Class description:
Representation of an Opower sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: OpowerCoordinator, description: OpowerEntityDescription, utility_account_id: str, device: DeviceInfo, device_id: str) -> None: Initializ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class OpowerSensor:
"""Representation of an Opower sensor."""
def __init__(self, coordinator: OpowerCoordinator, description: OpowerEntityDescription, utility_account_id: str, device: DeviceInfo, device_id: str) -> None:
"""Initialize the sensor."""
<|body_0|>
def native_value... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OpowerSensor:
"""Representation of an Opower sensor."""
def __init__(self, coordinator: OpowerCoordinator, description: OpowerEntityDescription, utility_account_id: str, device: DeviceInfo, device_id: str) -> None:
"""Initialize the sensor."""
super().__init__(coordinator)
self.en... | the_stack_v2_python_sparse | homeassistant/components/opower/sensor.py | home-assistant/core | train | 35,501 |
4ac58a08175a5f50eee8a26ea3620fb596f4c4f8 | [
"for iout in range(0, len(nums) - 2):\n if iout > 0 and nums[iout - 1] == nums[iout]:\n continue\n j, k = (iout + 1, len(nums) - 1)\n while j < k:\n if nums[iout] + nums[j] + nums[k] == target - first_num:\n numj, numk = (nums[j], nums[k])\n while j < k and numj == nums[... | <|body_start_0|>
for iout in range(0, len(nums) - 2):
if iout > 0 and nums[iout - 1] == nums[iout]:
continue
j, k = (iout + 1, len(nums) - 1)
while j < k:
if nums[iout] + nums[j] + nums[k] == target - first_num:
numj, numk =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def threeSum(self, nums, target, first_num, result):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def fourSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_10k_train_000539 | 1,432 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum",
"signature": "def threeSum(self, nums, target, first_num, result)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[List[int]]",
"name": "fourSum",
"signature": "def fourSum(self, n... | 2 | stack_v2_sparse_classes_30k_train_002540 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum(self, nums, target, first_num, result): :type nums: List[int] :rtype: List[List[int]]
- def fourSum(self, nums, target): :type nums: List[int] :type target: int :rty... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum(self, nums, target, first_num, result): :type nums: List[int] :rtype: List[List[int]]
- def fourSum(self, nums, target): :type nums: List[int] :type target: int :rty... | 22f208400cd7e13fcf2ebf189e61ccad7e22b098 | <|skeleton|>
class Solution:
def threeSum(self, nums, target, first_num, result):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def fourSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def threeSum(self, nums, target, first_num, result):
""":type nums: List[int] :rtype: List[List[int]]"""
for iout in range(0, len(nums) - 2):
if iout > 0 and nums[iout - 1] == nums[iout]:
continue
j, k = (iout + 1, len(nums) - 1)
wh... | the_stack_v2_python_sparse | previously_completed/1-30/18-4sum.py | learnerjiahao/leetcode-solve | train | 0 | |
18cd624a6d1ab97fff2a8d7966a3e7e2efa0590a | [
"super(CharCNN, self).__init__()\nself.device = device\nself.char_len = char_len\nself.word_emb_dim = word_emb_dim\nself.kernel_sizes = kernel_sizes\nself.embedding = nn.Embedding(vocab_size, char_emb_dim)\nself.kernels = nn.ModuleList([nn.Conv1d(in_channels=char_emb_dim, out_channels=num_features, kernel_size=kern... | <|body_start_0|>
super(CharCNN, self).__init__()
self.device = device
self.char_len = char_len
self.word_emb_dim = word_emb_dim
self.kernel_sizes = kernel_sizes
self.embedding = nn.Embedding(vocab_size, char_emb_dim)
self.kernels = nn.ModuleList([nn.Conv1d(in_chan... | An implementation of 'Character-Aware Neural Language Models' of Kim et al. (2015). | CharCNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CharCNN:
"""An implementation of 'Character-Aware Neural Language Models' of Kim et al. (2015)."""
def __init__(self, vocab_size: int, char_emb_dim: int, word_emb_dim: int, kernel_sizes: List[List[int]], char_len: int, device: str):
"""Parameters: vocab_size: `int`. Vocabulary size o... | stack_v2_sparse_classes_10k_train_000540 | 4,912 | no_license | [
{
"docstring": "Parameters: vocab_size: `int`. Vocabulary size of chracters used in the model emb_dim: `int`. Embedding size kernel_sizes: A `list` of `list`s of `int`s. The nested list indicates feature maps for the convolutions in the paper (i.e. [(kernel_size, # kernels), ...]) char_len: 'int'. Character len... | 2 | stack_v2_sparse_classes_30k_train_005836 | Implement the Python class `CharCNN` described below.
Class description:
An implementation of 'Character-Aware Neural Language Models' of Kim et al. (2015).
Method signatures and docstrings:
- def __init__(self, vocab_size: int, char_emb_dim: int, word_emb_dim: int, kernel_sizes: List[List[int]], char_len: int, devic... | Implement the Python class `CharCNN` described below.
Class description:
An implementation of 'Character-Aware Neural Language Models' of Kim et al. (2015).
Method signatures and docstrings:
- def __init__(self, vocab_size: int, char_emb_dim: int, word_emb_dim: int, kernel_sizes: List[List[int]], char_len: int, devic... | ca033284850147b334d3771df8235a1135eba76c | <|skeleton|>
class CharCNN:
"""An implementation of 'Character-Aware Neural Language Models' of Kim et al. (2015)."""
def __init__(self, vocab_size: int, char_emb_dim: int, word_emb_dim: int, kernel_sizes: List[List[int]], char_len: int, device: str):
"""Parameters: vocab_size: `int`. Vocabulary size o... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CharCNN:
"""An implementation of 'Character-Aware Neural Language Models' of Kim et al. (2015)."""
def __init__(self, vocab_size: int, char_emb_dim: int, word_emb_dim: int, kernel_sizes: List[List[int]], char_len: int, device: str):
"""Parameters: vocab_size: `int`. Vocabulary size of chracters u... | the_stack_v2_python_sparse | papers/4.ELMo/char_cnn.py | euhkim/NLP | train | 0 |
34d044002269d8927a730fb717cd768e0e0445e5 | [
"inf = sys.maxsize\ngraph = [[inf for _ in range(n)] for _ in range(n)]\nfor i in range(n):\n graph[i][i] = 0\nfor u, v, w in edges:\n graph[u][v] = w\n graph[v][u] = w\nfor k in range(n):\n for i in range(n):\n for j in range(n):\n graph[i][j] = min(graph[i][j], graph[i][k] + graph[k]... | <|body_start_0|>
inf = sys.maxsize
graph = [[inf for _ in range(n)] for _ in range(n)]
for i in range(n):
graph[i][i] = 0
for u, v, w in edges:
graph[u][v] = w
graph[v][u] = w
for k in range(n):
for i in range(n):
fo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findTheCityFloyd(self, n, edges, distanceThreshold):
""":type n: int :type edges: List[List[int]] :type distanceThreshold: int :rtype: int"""
<|body_0|>
def findTheCity(self, n, edges, distanceThreshold):
""":type n: int :type edges: List[List[int]] :ty... | stack_v2_sparse_classes_10k_train_000541 | 4,208 | no_license | [
{
"docstring": ":type n: int :type edges: List[List[int]] :type distanceThreshold: int :rtype: int",
"name": "findTheCityFloyd",
"signature": "def findTheCityFloyd(self, n, edges, distanceThreshold)"
},
{
"docstring": ":type n: int :type edges: List[List[int]] :type distanceThreshold: int :rtype... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTheCityFloyd(self, n, edges, distanceThreshold): :type n: int :type edges: List[List[int]] :type distanceThreshold: int :rtype: int
- def findTheCity(self, n, edges, dist... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTheCityFloyd(self, n, edges, distanceThreshold): :type n: int :type edges: List[List[int]] :type distanceThreshold: int :rtype: int
- def findTheCity(self, n, edges, dist... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def findTheCityFloyd(self, n, edges, distanceThreshold):
""":type n: int :type edges: List[List[int]] :type distanceThreshold: int :rtype: int"""
<|body_0|>
def findTheCity(self, n, edges, distanceThreshold):
""":type n: int :type edges: List[List[int]] :ty... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findTheCityFloyd(self, n, edges, distanceThreshold):
""":type n: int :type edges: List[List[int]] :type distanceThreshold: int :rtype: int"""
inf = sys.maxsize
graph = [[inf for _ in range(n)] for _ in range(n)]
for i in range(n):
graph[i][i] = 0
... | the_stack_v2_python_sparse | F/FindTheCityWithTheSmallestNumberOfNeighborsAtAThresholdDistance.py | bssrdf/pyleet | train | 2 | |
7c34c1662c0e62da35a805dbb0ac6efa7ac5f12e | [
"self.w = INITIALIZERS[initializer](inputdim, units) if initializer else INITIALIZERS['random'](inputdim, units)\nself.regularizer = regularizer if regularizer else 'l'\nself.activation = activation\nself.dropout = dropout\nself.optimizer = None\nself.dz_dw = None\nself.dz_dx = None\nself.da_dz = None\nself.dr_dw =... | <|body_start_0|>
self.w = INITIALIZERS[initializer](inputdim, units) if initializer else INITIALIZERS['random'](inputdim, units)
self.regularizer = regularizer if regularizer else 'l'
self.activation = activation
self.dropout = dropout
self.optimizer = None
self.dz_dw = N... | Default dense layer class | DefaultDenseLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DefaultDenseLayer:
"""Default dense layer class"""
def __init__(self, inputdim: int, units: int, activation: str, initializer: str=None, regularizer: str=None, dropout: float=None) -> None:
"""Initialize default dense layer Args: inputdim: number of input units units: number of units... | stack_v2_sparse_classes_10k_train_000542 | 5,858 | no_license | [
{
"docstring": "Initialize default dense layer Args: inputdim: number of input units units: number of units in layer activation: activation function string => should be a key of ACTIVATIONS initializer: weight initialization scheme => should be a key of INITIALIZERS regularizer: regularization method => should ... | 3 | stack_v2_sparse_classes_30k_train_006395 | Implement the Python class `DefaultDenseLayer` described below.
Class description:
Default dense layer class
Method signatures and docstrings:
- def __init__(self, inputdim: int, units: int, activation: str, initializer: str=None, regularizer: str=None, dropout: float=None) -> None: Initialize default dense layer Arg... | Implement the Python class `DefaultDenseLayer` described below.
Class description:
Default dense layer class
Method signatures and docstrings:
- def __init__(self, inputdim: int, units: int, activation: str, initializer: str=None, regularizer: str=None, dropout: float=None) -> None: Initialize default dense layer Arg... | 9e6d3846968597349eabda3eb07e70253baf4786 | <|skeleton|>
class DefaultDenseLayer:
"""Default dense layer class"""
def __init__(self, inputdim: int, units: int, activation: str, initializer: str=None, regularizer: str=None, dropout: float=None) -> None:
"""Initialize default dense layer Args: inputdim: number of input units units: number of units... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DefaultDenseLayer:
"""Default dense layer class"""
def __init__(self, inputdim: int, units: int, activation: str, initializer: str=None, regularizer: str=None, dropout: float=None) -> None:
"""Initialize default dense layer Args: inputdim: number of input units units: number of units in layer act... | the_stack_v2_python_sparse | Packages/mlr/NN/Layer.py | akshat0123/MLReview | train | 0 |
7851fc560bbb59297aa582e70a58aed5938f8d88 | [
"user = User.get_user_by_id(user_id=user_id)\nif not user:\n raise SystemGlobalException(StatusCodeMessage.USERNAME_NOT_EXISTS)\nserializer = UserListSerializers(user)\nreturn APIResponse(data=serializer.data).get_result()",
"user = User.get_user_by_id(user_id=user_id)\nif not user:\n raise SystemGlobalExce... | <|body_start_0|>
user = User.get_user_by_id(user_id=user_id)
if not user:
raise SystemGlobalException(StatusCodeMessage.USERNAME_NOT_EXISTS)
serializer = UserListSerializers(user)
return APIResponse(data=serializer.data).get_result()
<|end_body_0|>
<|body_start_1|>
u... | 用户查询,更新APIView | UserFindUpdateDelAPIView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserFindUpdateDelAPIView:
"""用户查询,更新APIView"""
def get(_, user_id):
"""用户查询"""
<|body_0|>
def put(request, user_id):
"""用户修改"""
<|body_1|>
def delete(request, user_id):
"""用户删除"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_000543 | 2,573 | no_license | [
{
"docstring": "用户查询",
"name": "get",
"signature": "def get(_, user_id)"
},
{
"docstring": "用户修改",
"name": "put",
"signature": "def put(request, user_id)"
},
{
"docstring": "用户删除",
"name": "delete",
"signature": "def delete(request, user_id)"
}
] | 3 | stack_v2_sparse_classes_30k_train_002080 | Implement the Python class `UserFindUpdateDelAPIView` described below.
Class description:
用户查询,更新APIView
Method signatures and docstrings:
- def get(_, user_id): 用户查询
- def put(request, user_id): 用户修改
- def delete(request, user_id): 用户删除 | Implement the Python class `UserFindUpdateDelAPIView` described below.
Class description:
用户查询,更新APIView
Method signatures and docstrings:
- def get(_, user_id): 用户查询
- def put(request, user_id): 用户修改
- def delete(request, user_id): 用户删除
<|skeleton|>
class UserFindUpdateDelAPIView:
"""用户查询,更新APIView"""
def ... | bb85b52598d68956bde8756c8321ade7b8479ba7 | <|skeleton|>
class UserFindUpdateDelAPIView:
"""用户查询,更新APIView"""
def get(_, user_id):
"""用户查询"""
<|body_0|>
def put(request, user_id):
"""用户修改"""
<|body_1|>
def delete(request, user_id):
"""用户删除"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserFindUpdateDelAPIView:
"""用户查询,更新APIView"""
def get(_, user_id):
"""用户查询"""
user = User.get_user_by_id(user_id=user_id)
if not user:
raise SystemGlobalException(StatusCodeMessage.USERNAME_NOT_EXISTS)
serializer = UserListSerializers(user)
return APIR... | the_stack_v2_python_sparse | rbac_v1/v1/rbac_app/views/user/user_views.py | huiiiuh/huihuiproject | train | 0 |
9fe18658a43d2b99dd84819b1e9aa2b603f41a22 | [
"super(Mixer, self).__init__()\nself.n_agents = agent_num\nself.state_dim = state_dim\nself.embed_dim = mixing_embed_dim\nself.hyper_w_1 = nn.Sequential(nn.Linear(self.state_dim, hypernet_embed), nn.ReLU(), nn.Linear(hypernet_embed, self.embed_dim * self.n_agents))\nself.hyper_w_final = nn.Sequential(nn.Linear(self... | <|body_start_0|>
super(Mixer, self).__init__()
self.n_agents = agent_num
self.state_dim = state_dim
self.embed_dim = mixing_embed_dim
self.hyper_w_1 = nn.Sequential(nn.Linear(self.state_dim, hypernet_embed), nn.ReLU(), nn.Linear(hypernet_embed, self.embed_dim * self.n_agents))
... | Overview: mixer network in QMIX, which mix up the independent q_value of each agent to a total q_value Interface: __init__, forward | Mixer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Mixer:
"""Overview: mixer network in QMIX, which mix up the independent q_value of each agent to a total q_value Interface: __init__, forward"""
def __init__(self, agent_num, state_dim, mixing_embed_dim, hypernet_embed=64):
"""Overview: initialize pymarl mixer network Arguments: - ag... | stack_v2_sparse_classes_10k_train_000544 | 27,383 | permissive | [
{
"docstring": "Overview: initialize pymarl mixer network Arguments: - agent_num (:obj:`int`): the number of agent - state_dim(:obj:`int`): the dimension of global observation state - mixing_embed_dim (:obj:`int`): the dimension of mixing state emdedding - hypernet_embed (:obj:`int`): the dimension of hypernet ... | 2 | stack_v2_sparse_classes_30k_val_000001 | Implement the Python class `Mixer` described below.
Class description:
Overview: mixer network in QMIX, which mix up the independent q_value of each agent to a total q_value Interface: __init__, forward
Method signatures and docstrings:
- def __init__(self, agent_num, state_dim, mixing_embed_dim, hypernet_embed=64): ... | Implement the Python class `Mixer` described below.
Class description:
Overview: mixer network in QMIX, which mix up the independent q_value of each agent to a total q_value Interface: __init__, forward
Method signatures and docstrings:
- def __init__(self, agent_num, state_dim, mixing_embed_dim, hypernet_embed=64): ... | eb483fa6e46602d58c8e7d2ca1e566adca28e703 | <|skeleton|>
class Mixer:
"""Overview: mixer network in QMIX, which mix up the independent q_value of each agent to a total q_value Interface: __init__, forward"""
def __init__(self, agent_num, state_dim, mixing_embed_dim, hypernet_embed=64):
"""Overview: initialize pymarl mixer network Arguments: - ag... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Mixer:
"""Overview: mixer network in QMIX, which mix up the independent q_value of each agent to a total q_value Interface: __init__, forward"""
def __init__(self, agent_num, state_dim, mixing_embed_dim, hypernet_embed=64):
"""Overview: initialize pymarl mixer network Arguments: - agent_num (:obj... | the_stack_v2_python_sparse | ding/model/template/qmix.py | shengxuesun/DI-engine | train | 1 |
97cf5fe2bc9be4a1732cb159b55adadf649d4fb4 | [
"\"\"\"Initialization\"\"\"\nself.img_shape = img_shape\nself.chunk_size = chunk_size\nself.attr_vals = load_attr_vals_txts()\nself.attr_cnt = len(self.attr_vals)\nself.train_ids, self.validation_ids, self.test_ids, self.attr_map = load_config_wiki()\nprint('-- Generator Wiki initialized.')",
"images = []\nerrs =... | <|body_start_0|>
"""Initialization"""
self.img_shape = img_shape
self.chunk_size = chunk_size
self.attr_vals = load_attr_vals_txts()
self.attr_cnt = len(self.attr_vals)
self.train_ids, self.validation_ids, self.test_ids, self.attr_map = load_config_wiki()
print('-... | DataGeneratorWiki | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataGeneratorWiki:
def __init__(self, img_shape=(100, 100), chunk_size=1024):
""":param img_shape: resolution of final image :param chunk_size: size of super batch :param rot_int: interval for image rotation"""
<|body_0|>
def get_images_online(self, img_names):
"""Re... | stack_v2_sparse_classes_10k_train_000545 | 3,756 | no_license | [
{
"docstring": ":param img_shape: resolution of final image :param chunk_size: size of super batch :param rot_int: interval for image rotation",
"name": "__init__",
"signature": "def __init__(self, img_shape=(100, 100), chunk_size=1024)"
},
{
"docstring": "Reads list of images from specidied fol... | 4 | stack_v2_sparse_classes_30k_train_005492 | Implement the Python class `DataGeneratorWiki` described below.
Class description:
Implement the DataGeneratorWiki class.
Method signatures and docstrings:
- def __init__(self, img_shape=(100, 100), chunk_size=1024): :param img_shape: resolution of final image :param chunk_size: size of super batch :param rot_int: in... | Implement the Python class `DataGeneratorWiki` described below.
Class description:
Implement the DataGeneratorWiki class.
Method signatures and docstrings:
- def __init__(self, img_shape=(100, 100), chunk_size=1024): :param img_shape: resolution of final image :param chunk_size: size of super batch :param rot_int: in... | acd540fe845d0496c9cf2560f59623de3b93898c | <|skeleton|>
class DataGeneratorWiki:
def __init__(self, img_shape=(100, 100), chunk_size=1024):
""":param img_shape: resolution of final image :param chunk_size: size of super batch :param rot_int: interval for image rotation"""
<|body_0|>
def get_images_online(self, img_names):
"""Re... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DataGeneratorWiki:
def __init__(self, img_shape=(100, 100), chunk_size=1024):
""":param img_shape: resolution of final image :param chunk_size: size of super batch :param rot_int: interval for image rotation"""
"""Initialization"""
self.img_shape = img_shape
self.chunk_size = c... | the_stack_v2_python_sparse | data_proc/DataGeneratorWiki.py | MarcisinMatej/CNN | train | 0 | |
6d7e1f8a1a096364cc493ba82661ee7184ab62a9 | [
"super().__init__()\nif out_channels is None:\n out_channels = in_channels\nself.in_channels, self.out_channels = (in_channels, out_channels)\nself.map = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation)",
"x = self.map(input)\nx_gate = torch.sigmo... | <|body_start_0|>
super().__init__()
if out_channels is None:
out_channels = in_channels
self.in_channels, self.out_channels = (in_channels, out_channels)
self.map = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation... | Sigmoid Linear Units for 2D inputs | SiLU2d | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SiLU2d:
"""Sigmoid Linear Units for 2D inputs"""
def __init__(self, in_channels, out_channels, kernel_size, stride=(1, 1), padding=(0, 0), dilation=(1, 1)):
"""Args: in_channels <int> out_channels <int>"""
<|body_0|>
def forward(self, input):
"""Args: input (batc... | stack_v2_sparse_classes_10k_train_000546 | 2,967 | no_license | [
{
"docstring": "Args: in_channels <int> out_channels <int>",
"name": "__init__",
"signature": "def __init__(self, in_channels, out_channels, kernel_size, stride=(1, 1), padding=(0, 0), dilation=(1, 1))"
},
{
"docstring": "Args: input (batch_size, in_channels, H, W) Returns: output (batch_size, o... | 2 | stack_v2_sparse_classes_30k_train_001994 | Implement the Python class `SiLU2d` described below.
Class description:
Sigmoid Linear Units for 2D inputs
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, kernel_size, stride=(1, 1), padding=(0, 0), dilation=(1, 1)): Args: in_channels <int> out_channels <int>
- def forward(self, inpu... | Implement the Python class `SiLU2d` described below.
Class description:
Sigmoid Linear Units for 2D inputs
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, kernel_size, stride=(1, 1), padding=(0, 0), dilation=(1, 1)): Args: in_channels <int> out_channels <int>
- def forward(self, inpu... | 4f7f77406cf580785ebf932d78069e7d6e35b765 | <|skeleton|>
class SiLU2d:
"""Sigmoid Linear Units for 2D inputs"""
def __init__(self, in_channels, out_channels, kernel_size, stride=(1, 1), padding=(0, 0), dilation=(1, 1)):
"""Args: in_channels <int> out_channels <int>"""
<|body_0|>
def forward(self, input):
"""Args: input (batc... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SiLU2d:
"""Sigmoid Linear Units for 2D inputs"""
def __init__(self, in_channels, out_channels, kernel_size, stride=(1, 1), padding=(0, 0), dilation=(1, 1)):
"""Args: in_channels <int> out_channels <int>"""
super().__init__()
if out_channels is None:
out_channels = in_c... | the_stack_v2_python_sparse | src/models/silu.py | shelly-tang/DNN-based_source_separation | train | 0 |
e06fb8c1064aa1dcfcf8cef4a7d54ac17f5c084e | [
"self.capacity = capacity\nself.size = 0\nself.cache = dict()\nself.cachelist = DoubleList()",
"if key not in self.cache:\n return -1\nnode = self.cache[key]\nself.cachelist.delete(node)\nself.cachelist.append(node)\nreturn node.val",
"if key in self.cache:\n node = self.cache[key]\n node.val = value\n... | <|body_start_0|>
self.capacity = capacity
self.size = 0
self.cache = dict()
self.cachelist = DoubleList()
<|end_body_0|>
<|body_start_1|>
if key not in self.cache:
return -1
node = self.cache[key]
self.cachelist.delete(node)
self.cachelist.app... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_10k_train_000547 | 2,925 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: None",
"name": "pu... | 3 | null | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None
<|sk... | 837957ea22aa07ce28a6c23ea0419bd2011e1f88 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.size = 0
self.cache = dict()
self.cachelist = DoubleList()
def get(self, key):
""":type key: int :rtype: int"""
if key not in self.cache:
ret... | the_stack_v2_python_sparse | Tencent/midum/LRU缓存.py | 2226171237/Algorithmpractice | train | 0 | |
897869c998776c67cbfce2f552e2fd2397c06eb1 | [
"super().__init__('opendr_object_tracking_3d_ab3dmot_node')\nself.detector = detector\nself.learner = ObjectTracking3DAb3dmotLearner(device=device)\nself.bridge = ROS2Bridge()\nif output_detection3d_topic is not None:\n self.detection_publisher = self.create_publisher(Detection3DArray, output_detection3d_topic, ... | <|body_start_0|>
super().__init__('opendr_object_tracking_3d_ab3dmot_node')
self.detector = detector
self.learner = ObjectTracking3DAb3dmotLearner(device=device)
self.bridge = ROS2Bridge()
if output_detection3d_topic is not None:
self.detection_publisher = self.create... | ObjectTracking3DAb3dmotNode | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectTracking3DAb3dmotNode:
def __init__(self, detector=None, input_point_cloud_topic='/opendr/dataset_point_cloud', output_detection3d_topic='/opendr/detection3d', output_tracking3d_id_topic='/opendr/tracking3d_id', device='cuda:0'):
"""Creates a ROS2 Node for 3D object tracking :param... | stack_v2_sparse_classes_10k_train_000548 | 7,413 | permissive | [
{
"docstring": "Creates a ROS2 Node for 3D object tracking :param detector: Learner that provides 3D object detections :type detector: Learner :param input_point_cloud_topic: Topic from which we are reading the input point cloud :type input_point_cloud_topic: str :param output_detection3d_topic: Topic to which ... | 2 | stack_v2_sparse_classes_30k_train_000547 | Implement the Python class `ObjectTracking3DAb3dmotNode` described below.
Class description:
Implement the ObjectTracking3DAb3dmotNode class.
Method signatures and docstrings:
- def __init__(self, detector=None, input_point_cloud_topic='/opendr/dataset_point_cloud', output_detection3d_topic='/opendr/detection3d', out... | Implement the Python class `ObjectTracking3DAb3dmotNode` described below.
Class description:
Implement the ObjectTracking3DAb3dmotNode class.
Method signatures and docstrings:
- def __init__(self, detector=None, input_point_cloud_topic='/opendr/dataset_point_cloud', output_detection3d_topic='/opendr/detection3d', out... | b3d6ce670cdf63469fc5766630eb295d67b3d788 | <|skeleton|>
class ObjectTracking3DAb3dmotNode:
def __init__(self, detector=None, input_point_cloud_topic='/opendr/dataset_point_cloud', output_detection3d_topic='/opendr/detection3d', output_tracking3d_id_topic='/opendr/tracking3d_id', device='cuda:0'):
"""Creates a ROS2 Node for 3D object tracking :param... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ObjectTracking3DAb3dmotNode:
def __init__(self, detector=None, input_point_cloud_topic='/opendr/dataset_point_cloud', output_detection3d_topic='/opendr/detection3d', output_tracking3d_id_topic='/opendr/tracking3d_id', device='cuda:0'):
"""Creates a ROS2 Node for 3D object tracking :param detector: Lea... | the_stack_v2_python_sparse | projects/opendr_ws_2/src/opendr_perception/opendr_perception/object_tracking_3d_ab3dmot_node.py | opendr-eu/opendr | train | 535 | |
32d143d07062c9fe2b828ae50efc8697cb18b37b | [
"from promptlayer.utils import get_api_key, promptlayer_api_request\nrequest_start_time = datetime.datetime.now().timestamp()\ngenerated_responses = super()._generate(messages, stop)\nrequest_end_time = datetime.datetime.now().timestamp()\nmessage_dicts, params = super()._create_message_dicts(messages, stop)\nfor i... | <|body_start_0|>
from promptlayer.utils import get_api_key, promptlayer_api_request
request_start_time = datetime.datetime.now().timestamp()
generated_responses = super()._generate(messages, stop)
request_end_time = datetime.datetime.now().timestamp()
message_dicts, params = supe... | Wrapper around OpenAI Chat large language models and PromptLayer. To use, you should have the ``openai`` and ``promptlayer`` python package installed, and the environment variable ``OPENAI_API_KEY`` and ``PROMPTLAYER_API_KEY`` set with your openAI API key and promptlayer key respectively. All parameters that can be pas... | PromptLayerChatOpenAI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PromptLayerChatOpenAI:
"""Wrapper around OpenAI Chat large language models and PromptLayer. To use, you should have the ``openai`` and ``promptlayer`` python package installed, and the environment variable ``OPENAI_API_KEY`` and ``PROMPTLAYER_API_KEY`` set with your openAI API key and promptlayer... | stack_v2_sparse_classes_10k_train_000549 | 4,203 | no_license | [
{
"docstring": "Call ChatOpenAI generate and then call PromptLayer API to log the request.",
"name": "_generate",
"signature": "def _generate(self, messages: List[BaseMessage], stop: Optional[List[str]]=None) -> ChatResult"
},
{
"docstring": "Call ChatOpenAI agenerate and then call PromptLayer t... | 2 | stack_v2_sparse_classes_30k_train_005505 | Implement the Python class `PromptLayerChatOpenAI` described below.
Class description:
Wrapper around OpenAI Chat large language models and PromptLayer. To use, you should have the ``openai`` and ``promptlayer`` python package installed, and the environment variable ``OPENAI_API_KEY`` and ``PROMPTLAYER_API_KEY`` set w... | Implement the Python class `PromptLayerChatOpenAI` described below.
Class description:
Wrapper around OpenAI Chat large language models and PromptLayer. To use, you should have the ``openai`` and ``promptlayer`` python package installed, and the environment variable ``OPENAI_API_KEY`` and ``PROMPTLAYER_API_KEY`` set w... | b7aaa920a52613e3f1f04fa5cd7568ad37302d11 | <|skeleton|>
class PromptLayerChatOpenAI:
"""Wrapper around OpenAI Chat large language models and PromptLayer. To use, you should have the ``openai`` and ``promptlayer`` python package installed, and the environment variable ``OPENAI_API_KEY`` and ``PROMPTLAYER_API_KEY`` set with your openAI API key and promptlayer... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PromptLayerChatOpenAI:
"""Wrapper around OpenAI Chat large language models and PromptLayer. To use, you should have the ``openai`` and ``promptlayer`` python package installed, and the environment variable ``OPENAI_API_KEY`` and ``PROMPTLAYER_API_KEY`` set with your openAI API key and promptlayer key respecti... | the_stack_v2_python_sparse | openai/venv/lib/python3.10/site-packages/langchain/chat_models/promptlayer_openai.py | henrymendez/garage | train | 0 |
43c6fb8d8f3b0b77a28381237cff91cae42ef6b8 | [
"self.img_u = dataset_loader\nif mode == 'GAP_CAM':\n self.model = Sequential(applications.VGG16(weights='imagenet', include_top=False).layers)\n self.model.add(Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='CAM'))\n self.model.add(GlobalAveragePooling2D(name='GAP'))\n self.model.... | <|body_start_0|>
self.img_u = dataset_loader
if mode == 'GAP_CAM':
self.model = Sequential(applications.VGG16(weights='imagenet', include_top=False).layers)
self.model.add(Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='CAM'))
self.model.add(Glob... | VGG16 fine tuned. | VGG16FineTuned | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VGG16FineTuned:
"""VGG16 fine tuned."""
def __init__(self, dataset_loader: DatasetLoader, mode: str):
"""Create and compile the custom VGG16 model. :param dataset_loader: The data set loader with the model will train."""
<|body_0|>
def train(self, nb_epochs, weights_in=N... | stack_v2_sparse_classes_10k_train_000550 | 2,317 | no_license | [
{
"docstring": "Create and compile the custom VGG16 model. :param dataset_loader: The data set loader with the model will train.",
"name": "__init__",
"signature": "def __init__(self, dataset_loader: DatasetLoader, mode: str)"
},
{
"docstring": "Trains the custom VGG16 model. :param weights_in: ... | 2 | stack_v2_sparse_classes_30k_test_000033 | Implement the Python class `VGG16FineTuned` described below.
Class description:
VGG16 fine tuned.
Method signatures and docstrings:
- def __init__(self, dataset_loader: DatasetLoader, mode: str): Create and compile the custom VGG16 model. :param dataset_loader: The data set loader with the model will train.
- def tra... | Implement the Python class `VGG16FineTuned` described below.
Class description:
VGG16 fine tuned.
Method signatures and docstrings:
- def __init__(self, dataset_loader: DatasetLoader, mode: str): Create and compile the custom VGG16 model. :param dataset_loader: The data set loader with the model will train.
- def tra... | 59b979521c66ad7509295c3cbb2696e3b38ebbd9 | <|skeleton|>
class VGG16FineTuned:
"""VGG16 fine tuned."""
def __init__(self, dataset_loader: DatasetLoader, mode: str):
"""Create and compile the custom VGG16 model. :param dataset_loader: The data set loader with the model will train."""
<|body_0|>
def train(self, nb_epochs, weights_in=N... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class VGG16FineTuned:
"""VGG16 fine tuned."""
def __init__(self, dataset_loader: DatasetLoader, mode: str):
"""Create and compile the custom VGG16 model. :param dataset_loader: The data set loader with the model will train."""
self.img_u = dataset_loader
if mode == 'GAP_CAM':
... | the_stack_v2_python_sparse | keras/VGG16_ft.py | ioannisNoukakis/Bachelor-2017 | train | 0 |
2a8b743b2f6bf620fe1080888a54ee19fbab46ec | [
"super().__init__(('', port), handler)\nself.delete_kv_lock = threading.Lock()\nself.delete_kv = {}\nself.kv_lock = threading.Lock()\nself.kv = {}",
"ret = 0\nwith self.delete_kv_lock:\n ret = len(self.delete_kv.get(key, set()))\nreturn ret"
] | <|body_start_0|>
super().__init__(('', port), handler)
self.delete_kv_lock = threading.Lock()
self.delete_kv = {}
self.kv_lock = threading.Lock()
self.kv = {}
<|end_body_0|>
<|body_start_1|>
ret = 0
with self.delete_kv_lock:
ret = len(self.delete_kv.g... | it is a http server storing kv pairs. | KVHTTPServer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KVHTTPServer:
"""it is a http server storing kv pairs."""
def __init__(self, port, handler):
"""Init."""
<|body_0|>
def get_deleted_size(self, key):
"""get deleted size in key."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__((''... | stack_v2_sparse_classes_10k_train_000551 | 5,744 | permissive | [
{
"docstring": "Init.",
"name": "__init__",
"signature": "def __init__(self, port, handler)"
},
{
"docstring": "get deleted size in key.",
"name": "get_deleted_size",
"signature": "def get_deleted_size(self, key)"
}
] | 2 | null | Implement the Python class `KVHTTPServer` described below.
Class description:
it is a http server storing kv pairs.
Method signatures and docstrings:
- def __init__(self, port, handler): Init.
- def get_deleted_size(self, key): get deleted size in key. | Implement the Python class `KVHTTPServer` described below.
Class description:
it is a http server storing kv pairs.
Method signatures and docstrings:
- def __init__(self, port, handler): Init.
- def get_deleted_size(self, key): get deleted size in key.
<|skeleton|>
class KVHTTPServer:
"""it is a http server stor... | 22a11a60e0e3d10a3cf610077a3d9942a6f964cb | <|skeleton|>
class KVHTTPServer:
"""it is a http server storing kv pairs."""
def __init__(self, port, handler):
"""Init."""
<|body_0|>
def get_deleted_size(self, key):
"""get deleted size in key."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class KVHTTPServer:
"""it is a http server storing kv pairs."""
def __init__(self, port, handler):
"""Init."""
super().__init__(('', port), handler)
self.delete_kv_lock = threading.Lock()
self.delete_kv = {}
self.kv_lock = threading.Lock()
self.kv = {}
def g... | the_stack_v2_python_sparse | python/paddle/distributed/fleet/utils/http_server.py | PaddlePaddle/Paddle | train | 20,414 |
daaedc4d37aed9872e8e607cea152120df431497 | [
"super(ResBlk, self).__init__()\nself.conv1 = nn.Conv2d(ch_in, ch_out, kernel_size=3, stride=stride, padding=1)\nself.bn1 = nn.BatchNorm2d(ch_out)\nself.conv2 = nn.Conv2d(ch_out, ch_out, kernel_size=3, stride=1, padding=1)\nself.bn2 = nn.BatchNorm2d(ch_out)\nself.extra = nn.Sequential()\nif ch_out != ch_in:\n se... | <|body_start_0|>
super(ResBlk, self).__init__()
self.conv1 = nn.Conv2d(ch_in, ch_out, kernel_size=3, stride=stride, padding=1)
self.bn1 = nn.BatchNorm2d(ch_out)
self.conv2 = nn.Conv2d(ch_out, ch_out, kernel_size=3, stride=1, padding=1)
self.bn2 = nn.BatchNorm2d(ch_out)
se... | resnet block | ResBlk | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResBlk:
"""resnet block"""
def __init__(self, ch_in, ch_out, stride=1):
""":param ch_in: :param ch_out:"""
<|body_0|>
def forward(self, x):
""":param x: [b, ch, h, w] :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(ResBlk, self)._... | stack_v2_sparse_classes_10k_train_000552 | 12,300 | no_license | [
{
"docstring": ":param ch_in: :param ch_out:",
"name": "__init__",
"signature": "def __init__(self, ch_in, ch_out, stride=1)"
},
{
"docstring": ":param x: [b, ch, h, w] :return:",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | null | Implement the Python class `ResBlk` described below.
Class description:
resnet block
Method signatures and docstrings:
- def __init__(self, ch_in, ch_out, stride=1): :param ch_in: :param ch_out:
- def forward(self, x): :param x: [b, ch, h, w] :return: | Implement the Python class `ResBlk` described below.
Class description:
resnet block
Method signatures and docstrings:
- def __init__(self, ch_in, ch_out, stride=1): :param ch_in: :param ch_out:
- def forward(self, x): :param x: [b, ch, h, w] :return:
<|skeleton|>
class ResBlk:
"""resnet block"""
def __init... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class ResBlk:
"""resnet block"""
def __init__(self, ch_in, ch_out, stride=1):
""":param ch_in: :param ch_out:"""
<|body_0|>
def forward(self, x):
""":param x: [b, ch, h, w] :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ResBlk:
"""resnet block"""
def __init__(self, ch_in, ch_out, stride=1):
""":param ch_in: :param ch_out:"""
super(ResBlk, self).__init__()
self.conv1 = nn.Conv2d(ch_in, ch_out, kernel_size=3, stride=stride, padding=1)
self.bn1 = nn.BatchNorm2d(ch_out)
self.conv2 = n... | the_stack_v2_python_sparse | generated/test_dragen1860_Deep_Learning_with_PyTorch_Tutorials.py | jansel/pytorch-jit-paritybench | train | 35 |
bf9588ee2a4af4d9357a51e13ab14a30f1f6561b | [
"self.res = []\nself.dfs(root, [], target)\nreturn self.res",
"if not root:\n return\npath.append(root.val)\ntarget -= root.val\nif target == 0 and (not root.left) and (not root.right):\n self.res.append(path[:])\nself.dfs(root.left, path, target)\nself.dfs(root.right, path, target)\npath.pop()"
] | <|body_start_0|>
self.res = []
self.dfs(root, [], target)
return self.res
<|end_body_0|>
<|body_start_1|>
if not root:
return
path.append(root.val)
target -= root.val
if target == 0 and (not root.left) and (not root.right):
self.res.append... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def pathSum(self, root, target):
"""Args: root: TreeNode target: int Return: list[list[int]]"""
<|body_0|>
def dfs(self, root, path, target):
"""Args: root: TreeNode path: list[int] target: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_000553 | 902 | no_license | [
{
"docstring": "Args: root: TreeNode target: int Return: list[list[int]]",
"name": "pathSum",
"signature": "def pathSum(self, root, target)"
},
{
"docstring": "Args: root: TreeNode path: list[int] target: int",
"name": "dfs",
"signature": "def dfs(self, root, path, target)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003025 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum(self, root, target): Args: root: TreeNode target: int Return: list[list[int]]
- def dfs(self, root, path, target): Args: root: TreeNode path: list[int] target: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum(self, root, target): Args: root: TreeNode target: int Return: list[list[int]]
- def dfs(self, root, path, target): Args: root: TreeNode path: list[int] target: int
<... | 101bce2fac8b188a4eb2f5e017293d21ad0ecb21 | <|skeleton|>
class Solution:
def pathSum(self, root, target):
"""Args: root: TreeNode target: int Return: list[list[int]]"""
<|body_0|>
def dfs(self, root, path, target):
"""Args: root: TreeNode path: list[int] target: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def pathSum(self, root, target):
"""Args: root: TreeNode target: int Return: list[list[int]]"""
self.res = []
self.dfs(root, [], target)
return self.res
def dfs(self, root, path, target):
"""Args: root: TreeNode path: list[int] target: int"""
if n... | the_stack_v2_python_sparse | 剑指offer/剑指 Offer 34. 二叉树中和为某一值的路径.py | AiZhanghan/Leetcode | train | 0 | |
e519818d46b87df968a344b4952abc6198df954e | [
"super().__init__(search_key, **kwargs)\nself.search_url_prefix = kwargs.get('search_url_prefix', 'https://www.google.com.sg/search?q=')\nself.search_url_postfix = kwargs.get('search_url_postfix', '&source=lnms&tbm=isch&sa=X&ei=0eZEVbj3IJG5uATalICQAQ&ved=0CAcQ_AUoAQ&biw=939&bih=591')\nself.show_more_find_type = kwa... | <|body_start_0|>
super().__init__(search_key, **kwargs)
self.search_url_prefix = kwargs.get('search_url_prefix', 'https://www.google.com.sg/search?q=')
self.search_url_postfix = kwargs.get('search_url_postfix', '&source=lnms&tbm=isch&sa=X&ei=0eZEVbj3IJG5uATalICQAQ&ved=0CAcQ_AUoAQ&biw=939&bih=591... | docstr | GoogleCrawler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoogleCrawler:
"""docstr"""
def __init__(self, search_key='', **kwargs):
"""docstr"""
<|body_0|>
def extract_pic_url(self, driver):
"""extract all the raw pic url in list"""
<|body_1|>
def load_page(self, driver):
"""docstr"""
<|body_... | stack_v2_sparse_classes_10k_train_000554 | 3,374 | no_license | [
{
"docstring": "docstr",
"name": "__init__",
"signature": "def __init__(self, search_key='', **kwargs)"
},
{
"docstring": "extract all the raw pic url in list",
"name": "extract_pic_url",
"signature": "def extract_pic_url(self, driver)"
},
{
"docstring": "docstr",
"name": "lo... | 3 | null | Implement the Python class `GoogleCrawler` described below.
Class description:
docstr
Method signatures and docstrings:
- def __init__(self, search_key='', **kwargs): docstr
- def extract_pic_url(self, driver): extract all the raw pic url in list
- def load_page(self, driver): docstr | Implement the Python class `GoogleCrawler` described below.
Class description:
docstr
Method signatures and docstrings:
- def __init__(self, search_key='', **kwargs): docstr
- def extract_pic_url(self, driver): extract all the raw pic url in list
- def load_page(self, driver): docstr
<|skeleton|>
class GoogleCrawler... | 9123aa6baf538b662143b9098d963d55165e8409 | <|skeleton|>
class GoogleCrawler:
"""docstr"""
def __init__(self, search_key='', **kwargs):
"""docstr"""
<|body_0|>
def extract_pic_url(self, driver):
"""extract all the raw pic url in list"""
<|body_1|>
def load_page(self, driver):
"""docstr"""
<|body_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GoogleCrawler:
"""docstr"""
def __init__(self, search_key='', **kwargs):
"""docstr"""
super().__init__(search_key, **kwargs)
self.search_url_prefix = kwargs.get('search_url_prefix', 'https://www.google.com.sg/search?q=')
self.search_url_postfix = kwargs.get('search_url_pos... | the_stack_v2_python_sparse | imgscrape/sel/crawler/GoogleCrawler.py | gmonkman/python | train | 0 |
8d0b9c75fa3fd01470a3c3cfa09c0bc22472084d | [
"dp = [float('inf')] * (amount + 1)\ndp[0] = 0\nfor coin in coins:\n for i in range(coin, amount + 1):\n dp[i] = min(dp[i], dp[i - coin] + 1)\nreturn dp[amount] if dp[amount] != float('inf') else -1",
"@functools.lru_cache(amount)\ndef memory_search(amount) -> int:\n if amount == 0:\n return 0... | <|body_start_0|>
dp = [float('inf')] * (amount + 1)
dp[0] = 0
for coin in coins:
for i in range(coin, amount + 1):
dp[i] = min(dp[i], dp[i - coin] + 1)
return dp[amount] if dp[amount] != float('inf') else -1
<|end_body_0|>
<|body_start_1|>
@functools.... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
"""动态规划(自底而上)"""
<|body_0|>
def coinChangeMemory(self, coins: List[int], amount: int) -> int:
"""记忆化回溯(自顶而上)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dp = [float('inf')] * ... | stack_v2_sparse_classes_10k_train_000555 | 2,286 | no_license | [
{
"docstring": "动态规划(自底而上)",
"name": "coinChange",
"signature": "def coinChange(self, coins: List[int], amount: int) -> int"
},
{
"docstring": "记忆化回溯(自顶而上)",
"name": "coinChangeMemory",
"signature": "def coinChangeMemory(self, coins: List[int], amount: int) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_val_000107 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coinChange(self, coins: List[int], amount: int) -> int: 动态规划(自底而上)
- def coinChangeMemory(self, coins: List[int], amount: int) -> int: 记忆化回溯(自顶而上) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coinChange(self, coins: List[int], amount: int) -> int: 动态规划(自底而上)
- def coinChangeMemory(self, coins: List[int], amount: int) -> int: 记忆化回溯(自顶而上)
<|skeleton|>
class Solutio... | 52756b30e9d51794591aca030bc918e707f473f1 | <|skeleton|>
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
"""动态规划(自底而上)"""
<|body_0|>
def coinChangeMemory(self, coins: List[int], amount: int) -> int:
"""记忆化回溯(自顶而上)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
"""动态规划(自底而上)"""
dp = [float('inf')] * (amount + 1)
dp[0] = 0
for coin in coins:
for i in range(coin, amount + 1):
dp[i] = min(dp[i], dp[i - coin] + 1)
return dp[amount] if... | the_stack_v2_python_sparse | 322.零钱兑换/solution.py | QtTao/daily_leetcode | train | 0 | |
3ef81a0d6c870bb318567c05f2377cf0b50ff0a4 | [
"super(DerivativeDetector, self).__init__(self.__class__.__name__, time_series, baseline_time_series)\nself.smoothing_factor = smoothing_factor or DEFAULT_DERI_SMOOTHING_FACTOR\nself.time_series_items = self.time_series.items()",
"derivatives = []\nfor i, (timestamp, value) in enumerate(self.time_series_items):\n... | <|body_start_0|>
super(DerivativeDetector, self).__init__(self.__class__.__name__, time_series, baseline_time_series)
self.smoothing_factor = smoothing_factor or DEFAULT_DERI_SMOOTHING_FACTOR
self.time_series_items = self.time_series.items()
<|end_body_0|>
<|body_start_1|>
derivatives =... | Derivative Algorithm. This method is the derivative version of Method 1. Instead of data point value, it uses the derivative of the data point. | DerivativeDetector | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DerivativeDetector:
"""Derivative Algorithm. This method is the derivative version of Method 1. Instead of data point value, it uses the derivative of the data point."""
def __init__(self, time_series, baseline_time_series=None, smoothing_factor=None):
"""Initializer :param TimeSerie... | stack_v2_sparse_classes_10k_train_000556 | 2,965 | permissive | [
{
"docstring": "Initializer :param TimeSeries time_series: a TimeSeries object. :param TimeSeries baseline_time_series: baseline TimeSeries. :param float smoothing_factor: smoothing factor.",
"name": "__init__",
"signature": "def __init__(self, time_series, baseline_time_series=None, smoothing_factor=No... | 3 | stack_v2_sparse_classes_30k_train_004849 | Implement the Python class `DerivativeDetector` described below.
Class description:
Derivative Algorithm. This method is the derivative version of Method 1. Instead of data point value, it uses the derivative of the data point.
Method signatures and docstrings:
- def __init__(self, time_series, baseline_time_series=N... | Implement the Python class `DerivativeDetector` described below.
Class description:
Derivative Algorithm. This method is the derivative version of Method 1. Instead of data point value, it uses the derivative of the data point.
Method signatures and docstrings:
- def __init__(self, time_series, baseline_time_series=N... | b0dc7df586394578d29389d306223523dc99c827 | <|skeleton|>
class DerivativeDetector:
"""Derivative Algorithm. This method is the derivative version of Method 1. Instead of data point value, it uses the derivative of the data point."""
def __init__(self, time_series, baseline_time_series=None, smoothing_factor=None):
"""Initializer :param TimeSerie... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DerivativeDetector:
"""Derivative Algorithm. This method is the derivative version of Method 1. Instead of data point value, it uses the derivative of the data point."""
def __init__(self, time_series, baseline_time_series=None, smoothing_factor=None):
"""Initializer :param TimeSeries time_series... | the_stack_v2_python_sparse | src/luminol/algorithms/anomaly_detector_algorithms/derivative_detector.py | linkedin/luminol | train | 1,159 |
594f253eadf5775d70fc88558aaf3ed584f45560 | [
"t0 = time.time()\nextract_vect = EigenValueVectorizeFeatureExtractor()\neigvals_vect = extract_vect.extract(self.point_cloud, self.neigh, None, None, None)\nprint('Timing Vectorize : {}'.format(time.time() - t0))\neigvals_vect = np.vstack(eigvals_vect[:3]).T\neigvals = []\nt0 = time.time()\nfor n in self.neigh:\n ... | <|body_start_0|>
t0 = time.time()
extract_vect = EigenValueVectorizeFeatureExtractor()
eigvals_vect = extract_vect.extract(self.point_cloud, self.neigh, None, None, None)
print('Timing Vectorize : {}'.format(time.time() - t0))
eigvals_vect = np.vstack(eigvals_vect[:3]).T
... | TestExtractEigenvaluesComparison | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestExtractEigenvaluesComparison:
def test_eigen_multiple_neighborhoods(self):
"""Test and compare the serial and vectorized eigenvalues. Eigenvalues are computed for a list of neighborhoods in real data. A vectorized implementation and a serial implementation are compared and timed. Any... | stack_v2_sparse_classes_10k_train_000557 | 11,643 | permissive | [
{
"docstring": "Test and compare the serial and vectorized eigenvalues. Eigenvalues are computed for a list of neighborhoods in real data. A vectorized implementation and a serial implementation are compared and timed. Any difference in result between the two methods is definitely unexpected (except maybe in or... | 2 | stack_v2_sparse_classes_30k_train_007016 | Implement the Python class `TestExtractEigenvaluesComparison` described below.
Class description:
Implement the TestExtractEigenvaluesComparison class.
Method signatures and docstrings:
- def test_eigen_multiple_neighborhoods(self): Test and compare the serial and vectorized eigenvalues. Eigenvalues are computed for ... | Implement the Python class `TestExtractEigenvaluesComparison` described below.
Class description:
Implement the TestExtractEigenvaluesComparison class.
Method signatures and docstrings:
- def test_eigen_multiple_neighborhoods(self): Test and compare the serial and vectorized eigenvalues. Eigenvalues are computed for ... | f6c22841dcbd375639c7f7aecec70f2602b91ee4 | <|skeleton|>
class TestExtractEigenvaluesComparison:
def test_eigen_multiple_neighborhoods(self):
"""Test and compare the serial and vectorized eigenvalues. Eigenvalues are computed for a list of neighborhoods in real data. A vectorized implementation and a serial implementation are compared and timed. Any... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestExtractEigenvaluesComparison:
def test_eigen_multiple_neighborhoods(self):
"""Test and compare the serial and vectorized eigenvalues. Eigenvalues are computed for a list of neighborhoods in real data. A vectorized implementation and a serial implementation are compared and timed. Any difference in... | the_stack_v2_python_sparse | laserchicken/feature_extractor/test_eigenvals_feature_extractor.py | eEcoLiDAR/laserchicken | train | 28 | |
83b0a3f97de7481acb97e64e3b6a389c3f9b76b8 | [
"super().__init__(coordinator, vehicle)\nself.entity_description = description\nself._attr_unique_id = f'{vehicle.vin}-{description.key}'\nif description.unit_type:\n self._attr_native_unit_of_measurement = coordinator.hass.config.units.as_dict().get(description.unit_type) or description.unit_type",
"_LOGGER.d... | <|body_start_0|>
super().__init__(coordinator, vehicle)
self.entity_description = description
self._attr_unique_id = f'{vehicle.vin}-{description.key}'
if description.unit_type:
self._attr_native_unit_of_measurement = coordinator.hass.config.units.as_dict().get(description.un... | Representation of a BMW vehicle sensor. | BMWSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BMWSensor:
"""Representation of a BMW vehicle sensor."""
def __init__(self, coordinator: BMWDataUpdateCoordinator, vehicle: MyBMWVehicle, description: BMWSensorEntityDescription) -> None:
"""Initialize BMW vehicle sensor."""
<|body_0|>
def _handle_coordinator_update(self... | stack_v2_sparse_classes_10k_train_000558 | 7,206 | permissive | [
{
"docstring": "Initialize BMW vehicle sensor.",
"name": "__init__",
"signature": "def __init__(self, coordinator: BMWDataUpdateCoordinator, vehicle: MyBMWVehicle, description: BMWSensorEntityDescription) -> None"
},
{
"docstring": "Handle updated data from the coordinator.",
"name": "_handl... | 2 | stack_v2_sparse_classes_30k_train_001274 | Implement the Python class `BMWSensor` described below.
Class description:
Representation of a BMW vehicle sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: BMWDataUpdateCoordinator, vehicle: MyBMWVehicle, description: BMWSensorEntityDescription) -> None: Initialize BMW vehicle sensor.
- def... | Implement the Python class `BMWSensor` described below.
Class description:
Representation of a BMW vehicle sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: BMWDataUpdateCoordinator, vehicle: MyBMWVehicle, description: BMWSensorEntityDescription) -> None: Initialize BMW vehicle sensor.
- def... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class BMWSensor:
"""Representation of a BMW vehicle sensor."""
def __init__(self, coordinator: BMWDataUpdateCoordinator, vehicle: MyBMWVehicle, description: BMWSensorEntityDescription) -> None:
"""Initialize BMW vehicle sensor."""
<|body_0|>
def _handle_coordinator_update(self... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BMWSensor:
"""Representation of a BMW vehicle sensor."""
def __init__(self, coordinator: BMWDataUpdateCoordinator, vehicle: MyBMWVehicle, description: BMWSensorEntityDescription) -> None:
"""Initialize BMW vehicle sensor."""
super().__init__(coordinator, vehicle)
self.entity_descr... | the_stack_v2_python_sparse | homeassistant/components/bmw_connected_drive/sensor.py | home-assistant/core | train | 35,501 |
1fb6860eaf2621479bf6bd803381eea33bfc5503 | [
"SpokeLDAP.__init__(self)\nself.config = config.setup()\nself.log = logging.getLogger(__name__)\nself.search_scope = 2\nself.retrieve_attr = None\nself.base_dn = self.config.get('LDAP', 'basedn')\nself.org_class = self.config.get('ATTR_MAP', 'org_class', 'organization')\nself.user_class = self.config.get('ATTR_MAP'... | <|body_start_0|>
SpokeLDAP.__init__(self)
self.config = config.setup()
self.log = logging.getLogger(__name__)
self.search_scope = 2
self.retrieve_attr = None
self.base_dn = self.config.get('LDAP', 'basedn')
self.org_class = self.config.get('ATTR_MAP', 'org_class',... | Provide CRUD methods to LDAP organisation objects. | SpokeOrg | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpokeOrg:
"""Provide CRUD methods to LDAP organisation objects."""
def __init__(self):
"""Get config, setup logging and LDAP connection."""
<|body_0|>
def create(self, org_name, org_children=None, suffix=None):
"""Create organisation (+containers); return organis... | stack_v2_sparse_classes_10k_train_000559 | 8,067 | permissive | [
{
"docstring": "Get config, setup logging and LDAP connection.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Create organisation (+containers); return organisation object.",
"name": "create",
"signature": "def create(self, org_name, org_children=None, suffix=... | 5 | stack_v2_sparse_classes_30k_train_004727 | Implement the Python class `SpokeOrg` described below.
Class description:
Provide CRUD methods to LDAP organisation objects.
Method signatures and docstrings:
- def __init__(self): Get config, setup logging and LDAP connection.
- def create(self, org_name, org_children=None, suffix=None): Create organisation (+contai... | Implement the Python class `SpokeOrg` described below.
Class description:
Provide CRUD methods to LDAP organisation objects.
Method signatures and docstrings:
- def __init__(self): Get config, setup logging and LDAP connection.
- def create(self, org_name, org_children=None, suffix=None): Create organisation (+contai... | 077d45750643a38b1062a9199800de9c9de900ae | <|skeleton|>
class SpokeOrg:
"""Provide CRUD methods to LDAP organisation objects."""
def __init__(self):
"""Get config, setup logging and LDAP connection."""
<|body_0|>
def create(self, org_name, org_children=None, suffix=None):
"""Create organisation (+containers); return organis... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SpokeOrg:
"""Provide CRUD methods to LDAP organisation objects."""
def __init__(self):
"""Get config, setup logging and LDAP connection."""
SpokeLDAP.__init__(self)
self.config = config.setup()
self.log = logging.getLogger(__name__)
self.search_scope = 2
se... | the_stack_v2_python_sparse | spoke/lib/org.py | KrisSaxton/spoke | train | 0 |
9bae1fa633e3c92f65354aad69627d8ee4b18c33 | [
"parser = config_file.SshdConfigParser()\nresults = list(parser.ParseFile(None, None, io.BytesIO(CFG)))\nself.assertLen(results, 1)\nreturn results[0]",
"result = self.GetConfig()\nself.assertIsInstance(result, rdf_config_file.SshdConfig)\nself.assertCountEqual([2], result.config.protocol)\nexpect = ['aes128-ctr'... | <|body_start_0|>
parser = config_file.SshdConfigParser()
results = list(parser.ParseFile(None, None, io.BytesIO(CFG)))
self.assertLen(results, 1)
return results[0]
<|end_body_0|>
<|body_start_1|>
result = self.GetConfig()
self.assertIsInstance(result, rdf_config_file.Ssh... | Test parsing of an sshd configuration. | SshdConfigTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SshdConfigTest:
"""Test parsing of an sshd configuration."""
def GetConfig(self):
"""Read in the test configuration file."""
<|body_0|>
def testParseConfig(self):
"""Ensure we can extract sshd settings."""
<|body_1|>
def testFindNumericValues(self):
... | stack_v2_sparse_classes_10k_train_000560 | 28,097 | permissive | [
{
"docstring": "Read in the test configuration file.",
"name": "GetConfig",
"signature": "def GetConfig(self)"
},
{
"docstring": "Ensure we can extract sshd settings.",
"name": "testParseConfig",
"signature": "def testParseConfig(self)"
},
{
"docstring": "Keywords with numeric se... | 4 | stack_v2_sparse_classes_30k_train_003604 | Implement the Python class `SshdConfigTest` described below.
Class description:
Test parsing of an sshd configuration.
Method signatures and docstrings:
- def GetConfig(self): Read in the test configuration file.
- def testParseConfig(self): Ensure we can extract sshd settings.
- def testFindNumericValues(self): Keyw... | Implement the Python class `SshdConfigTest` described below.
Class description:
Test parsing of an sshd configuration.
Method signatures and docstrings:
- def GetConfig(self): Read in the test configuration file.
- def testParseConfig(self): Ensure we can extract sshd settings.
- def testFindNumericValues(self): Keyw... | 44c0eb8c938302098ef7efae8cfd6b90bcfbb2d6 | <|skeleton|>
class SshdConfigTest:
"""Test parsing of an sshd configuration."""
def GetConfig(self):
"""Read in the test configuration file."""
<|body_0|>
def testParseConfig(self):
"""Ensure we can extract sshd settings."""
<|body_1|>
def testFindNumericValues(self):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SshdConfigTest:
"""Test parsing of an sshd configuration."""
def GetConfig(self):
"""Read in the test configuration file."""
parser = config_file.SshdConfigParser()
results = list(parser.ParseFile(None, None, io.BytesIO(CFG)))
self.assertLen(results, 1)
return resu... | the_stack_v2_python_sparse | grr/core/grr_response_core/lib/parsers/config_file_test.py | google/grr | train | 4,683 |
2e4357d3efbb41dec5efcf860ed2f2e500a4ec0d | [
"server, validation_resources = self._create_server()\nvolume = self.create_volume()\nself.attach_volume(server, volume)\nself.assertRaises(lib_exc.BadRequest, self.delete_volume, volume['id'])",
"server, validation_resources = self._create_server()\nvolume = self.create_volume()\nself.attach_volume(server, volum... | <|body_start_0|>
server, validation_resources = self._create_server()
volume = self.create_volume()
self.attach_volume(server, volume)
self.assertRaises(lib_exc.BadRequest, self.delete_volume, volume['id'])
<|end_body_0|>
<|body_start_1|>
server, validation_resources = self._cre... | Negative tests of volume attaching | AttachVolumeNegativeTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttachVolumeNegativeTest:
"""Negative tests of volume attaching"""
def test_delete_attached_volume(self):
"""Test deleting attachemd volume should fail"""
<|body_0|>
def test_attach_attached_volume_to_same_server(self):
"""Test attaching attached volume to same s... | stack_v2_sparse_classes_10k_train_000561 | 2,824 | permissive | [
{
"docstring": "Test deleting attachemd volume should fail",
"name": "test_delete_attached_volume",
"signature": "def test_delete_attached_volume(self)"
},
{
"docstring": "Test attaching attached volume to same server should fail Test attaching the same volume to the same instance once it's alre... | 3 | stack_v2_sparse_classes_30k_train_000706 | Implement the Python class `AttachVolumeNegativeTest` described below.
Class description:
Negative tests of volume attaching
Method signatures and docstrings:
- def test_delete_attached_volume(self): Test deleting attachemd volume should fail
- def test_attach_attached_volume_to_same_server(self): Test attaching atta... | Implement the Python class `AttachVolumeNegativeTest` described below.
Class description:
Negative tests of volume attaching
Method signatures and docstrings:
- def test_delete_attached_volume(self): Test deleting attachemd volume should fail
- def test_attach_attached_volume_to_same_server(self): Test attaching atta... | 3932a799e620a20d7abf7b89e21b520683a1809b | <|skeleton|>
class AttachVolumeNegativeTest:
"""Negative tests of volume attaching"""
def test_delete_attached_volume(self):
"""Test deleting attachemd volume should fail"""
<|body_0|>
def test_attach_attached_volume_to_same_server(self):
"""Test attaching attached volume to same s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AttachVolumeNegativeTest:
"""Negative tests of volume attaching"""
def test_delete_attached_volume(self):
"""Test deleting attachemd volume should fail"""
server, validation_resources = self._create_server()
volume = self.create_volume()
self.attach_volume(server, volume)
... | the_stack_v2_python_sparse | tempest/api/compute/volumes/test_attach_volume_negative.py | openstack/tempest | train | 270 |
74ba213d4fab33b0a7cfabe35671d93818512ca4 | [
"self.mu_g = mu_g\nself.s_g = s_g\nself.s_s = s_s\nself.h = h\nself.alpha = alpha",
"assert len(f1.shape) == 1, 'input must be 1d ndarray'\nassert len(f2.shape) == 1, 'input must be 1d ndarray'\nassert f1.shape == f2.shape\nn_trial = len(f1)\nf1_ = np.tile(f1, (n_samp, 1)) + self.s_s * np.random.randn(n_samp, n_t... | <|body_start_0|>
self.mu_g = mu_g
self.s_g = s_g
self.s_s = s_s
self.h = h
self.alpha = alpha
<|end_body_0|>
<|body_start_1|>
assert len(f1.shape) == 1, 'input must be 1d ndarray'
assert len(f2.shape) == 1, 'input must be 1d ndarray'
assert f1.shape == f2... | Same as recency model except that gaussian prior mean is set somewhere between - average of previous tones - long term prior mean | LocalGlobalModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocalGlobalModel:
"""Same as recency model except that gaussian prior mean is set somewhere between - average of previous tones - long term prior mean"""
def __init__(self, mu_g, s_g, h, s_s, alpha=0.0):
"""Constructor :param mu_g: mean of gaussian part of unigauss :param s_g: std of... | stack_v2_sparse_classes_10k_train_000562 | 11,426 | no_license | [
{
"docstring": "Constructor :param mu_g: mean of gaussian part of unigauss :param s_g: std of gaussian part of unigauss :param h: weight of flat prior in unigauss mixture assuming unnormalized gaussian p(x) 1/Z*( h + exp((x-mu)/2/s^2) ) :param s_s: std of likelihood :param alpha: interpolation factor 1=local,0=... | 2 | stack_v2_sparse_classes_30k_train_007139 | Implement the Python class `LocalGlobalModel` described below.
Class description:
Same as recency model except that gaussian prior mean is set somewhere between - average of previous tones - long term prior mean
Method signatures and docstrings:
- def __init__(self, mu_g, s_g, h, s_s, alpha=0.0): Constructor :param m... | Implement the Python class `LocalGlobalModel` described below.
Class description:
Same as recency model except that gaussian prior mean is set somewhere between - average of previous tones - long term prior mean
Method signatures and docstrings:
- def __init__(self, mu_g, s_g, h, s_s, alpha=0.0): Constructor :param m... | 2a05aa98b501c8633e1fe2baf611d137740709de | <|skeleton|>
class LocalGlobalModel:
"""Same as recency model except that gaussian prior mean is set somewhere between - average of previous tones - long term prior mean"""
def __init__(self, mu_g, s_g, h, s_s, alpha=0.0):
"""Constructor :param mu_g: mean of gaussian part of unigauss :param s_g: std of... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LocalGlobalModel:
"""Same as recency model except that gaussian prior mean is set somewhere between - average of previous tones - long term prior mean"""
def __init__(self, mu_g, s_g, h, s_s, alpha=0.0):
"""Constructor :param mu_g: mean of gaussian part of unigauss :param s_g: std of gaussian par... | the_stack_v2_python_sparse | model/simple_model.py | ItayLieder/GMM_simulations | train | 0 |
ee3995f36d7769e51544e3923d793ae6fefee84d | [
"question = '你喜欢吃什么食物?'\nmy_surey = AnonymousSurvey(question)\nmy_surey.store_respone('蛋糕')\n'核实-蛋糕在AnonymousSurvey类的responses列表内'\nself.assertIn('蛋糕', my_surey.responses)",
"question = '你喜欢吃什么食物?'\nmy_surey = AnonymousSurvey(question)\nresponses = ['蛋糕', '草莓', '巧克力']\nfor response in responses:\n my_surey.sto... | <|body_start_0|>
question = '你喜欢吃什么食物?'
my_surey = AnonymousSurvey(question)
my_surey.store_respone('蛋糕')
'核实-蛋糕在AnonymousSurvey类的responses列表内'
self.assertIn('蛋糕', my_surey.responses)
<|end_body_0|>
<|body_start_1|>
question = '你喜欢吃什么食物?'
my_surey = AnonymousSurv... | 针对 AnonymousSurvey 类的测试 | TestAnonymousSurvey | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAnonymousSurvey:
"""针对 AnonymousSurvey 类的测试"""
def test_store_single_respone(self):
"""测试单个答案会被妥善地存储"""
<|body_0|>
def test_store_three_respone(self):
"""测试三个答案会被妥善地存储"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
question = '你喜欢吃什么食物?'
... | stack_v2_sparse_classes_10k_train_000563 | 1,843 | no_license | [
{
"docstring": "测试单个答案会被妥善地存储",
"name": "test_store_single_respone",
"signature": "def test_store_single_respone(self)"
},
{
"docstring": "测试三个答案会被妥善地存储",
"name": "test_store_three_respone",
"signature": "def test_store_three_respone(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001532 | Implement the Python class `TestAnonymousSurvey` described below.
Class description:
针对 AnonymousSurvey 类的测试
Method signatures and docstrings:
- def test_store_single_respone(self): 测试单个答案会被妥善地存储
- def test_store_three_respone(self): 测试三个答案会被妥善地存储 | Implement the Python class `TestAnonymousSurvey` described below.
Class description:
针对 AnonymousSurvey 类的测试
Method signatures and docstrings:
- def test_store_single_respone(self): 测试单个答案会被妥善地存储
- def test_store_three_respone(self): 测试三个答案会被妥善地存储
<|skeleton|>
class TestAnonymousSurvey:
"""针对 AnonymousSurvey 类的测... | 525a3a6cec25b540734acc2c8d033a11706cf01a | <|skeleton|>
class TestAnonymousSurvey:
"""针对 AnonymousSurvey 类的测试"""
def test_store_single_respone(self):
"""测试单个答案会被妥善地存储"""
<|body_0|>
def test_store_three_respone(self):
"""测试三个答案会被妥善地存储"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestAnonymousSurvey:
"""针对 AnonymousSurvey 类的测试"""
def test_store_single_respone(self):
"""测试单个答案会被妥善地存储"""
question = '你喜欢吃什么食物?'
my_surey = AnonymousSurvey(question)
my_surey.store_respone('蛋糕')
'核实-蛋糕在AnonymousSurvey类的responses列表内'
self.assertIn('蛋糕', my... | the_stack_v2_python_sparse | group_one/lesson_11_1.py | shyan520/python | train | 0 |
a25cfd7578aaee0e0c84a1200d7c5c14db1fd9b2 | [
"n = len(nums)\nif n * k == 0:\n return []\nif k == 1:\n return nums\nleft, right = ([0] * n, [0] * n)\nleft[0], right[n - 1] = (nums[0], nums[n - 1])\nfor lft_idx in range(1, n):\n if lft_idx % k == 0:\n left[lft_idx] = nums[lft_idx]\n else:\n left[lft_idx] = max(left[lft_idx - 1], nums[l... | <|body_start_0|>
n = len(nums)
if n * k == 0:
return []
if k == 1:
return nums
left, right = ([0] * n, [0] * n)
left[0], right[n - 1] = (nums[0], nums[n - 1])
for lft_idx in range(1, n):
if lft_idx % k == 0:
left[lft_idx... | SlidingWindow | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SlidingWindow:
def get_all_max_(self, nums: List[int], k: int) -> List[int]:
"""Approach: DP Time Complexity: O(N) Space Complexity: O(N) :param nums: :param k: :return:"""
<|body_0|>
def get_all_max(self, nums: List[int], k: int) -> List[int]:
"""Approach: Deque / D... | stack_v2_sparse_classes_10k_train_000564 | 3,324 | no_license | [
{
"docstring": "Approach: DP Time Complexity: O(N) Space Complexity: O(N) :param nums: :param k: :return:",
"name": "get_all_max_",
"signature": "def get_all_max_(self, nums: List[int], k: int) -> List[int]"
},
{
"docstring": "Approach: Deque / Doubly Linked List Time Complexity: O(N) - since ea... | 2 | stack_v2_sparse_classes_30k_train_000943 | Implement the Python class `SlidingWindow` described below.
Class description:
Implement the SlidingWindow class.
Method signatures and docstrings:
- def get_all_max_(self, nums: List[int], k: int) -> List[int]: Approach: DP Time Complexity: O(N) Space Complexity: O(N) :param nums: :param k: :return:
- def get_all_ma... | Implement the Python class `SlidingWindow` described below.
Class description:
Implement the SlidingWindow class.
Method signatures and docstrings:
- def get_all_max_(self, nums: List[int], k: int) -> List[int]: Approach: DP Time Complexity: O(N) Space Complexity: O(N) :param nums: :param k: :return:
- def get_all_ma... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class SlidingWindow:
def get_all_max_(self, nums: List[int], k: int) -> List[int]:
"""Approach: DP Time Complexity: O(N) Space Complexity: O(N) :param nums: :param k: :return:"""
<|body_0|>
def get_all_max(self, nums: List[int], k: int) -> List[int]:
"""Approach: Deque / D... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SlidingWindow:
def get_all_max_(self, nums: List[int], k: int) -> List[int]:
"""Approach: DP Time Complexity: O(N) Space Complexity: O(N) :param nums: :param k: :return:"""
n = len(nums)
if n * k == 0:
return []
if k == 1:
return nums
left, right... | the_stack_v2_python_sparse | amazon/sliding_window/sliding_window_maximum.py | Shiv2157k/leet_code | train | 1 | |
0f9c22d0619771241895bda5077b516105d52d89 | [
"self.x = x\nself.y = y\nself.N = np.shape(x)[0]",
"prod = 0\nfor i in range(self.N):\n for j in range(self.N):\n prod = prod + self.x[i, j] * np.conj(self.y[i, j])\nreturn prod"
] | <|body_start_0|>
self.x = x
self.y = y
self.N = np.shape(x)[0]
<|end_body_0|>
<|body_start_1|>
prod = 0
for i in range(self.N):
for j in range(self.N):
prod = prod + self.x[i, j] * np.conj(self.y[i, j])
return prod
<|end_body_1|>
| 2—D inner-product | inner_prod_2D | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class inner_prod_2D:
"""2—D inner-product"""
def __init__(self, x, y):
"""x,y: two 2-D signals"""
<|body_0|>
def solve(self):
"""\\\\\\ METHOD: Compute the inner product"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.x = x
self.y = y
... | stack_v2_sparse_classes_10k_train_000565 | 4,947 | no_license | [
{
"docstring": "x,y: two 2-D signals",
"name": "__init__",
"signature": "def __init__(self, x, y)"
},
{
"docstring": "\\\\\\\\\\\\ METHOD: Compute the inner product",
"name": "solve",
"signature": "def solve(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004168 | Implement the Python class `inner_prod_2D` described below.
Class description:
2—D inner-product
Method signatures and docstrings:
- def __init__(self, x, y): x,y: two 2-D signals
- def solve(self): \\\\\\ METHOD: Compute the inner product | Implement the Python class `inner_prod_2D` described below.
Class description:
2—D inner-product
Method signatures and docstrings:
- def __init__(self, x, y): x,y: two 2-D signals
- def solve(self): \\\\\\ METHOD: Compute the inner product
<|skeleton|>
class inner_prod_2D:
"""2—D inner-product"""
def __init... | b72322cfc6d81c996117cea2160ee312da62d3ed | <|skeleton|>
class inner_prod_2D:
"""2—D inner-product"""
def __init__(self, x, y):
"""x,y: two 2-D signals"""
<|body_0|>
def solve(self):
"""\\\\\\ METHOD: Compute the inner product"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class inner_prod_2D:
"""2—D inner-product"""
def __init__(self, x, y):
"""x,y: two 2-D signals"""
self.x = x
self.y = y
self.N = np.shape(x)[0]
def solve(self):
"""\\\\\\ METHOD: Compute the inner product"""
prod = 0
for i in range(self.N):
... | the_stack_v2_python_sparse | 2D Signal Processing and Image De-noising/discrete_signal.py | FG-14/Signals-and-Information-Processing-DSP- | train | 0 |
4060f62f62d6c2be35572e1196817f3ada349a98 | [
"super(TurntableCrawler, self).__init__(*args, **kwargs)\nparts = self.var('name').split('_')\nself.setVar('assetName', parts[1], True)\nself.setVar('step', parts[2], True)\nself.setVar('variant', parts[3], True)\nself.setVar('pass', parts[4], True)\nself.setVar('renderName', '{}-{}-{}'.format(self.var('assetName')... | <|body_start_0|>
super(TurntableCrawler, self).__init__(*args, **kwargs)
parts = self.var('name').split('_')
self.setVar('assetName', parts[1], True)
self.setVar('step', parts[2], True)
self.setVar('variant', parts[3], True)
self.setVar('pass', parts[4], True)
sel... | Custom crawler used to detect turntable renders. | TurntableCrawler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TurntableCrawler:
"""Custom crawler used to detect turntable renders."""
def __init__(self, *args, **kwargs):
"""Create a TurntableCrawler object."""
<|body_0|>
def test(cls, pathHolder, parentCrawler):
"""Test if the path holder contains a turntable."""
... | stack_v2_sparse_classes_10k_train_000566 | 1,277 | permissive | [
{
"docstring": "Create a TurntableCrawler object.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Test if the path holder contains a turntable.",
"name": "test",
"signature": "def test(cls, pathHolder, parentCrawler)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002402 | Implement the Python class `TurntableCrawler` described below.
Class description:
Custom crawler used to detect turntable renders.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create a TurntableCrawler object.
- def test(cls, pathHolder, parentCrawler): Test if the path holder contains a t... | Implement the Python class `TurntableCrawler` described below.
Class description:
Custom crawler used to detect turntable renders.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create a TurntableCrawler object.
- def test(cls, pathHolder, parentCrawler): Test if the path holder contains a t... | 046dbb0c1b4ff20ea5f2e1679f8d89f3089b6aa4 | <|skeleton|>
class TurntableCrawler:
"""Custom crawler used to detect turntable renders."""
def __init__(self, *args, **kwargs):
"""Create a TurntableCrawler object."""
<|body_0|>
def test(cls, pathHolder, parentCrawler):
"""Test if the path holder contains a turntable."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TurntableCrawler:
"""Custom crawler used to detect turntable renders."""
def __init__(self, *args, **kwargs):
"""Create a TurntableCrawler object."""
super(TurntableCrawler, self).__init__(*args, **kwargs)
parts = self.var('name').split('_')
self.setVar('assetName', parts[... | the_stack_v2_python_sparse | src/lib/kombi/Crawler/Fs/Render/TurntableCrawler.py | kombiHQ/kombi | train | 2 |
f2674c59d076454d41b1499abb16c0505beaa9c1 | [
"self.time = time\nself.name = name\nself._text = None\nself._position = None\nself._class_name = None",
"if self._text:\n return Tag(time=self.time, text=self._text, position=self._position, class_name=self._class_name)\nreturn None"
] | <|body_start_0|>
self.time = time
self.name = name
self._text = None
self._position = None
self._class_name = None
<|end_body_0|>
<|body_start_1|>
if self._text:
return Tag(time=self.time, text=self._text, position=self._position, class_name=self._class_name)... | The base class of an event. | EventData | [
"BSD-3-Clause",
"BSD-1-Clause",
"LicenseRef-scancode-bsd-x11",
"LicenseRef-scancode-other-permissive"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventData:
"""The base class of an event."""
def __init__(self, time, name):
"""Initializes an EventData. @param time: A string for event time. @param name: A string for event name."""
<|body_0|>
def GetTag(self):
"""Gets the tag for this event. @returns: A Tag o... | stack_v2_sparse_classes_10k_train_000567 | 17,308 | permissive | [
{
"docstring": "Initializes an EventData. @param time: A string for event time. @param name: A string for event name.",
"name": "__init__",
"signature": "def __init__(self, time, name)"
},
{
"docstring": "Gets the tag for this event. @returns: A Tag object. Returns None if no need to show tag.",... | 2 | stack_v2_sparse_classes_30k_test_000251 | Implement the Python class `EventData` described below.
Class description:
The base class of an event.
Method signatures and docstrings:
- def __init__(self, time, name): Initializes an EventData. @param time: A string for event time. @param name: A string for event name.
- def GetTag(self): Gets the tag for this eve... | Implement the Python class `EventData` described below.
Class description:
The base class of an event.
Method signatures and docstrings:
- def __init__(self, time, name): Initializes an EventData. @param time: A string for event time. @param name: A string for event name.
- def GetTag(self): Gets the tag for this eve... | 2ba7bcea4f9d9715cbb1c4e69271f7b185a0786e | <|skeleton|>
class EventData:
"""The base class of an event."""
def __init__(self, time, name):
"""Initializes an EventData. @param time: A string for event time. @param name: A string for event name."""
<|body_0|>
def GetTag(self):
"""Gets the tag for this event. @returns: A Tag o... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EventData:
"""The base class of an event."""
def __init__(self, time, name):
"""Initializes an EventData. @param time: A string for event time. @param name: A string for event name."""
self.time = time
self.name = name
self._text = None
self._position = None
... | the_stack_v2_python_sparse | external/adhd/scripts/audio_thread_log_viewer/viewer_c3.py | dongdong331/test | train | 2 |
d857deb39821d9ef9e0c9979dc256fdc30c7988d | [
"super().__init__(group_norm)\nself.output_levels = output_levels\nself.conv1 = nn.ModuleList()\nself.conv2 = nn.ModuleList()\nself.maxpool = nn.MaxPool2d(kernel_size=1, stride=2, padding=0)\nself.scales_in = scales_in\nself.scales_out = scales_in\nself.dims_in = dims_in\nself.dim_out = dim_out\ndims_out = dim_out\... | <|body_start_0|>
super().__init__(group_norm)
self.output_levels = output_levels
self.conv1 = nn.ModuleList()
self.conv2 = nn.ModuleList()
self.maxpool = nn.MaxPool2d(kernel_size=1, stride=2, padding=0)
self.scales_in = scales_in
self.scales_out = scales_in
... | Feature bottom-up-path-augmentation with usual 2d convolutions 3x3 | BottomUpPathAugmentation | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BottomUpPathAugmentation:
"""Feature bottom-up-path-augmentation with usual 2d convolutions 3x3"""
def __init__(self, output_levels, dims_in, scales_in, dim_out, group_norm):
"""Initialization with the next parameters: :param output_levels: number of levels (feature maps) from FPN :p... | stack_v2_sparse_classes_10k_train_000568 | 16,312 | permissive | [
{
"docstring": "Initialization with the next parameters: :param output_levels: number of levels (feature maps) from FPN :param dims_in: number of channels in input feature maps :param scales_in: scale of each input feature map :param dim_out: number of channels in output feature maps :param group_norm: if True,... | 2 | null | Implement the Python class `BottomUpPathAugmentation` described below.
Class description:
Feature bottom-up-path-augmentation with usual 2d convolutions 3x3
Method signatures and docstrings:
- def __init__(self, output_levels, dims_in, scales_in, dim_out, group_norm): Initialization with the next parameters: :param o... | Implement the Python class `BottomUpPathAugmentation` described below.
Class description:
Feature bottom-up-path-augmentation with usual 2d convolutions 3x3
Method signatures and docstrings:
- def __init__(self, output_levels, dims_in, scales_in, dim_out, group_norm): Initialization with the next parameters: :param o... | c553a56088f0055baba838b68c9299e19683227e | <|skeleton|>
class BottomUpPathAugmentation:
"""Feature bottom-up-path-augmentation with usual 2d convolutions 3x3"""
def __init__(self, output_levels, dims_in, scales_in, dim_out, group_norm):
"""Initialization with the next parameters: :param output_levels: number of levels (feature maps) from FPN :p... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BottomUpPathAugmentation:
"""Feature bottom-up-path-augmentation with usual 2d convolutions 3x3"""
def __init__(self, output_levels, dims_in, scales_in, dim_out, group_norm):
"""Initialization with the next parameters: :param output_levels: number of levels (feature maps) from FPN :param dims_in:... | the_stack_v2_python_sparse | pytorch_toolkit/instance_segmentation/segmentoly/rcnn/panet.py | DmitriySidnev/openvino_training_extensions | train | 0 |
3c59f48bf7f1b88b435c291f4b78a6bf5c1c3694 | [
"self.size = size\nself.arr = []\nself.sum = 0",
"if len(self.arr) > 0 and len(self.arr) == self.size:\n left = self.arr.pop(0)\n self.sum -= left\nself.sum += val\nself.arr.append(val)\nreturn self.sum / float(len(self.arr))"
] | <|body_start_0|>
self.size = size
self.arr = []
self.sum = 0
<|end_body_0|>
<|body_start_1|>
if len(self.arr) > 0 and len(self.arr) == self.size:
left = self.arr.pop(0)
self.sum -= left
self.sum += val
self.arr.append(val)
return self.sum ... | MovingAverage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.size = size
self.arr = [... | stack_v2_sparse_classes_10k_train_000569 | 704 | no_license | [
{
"docstring": "Initialize your data structure here. :type size: int",
"name": "__init__",
"signature": "def __init__(self, size)"
},
{
"docstring": ":type val: int :rtype: float",
"name": "next",
"signature": "def next(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004946 | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float
<|skeleton|>
class MovingAverage:
... | 1bd17e867d1d557a6ebbbd99f693d5fbd9f5b61e | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
self.size = size
self.arr = []
self.sum = 0
def next(self, val):
""":type val: int :rtype: float"""
if len(self.arr) > 0 and len(self.arr) == self.size:
... | the_stack_v2_python_sparse | leetcode/346-moving-average-from-data-stream/main.py | shriharshs/AlgoDaily | train | 0 | |
fd8d36cc17b7958f40f803b6c9c6fcd3294a2454 | [
"self.user.email = 'Hello@magnet.cl'\nself.user.save()\nself.assertEqual(self.user.email, 'hello@magnet.cl')",
"url = reverse('password_change')\nresponse = self.client.get(url)\nself.assertEqual(response.status_code, 200)\nself.user.force_logout()\nresponse = self.client.get(url)\nself.assertEqual(response.statu... | <|body_start_0|>
self.user.email = 'Hello@magnet.cl'
self.user.save()
self.assertEqual(self.user.email, 'hello@magnet.cl')
<|end_body_0|>
<|body_start_1|>
url = reverse('password_change')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
... | UserTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserTests:
def test_lower_case_emails(self):
"""Tests that users are created with lower case emails"""
<|body_0|>
def test_force_logout(self):
"""Tests that users are created with lower case emails"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sel... | stack_v2_sparse_classes_10k_train_000570 | 878 | permissive | [
{
"docstring": "Tests that users are created with lower case emails",
"name": "test_lower_case_emails",
"signature": "def test_lower_case_emails(self)"
},
{
"docstring": "Tests that users are created with lower case emails",
"name": "test_force_logout",
"signature": "def test_force_logou... | 2 | stack_v2_sparse_classes_30k_train_002354 | Implement the Python class `UserTests` described below.
Class description:
Implement the UserTests class.
Method signatures and docstrings:
- def test_lower_case_emails(self): Tests that users are created with lower case emails
- def test_force_logout(self): Tests that users are created with lower case emails | Implement the Python class `UserTests` described below.
Class description:
Implement the UserTests class.
Method signatures and docstrings:
- def test_lower_case_emails(self): Tests that users are created with lower case emails
- def test_force_logout(self): Tests that users are created with lower case emails
<|skel... | 3520a95900c7e84a467b4b07db4a47008575a2be | <|skeleton|>
class UserTests:
def test_lower_case_emails(self):
"""Tests that users are created with lower case emails"""
<|body_0|>
def test_force_logout(self):
"""Tests that users are created with lower case emails"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserTests:
def test_lower_case_emails(self):
"""Tests that users are created with lower case emails"""
self.user.email = 'Hello@magnet.cl'
self.user.save()
self.assertEqual(self.user.email, 'hello@magnet.cl')
def test_force_logout(self):
"""Tests that users are cre... | the_stack_v2_python_sparse | users/tests.py | magnet-cl/django-project-template | train | 9 | |
297d24bc2ac40c285d60abb20a14071b3e94fe10 | [
"if not email:\n raise ValueError('The given email must be set')\nemail = self.normalize_email(email)\nuser = self.model(email=email, **extra_fields)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"extra_fields.setdefault('is_staff', False)\nextra_fields.setdefault('is_superuser', False... | <|body_start_0|>
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
<|end_body_0|>
<|body_start_1|>... | Define a model manager for User model with no username field. | ParticipantManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParticipantManager:
"""Define a model manager for User model with no username field."""
def _create_user(self, email, password, **extra_fields):
"""Create and save a User with the given email and password."""
<|body_0|>
def create_user(self, email, password=None, **extra... | stack_v2_sparse_classes_10k_train_000571 | 3,675 | no_license | [
{
"docstring": "Create and save a User with the given email and password.",
"name": "_create_user",
"signature": "def _create_user(self, email, password, **extra_fields)"
},
{
"docstring": "Create and save a regular User with the given email and password.",
"name": "create_user",
"signat... | 3 | stack_v2_sparse_classes_30k_train_001549 | Implement the Python class `ParticipantManager` described below.
Class description:
Define a model manager for User model with no username field.
Method signatures and docstrings:
- def _create_user(self, email, password, **extra_fields): Create and save a User with the given email and password.
- def create_user(sel... | Implement the Python class `ParticipantManager` described below.
Class description:
Define a model manager for User model with no username field.
Method signatures and docstrings:
- def _create_user(self, email, password, **extra_fields): Create and save a User with the given email and password.
- def create_user(sel... | a57b9fe5b73e58e703f15b6f3c55a9dde8102496 | <|skeleton|>
class ParticipantManager:
"""Define a model manager for User model with no username field."""
def _create_user(self, email, password, **extra_fields):
"""Create and save a User with the given email and password."""
<|body_0|>
def create_user(self, email, password=None, **extra... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ParticipantManager:
"""Define a model manager for User model with no username field."""
def _create_user(self, email, password, **extra_fields):
"""Create and save a User with the given email and password."""
if not email:
raise ValueError('The given email must be set')
... | the_stack_v2_python_sparse | meetings/models.py | gsoosk/Jalas-Backend | train | 0 |
a010d69c47164225eb4103b9030e9501db02118e | [
"assert nums is not None\nnums.sort()\nn = len(nums)\nres = set()\nadict = {}\nfor i in xrange(n - 1):\n for j in xrange(i + 1, n):\n asum = nums[i] + nums[j]\n if asum not in adict:\n adict[asum] = [(i, j)]\n else:\n adict[asum].append((i, j))\nfor i in xrange(n - 4 + ... | <|body_start_0|>
assert nums is not None
nums.sort()
n = len(nums)
res = set()
adict = {}
for i in xrange(n - 1):
for j in xrange(i + 1, n):
asum = nums[i] + nums[j]
if asum not in adict:
adict[asum] = [(i, j... | Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Note: Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a+b+c+d) The solution set must not contain duplicate quadruplets... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Note: Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a+b+c+d) The solution set mu... | stack_v2_sparse_classes_10k_train_000572 | 2,724 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[List[int]]",
"name": "fourSum_hash",
"signature": "def fourSum_hash(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[List[int]]",
"name": "fourSum_Generic",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_val_000173 | Implement the Python class `Solution` described below.
Class description:
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Note: Elements in a quadruplet (a,b,c,d) must be in non-descending o... | Implement the Python class `Solution` described below.
Class description:
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Note: Elements in a quadruplet (a,b,c,d) must be in non-descending o... | cbe6a7e7f05eccb4f9c5fce8651c0d87e5168516 | <|skeleton|>
class Solution:
"""Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Note: Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a+b+c+d) The solution set mu... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
"""Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Note: Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a+b+c+d) The solution set must not contai... | the_stack_v2_python_sparse | src/array/leetcode18_4Sum.py | apepkuss/Cracking-Leetcode-in-Python | train | 2 |
05cd67a57b00d1fa61a3dcfea266762edda91c78 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Proto file describing the Feed service. Service to manage feeds. | FeedServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeedServiceServicer:
"""Proto file describing the Feed service. Service to manage feeds."""
def GetFeed(self, request, context):
"""Returns the requested feed in full detail."""
<|body_0|>
def MutateFeeds(self, request, context):
"""Creates, updates, or removes f... | stack_v2_sparse_classes_10k_train_000573 | 5,053 | permissive | [
{
"docstring": "Returns the requested feed in full detail.",
"name": "GetFeed",
"signature": "def GetFeed(self, request, context)"
},
{
"docstring": "Creates, updates, or removes feeds. Operation statuses are returned.",
"name": "MutateFeeds",
"signature": "def MutateFeeds(self, request,... | 2 | stack_v2_sparse_classes_30k_train_001155 | Implement the Python class `FeedServiceServicer` described below.
Class description:
Proto file describing the Feed service. Service to manage feeds.
Method signatures and docstrings:
- def GetFeed(self, request, context): Returns the requested feed in full detail.
- def MutateFeeds(self, request, context): Creates, ... | Implement the Python class `FeedServiceServicer` described below.
Class description:
Proto file describing the Feed service. Service to manage feeds.
Method signatures and docstrings:
- def GetFeed(self, request, context): Returns the requested feed in full detail.
- def MutateFeeds(self, request, context): Creates, ... | a5b6cede64f4d9912ae6ad26927a54e40448c9fe | <|skeleton|>
class FeedServiceServicer:
"""Proto file describing the Feed service. Service to manage feeds."""
def GetFeed(self, request, context):
"""Returns the requested feed in full detail."""
<|body_0|>
def MutateFeeds(self, request, context):
"""Creates, updates, or removes f... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FeedServiceServicer:
"""Proto file describing the Feed service. Service to manage feeds."""
def GetFeed(self, request, context):
"""Returns the requested feed in full detail."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
... | the_stack_v2_python_sparse | google/ads/google_ads/v5/proto/services/feed_service_pb2_grpc.py | fiboknacky/google-ads-python | train | 0 |
4a0521e733d7580ef3eba6519f3e26a369b68637 | [
"super().__init__()\nself.spherical_cheb_bn_pool = SphericalChebBNPool(in_channels, middle_channels, lap, pooling, kernel_size)\nself.spherical_cheb = SphericalChebConv(middle_channels, out_channels, lap, kernel_size)",
"x = self.spherical_cheb_bn_pool(x)\nx = self.spherical_cheb(x)\nreturn x"
] | <|body_start_0|>
super().__init__()
self.spherical_cheb_bn_pool = SphericalChebBNPool(in_channels, middle_channels, lap, pooling, kernel_size)
self.spherical_cheb = SphericalChebConv(middle_channels, out_channels, lap, kernel_size)
<|end_body_0|>
<|body_start_1|>
x = self.spherical_cheb... | Building Block calling a SphericalChebBNPool block then a SphericalCheb. | SphericalChebBNPoolCheb | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SphericalChebBNPoolCheb:
"""Building Block calling a SphericalChebBNPool block then a SphericalCheb."""
def __init__(self, in_channels, middle_channels, out_channels, lap, pooling, kernel_size):
"""Initialization. Args: in_channels (int): initial number of channels. middle_channels (... | stack_v2_sparse_classes_10k_train_000574 | 41,403 | no_license | [
{
"docstring": "Initialization. Args: in_channels (int): initial number of channels. middle_channels (int): middle number of channels. out_channels (int): output number of channels. lap (:obj:`torch.sparse.FloatTensor`): laplacian. pooling (:obj:`torch.nn.Module`): pooling/unpooling module. kernel_size (int, op... | 2 | null | Implement the Python class `SphericalChebBNPoolCheb` described below.
Class description:
Building Block calling a SphericalChebBNPool block then a SphericalCheb.
Method signatures and docstrings:
- def __init__(self, in_channels, middle_channels, out_channels, lap, pooling, kernel_size): Initialization. Args: in_chan... | Implement the Python class `SphericalChebBNPoolCheb` described below.
Class description:
Building Block calling a SphericalChebBNPool block then a SphericalCheb.
Method signatures and docstrings:
- def __init__(self, in_channels, middle_channels, out_channels, lap, pooling, kernel_size): Initialization. Args: in_chan... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class SphericalChebBNPoolCheb:
"""Building Block calling a SphericalChebBNPool block then a SphericalCheb."""
def __init__(self, in_channels, middle_channels, out_channels, lap, pooling, kernel_size):
"""Initialization. Args: in_channels (int): initial number of channels. middle_channels (... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SphericalChebBNPoolCheb:
"""Building Block calling a SphericalChebBNPool block then a SphericalCheb."""
def __init__(self, in_channels, middle_channels, out_channels, lap, pooling, kernel_size):
"""Initialization. Args: in_channels (int): initial number of channels. middle_channels (int): middle ... | the_stack_v2_python_sparse | generated/test_deepsphere_deepsphere_pytorch.py | jansel/pytorch-jit-paritybench | train | 35 |
f93f46dc0c834c774173be259cb70e1bcef527c0 | [
"super().__init__()\nself.dml = dml\nself.evaluate = evaluate\nif dml == 2:\n self.json_backbone_description = json_arch_file_backbone[0]\n self.weight_standardization = weight_standardization\n with open(self.json_backbone_description, 'r', encoding='utf-8') as read_file:\n data_backbone = json.loa... | <|body_start_0|>
super().__init__()
self.dml = dml
self.evaluate = evaluate
if dml == 2:
self.json_backbone_description = json_arch_file_backbone[0]
self.weight_standardization = weight_standardization
with open(self.json_backbone_description, 'r', enc... | ISyNet | ISyNet | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ISyNet:
"""ISyNet"""
def __init__(self, num_classes=1000, json_arch_file_backbone='', dropout=0.5, weight_standardization=0, last_bn=0, dml=1, evaluate=False):
"""Network initialisation"""
<|body_0|>
def construct(self, *inputs, **_kwargs):
"""IsyNet construct fo... | stack_v2_sparse_classes_10k_train_000575 | 4,662 | permissive | [
{
"docstring": "Network initialisation",
"name": "__init__",
"signature": "def __init__(self, num_classes=1000, json_arch_file_backbone='', dropout=0.5, weight_standardization=0, last_bn=0, dml=1, evaluate=False)"
},
{
"docstring": "IsyNet construct for dml=1 and dml=2",
"name": "construct",... | 3 | null | Implement the Python class `ISyNet` described below.
Class description:
ISyNet
Method signatures and docstrings:
- def __init__(self, num_classes=1000, json_arch_file_backbone='', dropout=0.5, weight_standardization=0, last_bn=0, dml=1, evaluate=False): Network initialisation
- def construct(self, *inputs, **_kwargs)... | Implement the Python class `ISyNet` described below.
Class description:
ISyNet
Method signatures and docstrings:
- def __init__(self, num_classes=1000, json_arch_file_backbone='', dropout=0.5, weight_standardization=0, last_bn=0, dml=1, evaluate=False): Network initialisation
- def construct(self, *inputs, **_kwargs)... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class ISyNet:
"""ISyNet"""
def __init__(self, num_classes=1000, json_arch_file_backbone='', dropout=0.5, weight_standardization=0, last_bn=0, dml=1, evaluate=False):
"""Network initialisation"""
<|body_0|>
def construct(self, *inputs, **_kwargs):
"""IsyNet construct fo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ISyNet:
"""ISyNet"""
def __init__(self, num_classes=1000, json_arch_file_backbone='', dropout=0.5, weight_standardization=0, last_bn=0, dml=1, evaluate=False):
"""Network initialisation"""
super().__init__()
self.dml = dml
self.evaluate = evaluate
if dml == 2:
... | the_stack_v2_python_sparse | research/cv/ISyNet/ISyNet/model.py | mindspore-ai/models | train | 301 |
5c5df63bcc9aadf2c703bf2ff0213e4f08b150a9 | [
"self.cfg_mk = loadcfgcm.load('codegen_maker_module.json', default_config)\nself.tpl_path = tpl_path\nself.out_path = out_path\nself.cfg_tpl = loadcfgcm.load_cfg_file(self.tpl_path, 'tpl_config.json')\nif self.cfg_tpl is None:\n logcm.print_info('Template Config Load Failed!', fg='red')\n sys.exit()",
"logc... | <|body_start_0|>
self.cfg_mk = loadcfgcm.load('codegen_maker_module.json', default_config)
self.tpl_path = tpl_path
self.out_path = out_path
self.cfg_tpl = loadcfgcm.load_cfg_file(self.tpl_path, 'tpl_config.json')
if self.cfg_tpl is None:
logcm.print_info('Template Co... | 代码生成-代码生成类 | CodeGenModuleMaker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CodeGenModuleMaker:
"""代码生成-代码生成类"""
def __init__(self, tpl_path, out_path):
"""初始化 :param tpl_path: 模版路径 :param out_path: 生成文件路径"""
<|body_0|>
def make(self, mdl):
"""根据指定模块信息,和代码模版目录,生成代码 :param mdl: 模块 :return: 无"""
<|body_1|>
def make_by_path(sel... | stack_v2_sparse_classes_10k_train_000576 | 4,475 | no_license | [
{
"docstring": "初始化 :param tpl_path: 模版路径 :param out_path: 生成文件路径",
"name": "__init__",
"signature": "def __init__(self, tpl_path, out_path)"
},
{
"docstring": "根据指定模块信息,和代码模版目录,生成代码 :param mdl: 模块 :return: 无",
"name": "make",
"signature": "def make(self, mdl)"
},
{
"docstring": ... | 4 | stack_v2_sparse_classes_30k_train_007111 | Implement the Python class `CodeGenModuleMaker` described below.
Class description:
代码生成-代码生成类
Method signatures and docstrings:
- def __init__(self, tpl_path, out_path): 初始化 :param tpl_path: 模版路径 :param out_path: 生成文件路径
- def make(self, mdl): 根据指定模块信息,和代码模版目录,生成代码 :param mdl: 模块 :return: 无
- def make_by_path(self, p... | Implement the Python class `CodeGenModuleMaker` described below.
Class description:
代码生成-代码生成类
Method signatures and docstrings:
- def __init__(self, tpl_path, out_path): 初始化 :param tpl_path: 模版路径 :param out_path: 生成文件路径
- def make(self, mdl): 根据指定模块信息,和代码模版目录,生成代码 :param mdl: 模块 :return: 无
- def make_by_path(self, p... | e5887ccf0a241b757dc4f9aa12bcb89456321a24 | <|skeleton|>
class CodeGenModuleMaker:
"""代码生成-代码生成类"""
def __init__(self, tpl_path, out_path):
"""初始化 :param tpl_path: 模版路径 :param out_path: 生成文件路径"""
<|body_0|>
def make(self, mdl):
"""根据指定模块信息,和代码模版目录,生成代码 :param mdl: 模块 :return: 无"""
<|body_1|>
def make_by_path(sel... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CodeGenModuleMaker:
"""代码生成-代码生成类"""
def __init__(self, tpl_path, out_path):
"""初始化 :param tpl_path: 模版路径 :param out_path: 生成文件路径"""
self.cfg_mk = loadcfgcm.load('codegen_maker_module.json', default_config)
self.tpl_path = tpl_path
self.out_path = out_path
self.cfg... | the_stack_v2_python_sparse | codegen/codegen_mk.py | elthe/LearnPythonStats | train | 3 |
e28d554447a8898c872e589129b2ca698eae1bf8 | [
"n = len(nums)\nif n <= 0:\n return 0\nnCurSum, nGreatestSum = (0, float('-inf'))\nfor i in range(n):\n if nCurSum <= 0:\n nCurSum = nums[i]\n else:\n nCurSum += nums[i]\n if nCurSum > nGreatestSum:\n nGreatestSum = nCurSum\nreturn nGreatestSum",
"n = len(nums)\nif n <= 0:\n re... | <|body_start_0|>
n = len(nums)
if n <= 0:
return 0
nCurSum, nGreatestSum = (0, float('-inf'))
for i in range(n):
if nCurSum <= 0:
nCurSum = nums[i]
else:
nCurSum += nums[i]
if nCurSum > nGreatestSum:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
"""分析规律:贪心"""
<|body_0|>
def maxSubArray1(self, nums: List[int]) -> int:
"""状态转移方程:dp[i] 的值代表 nums 前 i 个数字的最大子数组和 if nums[i] > nums[i-1], dp[i] = max(dp[i], dp[j] + 1)"""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_10k_train_000577 | 2,099 | permissive | [
{
"docstring": "分析规律:贪心",
"name": "maxSubArray",
"signature": "def maxSubArray(self, nums: List[int]) -> int"
},
{
"docstring": "状态转移方程:dp[i] 的值代表 nums 前 i 个数字的最大子数组和 if nums[i] > nums[i-1], dp[i] = max(dp[i], dp[j] + 1)",
"name": "maxSubArray1",
"signature": "def maxSubArray1(self, nums... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray(self, nums: List[int]) -> int: 分析规律:贪心
- def maxSubArray1(self, nums: List[int]) -> int: 状态转移方程:dp[i] 的值代表 nums 前 i 个数字的最大子数组和 if nums[i] > nums[i-1], dp[i] = max... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray(self, nums: List[int]) -> int: 分析规律:贪心
- def maxSubArray1(self, nums: List[int]) -> int: 状态转移方程:dp[i] 的值代表 nums 前 i 个数字的最大子数组和 if nums[i] > nums[i-1], dp[i] = max... | e8a1c6cae6547cbcb6e8494be6df685f3e7c837c | <|skeleton|>
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
"""分析规律:贪心"""
<|body_0|>
def maxSubArray1(self, nums: List[int]) -> int:
"""状态转移方程:dp[i] 的值代表 nums 前 i 个数字的最大子数组和 if nums[i] > nums[i-1], dp[i] = max(dp[i], dp[j] + 1)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxSubArray(self, nums: List[int]) -> int:
"""分析规律:贪心"""
n = len(nums)
if n <= 0:
return 0
nCurSum, nGreatestSum = (0, float('-inf'))
for i in range(n):
if nCurSum <= 0:
nCurSum = nums[i]
else:
... | the_stack_v2_python_sparse | lcof/42-lian-xu-zi-shu-zu-de-zui-da-he-lcof.py | yuenliou/leetcode | train | 0 | |
3d443c5e9282820a05a1b4e7f121362d843983e1 | [
"test = '4 4 0\\n2 1 2'\nd = Spheres(test)\nself.assertEqual(d.numa, [4, 4, 0])\nself.assertEqual(d.numb, [2, 1, 2])\nself.assertEqual(d.delta, [2, 3, -2])\nself.assertEqual(Spheres(test).calculate(), 'Yes')\ntest = '5 6 1\\n2 7 2'\nself.assertEqual(Spheres(test).calculate(), 'No')\ntest = '3 3 3\\n2 2 2'\nself.ass... | <|body_start_0|>
test = '4 4 0\n2 1 2'
d = Spheres(test)
self.assertEqual(d.numa, [4, 4, 0])
self.assertEqual(d.numb, [2, 1, 2])
self.assertEqual(d.delta, [2, 3, -2])
self.assertEqual(Spheres(test).calculate(), 'Yes')
test = '5 6 1\n2 7 2'
self.assertEqual... | unitTests | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class unitTests:
def test_single_test(self):
"""Spheres class testing"""
<|body_0|>
def time_limit_test(self, nmax):
"""Timelimit testing"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
test = '4 4 0\n2 1 2'
d = Spheres(test)
self.assertEq... | stack_v2_sparse_classes_10k_train_000578 | 3,011 | permissive | [
{
"docstring": "Spheres class testing",
"name": "test_single_test",
"signature": "def test_single_test(self)"
},
{
"docstring": "Timelimit testing",
"name": "time_limit_test",
"signature": "def time_limit_test(self, nmax)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000386 | Implement the Python class `unitTests` described below.
Class description:
Implement the unitTests class.
Method signatures and docstrings:
- def test_single_test(self): Spheres class testing
- def time_limit_test(self, nmax): Timelimit testing | Implement the Python class `unitTests` described below.
Class description:
Implement the unitTests class.
Method signatures and docstrings:
- def test_single_test(self): Spheres class testing
- def time_limit_test(self, nmax): Timelimit testing
<|skeleton|>
class unitTests:
def test_single_test(self):
"... | ae02ea872ca91ef98630cc172a844b82cc56f621 | <|skeleton|>
class unitTests:
def test_single_test(self):
"""Spheres class testing"""
<|body_0|>
def time_limit_test(self, nmax):
"""Timelimit testing"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class unitTests:
def test_single_test(self):
"""Spheres class testing"""
test = '4 4 0\n2 1 2'
d = Spheres(test)
self.assertEqual(d.numa, [4, 4, 0])
self.assertEqual(d.numb, [2, 1, 2])
self.assertEqual(d.delta, [2, 3, -2])
self.assertEqual(Spheres(test).calcul... | the_stack_v2_python_sparse | codeforces/606A_spheres.py | snsokolov/contests | train | 1 | |
f0df91748f61ac1f7625c90c394626a388631130 | [
"User = apps.get_model('auth', 'User')\ntry:\n user = User.objects.get(username=USERNAME, email=OLD_EMAIL)\nexcept User.DoesNotExist:\n return\nuser.email = NEW_EMAIL\nuser.save()",
"User = apps.get_model('auth', 'User')\ntry:\n user = User.objects.get(username=USERNAME, email=NEW_EMAIL)\nexcept User.Doe... | <|body_start_0|>
User = apps.get_model('auth', 'User')
try:
user = User.objects.get(username=USERNAME, email=OLD_EMAIL)
except User.DoesNotExist:
return
user.email = NEW_EMAIL
user.save()
<|end_body_0|>
<|body_start_1|>
User = apps.get_model('auth... | Migration | [
"MIT",
"AGPL-3.0-only",
"AGPL-3.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Migration:
def forwards(apps, schema_editor):
"""Update the email of the service user."""
<|body_0|>
def backwards(apps, schema_editor):
"""Replaces new email with old email for the service user."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
User ... | stack_v2_sparse_classes_10k_train_000579 | 1,271 | permissive | [
{
"docstring": "Update the email of the service user.",
"name": "forwards",
"signature": "def forwards(apps, schema_editor)"
},
{
"docstring": "Replaces new email with old email for the service user.",
"name": "backwards",
"signature": "def backwards(apps, schema_editor)"
}
] | 2 | null | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(apps, schema_editor): Update the email of the service user.
- def backwards(apps, schema_editor): Replaces new email with old email for the service user. | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(apps, schema_editor): Update the email of the service user.
- def backwards(apps, schema_editor): Replaces new email with old email for the service user.
<|skelet... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class Migration:
def forwards(apps, schema_editor):
"""Update the email of the service user."""
<|body_0|>
def backwards(apps, schema_editor):
"""Replaces new email with old email for the service user."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Migration:
def forwards(apps, schema_editor):
"""Update the email of the service user."""
User = apps.get_model('auth', 'User')
try:
user = User.objects.get(username=USERNAME, email=OLD_EMAIL)
except User.DoesNotExist:
return
user.email = NEW_EMA... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/djangoapps/commerce/migrations/0008_auto_20191024_2048.py | luque/better-ways-of-thinking-about-software | train | 3 | |
8db267cd96c592043aff3d74b1c300aa773bb56d | [
"ans = 0\nwhile n > 0:\n n &= n - 1\n ans += 1\nreturn ans",
"x = [0] * (num + 1)\nfor i in range(1, num + 1):\n x[i] = self.hammingWeight(i)\nreturn x"
] | <|body_start_0|>
ans = 0
while n > 0:
n &= n - 1
ans += 1
return ans
<|end_body_0|>
<|body_start_1|>
x = [0] * (num + 1)
for i in range(1, num + 1):
x[i] = self.hammingWeight(i)
return x
<|end_body_1|>
| Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hammingWeight(self, n: int) -> int:
"""bit manipulation: n & (n - 1) flip the rightmost 1 into 0 n & ~(n - 1) or n & (-n) get out rigthmost 1 with trailing zeros, e.g., rightmost 1's index"""
<|body_0|>
def countBits(self, num: int) -> List[int]:
"""Q19... | stack_v2_sparse_classes_10k_train_000580 | 1,788 | no_license | [
{
"docstring": "bit manipulation: n & (n - 1) flip the rightmost 1 into 0 n & ~(n - 1) or n & (-n) get out rigthmost 1 with trailing zeros, e.g., rightmost 1's index",
"name": "hammingWeight",
"signature": "def hammingWeight(self, n: int) -> int"
},
{
"docstring": "Q191",
"name": "countBits"... | 2 | stack_v2_sparse_classes_30k_train_001830 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hammingWeight(self, n: int) -> int: bit manipulation: n & (n - 1) flip the rightmost 1 into 0 n & ~(n - 1) or n & (-n) get out rigthmost 1 with trailing zeros, e.g., rightmos... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hammingWeight(self, n: int) -> int: bit manipulation: n & (n - 1) flip the rightmost 1 into 0 n & ~(n - 1) or n & (-n) get out rigthmost 1 with trailing zeros, e.g., rightmos... | 6043134736452a6f4704b62857d0aed2e9571164 | <|skeleton|>
class Solution:
def hammingWeight(self, n: int) -> int:
"""bit manipulation: n & (n - 1) flip the rightmost 1 into 0 n & ~(n - 1) or n & (-n) get out rigthmost 1 with trailing zeros, e.g., rightmost 1's index"""
<|body_0|>
def countBits(self, num: int) -> List[int]:
"""Q19... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def hammingWeight(self, n: int) -> int:
"""bit manipulation: n & (n - 1) flip the rightmost 1 into 0 n & ~(n - 1) or n & (-n) get out rigthmost 1 with trailing zeros, e.g., rightmost 1's index"""
ans = 0
while n > 0:
n &= n - 1
ans += 1
return ... | the_stack_v2_python_sparse | src/0300-0399/0338.count.bits.py | gyang274/leetcode | train | 1 | |
fa92587ab29b36278f5d704907da294f8c5dafe4 | [
"n = len(coins)\ndp = [[0] * (amount + 1) for _ in range(n + 1)]\nfor i in range(n + 1):\n dp[i][0] = 1\nfor i in range(1, n + 1):\n for j in range(1, amount + 1):\n dp[i][j] = dp[i - 1][j]\n if j >= coins[i - 1]:\n dp[i][j] = dp[i - 1][j] + dp[i][j - coins[i - 1]]\nreturn dp[-1][-1]"... | <|body_start_0|>
n = len(coins)
dp = [[0] * (amount + 1) for _ in range(n + 1)]
for i in range(n + 1):
dp[i][0] = 1
for i in range(1, n + 1):
for j in range(1, amount + 1):
dp[i][j] = dp[i - 1][j]
if j >= coins[i - 1]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def change1(self, amount: int, coins: List[int]) -> int:
"""1. 每个物品可以用无数次 2. dp[i][j]表示用硬币的前i个可以凑成金额j的个数"""
<|body_0|>
def change2(self, amount: int, coins: List[int]) -> int:
"""1. 每个物品可以用无数次 2. 每次会用到上面一层的结果,可以将上面dp[i-1][j]改为dp[j]"""
<|body_1|>
<|... | stack_v2_sparse_classes_10k_train_000581 | 1,814 | no_license | [
{
"docstring": "1. 每个物品可以用无数次 2. dp[i][j]表示用硬币的前i个可以凑成金额j的个数",
"name": "change1",
"signature": "def change1(self, amount: int, coins: List[int]) -> int"
},
{
"docstring": "1. 每个物品可以用无数次 2. 每次会用到上面一层的结果,可以将上面dp[i-1][j]改为dp[j]",
"name": "change2",
"signature": "def change2(self, amount: in... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def change1(self, amount: int, coins: List[int]) -> int: 1. 每个物品可以用无数次 2. dp[i][j]表示用硬币的前i个可以凑成金额j的个数
- def change2(self, amount: int, coins: List[int]) -> int: 1. 每个物品可以用无数次 2. ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def change1(self, amount: int, coins: List[int]) -> int: 1. 每个物品可以用无数次 2. dp[i][j]表示用硬币的前i个可以凑成金额j的个数
- def change2(self, amount: int, coins: List[int]) -> int: 1. 每个物品可以用无数次 2. ... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def change1(self, amount: int, coins: List[int]) -> int:
"""1. 每个物品可以用无数次 2. dp[i][j]表示用硬币的前i个可以凑成金额j的个数"""
<|body_0|>
def change2(self, amount: int, coins: List[int]) -> int:
"""1. 每个物品可以用无数次 2. 每次会用到上面一层的结果,可以将上面dp[i-1][j]改为dp[j]"""
<|body_1|>
<|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def change1(self, amount: int, coins: List[int]) -> int:
"""1. 每个物品可以用无数次 2. dp[i][j]表示用硬币的前i个可以凑成金额j的个数"""
n = len(coins)
dp = [[0] * (amount + 1) for _ in range(n + 1)]
for i in range(n + 1):
dp[i][0] = 1
for i in range(1, n + 1):
for... | the_stack_v2_python_sparse | LeetCode/动态规划法(dp)/背包问题/完全背包问题.py | yiming1012/MyLeetCode | train | 2 | |
3d298b52eda0cc5ae0f6f056f631ad9f50ae34c9 | [
"length = len(nums)\nn = 1\nwhile n < length:\n n *= 2\nself.n = n\nself.d = [0] * (2 * n - 1)\nfor i in range(length):\n self.update(i, nums[i])",
"p = i + self.n - 1\nself.d[p] = val\nwhile p > 0:\n p = (p - 1) // 2\n self.d[p] = self.d[2 * p + 1] + self.d[2 * p + 2]",
"if lo <= s and hi >= t:\n ... | <|body_start_0|>
length = len(nums)
n = 1
while n < length:
n *= 2
self.n = n
self.d = [0] * (2 * n - 1)
for i in range(length):
self.update(i, nums[i])
<|end_body_0|>
<|body_start_1|>
p = i + self.n - 1
self.d[p] = val
whi... | 求和线段树, 完美二叉树版本,即 叶子结点树木是满的 所有的nums的值都位于 叶子结点, 而且二叉树的每一层的节点个数都是偶数 | segmentTree | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class segmentTree:
"""求和线段树, 完美二叉树版本,即 叶子结点树木是满的 所有的nums的值都位于 叶子结点, 而且二叉树的每一层的节点个数都是偶数"""
def __init__(self, nums) -> None:
"""d: 线段树数组 0-based nums: 索引 0-based"""
<|body_0|>
def update(self, i, val):
"""i: 0-based p: 1-based 相当于数组 nums[i] = val 那么就需要修改二叉树关联所有值,类似于 堆中的... | stack_v2_sparse_classes_10k_train_000582 | 4,234 | permissive | [
{
"docstring": "d: 线段树数组 0-based nums: 索引 0-based",
"name": "__init__",
"signature": "def __init__(self, nums) -> None"
},
{
"docstring": "i: 0-based p: 1-based 相当于数组 nums[i] = val 那么就需要修改二叉树关联所有值,类似于 堆中的 swim",
"name": "update",
"signature": "def update(self, i, val)"
},
{
"docs... | 3 | null | Implement the Python class `segmentTree` described below.
Class description:
求和线段树, 完美二叉树版本,即 叶子结点树木是满的 所有的nums的值都位于 叶子结点, 而且二叉树的每一层的节点个数都是偶数
Method signatures and docstrings:
- def __init__(self, nums) -> None: d: 线段树数组 0-based nums: 索引 0-based
- def update(self, i, val): i: 0-based p: 1-based 相当于数组 nums[i] = val 那么... | Implement the Python class `segmentTree` described below.
Class description:
求和线段树, 完美二叉树版本,即 叶子结点树木是满的 所有的nums的值都位于 叶子结点, 而且二叉树的每一层的节点个数都是偶数
Method signatures and docstrings:
- def __init__(self, nums) -> None: d: 线段树数组 0-based nums: 索引 0-based
- def update(self, i, val): i: 0-based p: 1-based 相当于数组 nums[i] = val 那么... | 65549f72c565d9f11641c86d6cef9c7988805817 | <|skeleton|>
class segmentTree:
"""求和线段树, 完美二叉树版本,即 叶子结点树木是满的 所有的nums的值都位于 叶子结点, 而且二叉树的每一层的节点个数都是偶数"""
def __init__(self, nums) -> None:
"""d: 线段树数组 0-based nums: 索引 0-based"""
<|body_0|>
def update(self, i, val):
"""i: 0-based p: 1-based 相当于数组 nums[i] = val 那么就需要修改二叉树关联所有值,类似于 堆中的... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class segmentTree:
"""求和线段树, 完美二叉树版本,即 叶子结点树木是满的 所有的nums的值都位于 叶子结点, 而且二叉树的每一层的节点个数都是偶数"""
def __init__(self, nums) -> None:
"""d: 线段树数组 0-based nums: 索引 0-based"""
length = len(nums)
n = 1
while n < length:
n *= 2
self.n = n
self.d = [0] * (2 * n - 1)... | the_stack_v2_python_sparse | utils/segmentTree.py | wisesky/LeetCode-Practice | train | 0 |
b912dbe5da6fc486dfb8d615f7c3c836236f9376 | [
"if field is None:\n return field\nelif field is '':\n return None\nelif isinstance(field, basestring):\n result = dateutil.parser.parse(field)\n if result.tzinfo is None:\n result = result.replace(tzinfo=UTC())\n return result\nelif isinstance(field, (int, long, float)):\n return datetime.... | <|body_start_0|>
if field is None:
return field
elif field is '':
return None
elif isinstance(field, basestring):
result = dateutil.parser.parse(field)
if result.tzinfo is None:
result = result.replace(tzinfo=UTC())
retu... | Date fields know how to parse and produce json (iso) compatible formats. Converts to tz aware datetimes. | Date | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Date:
"""Date fields know how to parse and produce json (iso) compatible formats. Converts to tz aware datetimes."""
def from_json(self, field):
"""Parse an optional metadata key containing a time: if present, complain if it doesn't parse. Return None if not present or invalid."""
... | stack_v2_sparse_classes_10k_train_000583 | 3,123 | no_license | [
{
"docstring": "Parse an optional metadata key containing a time: if present, complain if it doesn't parse. Return None if not present or invalid.",
"name": "from_json",
"signature": "def from_json(self, field)"
},
{
"docstring": "Convert a time struct to a string",
"name": "to_json",
"s... | 2 | null | Implement the Python class `Date` described below.
Class description:
Date fields know how to parse and produce json (iso) compatible formats. Converts to tz aware datetimes.
Method signatures and docstrings:
- def from_json(self, field): Parse an optional metadata key containing a time: if present, complain if it do... | Implement the Python class `Date` described below.
Class description:
Date fields know how to parse and produce json (iso) compatible formats. Converts to tz aware datetimes.
Method signatures and docstrings:
- def from_json(self, field): Parse an optional metadata key containing a time: if present, complain if it do... | 5fa3a818c3d41bd9c3eb25122e1d376c8910269c | <|skeleton|>
class Date:
"""Date fields know how to parse and produce json (iso) compatible formats. Converts to tz aware datetimes."""
def from_json(self, field):
"""Parse an optional metadata key containing a time: if present, complain if it doesn't parse. Return None if not present or invalid."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Date:
"""Date fields know how to parse and produce json (iso) compatible formats. Converts to tz aware datetimes."""
def from_json(self, field):
"""Parse an optional metadata key containing a time: if present, complain if it doesn't parse. Return None if not present or invalid."""
if fiel... | the_stack_v2_python_sparse | ExtractFeatures/Data/pratik98/fields.py | vivekaxl/LexisNexis | train | 9 |
ba991809856a415d22abdc466deaa8431100a04f | [
"strs = map(lambda x: x.replace('\\x00', '\\\\x00'), strs)\nret = ''\nfor s in strs:\n ret += s + '\\x00'\nreturn ret",
"if '\\x00' not in s:\n return []\ns = s[:-1]\nstrs = s.split('\\x00')\nstrs = map(lambda x: x.replace('\\\\x00', '\\x00'), strs)\nreturn strs"
] | <|body_start_0|>
strs = map(lambda x: x.replace('\x00', '\\x00'), strs)
ret = ''
for s in strs:
ret += s + '\x00'
return ret
<|end_body_0|>
<|body_start_1|>
if '\x00' not in s:
return []
s = s[:-1]
strs = s.split('\x00')
strs = map... | CodecError | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CodecError:
def encode(self, strs):
"""Encodes a list of strings to a single string. This algorithm contains bugs if \\x00 exits in the original string :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of string... | stack_v2_sparse_classes_10k_train_000584 | 2,130 | permissive | [
{
"docstring": "Encodes a list of strings to a single string. This algorithm contains bugs if \\\\x00 exits in the original string :type strs: List[str] :rtype: str",
"name": "encode",
"signature": "def encode(self, strs)"
},
{
"docstring": "Decodes a single string to a list of strings. :type s:... | 2 | null | Implement the Python class `CodecError` described below.
Class description:
Implement the CodecError class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. This algorithm contains bugs if \\x00 exits in the original string :type strs: List[str] :rtype: str
- d... | Implement the Python class `CodecError` described below.
Class description:
Implement the CodecError class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. This algorithm contains bugs if \\x00 exits in the original string :type strs: List[str] :rtype: str
- d... | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | <|skeleton|>
class CodecError:
def encode(self, strs):
"""Encodes a list of strings to a single string. This algorithm contains bugs if \\x00 exits in the original string :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of string... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CodecError:
def encode(self, strs):
"""Encodes a list of strings to a single string. This algorithm contains bugs if \\x00 exits in the original string :type strs: List[str] :rtype: str"""
strs = map(lambda x: x.replace('\x00', '\\x00'), strs)
ret = ''
for s in strs:
... | the_stack_v2_python_sparse | 271 Encode and Decode Strings.py | Aminaba123/LeetCode | train | 1 | |
46b2f7ce35f6a03d6687632196fe2f09abcacd2c | [
"event_list_container = response.css('dl.simcal-events-list-container')\nfor event_date, event_details in zip(event_list_container.css('dt.simcal-day-label'), event_list_container.css('dd.simcal-day')):\n date = event_date.css('.simcal-date-format::text').get()\n for event_detail in event_details.css('li.simc... | <|body_start_0|>
event_list_container = response.css('dl.simcal-events-list-container')
for event_date, event_details in zip(event_list_container.css('dt.simcal-day-label'), event_list_container.css('dd.simcal-day')):
date = event_date.css('.simcal-date-format::text').get()
for e... | Spider to crawl Heritage's website. | HeritageSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HeritageSpider:
"""Spider to crawl Heritage's website."""
def parse(self, response):
"""Parse the html for performance information and yield PerformanceItem instances."""
<|body_0|>
def format_datetime(self, date_string, time_string):
"""Given a time and date in ... | stack_v2_sparse_classes_10k_train_000585 | 2,595 | no_license | [
{
"docstring": "Parse the html for performance information and yield PerformanceItem instances.",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "Given a time and date in string form, format the date so that it is in the format month/day/year hour:minute.",
"name... | 2 | stack_v2_sparse_classes_30k_train_003299 | Implement the Python class `HeritageSpider` described below.
Class description:
Spider to crawl Heritage's website.
Method signatures and docstrings:
- def parse(self, response): Parse the html for performance information and yield PerformanceItem instances.
- def format_datetime(self, date_string, time_string): Give... | Implement the Python class `HeritageSpider` described below.
Class description:
Spider to crawl Heritage's website.
Method signatures and docstrings:
- def parse(self, response): Parse the html for performance information and yield PerformanceItem instances.
- def format_datetime(self, date_string, time_string): Give... | d5ae552d383f5f971e29a38055c518fc68172f32 | <|skeleton|>
class HeritageSpider:
"""Spider to crawl Heritage's website."""
def parse(self, response):
"""Parse the html for performance information and yield PerformanceItem instances."""
<|body_0|>
def format_datetime(self, date_string, time_string):
"""Given a time and date in ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HeritageSpider:
"""Spider to crawl Heritage's website."""
def parse(self, response):
"""Parse the html for performance information and yield PerformanceItem instances."""
event_list_container = response.css('dl.simcal-events-list-container')
for event_date, event_details in zip(ev... | the_stack_v2_python_sparse | server/app/performance_scraper/performance_scraper/spiders/heritage_spider.py | EricMontague/MailChimp-Newsletter-Project | train | 0 |
b62173335183be65b5f41cc1779a5b84b3e2cbfb | [
"super(RainbowDQN, self).__init__()\nobs_shape, action_shape = (squeeze(obs_shape), squeeze(action_shape))\nif head_hidden_size is None:\n head_hidden_size = encoder_hidden_size_list[-1]\nif isinstance(obs_shape, int) or len(obs_shape) == 1:\n self.encoder = FCEncoder(obs_shape, encoder_hidden_size_list, acti... | <|body_start_0|>
super(RainbowDQN, self).__init__()
obs_shape, action_shape = (squeeze(obs_shape), squeeze(action_shape))
if head_hidden_size is None:
head_hidden_size = encoder_hidden_size_list[-1]
if isinstance(obs_shape, int) or len(obs_shape) == 1:
self.encode... | Overview: RainbowDQN network (C51 + Dueling + Noisy Block) .. note:: RainbowDQN contains dueling architecture by default | RainbowDQN | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RainbowDQN:
"""Overview: RainbowDQN network (C51 + Dueling + Noisy Block) .. note:: RainbowDQN contains dueling architecture by default"""
def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], he... | stack_v2_sparse_classes_10k_train_000586 | 30,380 | permissive | [
{
"docstring": "Overview: Init the Rainbow Model according to arguments. Arguments: - obs_shape (:obj:`Union[int, SequenceType]`): Observation space shape. - action_shape (:obj:`Union[int, SequenceType]`): Action space shape. - encoder_hidden_size_list (:obj:`SequenceType`): Collection of ``hidden_size`` to pas... | 2 | null | Implement the Python class `RainbowDQN` described below.
Class description:
Overview: RainbowDQN network (C51 + Dueling + Noisy Block) .. note:: RainbowDQN contains dueling architecture by default
Method signatures and docstrings:
- def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, Sequ... | Implement the Python class `RainbowDQN` described below.
Class description:
Overview: RainbowDQN network (C51 + Dueling + Noisy Block) .. note:: RainbowDQN contains dueling architecture by default
Method signatures and docstrings:
- def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, Sequ... | eb483fa6e46602d58c8e7d2ca1e566adca28e703 | <|skeleton|>
class RainbowDQN:
"""Overview: RainbowDQN network (C51 + Dueling + Noisy Block) .. note:: RainbowDQN contains dueling architecture by default"""
def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], he... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RainbowDQN:
"""Overview: RainbowDQN network (C51 + Dueling + Noisy Block) .. note:: RainbowDQN contains dueling architecture by default"""
def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_siz... | the_stack_v2_python_sparse | ding/model/template/q_learning.py | shengxuesun/DI-engine | train | 1 |
10ccbd8041655ad4bbbcac7d6dfe62cfc2bfa94f | [
"test = '3 2'\nd = Modular(test)\nself.assertEqual(d.k, 2)\nself.assertEqual(d.p, 3)\nself.assertEqual(Modular(test).calculate(), '3')\ntest = '5 4'\nself.assertEqual(Modular(test).calculate(), '25')\ntest = ''",
"import random\nimport timeit\ntest = str(nmax) + ' ' + str(nmax) + '\\n'\nnumnums = [str(i) + ' ' + ... | <|body_start_0|>
test = '3 2'
d = Modular(test)
self.assertEqual(d.k, 2)
self.assertEqual(d.p, 3)
self.assertEqual(Modular(test).calculate(), '3')
test = '5 4'
self.assertEqual(Modular(test).calculate(), '25')
test = ''
<|end_body_0|>
<|body_start_1|>
... | unitTests | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class unitTests:
def test_single_test(self):
"""Modular class testing"""
<|body_0|>
def time_limit_test(self, nmax):
"""Timelimit testing"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
test = '3 2'
d = Modular(test)
self.assertEqual(d.k, ... | stack_v2_sparse_classes_10k_train_000587 | 3,558 | permissive | [
{
"docstring": "Modular class testing",
"name": "test_single_test",
"signature": "def test_single_test(self)"
},
{
"docstring": "Timelimit testing",
"name": "time_limit_test",
"signature": "def time_limit_test(self, nmax)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003503 | Implement the Python class `unitTests` described below.
Class description:
Implement the unitTests class.
Method signatures and docstrings:
- def test_single_test(self): Modular class testing
- def time_limit_test(self, nmax): Timelimit testing | Implement the Python class `unitTests` described below.
Class description:
Implement the unitTests class.
Method signatures and docstrings:
- def test_single_test(self): Modular class testing
- def time_limit_test(self, nmax): Timelimit testing
<|skeleton|>
class unitTests:
def test_single_test(self):
"... | ae02ea872ca91ef98630cc172a844b82cc56f621 | <|skeleton|>
class unitTests:
def test_single_test(self):
"""Modular class testing"""
<|body_0|>
def time_limit_test(self, nmax):
"""Timelimit testing"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class unitTests:
def test_single_test(self):
"""Modular class testing"""
test = '3 2'
d = Modular(test)
self.assertEqual(d.k, 2)
self.assertEqual(d.p, 3)
self.assertEqual(Modular(test).calculate(), '3')
test = '5 4'
self.assertEqual(Modular(test).calcu... | the_stack_v2_python_sparse | codeforces/604D_modular.py | snsokolov/contests | train | 1 | |
08e328e884ead0778f24f6f56efb5ac20dcbab56 | [
"super(PlotCellTypeStack, self).__init__(experiment, name='PlotCellTypeStack', label=label)\nself.epoch_start = self.experiment.config.getint(self.config_section, 'epoch_start', 0)\nself.epoch_end = self.experiment.config.getint(self.config_section, 'epoch_end', default=self.experiment.config.getint('Experiment', '... | <|body_start_0|>
super(PlotCellTypeStack, self).__init__(experiment, name='PlotCellTypeStack', label=label)
self.epoch_start = self.experiment.config.getint(self.config_section, 'epoch_start', 0)
self.epoch_end = self.experiment.config.getint(self.config_section, 'epoch_end', default=self.experi... | TODO: description Configuration is done in the [PlotCellTypeStack] section Configuration Options: epoch_start The epoch at which to start executing (default: 0) epoch_end The epoch at which to stop executing (default: end of experiment) frequency The frequency (epochs) at which to execute (default: 1) priority The prio... | PlotCellTypeStack | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlotCellTypeStack:
"""TODO: description Configuration is done in the [PlotCellTypeStack] section Configuration Options: epoch_start The epoch at which to start executing (default: 0) epoch_end The epoch at which to stop executing (default: end of experiment) frequency The frequency (epochs) at wh... | stack_v2_sparse_classes_10k_train_000588 | 3,421 | permissive | [
{
"docstring": "Initialize the PlotCellTypeStack Action",
"name": "__init__",
"signature": "def __init__(self, experiment, label=None)"
},
{
"docstring": "Execute the action",
"name": "update",
"signature": "def update(self)"
},
{
"docstring": "Since we're at the end of the run, ... | 3 | stack_v2_sparse_classes_30k_train_006134 | Implement the Python class `PlotCellTypeStack` described below.
Class description:
TODO: description Configuration is done in the [PlotCellTypeStack] section Configuration Options: epoch_start The epoch at which to start executing (default: 0) epoch_end The epoch at which to stop executing (default: end of experiment)... | Implement the Python class `PlotCellTypeStack` described below.
Class description:
TODO: description Configuration is done in the [PlotCellTypeStack] section Configuration Options: epoch_start The epoch at which to start executing (default: 0) epoch_end The epoch at which to stop executing (default: end of experiment)... | a114ac66e62a960e18127faf52cff9e48831e212 | <|skeleton|>
class PlotCellTypeStack:
"""TODO: description Configuration is done in the [PlotCellTypeStack] section Configuration Options: epoch_start The epoch at which to start executing (default: 0) epoch_end The epoch at which to stop executing (default: end of experiment) frequency The frequency (epochs) at wh... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PlotCellTypeStack:
"""TODO: description Configuration is done in the [PlotCellTypeStack] section Configuration Options: epoch_start The epoch at which to start executing (default: 0) epoch_end The epoch at which to stop executing (default: end of experiment) frequency The frequency (epochs) at which to execut... | the_stack_v2_python_sparse | contrib/actions/PlotCellTypeStack.py | namlehai/seeds | train | 0 |
213540831ee82252ddb77e8b42e3cce542a13f3a | [
"parser.add_argument('--radon-no-assert', default=False, action='store_true', help='Ignore `assert` statements.')\nparser.add_argument('--radon-show-closures', default=False, action='store_true', help='Increase complexity on closures.')\ntry:\n parser.add_argument('--max-complexity', default=10, type=int, help='... | <|body_start_0|>
parser.add_argument('--radon-no-assert', default=False, action='store_true', help='Ignore `assert` statements.')
parser.add_argument('--radon-show-closures', default=False, action='store_true', help='Increase complexity on closures.')
try:
parser.add_argument('--max-... | Radon runner. | Linter | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Linter:
"""Radon runner."""
def add_args(cls, parser: ArgumentParser):
"""Add --max-complexity option."""
<|body_0|>
def run_check(self, ctx: RunContext):
"""Check code with Radon."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
parser.add_argum... | stack_v2_sparse_classes_10k_train_000589 | 2,192 | permissive | [
{
"docstring": "Add --max-complexity option.",
"name": "add_args",
"signature": "def add_args(cls, parser: ArgumentParser)"
},
{
"docstring": "Check code with Radon.",
"name": "run_check",
"signature": "def run_check(self, ctx: RunContext)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001054 | Implement the Python class `Linter` described below.
Class description:
Radon runner.
Method signatures and docstrings:
- def add_args(cls, parser: ArgumentParser): Add --max-complexity option.
- def run_check(self, ctx: RunContext): Check code with Radon. | Implement the Python class `Linter` described below.
Class description:
Radon runner.
Method signatures and docstrings:
- def add_args(cls, parser: ArgumentParser): Add --max-complexity option.
- def run_check(self, ctx: RunContext): Check code with Radon.
<|skeleton|>
class Linter:
"""Radon runner."""
def ... | 53ad214de0aa9534e59bcd5f97d9d723d16cfdb8 | <|skeleton|>
class Linter:
"""Radon runner."""
def add_args(cls, parser: ArgumentParser):
"""Add --max-complexity option."""
<|body_0|>
def run_check(self, ctx: RunContext):
"""Check code with Radon."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Linter:
"""Radon runner."""
def add_args(cls, parser: ArgumentParser):
"""Add --max-complexity option."""
parser.add_argument('--radon-no-assert', default=False, action='store_true', help='Ignore `assert` statements.')
parser.add_argument('--radon-show-closures', default=False, ac... | the_stack_v2_python_sparse | pylama/lint/pylama_radon.py | klen/pylama | train | 1,022 |
f2bea8af40db8f098d2b53cdcf76fd00ce4388a1 | [
"super(BidirectionalLanguageModel, self).__init__()\nself.lstms = nn.ModuleList([nn.LSTM(emb_dim, hid_dim, bidirectional=True, dropout=dropout, batch_first=True), nn.LSTM(prj_emb, hid_dim, bidirectional=True, dropout=dropout, batch_first=True)])\nself.projection_layer = nn.Linear(2 * hid_dim, prj_emb)",
"first_ou... | <|body_start_0|>
super(BidirectionalLanguageModel, self).__init__()
self.lstms = nn.ModuleList([nn.LSTM(emb_dim, hid_dim, bidirectional=True, dropout=dropout, batch_first=True), nn.LSTM(prj_emb, hid_dim, bidirectional=True, dropout=dropout, batch_first=True)])
self.projection_layer = nn.Linear(2... | BidirectionalLanguageModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BidirectionalLanguageModel:
def __init__(self, emb_dim: int, hid_dim: int, prj_emb: int, dropout: float=0.0) -> None:
"""> We use dropout before and after evert LSTM layer"""
<|body_0|>
def forward(self, x: torch.Tensor, hidden: Tuple[torch.Tensor]=None):
"""Paramete... | stack_v2_sparse_classes_10k_train_000590 | 4,549 | no_license | [
{
"docstring": "> We use dropout before and after evert LSTM layer",
"name": "__init__",
"signature": "def __init__(self, emb_dim: int, hid_dim: int, prj_emb: int, dropout: float=0.0) -> None"
},
{
"docstring": "Parameters: x: A sentence tensor that embeded hidden: tuple of hidden and cell. The ... | 2 | stack_v2_sparse_classes_30k_train_006966 | Implement the Python class `BidirectionalLanguageModel` described below.
Class description:
Implement the BidirectionalLanguageModel class.
Method signatures and docstrings:
- def __init__(self, emb_dim: int, hid_dim: int, prj_emb: int, dropout: float=0.0) -> None: > We use dropout before and after evert LSTM layer
-... | Implement the Python class `BidirectionalLanguageModel` described below.
Class description:
Implement the BidirectionalLanguageModel class.
Method signatures and docstrings:
- def __init__(self, emb_dim: int, hid_dim: int, prj_emb: int, dropout: float=0.0) -> None: > We use dropout before and after evert LSTM layer
-... | ca033284850147b334d3771df8235a1135eba76c | <|skeleton|>
class BidirectionalLanguageModel:
def __init__(self, emb_dim: int, hid_dim: int, prj_emb: int, dropout: float=0.0) -> None:
"""> We use dropout before and after evert LSTM layer"""
<|body_0|>
def forward(self, x: torch.Tensor, hidden: Tuple[torch.Tensor]=None):
"""Paramete... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BidirectionalLanguageModel:
def __init__(self, emb_dim: int, hid_dim: int, prj_emb: int, dropout: float=0.0) -> None:
"""> We use dropout before and after evert LSTM layer"""
super(BidirectionalLanguageModel, self).__init__()
self.lstms = nn.ModuleList([nn.LSTM(emb_dim, hid_dim, bidire... | the_stack_v2_python_sparse | papers/4.ELMo/elmo.py | euhkim/NLP | train | 0 | |
055e0945666915c62de4dd740440837d972f1026 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('yjunchoi_yzhang71', 'yjunchoi_yzhang71')\nrepo.dropCollection('pollingLocation')\nrepo.createCollection('pollingLocation')\nurl = 'http://bostonopendata-boston.opendata.arcgis.com/datasets/f7c6dc9eb6b144... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('yjunchoi_yzhang71', 'yjunchoi_yzhang71')
repo.dropCollection('pollingLocation')
repo.createCollection('pollingLocation')
url = 'http://bos... | pollingLocation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class pollingLocation:
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 everythi... | stack_v2_sparse_classes_10k_train_000591 | 3,601 | 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_val_000088 | Implement the Python class `pollingLocation` described below.
Class description:
Implement the pollingLocation 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=Non... | Implement the Python class `pollingLocation` described below.
Class description:
Implement the pollingLocation 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=Non... | 97e72731ffadbeae57d7a332decd58706e7c08de | <|skeleton|>
class pollingLocation:
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 everythi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class pollingLocation:
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('yjunchoi_yzhang71', 'yjunchoi_yzhan... | the_stack_v2_python_sparse | yjunchoi_yzhang71/pollingLocation.py | ROODAY/course-2017-fal-proj | train | 3 | |
60dfebbf7e17ad808dc88026523469f4eca9367f | [
"try:\n\n def generate(vo):\n for exception in list_exceptions(exception_id, vo=vo):\n yield (dumps(exception, cls=APIEncoder) + '\\n')\n return try_stream(generate(vo=request.environ.get('vo')))\nexcept LifetimeExceptionNotFound as error:\n return generate_http_error_flask(404, error)",
... | <|body_start_0|>
try:
def generate(vo):
for exception in list_exceptions(exception_id, vo=vo):
yield (dumps(exception, cls=APIEncoder) + '\n')
return try_stream(generate(vo=request.environ.get('vo')))
except LifetimeExceptionNotFound as error:... | REST APIs for Lifetime Model exception. | LifetimeExceptionId | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LifetimeExceptionId:
"""REST APIs for Lifetime Model exception."""
def get(self, exception_id):
"""--- summary: Get Exception description: Get a single Lifetime Exception. tags: - Lifetime Exceptions parameters: - name: exception_id in: path description: The id of the lifetime except... | stack_v2_sparse_classes_10k_train_000592 | 12,043 | permissive | [
{
"docstring": "--- summary: Get Exception description: Get a single Lifetime Exception. tags: - Lifetime Exceptions parameters: - name: exception_id in: path description: The id of the lifetime exception. schema: type: string style: simple responses: 200: description: OK content: application/x-json-stream: sch... | 2 | null | Implement the Python class `LifetimeExceptionId` described below.
Class description:
REST APIs for Lifetime Model exception.
Method signatures and docstrings:
- def get(self, exception_id): --- summary: Get Exception description: Get a single Lifetime Exception. tags: - Lifetime Exceptions parameters: - name: excepti... | Implement the Python class `LifetimeExceptionId` described below.
Class description:
REST APIs for Lifetime Model exception.
Method signatures and docstrings:
- def get(self, exception_id): --- summary: Get Exception description: Get a single Lifetime Exception. tags: - Lifetime Exceptions parameters: - name: excepti... | 7f0d229ac0b3bc7dec12c6e158bea2b82d414a3b | <|skeleton|>
class LifetimeExceptionId:
"""REST APIs for Lifetime Model exception."""
def get(self, exception_id):
"""--- summary: Get Exception description: Get a single Lifetime Exception. tags: - Lifetime Exceptions parameters: - name: exception_id in: path description: The id of the lifetime except... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LifetimeExceptionId:
"""REST APIs for Lifetime Model exception."""
def get(self, exception_id):
"""--- summary: Get Exception description: Get a single Lifetime Exception. tags: - Lifetime Exceptions parameters: - name: exception_id in: path description: The id of the lifetime exception. schema: ... | the_stack_v2_python_sparse | lib/rucio/web/rest/flaskapi/v1/lifetime_exceptions.py | rucio/rucio | train | 232 |
52eb04366fc11b8baf473950626fb7b3b6b20735 | [
"threading.Thread.__init__(self)\nself.client = client\nself.address = address",
"joke = random.choice(jokes)\nprompt = joke['prompt']\nresponse = joke['response']\ndata = b''\nwhile data.strip() != b\"WHO'S THERE?\":\n self.client.send(b'KNOCK KNOCK\\n')\n data = self.client.recv(4096)\nself.client.send((p... | <|body_start_0|>
threading.Thread.__init__(self)
self.client = client
self.address = address
<|end_body_0|>
<|body_start_1|>
joke = random.choice(jokes)
prompt = joke['prompt']
response = joke['response']
data = b''
while data.strip() != b"WHO'S THERE?":
... | Runs a joke connection in a new thread. | JokeThread | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JokeThread:
"""Runs a joke connection in a new thread."""
def __init__(self, client, address):
"""Constructor"""
<|body_0|>
def run(self):
"""Runs joke procedure."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
threading.Thread.__init__(self)
... | stack_v2_sparse_classes_10k_train_000593 | 1,745 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, client, address)"
},
{
"docstring": "Runs joke procedure.",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004153 | Implement the Python class `JokeThread` described below.
Class description:
Runs a joke connection in a new thread.
Method signatures and docstrings:
- def __init__(self, client, address): Constructor
- def run(self): Runs joke procedure. | Implement the Python class `JokeThread` described below.
Class description:
Runs a joke connection in a new thread.
Method signatures and docstrings:
- def __init__(self, client, address): Constructor
- def run(self): Runs joke procedure.
<|skeleton|>
class JokeThread:
"""Runs a joke connection in a new thread."... | aad20f17ab99f86fb30dbc1f4d13ce5fab6633d2 | <|skeleton|>
class JokeThread:
"""Runs a joke connection in a new thread."""
def __init__(self, client, address):
"""Constructor"""
<|body_0|>
def run(self):
"""Runs joke procedure."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class JokeThread:
"""Runs a joke connection in a new thread."""
def __init__(self, client, address):
"""Constructor"""
threading.Thread.__init__(self)
self.client = client
self.address = address
def run(self):
"""Runs joke procedure."""
joke = random.choice(... | the_stack_v2_python_sparse | CSCI_4760/hw01/knock_knock_server.py | dsluo-archive/notes | train | 0 |
9d334671995beeb247af5ff2b5c3c983413d9e9d | [
"def help(root):\n if root:\n left = help(root.left)\n right = help(root.right)\n if left:\n root.right = left\n root.left = None\n while left.right:\n left = left.right\n left.right = right\n return root\n else:\n r... | <|body_start_0|>
def help(root):
if root:
left = help(root.left)
right = help(root.right)
if left:
root.right = left
root.left = None
while left.right:
left = left.righ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def flatten1(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
<|body_0|>
def flatten(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
... | stack_v2_sparse_classes_10k_train_000594 | 1,541 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.",
"name": "flatten1",
"signature": "def flatten1(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.",
"name": "flatten"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten1(self, root): :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.
- def flatten(self, root): :type root: TreeNode :rtype: void Do ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten1(self, root): :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.
- def flatten(self, root): :type root: TreeNode :rtype: void Do ... | e5b018493bbd12edcdcd0434f35d9c358106d391 | <|skeleton|>
class Solution:
def flatten1(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
<|body_0|>
def flatten(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def flatten1(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
def help(root):
if root:
left = help(root.left)
right = help(root.right)
if left:
ro... | the_stack_v2_python_sparse | py/leetcode/114.py | wfeng1991/learnpy | train | 0 | |
9d2be85fcbc878abfcef49e9a6ef17ad071ae8a4 | [
"group = handle.create_group('entry/data_processing')\ngroup.attrs['num_reflections'] = len(reflections)\nfor key, data in reflections.cols():\n self.encode_column(group, key, data)",
"from dials.array_family import flex\nif isinstance(data, flex.shoebox):\n self.encode_shoebox(group, key, data)\nelse:\n ... | <|body_start_0|>
group = handle.create_group('entry/data_processing')
group.attrs['num_reflections'] = len(reflections)
for key, data in reflections.cols():
self.encode_column(group, key, data)
<|end_body_0|>
<|body_start_1|>
from dials.array_family import flex
if is... | Encoder for the reflection data. | ReflectionListEncoder | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReflectionListEncoder:
"""Encoder for the reflection data."""
def encode(self, reflections, handle):
"""Encode the reflection data."""
<|body_0|>
def encode_column(self, group, key, data):
"""Encode a column of data."""
<|body_1|>
def encode_shoebox(... | stack_v2_sparse_classes_10k_train_000595 | 5,824 | permissive | [
{
"docstring": "Encode the reflection data.",
"name": "encode",
"signature": "def encode(self, reflections, handle)"
},
{
"docstring": "Encode a column of data.",
"name": "encode_column",
"signature": "def encode_column(self, group, key, data)"
},
{
"docstring": "Encode a column ... | 3 | stack_v2_sparse_classes_30k_train_004992 | Implement the Python class `ReflectionListEncoder` described below.
Class description:
Encoder for the reflection data.
Method signatures and docstrings:
- def encode(self, reflections, handle): Encode the reflection data.
- def encode_column(self, group, key, data): Encode a column of data.
- def encode_shoebox(self... | Implement the Python class `ReflectionListEncoder` described below.
Class description:
Encoder for the reflection data.
Method signatures and docstrings:
- def encode(self, reflections, handle): Encode the reflection data.
- def encode_column(self, group, key, data): Encode a column of data.
- def encode_shoebox(self... | 88bf7f7c5ac44defc046ebf0719cde748092cfff | <|skeleton|>
class ReflectionListEncoder:
"""Encoder for the reflection data."""
def encode(self, reflections, handle):
"""Encode the reflection data."""
<|body_0|>
def encode_column(self, group, key, data):
"""Encode a column of data."""
<|body_1|>
def encode_shoebox(... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ReflectionListEncoder:
"""Encoder for the reflection data."""
def encode(self, reflections, handle):
"""Encode the reflection data."""
group = handle.create_group('entry/data_processing')
group.attrs['num_reflections'] = len(reflections)
for key, data in reflections.cols()... | the_stack_v2_python_sparse | src/dials/util/nexus_old.py | dials/dials | train | 71 |
276fd56c742ca1ba7de4d4fd2a785853918cacac | [
"s = DynamicArrayStack()\nself.assertEqual(0, len(s))\nself.assertEqual(0, len(s._array))",
"s = DynamicArrayStack()\nself.assertEqual(0, len(s))\ns.push(1)\nself.assertEqual(1, len(s))\nself.assertEqual(1, len(s._array))\nself.assertEqual(1, s._array[0])\ns.push(StackEmptyException)\nself.assertEqual(2, len(s))\... | <|body_start_0|>
s = DynamicArrayStack()
self.assertEqual(0, len(s))
self.assertEqual(0, len(s._array))
<|end_body_0|>
<|body_start_1|>
s = DynamicArrayStack()
self.assertEqual(0, len(s))
s.push(1)
self.assertEqual(1, len(s))
self.assertEqual(1, len(s._ar... | TestDynamicArrayStack | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDynamicArrayStack:
def test_instantiation(self):
"""Test basic object creation."""
<|body_0|>
def test_push(self):
"""Test stack push operation."""
<|body_1|>
def test_pop(self):
"""Test stack pop operation."""
<|body_2|>
def tes... | stack_v2_sparse_classes_10k_train_000596 | 6,008 | no_license | [
{
"docstring": "Test basic object creation.",
"name": "test_instantiation",
"signature": "def test_instantiation(self)"
},
{
"docstring": "Test stack push operation.",
"name": "test_push",
"signature": "def test_push(self)"
},
{
"docstring": "Test stack pop operation.",
"name... | 4 | stack_v2_sparse_classes_30k_train_006637 | Implement the Python class `TestDynamicArrayStack` described below.
Class description:
Implement the TestDynamicArrayStack class.
Method signatures and docstrings:
- def test_instantiation(self): Test basic object creation.
- def test_push(self): Test stack push operation.
- def test_pop(self): Test stack pop operati... | Implement the Python class `TestDynamicArrayStack` described below.
Class description:
Implement the TestDynamicArrayStack class.
Method signatures and docstrings:
- def test_instantiation(self): Test basic object creation.
- def test_push(self): Test stack push operation.
- def test_pop(self): Test stack pop operati... | 66e553842998e22ee8ec4f9ebe901f76089128de | <|skeleton|>
class TestDynamicArrayStack:
def test_instantiation(self):
"""Test basic object creation."""
<|body_0|>
def test_push(self):
"""Test stack push operation."""
<|body_1|>
def test_pop(self):
"""Test stack pop operation."""
<|body_2|>
def tes... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestDynamicArrayStack:
def test_instantiation(self):
"""Test basic object creation."""
s = DynamicArrayStack()
self.assertEqual(0, len(s))
self.assertEqual(0, len(s._array))
def test_push(self):
"""Test stack push operation."""
s = DynamicArrayStack()
... | the_stack_v2_python_sparse | python/dsa/stacks_test.py | nehararora/practise-code | train | 0 | |
f322190a686c78c26c86198f03971c7d83184e43 | [
"makefile = stage / 'merlin' / self.makefile\nmarker = f'compiler settings'\nyield from super().generate(makefile=makefile, marker=marker, **kwds)",
"yield from super()._generate(builder=builder, **kwds)\nrenderer = builder.renderer\ncompilers = plexus.compilers\nfor compiler in compilers:\n language = compile... | <|body_start_0|>
makefile = stage / 'merlin' / self.makefile
marker = f'compiler settings'
yield from super().generate(makefile=makefile, marker=marker, **kwds)
<|end_body_0|>
<|body_start_1|>
yield from super()._generate(builder=builder, **kwds)
renderer = builder.renderer
... | The generator of the makefile with the compiler support | Compilers | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Compilers:
"""The generator of the makefile with the compiler support"""
def generate(self, stage, **kwds):
"""Generate my makefile"""
<|body_0|>
def _generate(self, plexus, builder, **kwds):
"""Build my contents"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_10k_train_000597 | 2,805 | permissive | [
{
"docstring": "Generate my makefile",
"name": "generate",
"signature": "def generate(self, stage, **kwds)"
},
{
"docstring": "Build my contents",
"name": "_generate",
"signature": "def _generate(self, plexus, builder, **kwds)"
}
] | 2 | null | Implement the Python class `Compilers` described below.
Class description:
The generator of the makefile with the compiler support
Method signatures and docstrings:
- def generate(self, stage, **kwds): Generate my makefile
- def _generate(self, plexus, builder, **kwds): Build my contents | Implement the Python class `Compilers` described below.
Class description:
The generator of the makefile with the compiler support
Method signatures and docstrings:
- def generate(self, stage, **kwds): Generate my makefile
- def _generate(self, plexus, builder, **kwds): Build my contents
<|skeleton|>
class Compilers... | d741c44ffb3e9e1f726bf492202ac8738bb4aa1c | <|skeleton|>
class Compilers:
"""The generator of the makefile with the compiler support"""
def generate(self, stage, **kwds):
"""Generate my makefile"""
<|body_0|>
def _generate(self, plexus, builder, **kwds):
"""Build my contents"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Compilers:
"""The generator of the makefile with the compiler support"""
def generate(self, stage, **kwds):
"""Generate my makefile"""
makefile = stage / 'merlin' / self.makefile
marker = f'compiler settings'
yield from super().generate(makefile=makefile, marker=marker, **... | the_stack_v2_python_sparse | packages/merlin/builders/make/Compilers.py | pyre/pyre | train | 27 |
f200a142c48d3fd1c792c6150aa8f9d2e7b830d9 | [
"if not matrix:\n return False\nmaxRowIndex = bisect.bisect_right([row[0] for row in matrix], target)\nmaxColIndex = bisect.bisect_right(matrix[0], target)\nfor ri in range(maxRowIndex):\n row = matrix[ri]\n if self.binary_search(row, 0, maxColIndex, target) != -1:\n return True\nreturn False",
"i... | <|body_start_0|>
if not matrix:
return False
maxRowIndex = bisect.bisect_right([row[0] for row in matrix], target)
maxColIndex = bisect.bisect_right(matrix[0], target)
for ri in range(maxRowIndex):
row = matrix[ri]
if self.binary_search(row, 0, maxColI... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchMatrix2(self, matrix, target):
"""268ms :type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrix3(self, matrix, target):
"""152ms 一行一行的进行二叉查找 如果第一个元素比target大,结束查找并返回False 每一行查找的有边界是上一行的最后一个小于target的元素的下标 :param m... | stack_v2_sparse_classes_10k_train_000598 | 3,455 | permissive | [
{
"docstring": "268ms :type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix2",
"signature": "def searchMatrix2(self, matrix, target)"
},
{
"docstring": "152ms 一行一行的进行二叉查找 如果第一个元素比target大,结束查找并返回False 每一行查找的有边界是上一行的最后一个小于target的元素的下标 :param matrix: :param target: :r... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix2(self, matrix, target): 268ms :type matrix: List[List[int]] :type target: int :rtype: bool
- def searchMatrix3(self, matrix, target): 152ms 一行一行的进行二叉查找 如果第一个元素比t... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix2(self, matrix, target): 268ms :type matrix: List[List[int]] :type target: int :rtype: bool
- def searchMatrix3(self, matrix, target): 152ms 一行一行的进行二叉查找 如果第一个元素比t... | 2830c7e2ada8dfd3dcdda7c06846116d4f944a27 | <|skeleton|>
class Solution:
def searchMatrix2(self, matrix, target):
"""268ms :type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrix3(self, matrix, target):
"""152ms 一行一行的进行二叉查找 如果第一个元素比target大,结束查找并返回False 每一行查找的有边界是上一行的最后一个小于target的元素的下标 :param m... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def searchMatrix2(self, matrix, target):
"""268ms :type matrix: List[List[int]] :type target: int :rtype: bool"""
if not matrix:
return False
maxRowIndex = bisect.bisect_right([row[0] for row in matrix], target)
maxColIndex = bisect.bisect_right(matrix[0],... | the_stack_v2_python_sparse | leetcode/medium/Search_a_2D_Matrix_II.py | shhuan/algorithms | train | 0 | |
452536988a1cb2311d0aa37ba05d1021bea91f2e | [
"if not host1:\n raise ValueError('No first host given for the disease')\nif not host2:\n raise ValueError('No second host given for the disease')\nif not disease_name:\n raise ValueError('No name given to the disease')\nself.host1 = host1\nself.host2 = host2\nself.disease_name = disease_name\nself.host1.d... | <|body_start_0|>
if not host1:
raise ValueError('No first host given for the disease')
if not host2:
raise ValueError('No second host given for the disease')
if not disease_name:
raise ValueError('No name given to the disease')
self.host1 = host1
... | BaseTwoSpeciesDisease | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseTwoSpeciesDisease:
def __init__(self, disease_name='', host1=None, host2=None):
"""todo :param host:"""
<|body_0|>
def count_nb_status_per_vertex(self, host, target_status, attribute_position='position'):
"""Count the number of agent having the targeted status in... | stack_v2_sparse_classes_10k_train_000599 | 1,818 | no_license | [
{
"docstring": "todo :param host:",
"name": "__init__",
"signature": "def __init__(self, disease_name='', host1=None, host2=None)"
},
{
"docstring": "Count the number of agent having the targeted status in each vertex. :param host: :param target_status: string in ['inf', 'con', 'imm'] :param att... | 2 | stack_v2_sparse_classes_30k_train_003541 | Implement the Python class `BaseTwoSpeciesDisease` described below.
Class description:
Implement the BaseTwoSpeciesDisease class.
Method signatures and docstrings:
- def __init__(self, disease_name='', host1=None, host2=None): todo :param host:
- def count_nb_status_per_vertex(self, host, target_status, attribute_pos... | Implement the Python class `BaseTwoSpeciesDisease` described below.
Class description:
Implement the BaseTwoSpeciesDisease class.
Method signatures and docstrings:
- def __init__(self, disease_name='', host1=None, host2=None): todo :param host:
- def count_nb_status_per_vertex(self, host, target_status, attribute_pos... | b12aa0e546e51a2cd751d6c08a34250a3bfe9607 | <|skeleton|>
class BaseTwoSpeciesDisease:
def __init__(self, disease_name='', host1=None, host2=None):
"""todo :param host:"""
<|body_0|>
def count_nb_status_per_vertex(self, host, target_status, attribute_position='position'):
"""Count the number of agent having the targeted status in... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BaseTwoSpeciesDisease:
def __init__(self, disease_name='', host1=None, host2=None):
"""todo :param host:"""
if not host1:
raise ValueError('No first host given for the disease')
if not host2:
raise ValueError('No second host given for the disease')
if no... | the_stack_v2_python_sparse | sampy/disease/two_species/base.py | em-ach/sampy | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.