blob_id
stringlengths
40
40
bodies
listlengths
2
6
bodies_text
stringlengths
196
6.73k
class_docstring
stringlengths
0
700
class_name
stringlengths
1
86
detected_licenses
listlengths
0
45
format_version
stringclasses
1 value
full_text
stringlengths
438
7.52k
id
stringlengths
40
40
length_bytes
int64
506
50k
license_type
stringclasses
2 values
methods
listlengths
2
6
n_methods
int64
2
6
original_id
stringlengths
38
40
prompt
stringlengths
153
4.25k
prompted_full_text
stringlengths
645
10.7k
revision_id
stringlengths
40
40
skeleton
stringlengths
162
4.34k
snapshot_name
stringclasses
1 value
snapshot_source_dir
stringclasses
1 value
solution
stringlengths
302
7.33k
source
stringclasses
1 value
source_path
stringlengths
4
177
source_repo
stringlengths
6
110
split
stringclasses
1 value
star_events_count
int64
0
209k
c0208317c3cd2e932e1a36395c7ead42cc35ab08
[ "if instance_id is None:\n instance_id = id(self)\nsuper().__init__('%s-%s' % (name, instance_id))\nself._proc = _BackgroundProcess(name, self)", "super().start(rusage)\nwith _bg_metrics_lock:\n _background_processes_active_since_last_scrape.add(self._proc)", "super().__exit__(type, value, traceback)\nwit...
<|body_start_0|> if instance_id is None: instance_id = id(self) super().__init__('%s-%s' % (name, instance_id)) self._proc = _BackgroundProcess(name, self) <|end_body_0|> <|body_start_1|> super().start(rusage) with _bg_metrics_lock: _background_processes_...
A logging context that tracks in flight metrics for background processes.
BackgroundProcessLoggingContext
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BackgroundProcessLoggingContext: """A logging context that tracks in flight metrics for background processes.""" def __init__(self, name: str, instance_id: Optional[Union[int, str]]=None): """Args: name: The name of the background process. Each distinct `name` gets a separate prometh...
stack_v2_sparse_classes_36k_train_032100
12,220
permissive
[ { "docstring": "Args: name: The name of the background process. Each distinct `name` gets a separate prometheus time series. instance_id: an identifer to add to `name` to distinguish this instance of the named background process in the logs. If this is `None`, one is made up based on id(self).", "name": "__...
3
null
Implement the Python class `BackgroundProcessLoggingContext` described below. Class description: A logging context that tracks in flight metrics for background processes. Method signatures and docstrings: - def __init__(self, name: str, instance_id: Optional[Union[int, str]]=None): Args: name: The name of the backgro...
Implement the Python class `BackgroundProcessLoggingContext` described below. Class description: A logging context that tracks in flight metrics for background processes. Method signatures and docstrings: - def __init__(self, name: str, instance_id: Optional[Union[int, str]]=None): Args: name: The name of the backgro...
d35bed8369514fe727b4fe1afb68f48cc8b2655a
<|skeleton|> class BackgroundProcessLoggingContext: """A logging context that tracks in flight metrics for background processes.""" def __init__(self, name: str, instance_id: Optional[Union[int, str]]=None): """Args: name: The name of the background process. Each distinct `name` gets a separate prometh...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BackgroundProcessLoggingContext: """A logging context that tracks in flight metrics for background processes.""" def __init__(self, name: str, instance_id: Optional[Union[int, str]]=None): """Args: name: The name of the background process. Each distinct `name` gets a separate prometheus time seri...
the_stack_v2_python_sparse
synapse/metrics/background_process_metrics.py
matrix-org/synapse
train
12,215
0eaff126a683866b8a16b515778bdc1fe2b8e949
[ "np.random.seed(seed)\nself.scale = scale\nif var is None:\n self.var = 10 ** (np.random.randn(ndim) * 1.5)\nelse:\n self.var = var\nif mu is None:\n self.mu = scipy.stats.norm(loc=0, scale=self.scale).rvs(ndim)\nelse:\n self.mu = mu", "if np.all(x < 500) and np.all(x > -500):\n return scipy.stats....
<|body_start_0|> np.random.seed(seed) self.scale = scale if var is None: self.var = 10 ** (np.random.randn(ndim) * 1.5) else: self.var = var if mu is None: self.mu = scipy.stats.norm(loc=0, scale=self.scale).rvs(ndim) else: ...
N-Dimensional Gaussian distribution with mu ~ Normal(0, 10) var ~ LogNormal(0, 1.5) Prior on mean is U(-500, 500)
MultidimensionalGaussianPosterior
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultidimensionalGaussianPosterior: """N-Dimensional Gaussian distribution with mu ~ Normal(0, 10) var ~ LogNormal(0, 1.5) Prior on mean is U(-500, 500)""" def __init__(self, ndim=2, seed=12345, scale=3, mu=None, var=None): """_summary_ Parameters ---------- ndim : int, optional _desc...
stack_v2_sparse_classes_36k_train_032101
14,651
permissive
[ { "docstring": "_summary_ Parameters ---------- ndim : int, optional _description_, by default 2 seed : int, optional _description_, by default 12345 scale : int, optional _description_, by default 10", "name": "__init__", "signature": "def __init__(self, ndim=2, seed=12345, scale=3, mu=None, var=None)"...
2
stack_v2_sparse_classes_30k_train_009495
Implement the Python class `MultidimensionalGaussianPosterior` described below. Class description: N-Dimensional Gaussian distribution with mu ~ Normal(0, 10) var ~ LogNormal(0, 1.5) Prior on mean is U(-500, 500) Method signatures and docstrings: - def __init__(self, ndim=2, seed=12345, scale=3, mu=None, var=None): _...
Implement the Python class `MultidimensionalGaussianPosterior` described below. Class description: N-Dimensional Gaussian distribution with mu ~ Normal(0, 10) var ~ LogNormal(0, 1.5) Prior on mean is U(-500, 500) Method signatures and docstrings: - def __init__(self, ndim=2, seed=12345, scale=3, mu=None, var=None): _...
5df233ea90aba16611d29c6a4b7717eb08ae7e09
<|skeleton|> class MultidimensionalGaussianPosterior: """N-Dimensional Gaussian distribution with mu ~ Normal(0, 10) var ~ LogNormal(0, 1.5) Prior on mean is U(-500, 500)""" def __init__(self, ndim=2, seed=12345, scale=3, mu=None, var=None): """_summary_ Parameters ---------- ndim : int, optional _desc...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MultidimensionalGaussianPosterior: """N-Dimensional Gaussian distribution with mu ~ Normal(0, 10) var ~ LogNormal(0, 1.5) Prior on mean is U(-500, 500)""" def __init__(self, ndim=2, seed=12345, scale=3, mu=None, var=None): """_summary_ Parameters ---------- ndim : int, optional _description_, by ...
the_stack_v2_python_sparse
manim_ml/diffusion/mcmc.py
helblazer811/ManimML
train
1,339
5cb10a7344a72eb9ab176a1bc5e4665e78299f14
[ "dao = self.repo.get(gsid)\ndao.enabled = True\nself.repo.persist_dao(dao)", "dao = self.repo.get(gsid)\ndao.enabled = False\nself.repo.persist_dao(dao)", "assert kind == 'totp', 'HOTP support is deprecated.'\nif self.finder.has_active_otp(kind, gsid) and (not force):\n raise self.OneTimePasswordActive()\nse...
<|body_start_0|> dao = self.repo.get(gsid) dao.enabled = True self.repo.persist_dao(dao) <|end_body_0|> <|body_start_1|> dao = self.repo.get(gsid) dao.enabled = False self.repo.persist_dao(dao) <|end_body_1|> <|body_start_2|> assert kind == 'totp', 'HOTP support...
Exposes an API to generate and verify One-Time Passwords (OTPs).
OneTimePasswordService
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OneTimePasswordService: """Exposes an API to generate and verify One-Time Passwords (OTPs).""" def enable(self, gsid): """Disables the TOTP for the **Subject** identified by `gsid`.""" <|body_0|> def disable(self, gsid): """Disables the TOTP for the **Subject** i...
stack_v2_sparse_classes_36k_train_032102
1,556
no_license
[ { "docstring": "Disables the TOTP for the **Subject** identified by `gsid`.", "name": "enable", "signature": "def enable(self, gsid)" }, { "docstring": "Disables the TOTP for the **Subject** identified by `gsid`.", "name": "disable", "signature": "def disable(self, gsid)" }, { "d...
3
stack_v2_sparse_classes_30k_train_014153
Implement the Python class `OneTimePasswordService` described below. Class description: Exposes an API to generate and verify One-Time Passwords (OTPs). Method signatures and docstrings: - def enable(self, gsid): Disables the TOTP for the **Subject** identified by `gsid`. - def disable(self, gsid): Disables the TOTP ...
Implement the Python class `OneTimePasswordService` described below. Class description: Exposes an API to generate and verify One-Time Passwords (OTPs). Method signatures and docstrings: - def enable(self, gsid): Disables the TOTP for the **Subject** identified by `gsid`. - def disable(self, gsid): Disables the TOTP ...
6c97ae544444e90753e375ecc68f25534d97764a
<|skeleton|> class OneTimePasswordService: """Exposes an API to generate and verify One-Time Passwords (OTPs).""" def enable(self, gsid): """Disables the TOTP for the **Subject** identified by `gsid`.""" <|body_0|> def disable(self, gsid): """Disables the TOTP for the **Subject** i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OneTimePasswordService: """Exposes an API to generate and verify One-Time Passwords (OTPs).""" def enable(self, gsid): """Disables the TOTP for the **Subject** identified by `gsid`.""" dao = self.repo.get(gsid) dao.enabled = True self.repo.persist_dao(dao) def disable...
the_stack_v2_python_sparse
safi/app/services/onetimepassword/impl.py
wizardsofindustry/quantum-safi
train
0
ffeffc1a88b7c63ca777c6c62936f3cd1e974fc0
[ "self._num_classes = num_classes\nself._mask_target_size = mask_target_size\nself._num_convs = num_convs\nself._num_filters = num_filters\nif use_separable_conv:\n self._conv2d_op = functools.partial(tf.keras.layers.SeparableConv2D, depth_multiplier=1, bias_initializer=tf.zeros_initializer())\nelse:\n self._c...
<|body_start_0|> self._num_classes = num_classes self._mask_target_size = mask_target_size self._num_convs = num_convs self._num_filters = num_filters if use_separable_conv: self._conv2d_op = functools.partial(tf.keras.layers.SeparableConv2D, depth_multiplier=1, bias_...
Mask R-CNN head.
MaskrcnnHead
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MaskrcnnHead: """Mask R-CNN head.""" def __init__(self, num_classes, mask_target_size, num_convs=4, num_filters=256, use_separable_conv=False, activation='relu', use_batch_norm=True, norm_activation=nn_ops.norm_activation_builder(activation='relu')): """Initialize params to build Fas...
stack_v2_sparse_classes_36k_train_032103
45,524
permissive
[ { "docstring": "Initialize params to build Fast R-CNN head. Args: num_classes: a integer for the number of classes. mask_target_size: a integer that is the resolution of masks. num_convs: `int` number that represents the number of the intermediate conv layers before the prediction. num_filters: `int` number tha...
2
stack_v2_sparse_classes_30k_train_007277
Implement the Python class `MaskrcnnHead` described below. Class description: Mask R-CNN head. Method signatures and docstrings: - def __init__(self, num_classes, mask_target_size, num_convs=4, num_filters=256, use_separable_conv=False, activation='relu', use_batch_norm=True, norm_activation=nn_ops.norm_activation_bu...
Implement the Python class `MaskrcnnHead` described below. Class description: Mask R-CNN head. Method signatures and docstrings: - def __init__(self, num_classes, mask_target_size, num_convs=4, num_filters=256, use_separable_conv=False, activation='relu', use_batch_norm=True, norm_activation=nn_ops.norm_activation_bu...
965cc3eef54a3a173a2347fe0059a35f1e5f2496
<|skeleton|> class MaskrcnnHead: """Mask R-CNN head.""" def __init__(self, num_classes, mask_target_size, num_convs=4, num_filters=256, use_separable_conv=False, activation='relu', use_batch_norm=True, norm_activation=nn_ops.norm_activation_builder(activation='relu')): """Initialize params to build Fas...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MaskrcnnHead: """Mask R-CNN head.""" def __init__(self, num_classes, mask_target_size, num_convs=4, num_filters=256, use_separable_conv=False, activation='relu', use_batch_norm=True, norm_activation=nn_ops.norm_activation_builder(activation='relu')): """Initialize params to build Fast R-CNN head....
the_stack_v2_python_sparse
official/vision/detection/modeling/architecture/heads.py
ayushmankumar7/models
train
4
c5a33049dbadecbe7038f6ad4e9d102e76117904
[ "request = kwargs['request']\nif request_from_master(request):\n config.master_contacted()\ntry:\n current_assignments = config['current_assignments'].itervalues\nexcept AttributeError:\n current_assignments = config['current_assignments'].values\ntasks = []\nfor assignment in current_assignments():\n t...
<|body_start_0|> request = kwargs['request'] if request_from_master(request): config.master_contacted() try: current_assignments = config['current_assignments'].itervalues except AttributeError: current_assignments = config['current_assignments'].value...
Tasks
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Tasks: def get(self, **kwargs): """Returns all tasks which are currently being processed locally by the agent. .. http:get:: /api/v1/tasks/ HTTP/1.1 **Request** .. sourcecode:: http GET /api/v1/tasks/ HTTP/1.1 **Response** .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/js...
stack_v2_sparse_classes_36k_train_032104
5,070
permissive
[ { "docstring": "Returns all tasks which are currently being processed locally by the agent. .. http:get:: /api/v1/tasks/ HTTP/1.1 **Request** .. sourcecode:: http GET /api/v1/tasks/ HTTP/1.1 **Response** .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/json [{ \"id\": \"732c1ef0-9488-4914-adef-c29...
2
stack_v2_sparse_classes_30k_train_002951
Implement the Python class `Tasks` described below. Class description: Implement the Tasks class. Method signatures and docstrings: - def get(self, **kwargs): Returns all tasks which are currently being processed locally by the agent. .. http:get:: /api/v1/tasks/ HTTP/1.1 **Request** .. sourcecode:: http GET /api/v1/...
Implement the Python class `Tasks` described below. Class description: Implement the Tasks class. Method signatures and docstrings: - def get(self, **kwargs): Returns all tasks which are currently being processed locally by the agent. .. http:get:: /api/v1/tasks/ HTTP/1.1 **Request** .. sourcecode:: http GET /api/v1/...
aa87504ab8679db0ed8da4818729b8e5fc1c0ecb
<|skeleton|> class Tasks: def get(self, **kwargs): """Returns all tasks which are currently being processed locally by the agent. .. http:get:: /api/v1/tasks/ HTTP/1.1 **Request** .. sourcecode:: http GET /api/v1/tasks/ HTTP/1.1 **Response** .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/js...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Tasks: def get(self, **kwargs): """Returns all tasks which are currently being processed locally by the agent. .. http:get:: /api/v1/tasks/ HTTP/1.1 **Request** .. sourcecode:: http GET /api/v1/tasks/ HTTP/1.1 **Response** .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/json [{ "id": "7...
the_stack_v2_python_sparse
pyfarm/agent/http/api/tasks.py
pyfarm/pyfarm-agent
train
1
ed41bfc5515008d62eee2b4e11ec55f39c8710c4
[ "query = request.GET.get('q')\nsort = request.GET.get('sort', 'name')\nasearch = Asignacion.objects.filter(server=kwargs['id']).first()\nform = AsignacionForm(instance=asearch)\nlist_asignacion = Asignacion.objects.filter(server=kwargs['id'])\nlist_server = Server.objects.filter(id=kwargs['id'])\nlist_client = Asig...
<|body_start_0|> query = request.GET.get('q') sort = request.GET.get('sort', 'name') asearch = Asignacion.objects.filter(server=kwargs['id']).first() form = AsignacionForm(instance=asearch) list_asignacion = Asignacion.objects.filter(server=kwargs['id']) list_server = Ser...
Clase para ver los detalles del servidor
ServerDetailView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ServerDetailView: """Clase para ver los detalles del servidor""" def get(self, request, *args, **kwargs): """Método get""" <|body_0|> def post(self, request, *args, **kwargs): """Método post""" <|body_1|> <|end_skeleton|> <|body_start_0|> query ...
stack_v2_sparse_classes_36k_train_032105
22,221
no_license
[ { "docstring": "Método get", "name": "get", "signature": "def get(self, request, *args, **kwargs)" }, { "docstring": "Método post", "name": "post", "signature": "def post(self, request, *args, **kwargs)" } ]
2
stack_v2_sparse_classes_30k_train_016538
Implement the Python class `ServerDetailView` described below. Class description: Clase para ver los detalles del servidor Method signatures and docstrings: - def get(self, request, *args, **kwargs): Método get - def post(self, request, *args, **kwargs): Método post
Implement the Python class `ServerDetailView` described below. Class description: Clase para ver los detalles del servidor Method signatures and docstrings: - def get(self, request, *args, **kwargs): Método get - def post(self, request, *args, **kwargs): Método post <|skeleton|> class ServerDetailView: """Clase ...
e28e2d968372609ad396c42fb572a00c2410a117
<|skeleton|> class ServerDetailView: """Clase para ver los detalles del servidor""" def get(self, request, *args, **kwargs): """Método get""" <|body_0|> def post(self, request, *args, **kwargs): """Método post""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ServerDetailView: """Clase para ver los detalles del servidor""" def get(self, request, *args, **kwargs): """Método get""" query = request.GET.get('q') sort = request.GET.get('sort', 'name') asearch = Asignacion.objects.filter(server=kwargs['id']).first() form = As...
the_stack_v2_python_sparse
list/views.py
damaos/server_list2
train
0
69b3a9aa9741fa2569400bf19628514633465aab
[ "super().__init__()\nself.cost_classes = cost_classes\nself.cost_segments = cost_segments\nself.cost_diou = cost_diou\nassert cost_classes != 0 or cost_segments != 0 or cost_diou != 0, 'all costs cant be 0'", "bs, num_queries = outputs['classes'].shape[:2]\nout_classes = outputs['classes'].flatten(0, 1).softmax(-...
<|body_start_0|> super().__init__() self.cost_classes = cost_classes self.cost_segments = cost_segments self.cost_diou = cost_diou assert cost_classes != 0 or cost_segments != 0 or cost_diou != 0, 'all costs cant be 0' <|end_body_0|> <|body_start_1|> bs, num_queries = ou...
This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predictions, while the others are un-matched (...
HungarianMatcher
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HungarianMatcher: """This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case, we do a 1-to-1 matching of the best pr...
stack_v2_sparse_classes_36k_train_032106
4,544
no_license
[ { "docstring": "Creates the matcher Params: cost_classes: This is the relative weight of the classification error in the matching cost cost_segments: This is the relative weight of the L1 error of the bounding box coordinates in the matching cost cost_diou: This is the relative weight of the giou loss of the bo...
2
stack_v2_sparse_classes_30k_train_018849
Implement the Python class `HungarianMatcher` described below. Class description: This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case,...
Implement the Python class `HungarianMatcher` described below. Class description: This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case,...
11337eab8ff3f5c79b8e7aa5ea7bdfc704785b38
<|skeleton|> class HungarianMatcher: """This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case, we do a 1-to-1 matching of the best pr...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HungarianMatcher: """This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predictions, wh...
the_stack_v2_python_sparse
src/models/detr/matcher.py
BianbBb/EventDetection
train
0
c49036d4a5743be390154fa3ed40305ca6d8947d
[ "event = {'current_location': (CourseURL('http://a/b/'), '2013-11-10 06:43:41'), 'time': '2013-12-10 06:44:00', 'page': ''}\nexpected_event = {'current_location': (CourseURL('http://a/b/'), '2013-11-10 06:43:41'), 'time': '2013-12-10 06:44:00', 'page': '', 'inherited': ''}\nno_url(event)\nself.assertEqual(expected_...
<|body_start_0|> event = {'current_location': (CourseURL('http://a/b/'), '2013-11-10 06:43:41'), 'time': '2013-12-10 06:44:00', 'page': ''} expected_event = {'current_location': (CourseURL('http://a/b/'), '2013-11-10 06:43:41'), 'time': '2013-12-10 06:44:00', 'page': '', 'inherited': ''} no_url(...
Tester for the inheritloc functions
InheritLocTest
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InheritLocTest: """Tester for the inheritloc functions""" def test_no_url_no_inheritance(self): """Test the no_url function with an event that should not inherit a url.""" <|body_0|> def test_no_url_yes_inheritance(self): """Test the no_url function with an event...
stack_v2_sparse_classes_36k_train_032107
3,026
permissive
[ { "docstring": "Test the no_url function with an event that should not inherit a url.", "name": "test_no_url_no_inheritance", "signature": "def test_no_url_no_inheritance(self)" }, { "docstring": "Test the no_url function with an event that should inherit a url.", "name": "test_no_url_yes_in...
3
stack_v2_sparse_classes_30k_train_019501
Implement the Python class `InheritLocTest` described below. Class description: Tester for the inheritloc functions Method signatures and docstrings: - def test_no_url_no_inheritance(self): Test the no_url function with an event that should not inherit a url. - def test_no_url_yes_inheritance(self): Test the no_url f...
Implement the Python class `InheritLocTest` described below. Class description: Tester for the inheritloc functions Method signatures and docstrings: - def test_no_url_no_inheritance(self): Test the no_url function with an event that should not inherit a url. - def test_no_url_yes_inheritance(self): Test the no_url f...
ad5ae27476c1dc02b1a06d2d90d4c8b7ada97c02
<|skeleton|> class InheritLocTest: """Tester for the inheritloc functions""" def test_no_url_no_inheritance(self): """Test the no_url function with an event that should not inherit a url.""" <|body_0|> def test_no_url_yes_inheritance(self): """Test the no_url function with an event...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InheritLocTest: """Tester for the inheritloc functions""" def test_no_url_no_inheritance(self): """Test the no_url function with an event that should not inherit a url.""" event = {'current_location': (CourseURL('http://a/b/'), '2013-11-10 06:43:41'), 'time': '2013-12-10 06:44:00', 'page'...
the_stack_v2_python_sparse
edx_pipe/qpipe/inheritloc_test.py
johnding1996/MOOC-Learner-Curated
train
0
5368d96683e21ee297c4b244d41eca1bf0a81336
[ "url = conf.get(_CFG_URL)\nport = conf.get(_CFG_PORT)\ncert_path = conf.get(_CFG_CERT_PATH)\nlog.debug(\"Using config '%s' = '%s'\", _CFG_URL, url)\nlog.debug(\"Using config '%s' = '%s'\", _CFG_PORT, port)\nlog.debug(\"Using config '%s' = '%s'\", _CFG_CERT_PATH, cert_path)\noptions = load_certificates(url, cert_pat...
<|body_start_0|> url = conf.get(_CFG_URL) port = conf.get(_CFG_PORT) cert_path = conf.get(_CFG_CERT_PATH) log.debug("Using config '%s' = '%s'", _CFG_URL, url) log.debug("Using config '%s' = '%s'", _CFG_PORT, port) log.debug("Using config '%s' = '%s'", _CFG_CERT_PATH, cert...
Provides an API to communicate with CyberArk.
CyberArkClient
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CyberArkClient: """Provides an API to communicate with CyberArk.""" def from_dict(conf): """Returns a new CyberArkClient object. :param conf: Contains the CyberArk configuration data :type conf: A dict-like object providing the 'get' method.""" <|body_0|> def __init__(se...
stack_v2_sparse_classes_36k_train_032108
16,014
no_license
[ { "docstring": "Returns a new CyberArkClient object. :param conf: Contains the CyberArk configuration data :type conf: A dict-like object providing the 'get' method.", "name": "from_dict", "signature": "def from_dict(conf)" }, { "docstring": "Initializes a CyberArkClient instance. :param str url...
3
null
Implement the Python class `CyberArkClient` described below. Class description: Provides an API to communicate with CyberArk. Method signatures and docstrings: - def from_dict(conf): Returns a new CyberArkClient object. :param conf: Contains the CyberArk configuration data :type conf: A dict-like object providing the...
Implement the Python class `CyberArkClient` described below. Class description: Provides an API to communicate with CyberArk. Method signatures and docstrings: - def from_dict(conf): Returns a new CyberArkClient object. :param conf: Contains the CyberArk configuration data :type conf: A dict-like object providing the...
1ea508c3d2b51742bc3b448c445cd0a3dba9e798
<|skeleton|> class CyberArkClient: """Provides an API to communicate with CyberArk.""" def from_dict(conf): """Returns a new CyberArkClient object. :param conf: Contains the CyberArk configuration data :type conf: A dict-like object providing the 'get' method.""" <|body_0|> def __init__(se...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CyberArkClient: """Provides an API to communicate with CyberArk.""" def from_dict(conf): """Returns a new CyberArkClient object. :param conf: Contains the CyberArk configuration data :type conf: A dict-like object providing the 'get' method.""" url = conf.get(_CFG_URL) port = conf...
the_stack_v2_python_sparse
Products/ZenCollector/cyberark.py
zenoss/zenoss-prodbin
train
27
4426b5e70ae0d8dc5d3c3366c1d3be8d8770d09e
[ "logging.Formatter.__init__(self, fmt, datefmt)\nself.technicolor = technicolor\nself._isatty = sys.stderr.isatty()", "if record.levelno == logging.INFO:\n msg = logging.Formatter.format(self, record)\n return msg\nif self.technicolor and self._isatty:\n colour = self.LEVEL_COLOURS[record.levelno]\n b...
<|body_start_0|> logging.Formatter.__init__(self, fmt, datefmt) self.technicolor = technicolor self._isatty = sys.stderr.isatty() <|end_body_0|> <|body_start_1|> if record.levelno == logging.INFO: msg = logging.Formatter.format(self, record) return msg if...
Intelligent and pretty log formatting. Colourise output to a TTY and prepend logging level name to levels other than INFO.
TechnicolorFormatter
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TechnicolorFormatter: """Intelligent and pretty log formatting. Colourise output to a TTY and prepend logging level name to levels other than INFO.""" def __init__(self, fmt=None, datefmt=None, technicolor=True): """Create new Formatter. Args: fmt (str): A `logging.Formatter` format ...
stack_v2_sparse_classes_36k_train_032109
9,687
permissive
[ { "docstring": "Create new Formatter. Args: fmt (str): A `logging.Formatter` format string. datefmt (str): `strftime` format string. technicolor (bool): Colourise TTY output?", "name": "__init__", "signature": "def __init__(self, fmt=None, datefmt=None, technicolor=True)" }, { "docstring": "Form...
3
stack_v2_sparse_classes_30k_train_014601
Implement the Python class `TechnicolorFormatter` described below. Class description: Intelligent and pretty log formatting. Colourise output to a TTY and prepend logging level name to levels other than INFO. Method signatures and docstrings: - def __init__(self, fmt=None, datefmt=None, technicolor=True): Create new ...
Implement the Python class `TechnicolorFormatter` described below. Class description: Intelligent and pretty log formatting. Colourise output to a TTY and prepend logging level name to levels other than INFO. Method signatures and docstrings: - def __init__(self, fmt=None, datefmt=None, technicolor=True): Create new ...
665d39a2bd82543d5196555f0801ef8fd4a3ee48
<|skeleton|> class TechnicolorFormatter: """Intelligent and pretty log formatting. Colourise output to a TTY and prepend logging level name to levels other than INFO.""" def __init__(self, fmt=None, datefmt=None, technicolor=True): """Create new Formatter. Args: fmt (str): A `logging.Formatter` format ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TechnicolorFormatter: """Intelligent and pretty log formatting. Colourise output to a TTY and prepend logging level name to levels other than INFO.""" def __init__(self, fmt=None, datefmt=None, technicolor=True): """Create new Formatter. Args: fmt (str): A `logging.Formatter` format string. datef...
the_stack_v2_python_sparse
all-gists/b16f018119ef3fe951af/snippet.py
gistable/gistable
train
76
b4bb2d1df7ae79a7abf22b6b0af7b6f4050ac5f6
[ "try:\n return_data = ''\n return Response(json.dumps(return_data))\nexcept Exception as e:\n return_data = {'status': '404', 'result': str(e)}\n return Response(json.dumps(return_data))", "try:\n return_data = ''\n return Response(json.dumps(return_data))\nexcept Exception as e:\n return_dat...
<|body_start_0|> try: return_data = '' return Response(json.dumps(return_data)) except Exception as e: return_data = {'status': '404', 'result': str(e)} return Response(json.dumps(return_data)) <|end_body_0|> <|body_start_1|> try: retu...
RunManagerSchedule
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RunManagerSchedule: def post(self, request, nnid): """Training Job schedule management We have predefined set of graph flow.. on Scheduler you can set a schedule this graph flow run on exact time. (everyday 1pm, every 5hours ... somting like this) So that we can feed new data and update ...
stack_v2_sparse_classes_36k_train_032110
3,545
permissive
[ { "docstring": "Training Job schedule management We have predefined set of graph flow.. on Scheduler you can set a schedule this graph flow run on exact time. (everyday 1pm, every 5hours ... somting like this) So that we can feed new data and update model automatically --- # Class Name : RunManagerSchedule # De...
4
null
Implement the Python class `RunManagerSchedule` described below. Class description: Implement the RunManagerSchedule class. Method signatures and docstrings: - def post(self, request, nnid): Training Job schedule management We have predefined set of graph flow.. on Scheduler you can set a schedule this graph flow run...
Implement the Python class `RunManagerSchedule` described below. Class description: Implement the RunManagerSchedule class. Method signatures and docstrings: - def post(self, request, nnid): Training Job schedule management We have predefined set of graph flow.. on Scheduler you can set a schedule this graph flow run...
6ad2fbc7384e4dbe7e3e63bdb44c8ce0387f4b7f
<|skeleton|> class RunManagerSchedule: def post(self, request, nnid): """Training Job schedule management We have predefined set of graph flow.. on Scheduler you can set a schedule this graph flow run on exact time. (everyday 1pm, every 5hours ... somting like this) So that we can feed new data and update ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RunManagerSchedule: def post(self, request, nnid): """Training Job schedule management We have predefined set of graph flow.. on Scheduler you can set a schedule this graph flow run on exact time. (everyday 1pm, every 5hours ... somting like this) So that we can feed new data and update model automati...
the_stack_v2_python_sparse
api/views/runmanager_schedule.py
yurimkoo/tensormsa
train
1
4e81a90244c89798331ba754fe5de81a329c88ba
[ "res = super(event_registration, self).confirm_registration(cr, uid, ids, context=context)\nmoodle_pool = self.pool.get('event.moodle.config.wiz')\nmoodle_config_wiz_id = moodle_pool.find(cr, uid, context=context)\nfor register in self.browse(cr, uid, ids, context=context):\n if register.event_id.state == 'confi...
<|body_start_0|> res = super(event_registration, self).confirm_registration(cr, uid, ids, context=context) moodle_pool = self.pool.get('event.moodle.config.wiz') moodle_config_wiz_id = moodle_pool.find(cr, uid, context=context) for register in self.browse(cr, uid, ids, context=context): ...
event_registration
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class event_registration: def confirm_registration(self, cr, uid, ids, context=None): """create a user and match to a course if the event is already confirmed""" <|body_0|> def onchange_moodle_name(self, cr, uid, ids, moodle_username, context=None): """This onchange receiv...
stack_v2_sparse_classes_36k_train_032111
13,266
no_license
[ { "docstring": "create a user and match to a course if the event is already confirmed", "name": "confirm_registration", "signature": "def confirm_registration(self, cr, uid, ids, context=None)" }, { "docstring": "This onchange receive as parameter a username moddle and will fill the moodle_uid a...
2
null
Implement the Python class `event_registration` described below. Class description: Implement the event_registration class. Method signatures and docstrings: - def confirm_registration(self, cr, uid, ids, context=None): create a user and match to a course if the event is already confirmed - def onchange_moodle_name(s...
Implement the Python class `event_registration` described below. Class description: Implement the event_registration class. Method signatures and docstrings: - def confirm_registration(self, cr, uid, ids, context=None): create a user and match to a course if the event is already confirmed - def onchange_moodle_name(s...
e6b06ea17fa44e35e3c99a83c6f3ec433c33c894
<|skeleton|> class event_registration: def confirm_registration(self, cr, uid, ids, context=None): """create a user and match to a course if the event is already confirmed""" <|body_0|> def onchange_moodle_name(self, cr, uid, ids, moodle_username, context=None): """This onchange receiv...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class event_registration: def confirm_registration(self, cr, uid, ids, context=None): """create a user and match to a course if the event is already confirmed""" res = super(event_registration, self).confirm_registration(cr, uid, ids, context=context) moodle_pool = self.pool.get('event.moodl...
the_stack_v2_python_sparse
event_moodle/event_moodle.py
rvalyi/openerp-addons
train
2
f16c84514defbbc1319eead11515ff60d318300d
[ "if interp not in {'linear', 'nearest'}:\n raise ValueError('interp must be one of {linear, nearest}')\nself.translation = list(translation)\nself.reference = reference\nself.interp = interp", "if X.pixeltype != 'float':\n raise ValueError('image.pixeltype must be float ... use TypeCast transform or clone t...
<|body_start_0|> if interp not in {'linear', 'nearest'}: raise ValueError('interp must be one of {linear, nearest}') self.translation = list(translation) self.reference = reference self.interp = interp <|end_body_0|> <|body_start_1|> if X.pixeltype != 'float': ...
Translate an image in physical space. This function calls highly optimized ITK/C++ code.
TranslateImage
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TranslateImage: """Translate an image in physical space. This function calls highly optimized ITK/C++ code.""" def __init__(self, translation, reference=None, interp='linear'): """Initialize a TranslateImage transform Arguments --------- translation : list, tuple, or numpy.ndarray ab...
stack_v2_sparse_classes_36k_train_032112
24,297
permissive
[ { "docstring": "Initialize a TranslateImage transform Arguments --------- translation : list, tuple, or numpy.ndarray absolute pixel transformation in each axis reference : ANTsImage (optional) image which provides the reference physical space in which to perform the transform interp : string type of interpolat...
2
null
Implement the Python class `TranslateImage` described below. Class description: Translate an image in physical space. This function calls highly optimized ITK/C++ code. Method signatures and docstrings: - def __init__(self, translation, reference=None, interp='linear'): Initialize a TranslateImage transform Arguments...
Implement the Python class `TranslateImage` described below. Class description: Translate an image in physical space. This function calls highly optimized ITK/C++ code. Method signatures and docstrings: - def __init__(self, translation, reference=None, interp='linear'): Initialize a TranslateImage transform Arguments...
41f2dd3fcf72654f284dac1a9448033e963f0afb
<|skeleton|> class TranslateImage: """Translate an image in physical space. This function calls highly optimized ITK/C++ code.""" def __init__(self, translation, reference=None, interp='linear'): """Initialize a TranslateImage transform Arguments --------- translation : list, tuple, or numpy.ndarray ab...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TranslateImage: """Translate an image in physical space. This function calls highly optimized ITK/C++ code.""" def __init__(self, translation, reference=None, interp='linear'): """Initialize a TranslateImage transform Arguments --------- translation : list, tuple, or numpy.ndarray absolute pixel ...
the_stack_v2_python_sparse
ants/contrib/sampling/transforms.py
ANTsX/ANTsPy
train
483
6a7f18cc07ca7e0724fc6d87bed510cdfc5778ad
[ "self.click_(self.loc_paihangbang)\nresult_1 = self.is_element_Exist(self.loc_dy_Day_1)\nresult_2 = self.is_element_Exist(self.loc_dy_Day_2)\nresult_3 = self.is_element_Exist(self.loc_dy_Day_3)\nif result_1 and result_2 and result_3:\n return True\nelse:\n return False", "self.click_(self.loc_Week)\nself.cl...
<|body_start_0|> self.click_(self.loc_paihangbang) result_1 = self.is_element_Exist(self.loc_dy_Day_1) result_2 = self.is_element_Exist(self.loc_dy_Day_2) result_3 = self.is_element_Exist(self.loc_dy_Day_3) if result_1 and result_2 and result_3: return True el...
学习-学习排行榜
Ranking_List
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Ranking_List: """学习-学习排行榜""" def day(self): """学习排行榜-Day""" <|body_0|> def week(self): """学习排行榜-Week""" <|body_1|> def month(self): """学习排行榜-Month""" <|body_2|> <|end_skeleton|> <|body_start_0|> self.click_(self.loc_paihangb...
stack_v2_sparse_classes_36k_train_032113
3,460
no_license
[ { "docstring": "学习排行榜-Day", "name": "day", "signature": "def day(self)" }, { "docstring": "学习排行榜-Week", "name": "week", "signature": "def week(self)" }, { "docstring": "学习排行榜-Month", "name": "month", "signature": "def month(self)" } ]
3
stack_v2_sparse_classes_30k_val_000384
Implement the Python class `Ranking_List` described below. Class description: 学习-学习排行榜 Method signatures and docstrings: - def day(self): 学习排行榜-Day - def week(self): 学习排行榜-Week - def month(self): 学习排行榜-Month
Implement the Python class `Ranking_List` described below. Class description: 学习-学习排行榜 Method signatures and docstrings: - def day(self): 学习排行榜-Day - def week(self): 学习排行榜-Week - def month(self): 学习排行榜-Month <|skeleton|> class Ranking_List: """学习-学习排行榜""" def day(self): """学习排行榜-Day""" <|bod...
9d8ad54fc982d3b2f8244e439705bcfee12ebd0c
<|skeleton|> class Ranking_List: """学习-学习排行榜""" def day(self): """学习排行榜-Day""" <|body_0|> def week(self): """学习排行榜-Week""" <|body_1|> def month(self): """学习排行榜-Month""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Ranking_List: """学习-学习排行榜""" def day(self): """学习排行榜-Day""" self.click_(self.loc_paihangbang) result_1 = self.is_element_Exist(self.loc_dy_Day_1) result_2 = self.is_element_Exist(self.loc_dy_Day_2) result_3 = self.is_element_Exist(self.loc_dy_Day_3) if resu...
the_stack_v2_python_sparse
wyt/page/ranking_list.py
mengmengxidi/wyt-APP-Automation-code
train
0
5f22af9a5bdcbd5cdec51e744c1f7117ba3c64b3
[ "slower = head\nfaster = head\nwhile faster and faster.next:\n slower = slower.next\n faster = faster.next.next\n if faster == slower:\n return True\nreturn False", "listSet = set()\nwhile head:\n if head == None:\n return False\n elif head in listSet:\n return True\n else:\...
<|body_start_0|> slower = head faster = head while faster and faster.next: slower = slower.next faster = faster.next.next if faster == slower: return True return False <|end_body_0|> <|body_start_1|> listSet = set() whi...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def hasCycle(self, head): """:type head: ListNode :rtype: bool""" <|body_0|> def hasCycle1(self, head): """:type head: ListNode :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> slower = head faster = head while ...
stack_v2_sparse_classes_36k_train_032114
1,012
no_license
[ { "docstring": ":type head: ListNode :rtype: bool", "name": "hasCycle", "signature": "def hasCycle(self, head)" }, { "docstring": ":type head: ListNode :rtype: bool", "name": "hasCycle1", "signature": "def hasCycle1(self, head)" } ]
2
stack_v2_sparse_classes_30k_train_001655
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def hasCycle(self, head): :type head: ListNode :rtype: bool - def hasCycle1(self, head): :type head: ListNode :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def hasCycle(self, head): :type head: ListNode :rtype: bool - def hasCycle1(self, head): :type head: ListNode :rtype: bool <|skeleton|> class Solution: def hasCycle(self, h...
639f4686308522d59cd8b818247d70ce57dc5c10
<|skeleton|> class Solution: def hasCycle(self, head): """:type head: ListNode :rtype: bool""" <|body_0|> def hasCycle1(self, head): """:type head: ListNode :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def hasCycle(self, head): """:type head: ListNode :rtype: bool""" slower = head faster = head while faster and faster.next: slower = slower.next faster = faster.next.next if faster == slower: return True retu...
the_stack_v2_python_sparse
src/141. Linked List Cycle.py
YoungXueya/LeetcodeSolution
train
0
d295aaa08b9473ce8f33ee75624d17147a66fbac
[ "for addr, comment in comments.items():\n db_comment = session.query(DbComment).filter_by(kb=db_kb, addr=addr).scalar()\n if db_comment is not None:\n if comment == db_comment.comment:\n continue\n db_comment.comment = comment\n else:\n db_comment = DbComment(kb=db_kb, addr=...
<|body_start_0|> for addr, comment in comments.items(): db_comment = session.query(DbComment).filter_by(kb=db_kb, addr=addr).scalar() if db_comment is not None: if comment == db_comment.comment: continue db_comment.comment = comment ...
Serialize/unserialize comments to/from a database session.
CommentsSerializer
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CommentsSerializer: """Serialize/unserialize comments to/from a database session.""" def dump(session, db_kb, comments): """:param session: :param DbKnowledgeBase db_kb: :param Comments comments: :return: None""" <|body_0|> def load(session, db_kb, kb): """:param...
stack_v2_sparse_classes_36k_train_032115
1,531
permissive
[ { "docstring": ":param session: :param DbKnowledgeBase db_kb: :param Comments comments: :return: None", "name": "dump", "signature": "def dump(session, db_kb, comments)" }, { "docstring": ":param session: :param DbKnowledgeBase db_kb: :param KnowledgeBase kb: :return:", "name": "load", "...
2
stack_v2_sparse_classes_30k_train_005019
Implement the Python class `CommentsSerializer` described below. Class description: Serialize/unserialize comments to/from a database session. Method signatures and docstrings: - def dump(session, db_kb, comments): :param session: :param DbKnowledgeBase db_kb: :param Comments comments: :return: None - def load(sessio...
Implement the Python class `CommentsSerializer` described below. Class description: Serialize/unserialize comments to/from a database session. Method signatures and docstrings: - def dump(session, db_kb, comments): :param session: :param DbKnowledgeBase db_kb: :param Comments comments: :return: None - def load(sessio...
37e8ca1c3308ec601ad1d7c6bc8081ff38a7cffd
<|skeleton|> class CommentsSerializer: """Serialize/unserialize comments to/from a database session.""" def dump(session, db_kb, comments): """:param session: :param DbKnowledgeBase db_kb: :param Comments comments: :return: None""" <|body_0|> def load(session, db_kb, kb): """:param...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CommentsSerializer: """Serialize/unserialize comments to/from a database session.""" def dump(session, db_kb, comments): """:param session: :param DbKnowledgeBase db_kb: :param Comments comments: :return: None""" for addr, comment in comments.items(): db_comment = session.quer...
the_stack_v2_python_sparse
angr/angrdb/serializers/comments.py
angr/angr
train
7,184
07e661ead5350de08a61d284cd7fdab2a7b7d42b
[ "self.file_path = file_path\nself.count_episodes = None\nself.count_states = None\nself.data = None", "with open(file=self.file_path, mode='a', buffering=1) as file:\n msg_annotated = '{0}\\t{1}\\t{2}\\n'.format(count_episodes, count_states, msg)\n file.write(msg_annotated)", "with open(self.file_path) as...
<|body_start_0|> self.file_path = file_path self.count_episodes = None self.count_states = None self.data = None <|end_body_0|> <|body_start_1|> with open(file=self.file_path, mode='a', buffering=1) as file: msg_annotated = '{0}\t{1}\t{2}\n'.format(count_episodes, co...
Base-class for logging data to a text-file during training. It is possible to use TensorFlow / TensorBoard for this, but it is quite awkward to implement, as it was intended for logging variables and other aspects of the TensorFlow graph. We want to log the reward and Q-values which are not in that graph.
Log
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Log: """Base-class for logging data to a text-file during training. It is possible to use TensorFlow / TensorBoard for this, but it is quite awkward to implement, as it was intended for logging variables and other aspects of the TensorFlow graph. We want to log the reward and Q-values which are n...
stack_v2_sparse_classes_36k_train_032116
4,975
permissive
[ { "docstring": "Set the path for the log-file. Nothing is saved or loaded yet.", "name": "__init__", "signature": "def __init__(self, file_path)" }, { "docstring": "Write a line to the log-file. This is only called by sub-classes. :param count_episodes: Counter for the number of episodes process...
3
stack_v2_sparse_classes_30k_train_007235
Implement the Python class `Log` described below. Class description: Base-class for logging data to a text-file during training. It is possible to use TensorFlow / TensorBoard for this, but it is quite awkward to implement, as it was intended for logging variables and other aspects of the TensorFlow graph. We want to ...
Implement the Python class `Log` described below. Class description: Base-class for logging data to a text-file during training. It is possible to use TensorFlow / TensorBoard for this, but it is quite awkward to implement, as it was intended for logging variables and other aspects of the TensorFlow graph. We want to ...
cc4181ed1a951ec9e82e86358a53f69b63d5328a
<|skeleton|> class Log: """Base-class for logging data to a text-file during training. It is possible to use TensorFlow / TensorBoard for this, but it is quite awkward to implement, as it was intended for logging variables and other aspects of the TensorFlow graph. We want to log the reward and Q-values which are n...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Log: """Base-class for logging data to a text-file during training. It is possible to use TensorFlow / TensorBoard for this, but it is quite awkward to implement, as it was intended for logging variables and other aspects of the TensorFlow graph. We want to log the reward and Q-values which are not in that gr...
the_stack_v2_python_sparse
log.py
sandip824/Reinforcement-Learning-for-Self-Driving-Cars
train
1
1b0bd28ce5705593a2dc05215f003a4c3640adf1
[ "def backtrack(res, path, index, s):\n if len(s) == index:\n res.append(path[:])\n return\n for i in range(index, len(s)):\n substr = s[index:i + 1]\n if substr == substr[::-1]:\n path.append(substr)\n backtrack(res, path, i + 1, s)\n path.pop()\nan...
<|body_start_0|> def backtrack(res, path, index, s): if len(s) == index: res.append(path[:]) return for i in range(index, len(s)): substr = s[index:i + 1] if substr == substr[::-1]: path.append(substr) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def partition(self, s): """:type s: str :rtype: List[List[str]]""" <|body_0|> def partition_wrong_answer(self, s): """:type s: str :rtype: List[List[str]]""" <|body_1|> <|end_skeleton|> <|body_start_0|> def backtrack(res, path, index, s): ...
stack_v2_sparse_classes_36k_train_032117
2,206
no_license
[ { "docstring": ":type s: str :rtype: List[List[str]]", "name": "partition", "signature": "def partition(self, s)" }, { "docstring": ":type s: str :rtype: List[List[str]]", "name": "partition_wrong_answer", "signature": "def partition_wrong_answer(self, s)" } ]
2
stack_v2_sparse_classes_30k_val_001175
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def partition(self, s): :type s: str :rtype: List[List[str]] - def partition_wrong_answer(self, s): :type s: str :rtype: List[List[str]]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def partition(self, s): :type s: str :rtype: List[List[str]] - def partition_wrong_answer(self, s): :type s: str :rtype: List[List[str]] <|skeleton|> class Solution: def pa...
2d5fa4cd696d5035ea8859befeadc5cc436959c9
<|skeleton|> class Solution: def partition(self, s): """:type s: str :rtype: List[List[str]]""" <|body_0|> def partition_wrong_answer(self, s): """:type s: str :rtype: List[List[str]]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def partition(self, s): """:type s: str :rtype: List[List[str]]""" def backtrack(res, path, index, s): if len(s) == index: res.append(path[:]) return for i in range(index, len(s)): substr = s[index:i + 1] ...
the_stack_v2_python_sparse
SourceCode/Python/Problem/00131.Palindrome Partitioning.py
roger6blog/LeetCode
train
0
5170b1cd5e706e01684a23760d574769852e3fae
[ "def buildList(root, lst):\n if not root:\n lst.append('N')\n else:\n lst.append(str(root.val))\n buildList(root.left, lst)\n buildList(root.right, lst)\nlst = []\nbuildList(root, lst)\nreturn ','.join(lst)", "def buildTree(it):\n val = next(it)\n if val == 'N':\n ro...
<|body_start_0|> def buildList(root, lst): if not root: lst.append('N') else: lst.append(str(root.val)) buildList(root.left, lst) buildList(root.right, lst) lst = [] buildList(root, lst) return ','.jo...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_36k_train_032118
1,719
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
stack_v2_sparse_classes_30k_train_016462
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
672816c504e56a1d2dfea72f96312f27cd9a3133
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" def buildList(root, lst): if not root: lst.append('N') else: lst.append(str(root.val)) buildList(root.left, lst) ...
the_stack_v2_python_sparse
297.Serialize_and_Deserialize_Binary_Tree.py
mikehung/leetcode
train
3
74bce0dbec2c1a92c40a962f3a099097be735c96
[ "super().__init__()\nself.input_size = input_size\nself.d_model = d_model\nif input_size != d_model:\n self.proj = nn.Linear(input_size, d_model)\nlayer = TransformerDecoderLayer(d_model, nhead, dim_feedforward, dropout)\nself.layers = nn.ModuleList([copy.deepcopy(layer) for _ in range(num_layers)])\nself.num_la...
<|body_start_0|> super().__init__() self.input_size = input_size self.d_model = d_model if input_size != d_model: self.proj = nn.Linear(input_size, d_model) layer = TransformerDecoderLayer(d_model, nhead, dim_feedforward, dropout) self.layers = nn.ModuleList([...
TransformerDecoder is a stack of N decoder layers
TransformerDecoder
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TransformerDecoder: """TransformerDecoder is a stack of N decoder layers""" def __init__(self, input_size: int, d_model: int, nhead: int, num_layers: int, dim_feedforward: int=2048, dropout: float=0.1) -> None: """Initialize the TransformerDecoder. Parameters --------- input_size : i...
stack_v2_sparse_classes_36k_train_032119
20,460
permissive
[ { "docstring": "Initialize the TransformerDecoder. Parameters --------- input_size : int The embedding dimension of the model. If different from d_model, a linear projection layer is added. d_model : int The number of expected features in encoder/decoder inputs. nhead : int, optional The number of heads in the ...
3
stack_v2_sparse_classes_30k_train_010709
Implement the Python class `TransformerDecoder` described below. Class description: TransformerDecoder is a stack of N decoder layers Method signatures and docstrings: - def __init__(self, input_size: int, d_model: int, nhead: int, num_layers: int, dim_feedforward: int=2048, dropout: float=0.1) -> None: Initialize th...
Implement the Python class `TransformerDecoder` described below. Class description: TransformerDecoder is a stack of N decoder layers Method signatures and docstrings: - def __init__(self, input_size: int, d_model: int, nhead: int, num_layers: int, dim_feedforward: int=2048, dropout: float=0.1) -> None: Initialize th...
0dc2f5b2b286694defe8abf450fe5be9ae12c097
<|skeleton|> class TransformerDecoder: """TransformerDecoder is a stack of N decoder layers""" def __init__(self, input_size: int, d_model: int, nhead: int, num_layers: int, dim_feedforward: int=2048, dropout: float=0.1) -> None: """Initialize the TransformerDecoder. Parameters --------- input_size : i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TransformerDecoder: """TransformerDecoder is a stack of N decoder layers""" def __init__(self, input_size: int, d_model: int, nhead: int, num_layers: int, dim_feedforward: int=2048, dropout: float=0.1) -> None: """Initialize the TransformerDecoder. Parameters --------- input_size : int The embedd...
the_stack_v2_python_sparse
flambe/nn/transformer.py
cle-ros/flambe
train
1
3c1b5c68516c2da141143af08e62c31bc43d3d43
[ "self.trade_date = None\nself.trade_no = None\nself.settlement_date = None\nself.security_descr = None\nself.buyer = None\nself.seller = None\nself.isin = None\nself.issuer = None\nself.maturity_date = None\nself.currency = None\nself.nominal = None\nself.yield_to_maturity = None\nself.clean_price = None\nself.clea...
<|body_start_0|> self.trade_date = None self.trade_no = None self.settlement_date = None self.security_descr = None self.buyer = None self.seller = None self.isin = None self.issuer = None self.maturity_date = None self.currency = None ...
A class representing the details of a trade for display on a broker note bulk.
Trade
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Trade: """A class representing the details of a trade for display on a broker note bulk.""" def __init__(self): """Constructor.""" <|body_0|> def to_xml_element(self): """Convert this Trade instance to its representation as an XML Element.""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_032120
26,096
no_license
[ { "docstring": "Constructor.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Convert this Trade instance to its representation as an XML Element.", "name": "to_xml_element", "signature": "def to_xml_element(self)" }, { "docstring": "Convert the XML Elem...
3
stack_v2_sparse_classes_30k_train_004901
Implement the Python class `Trade` described below. Class description: A class representing the details of a trade for display on a broker note bulk. Method signatures and docstrings: - def __init__(self): Constructor. - def to_xml_element(self): Convert this Trade instance to its representation as an XML Element. - ...
Implement the Python class `Trade` described below. Class description: A class representing the details of a trade for display on a broker note bulk. Method signatures and docstrings: - def __init__(self): Constructor. - def to_xml_element(self): Convert this Trade instance to its representation as an XML Element. - ...
5e7cc7de3495145501ca53deb9efee2233ab7e1c
<|skeleton|> class Trade: """A class representing the details of a trade for display on a broker note bulk.""" def __init__(self): """Constructor.""" <|body_0|> def to_xml_element(self): """Convert this Trade instance to its representation as an XML Element.""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Trade: """A class representing the details of a trade for display on a broker note bulk.""" def __init__(self): """Constructor.""" self.trade_date = None self.trade_no = None self.settlement_date = None self.security_descr = None self.buyer = None s...
the_stack_v2_python_sparse
Extensions/ABSA Documentation/FPythonCode/BrokerNoteBulkGeneral.py
webclinic017/fa-absa-py3
train
0
bf16bd030d10ceb7836ecce43222d882a34b1410
[ "if not super(self.__class__, self).validate(mention, mention_index):\n return False\nif not mention['form'] in dictionaries.pronouns.relative:\n self.debug('MENTION FILTERED Not a relative pronoun: %s ', mention['form'])\n return False\nreturn True", "candidate_tag = candidate.get('tag', False)\nif cand...
<|body_start_0|> if not super(self.__class__, self).validate(mention, mention_index): return False if not mention['form'] in dictionaries.pronouns.relative: self.debug('MENTION FILTERED Not a relative pronoun: %s ', mention['form']) return False return True <|...
A relative pronoun is referent to the NP that modified.
RelativePronoun
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RelativePronoun: """A relative pronoun is referent to the NP that modified.""" def validate(self, mention, mention_index): """Entity must be relative pronoun.""" <|body_0|> def are_coreferent(self, entity, mention, candidate): """Candidate is the NP that the rela...
stack_v2_sparse_classes_36k_train_032121
10,579
permissive
[ { "docstring": "Entity must be relative pronoun.", "name": "validate", "signature": "def validate(self, mention, mention_index)" }, { "docstring": "Candidate is the NP that the relative pronoun modified.", "name": "are_coreferent", "signature": "def are_coreferent(self, entity, mention, ...
2
stack_v2_sparse_classes_30k_train_018511
Implement the Python class `RelativePronoun` described below. Class description: A relative pronoun is referent to the NP that modified. Method signatures and docstrings: - def validate(self, mention, mention_index): Entity must be relative pronoun. - def are_coreferent(self, entity, mention, candidate): Candidate is...
Implement the Python class `RelativePronoun` described below. Class description: A relative pronoun is referent to the NP that modified. Method signatures and docstrings: - def validate(self, mention, mention_index): Entity must be relative pronoun. - def are_coreferent(self, entity, mention, candidate): Candidate is...
5fe41dda0da83a37a01220f8f0552a336f2294ef
<|skeleton|> class RelativePronoun: """A relative pronoun is referent to the NP that modified.""" def validate(self, mention, mention_index): """Entity must be relative pronoun.""" <|body_0|> def are_coreferent(self, entity, mention, candidate): """Candidate is the NP that the rela...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RelativePronoun: """A relative pronoun is referent to the NP that modified.""" def validate(self, mention, mention_index): """Entity must be relative pronoun.""" if not super(self.__class__, self).validate(mention, mention_index): return False if not mention['form'] in...
the_stack_v2_python_sparse
core/corefgraph/multisieve/sieves/preciseConstruct.py
malv007/coreference-base
train
0
81e3e13225ba8589d7204242681c688ce44e7de2
[ "test_numlist = [[1, 2], [-5, 6]]\nfor pos in test_numlist:\n qpos = QtCore.QPoint(pos[0], pos[1])\n npos = QtUtil.QPoint2numpy(qpos)\n assert npos[0] == float(pos[0])\n assert npos[1] == float(pos[1])", "ctrlmod = QtCore.Qt.KeyboardModifiers(QtCore.Qt.ControlModifier)\naltmod = QtCore.Qt.KeyboardModi...
<|body_start_0|> test_numlist = [[1, 2], [-5, 6]] for pos in test_numlist: qpos = QtCore.QPoint(pos[0], pos[1]) npos = QtUtil.QPoint2numpy(qpos) assert npos[0] == float(pos[0]) assert npos[1] == float(pos[1]) <|end_body_0|> <|body_start_1|> ctrlmo...
test: QtUtil
TestQtUtil
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestQtUtil: """test: QtUtil""" def test_QPoint2numpy(self): """test mapToSphere function""" <|body_0|> def test_key_modifier(self): """test key modifiers""" <|body_1|> <|end_skeleton|> <|body_start_0|> test_numlist = [[1, 2], [-5, 6]] fo...
stack_v2_sparse_classes_36k_train_032122
2,019
no_license
[ { "docstring": "test mapToSphere function", "name": "test_QPoint2numpy", "signature": "def test_QPoint2numpy(self)" }, { "docstring": "test key modifiers", "name": "test_key_modifier", "signature": "def test_key_modifier(self)" } ]
2
stack_v2_sparse_classes_30k_train_017692
Implement the Python class `TestQtUtil` described below. Class description: test: QtUtil Method signatures and docstrings: - def test_QPoint2numpy(self): test mapToSphere function - def test_key_modifier(self): test key modifiers
Implement the Python class `TestQtUtil` described below. Class description: test: QtUtil Method signatures and docstrings: - def test_QPoint2numpy(self): test mapToSphere function - def test_key_modifier(self): test key modifiers <|skeleton|> class TestQtUtil: """test: QtUtil""" def test_QPoint2numpy(self):...
f163b6b9e15100d223ddf4e180727a2b63fbae2d
<|skeleton|> class TestQtUtil: """test: QtUtil""" def test_QPoint2numpy(self): """test mapToSphere function""" <|body_0|> def test_key_modifier(self): """test key modifiers""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestQtUtil: """test: QtUtil""" def test_QPoint2numpy(self): """test mapToSphere function""" test_numlist = [[1, 2], [-5, 6]] for pos in test_numlist: qpos = QtCore.QPoint(pos[0], pos[1]) npos = QtUtil.QPoint2numpy(qpos) assert npos[0] == float(p...
the_stack_v2_python_sparse
examiner00/test_QtUtil.py
yamauchih/ifgi-path-tracer
train
0
b05c89fdba66c10dbccbcac279ac924066219267
[ "player = g.db.query(MatchPlayer).filter(MatchPlayer.match_id == match_id, MatchPlayer.player_id == player_id).first()\nif not player:\n abort(http_client.NOT_FOUND)\nret = player.as_dict()\nret['team_url'] = None\nif player.team_id:\n ret['team_url'] = url_for('matches.team', match_id=match_id, team_id=playe...
<|body_start_0|> player = g.db.query(MatchPlayer).filter(MatchPlayer.match_id == match_id, MatchPlayer.player_id == player_id).first() if not player: abort(http_client.NOT_FOUND) ret = player.as_dict() ret['team_url'] = None if player.team_id: ret['team_ur...
A specific player in a specific match
MatchPlayerAPI
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MatchPlayerAPI: """A specific player in a specific match""" def get(self, match_id, player_id): """Get a specific player from a battle""" <|body_0|> def delete(self, match_id, player_id): """A player has left an ongoing battle""" <|body_1|> <|end_skeleto...
stack_v2_sparse_classes_36k_train_032123
24,829
permissive
[ { "docstring": "Get a specific player from a battle", "name": "get", "signature": "def get(self, match_id, player_id)" }, { "docstring": "A player has left an ongoing battle", "name": "delete", "signature": "def delete(self, match_id, player_id)" } ]
2
null
Implement the Python class `MatchPlayerAPI` described below. Class description: A specific player in a specific match Method signatures and docstrings: - def get(self, match_id, player_id): Get a specific player from a battle - def delete(self, match_id, player_id): A player has left an ongoing battle
Implement the Python class `MatchPlayerAPI` described below. Class description: A specific player in a specific match Method signatures and docstrings: - def get(self, match_id, player_id): Get a specific player from a battle - def delete(self, match_id, player_id): A player has left an ongoing battle <|skeleton|> c...
9825cb22b26b577b715f2ce95453363bf90ecc7e
<|skeleton|> class MatchPlayerAPI: """A specific player in a specific match""" def get(self, match_id, player_id): """Get a specific player from a battle""" <|body_0|> def delete(self, match_id, player_id): """A player has left an ongoing battle""" <|body_1|> <|end_skeleto...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MatchPlayerAPI: """A specific player in a specific match""" def get(self, match_id, player_id): """Get a specific player from a battle""" player = g.db.query(MatchPlayer).filter(MatchPlayer.match_id == match_id, MatchPlayer.player_id == player_id).first() if not player: ...
the_stack_v2_python_sparse
driftbase/api/matches.py
dgnorth/drift-base
train
1
898b7cd6651312a4be77fae5e2c8c3914fed7b5a
[ "if len(strs) == 0:\n return ''\npreStr = strs[0]\nfor i in range(1, len(strs)):\n nowStr = strs[i]\n if preStr == '':\n break\n preStr = self.longestCommonPrefixTwo(preStr, nowStr)\nreturn preStr", "i = 0\nwhile i < len(str1) and i < len(str2):\n if str1[i] == str2[i]:\n i += 1\n ...
<|body_start_0|> if len(strs) == 0: return '' preStr = strs[0] for i in range(1, len(strs)): nowStr = strs[i] if preStr == '': break preStr = self.longestCommonPrefixTwo(preStr, nowStr) return preStr <|end_body_0|> <|body_s...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def longestCommonPrefix(self, strs): """:type strs: List[str] :rtype: str""" <|body_0|> def longestCommonPrefixTwo(self, str1, str2): """:type str1: str1 :type str2: str2 :rtype: str""" <|body_1|> <|end_skeleton|> <|body_start_0|> if len(s...
stack_v2_sparse_classes_36k_train_032124
754
no_license
[ { "docstring": ":type strs: List[str] :rtype: str", "name": "longestCommonPrefix", "signature": "def longestCommonPrefix(self, strs)" }, { "docstring": ":type str1: str1 :type str2: str2 :rtype: str", "name": "longestCommonPrefixTwo", "signature": "def longestCommonPrefixTwo(self, str1, ...
2
stack_v2_sparse_classes_30k_train_001349
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestCommonPrefix(self, strs): :type strs: List[str] :rtype: str - def longestCommonPrefixTwo(self, str1, str2): :type str1: str1 :type str2: str2 :rtype: str
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestCommonPrefix(self, strs): :type strs: List[str] :rtype: str - def longestCommonPrefixTwo(self, str1, str2): :type str1: str1 :type str2: str2 :rtype: str <|skeleton|>...
ba264d6d218afefc0af385b036840ae451b4d714
<|skeleton|> class Solution: def longestCommonPrefix(self, strs): """:type strs: List[str] :rtype: str""" <|body_0|> def longestCommonPrefixTwo(self, str1, str2): """:type str1: str1 :type str2: str2 :rtype: str""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def longestCommonPrefix(self, strs): """:type strs: List[str] :rtype: str""" if len(strs) == 0: return '' preStr = strs[0] for i in range(1, len(strs)): nowStr = strs[i] if preStr == '': break preStr = se...
the_stack_v2_python_sparse
python-code/15-LongestCommonPrefix.py
Yingminzhou/leetcode
train
0
5c7a4736cbbbd8f71bc1462f2b3e84dc787063ac
[ "guess_str = (str(merkle_root) + str(previous_hash) + str(nonce)).encode('utf8')\nguess_hash = FuncUtil.hashfunc_sha256(guess_str)\ndifficulty = 1\nwhile int('f' * difficulty, 16) < sum_stake:\n difficulty += 1\nguess_weight = int(guess_hash[:difficulty], 16) / int('f' * difficulty, 16)\nreturn guess_weight < st...
<|body_start_0|> guess_str = (str(merkle_root) + str(previous_hash) + str(nonce)).encode('utf8') guess_hash = FuncUtil.hashfunc_sha256(guess_str) difficulty = 1 while int('f' * difficulty, 16) < sum_stake: difficulty += 1 guess_weight = int(guess_hash[:difficulty], 16...
Proof-of-Stake consenses mechanism
POS
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class POS: """Proof-of-Stake consenses mechanism""" def valid_proof(merkle_root, previous_hash, nonce, stake_weight=1, sum_stake=1): """Check if a guessing hash value satisfies the mining difficulty conditions. @ previous_hash: The hash of parent block @ nonce: the stake deposit value @ me...
stack_v2_sparse_classes_36k_train_032125
5,661
no_license
[ { "docstring": "Check if a guessing hash value satisfies the mining difficulty conditions. @ previous_hash: The hash of parent block @ nonce: the stake deposit value @ merkle_root: merkle tree root of transactions in block", "name": "valid_proof", "signature": "def valid_proof(merkle_root, previous_hash...
3
null
Implement the Python class `POS` described below. Class description: Proof-of-Stake consenses mechanism Method signatures and docstrings: - def valid_proof(merkle_root, previous_hash, nonce, stake_weight=1, sum_stake=1): Check if a guessing hash value satisfies the mining difficulty conditions. @ previous_hash: The h...
Implement the Python class `POS` described below. Class description: Proof-of-Stake consenses mechanism Method signatures and docstrings: - def valid_proof(merkle_root, previous_hash, nonce, stake_weight=1, sum_stake=1): Check if a guessing hash value satisfies the mining difficulty conditions. @ previous_hash: The h...
03ff57e6fe0114ffd2dd953e79a73a893a6bc0ad
<|skeleton|> class POS: """Proof-of-Stake consenses mechanism""" def valid_proof(merkle_root, previous_hash, nonce, stake_weight=1, sum_stake=1): """Check if a guessing hash value satisfies the mining difficulty conditions. @ previous_hash: The hash of parent block @ nonce: the stake deposit value @ me...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class POS: """Proof-of-Stake consenses mechanism""" def valid_proof(merkle_root, previous_hash, nonce, stake_weight=1, sum_stake=1): """Check if a guessing hash value satisfies the mining difficulty conditions. @ previous_hash: The hash of parent block @ nonce: the stake deposit value @ merkle_root: me...
the_stack_v2_python_sparse
Security/py_dev/ENF_chain/consensus/consensus.py
samuelxu999/Research
train
1
e809ff6e95859b7e5e82607d1bb31e0676eeabc6
[ "queryset = self.queryset\npage = self.paginate_queryset(queryset)\nif page is not None:\n serializer = self.get_serializer(page, many=True)\n return self.get_paginated_response(serializer.data)\nserializer = self.get_serializer(queryset, many=True)\nreturn Response(serializer.data)", "merchant = Message.ob...
<|body_start_0|> queryset = self.queryset page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) ...
MessageViewSet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MessageViewSet: def list(self, request, *args, **kwargs): """消息列表""" <|body_0|> def partial_update(self, request, *args, **kwargs): """更新消息状态""" <|body_1|> <|end_skeleton|> <|body_start_0|> queryset = self.queryset page = self.paginate_query...
stack_v2_sparse_classes_36k_train_032126
1,718
no_license
[ { "docstring": "消息列表", "name": "list", "signature": "def list(self, request, *args, **kwargs)" }, { "docstring": "更新消息状态", "name": "partial_update", "signature": "def partial_update(self, request, *args, **kwargs)" } ]
2
null
Implement the Python class `MessageViewSet` described below. Class description: Implement the MessageViewSet class. Method signatures and docstrings: - def list(self, request, *args, **kwargs): 消息列表 - def partial_update(self, request, *args, **kwargs): 更新消息状态
Implement the Python class `MessageViewSet` described below. Class description: Implement the MessageViewSet class. Method signatures and docstrings: - def list(self, request, *args, **kwargs): 消息列表 - def partial_update(self, request, *args, **kwargs): 更新消息状态 <|skeleton|> class MessageViewSet: def list(self, re...
0d32f98f42591b43e0b4da5e978b627da517f758
<|skeleton|> class MessageViewSet: def list(self, request, *args, **kwargs): """消息列表""" <|body_0|> def partial_update(self, request, *args, **kwargs): """更新消息状态""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MessageViewSet: def list(self, request, *args, **kwargs): """消息列表""" queryset = self.queryset page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.dat...
the_stack_v2_python_sparse
payserver/padmin/views/message.py
yiyuhao/FukuanUnion
train
0
ae8e8d2a59a255d7b3aa52264a2a0f95e87f3d57
[ "self._registered = {}\nself._discovered = {}\nself._lock = threading.Lock()\nself._browser = None", "with self._lock:\n if device.serial in self._discovered:\n callback(self._discovered[device.serial])\n else:\n self._registered[device.serial] = callback", "if info.type == TYPE_DYSON_360_EY...
<|body_start_0|> self._registered = {} self._discovered = {} self._lock = threading.Lock() self._browser = None <|end_body_0|> <|body_start_1|> with self._lock: if device.serial in self._discovered: callback(self._discovered[device.serial]) ...
Dyson device discovery.
DysonDiscovery
[ "Unlicense" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DysonDiscovery: """Dyson device discovery.""" def __init__(self): """Initialize the instance.""" <|body_0|> def register_device(self, device: DysonDevice, callback: Callable[[str], None]) -> None: """Register a device.""" <|body_1|> def device_discov...
stack_v2_sparse_classes_36k_train_032127
2,876
permissive
[ { "docstring": "Initialize the instance.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Register a device.", "name": "register_device", "signature": "def register_device(self, device: DysonDevice, callback: Callable[[str], None]) -> None" }, { "docstri...
5
stack_v2_sparse_classes_30k_train_001773
Implement the Python class `DysonDiscovery` described below. Class description: Dyson device discovery. Method signatures and docstrings: - def __init__(self): Initialize the instance. - def register_device(self, device: DysonDevice, callback: Callable[[str], None]) -> None: Register a device. - def device_discovered...
Implement the Python class `DysonDiscovery` described below. Class description: Dyson device discovery. Method signatures and docstrings: - def __init__(self): Initialize the instance. - def register_device(self, device: DysonDevice, callback: Callable[[str], None]) -> None: Register a device. - def device_discovered...
8548d9999ddd54f13d6a307e013abcb8c897a74e
<|skeleton|> class DysonDiscovery: """Dyson device discovery.""" def __init__(self): """Initialize the instance.""" <|body_0|> def register_device(self, device: DysonDevice, callback: Callable[[str], None]) -> None: """Register a device.""" <|body_1|> def device_discov...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DysonDiscovery: """Dyson device discovery.""" def __init__(self): """Initialize the instance.""" self._registered = {} self._discovered = {} self._lock = threading.Lock() self._browser = None def register_device(self, device: DysonDevice, callback: Callable[[s...
the_stack_v2_python_sparse
custom_components/dyson_local/vendor/libdyson/discovery.py
bacco007/HomeAssistantConfig
train
98
d97a50c66eb719c680ab68d943d9fa12f37a1c09
[ "field_names = list(super().get_field_names(declared_fields, info))\nexclude = getattr(self.Meta, 'exclude', None)\nif exclude is None or 'id' not in exclude:\n if 'id' not in field_names:\n field_names.insert(0, 'id')\nif hasattr(self.Meta.model, 'ObjectMeta') and hasattr(self.Meta.model.ObjectMeta, 'det...
<|body_start_0|> field_names = list(super().get_field_names(declared_fields, info)) exclude = getattr(self.Meta, 'exclude', None) if exclude is None or 'id' not in exclude: if 'id' not in field_names: field_names.insert(0, 'id') if hasattr(self.Meta.model, 'Ob...
Serializer forcing id as field and adding 'url_field_name' (default: 'detail_url') if objects model has 'ObjectMeta'-class with 'detail_view_name' to view taking 'pk'.
DBObjectSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DBObjectSerializer: """Serializer forcing id as field and adding 'url_field_name' (default: 'detail_url') if objects model has 'ObjectMeta'-class with 'detail_view_name' to view taking 'pk'.""" def get_field_names(self, declared_fields, info): """Adds fields 'id' and self.url_field_n...
stack_v2_sparse_classes_36k_train_032128
11,760
no_license
[ { "docstring": "Adds fields 'id' and self.url_field_name if not explicitly said otherwise in exclude of metaclass.", "name": "get_field_names", "signature": "def get_field_names(self, declared_fields, info)" }, { "docstring": "Create a field representing the object's own URL. Uses objects", ...
2
stack_v2_sparse_classes_30k_train_012533
Implement the Python class `DBObjectSerializer` described below. Class description: Serializer forcing id as field and adding 'url_field_name' (default: 'detail_url') if objects model has 'ObjectMeta'-class with 'detail_view_name' to view taking 'pk'. Method signatures and docstrings: - def get_field_names(self, decl...
Implement the Python class `DBObjectSerializer` described below. Class description: Serializer forcing id as field and adding 'url_field_name' (default: 'detail_url') if objects model has 'ObjectMeta'-class with 'detail_view_name' to view taking 'pk'. Method signatures and docstrings: - def get_field_names(self, decl...
e5af3fff2ec3e2b54ae0c2583f7994714c83dd39
<|skeleton|> class DBObjectSerializer: """Serializer forcing id as field and adding 'url_field_name' (default: 'detail_url') if objects model has 'ObjectMeta'-class with 'detail_view_name' to view taking 'pk'.""" def get_field_names(self, declared_fields, info): """Adds fields 'id' and self.url_field_n...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DBObjectSerializer: """Serializer forcing id as field and adding 'url_field_name' (default: 'detail_url') if objects model has 'ObjectMeta'-class with 'detail_view_name' to view taking 'pk'.""" def get_field_names(self, declared_fields, info): """Adds fields 'id' and self.url_field_name if not ex...
the_stack_v2_python_sparse
utils/serializers.py
Fysiksektionen/Hemsida-Backend
train
0
73a08a944039b4fc8c0b18c7f70d89221dee9841
[ "_id = request.args.get('id', None)\nif not _id:\n return ({'msg': 'params error !'}, 400)\ntry:\n result = mongo_algo.db.algo_info.find_one({'_id': bson.ObjectId(_id)}, {'hyper_params': 1})\n if not result:\n return ({'msg': 'id is not exist !'}, 200)\nexcept Exception as e:\n logging.error(e, e...
<|body_start_0|> _id = request.args.get('id', None) if not _id: return ({'msg': 'params error !'}, 400) try: result = mongo_algo.db.algo_info.find_one({'_id': bson.ObjectId(_id)}, {'hyper_params': 1}) if not result: return ({'msg': 'id is not e...
HyperParamsViews
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HyperParamsViews: def get(self): """get one hyper params through id :return:""" <|body_0|> def post(self): """add an hyper params record :return:""" <|body_1|> def put(self): """update hyper params record :return:""" <|body_2|> <|end_ske...
stack_v2_sparse_classes_36k_train_032129
20,183
no_license
[ { "docstring": "get one hyper params through id :return:", "name": "get", "signature": "def get(self)" }, { "docstring": "add an hyper params record :return:", "name": "post", "signature": "def post(self)" }, { "docstring": "update hyper params record :return:", "name": "put"...
3
stack_v2_sparse_classes_30k_train_020715
Implement the Python class `HyperParamsViews` described below. Class description: Implement the HyperParamsViews class. Method signatures and docstrings: - def get(self): get one hyper params through id :return: - def post(self): add an hyper params record :return: - def put(self): update hyper params record :return:
Implement the Python class `HyperParamsViews` described below. Class description: Implement the HyperParamsViews class. Method signatures and docstrings: - def get(self): get one hyper params through id :return: - def post(self): add an hyper params record :return: - def put(self): update hyper params record :return:...
054324b50e807d6f4e98f4a1b67afac9a0653b06
<|skeleton|> class HyperParamsViews: def get(self): """get one hyper params through id :return:""" <|body_0|> def post(self): """add an hyper params record :return:""" <|body_1|> def put(self): """update hyper params record :return:""" <|body_2|> <|end_ske...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HyperParamsViews: def get(self): """get one hyper params through id :return:""" _id = request.args.get('id', None) if not _id: return ({'msg': 'params error !'}, 400) try: result = mongo_algo.db.algo_info.find_one({'_id': bson.ObjectId(_id)}, {'hyper_par...
the_stack_v2_python_sparse
services/AlgoVersion/views.py
condilin/DMS
train
0
df0278dea15e46cdbb666674db84128cb87dad3d
[ "super().configure_data(cfg, data_cfg)\nif self.training:\n if cfg.data.get('unlabeled', False) and cfg.data.unlabeled.get('otx_dataset', False):\n if len(cfg.data.unlabeled.get('pipeline', [])) == 0:\n cfg.data.unlabeled.pipeline = cfg.data.train.pipeline.copy()\n self.configure_unlabel...
<|body_start_0|> super().configure_data(cfg, data_cfg) if self.training: if cfg.data.get('unlabeled', False) and cfg.data.unlabeled.get('otx_dataset', False): if len(cfg.data.unlabeled.get('pipeline', [])) == 0: cfg.data.unlabeled.pipeline = cfg.data.train...
Patch config to support semi supervised learning.
SemiSLConfigurerMixin
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SemiSLConfigurerMixin: """Patch config to support semi supervised learning.""" def configure_data(self, cfg, data_cfg): """Patch cfg.data.""" <|body_0|> def configure_unlabeled_dataloader(cfg: Config): """Patch for unlabled dataloader.""" <|body_1|> <|en...
stack_v2_sparse_classes_36k_train_032130
2,319
permissive
[ { "docstring": "Patch cfg.data.", "name": "configure_data", "signature": "def configure_data(self, cfg, data_cfg)" }, { "docstring": "Patch for unlabled dataloader.", "name": "configure_unlabeled_dataloader", "signature": "def configure_unlabeled_dataloader(cfg: Config)" } ]
2
null
Implement the Python class `SemiSLConfigurerMixin` described below. Class description: Patch config to support semi supervised learning. Method signatures and docstrings: - def configure_data(self, cfg, data_cfg): Patch cfg.data. - def configure_unlabeled_dataloader(cfg: Config): Patch for unlabled dataloader.
Implement the Python class `SemiSLConfigurerMixin` described below. Class description: Patch config to support semi supervised learning. Method signatures and docstrings: - def configure_data(self, cfg, data_cfg): Patch cfg.data. - def configure_unlabeled_dataloader(cfg: Config): Patch for unlabled dataloader. <|ske...
80454808b38727e358e8b880043eeac0f18152fb
<|skeleton|> class SemiSLConfigurerMixin: """Patch config to support semi supervised learning.""" def configure_data(self, cfg, data_cfg): """Patch cfg.data.""" <|body_0|> def configure_unlabeled_dataloader(cfg: Config): """Patch for unlabled dataloader.""" <|body_1|> <|en...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SemiSLConfigurerMixin: """Patch config to support semi supervised learning.""" def configure_data(self, cfg, data_cfg): """Patch cfg.data.""" super().configure_data(cfg, data_cfg) if self.training: if cfg.data.get('unlabeled', False) and cfg.data.unlabeled.get('otx_dat...
the_stack_v2_python_sparse
src/otx/algorithms/common/adapters/mmcv/semisl_mixin.py
openvinotoolkit/training_extensions
train
397
962b2476b73530dac7b44dad1d2e5214fcddec46
[ "raise_error = kwargs.get(RAISE_ERROR, True)\ntry:\n cls.check_valid_status(appointment, cls.status_enum.ON_MODERATION)\nexcept WrongStatusError as err:\n valid_err = cls.reject_error(title=err.title)\n if raise_error:\n raise valid_err\n else:\n logging.warning(valid_err, extra={APPOINTME...
<|body_start_0|> raise_error = kwargs.get(RAISE_ERROR, True) try: cls.check_valid_status(appointment, cls.status_enum.ON_MODERATION) except WrongStatusError as err: valid_err = cls.reject_error(title=err.title) if raise_error: raise valid_err ...
AppointmentModerationValidator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AppointmentModerationValidator: def validate_before_reject(cls, appointment: Appointment, **kwargs) -> None: """:raises: apps.appointments.exceptions.AppointmentRejectError""" <|body_0|> def validate_before_approve(cls, appointment: Appointment) -> None: """:raises: ...
stack_v2_sparse_classes_36k_train_032131
12,944
no_license
[ { "docstring": ":raises: apps.appointments.exceptions.AppointmentRejectError", "name": "validate_before_reject", "signature": "def validate_before_reject(cls, appointment: Appointment, **kwargs) -> None" }, { "docstring": ":raises: apps.appointments.exceptions.AppointmentApproveError", "name...
3
stack_v2_sparse_classes_30k_train_020771
Implement the Python class `AppointmentModerationValidator` described below. Class description: Implement the AppointmentModerationValidator class. Method signatures and docstrings: - def validate_before_reject(cls, appointment: Appointment, **kwargs) -> None: :raises: apps.appointments.exceptions.AppointmentRejectEr...
Implement the Python class `AppointmentModerationValidator` described below. Class description: Implement the AppointmentModerationValidator class. Method signatures and docstrings: - def validate_before_reject(cls, appointment: Appointment, **kwargs) -> None: :raises: apps.appointments.exceptions.AppointmentRejectEr...
447a4c46e578f9aa1ae015edd39752d3b9b5cb28
<|skeleton|> class AppointmentModerationValidator: def validate_before_reject(cls, appointment: Appointment, **kwargs) -> None: """:raises: apps.appointments.exceptions.AppointmentRejectError""" <|body_0|> def validate_before_approve(cls, appointment: Appointment) -> None: """:raises: ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AppointmentModerationValidator: def validate_before_reject(cls, appointment: Appointment, **kwargs) -> None: """:raises: apps.appointments.exceptions.AppointmentRejectError""" raise_error = kwargs.get(RAISE_ERROR, True) try: cls.check_valid_status(appointment, cls.status_en...
the_stack_v2_python_sparse
apps/appointments/validators.py
kirmalyshev/django_example
train
0
b7968d334791692082fdd99c2624240106846c7e
[ "sums = [0]\nfor x in nums:\n sums.append(sums[-1] + x)\ncount = 0\nfor j in range(len(sums)):\n for i in range(j):\n if sums[j] - sums[i] == k:\n count += 1\nreturn count", "count, sums = (0, 0)\ndic = {0: 1}\nfor x in nums:\n sums += x\n count += dic.get(sums - k, 0)\n dic[sums]...
<|body_start_0|> sums = [0] for x in nums: sums.append(sums[-1] + x) count = 0 for j in range(len(sums)): for i in range(j): if sums[j] - sums[i] == k: count += 1 return count <|end_body_0|> <|body_start_1|> cou...
求连续子数组的和,直接用暴力破解,穷举出所有子数组,算出和等于k即可。 如何求子数组的和sum(i,j)? 暴力法需要重复多次计算,而使用前缀和记录则是O(1) 即:sum(i,j) = sum(0,j) - sum(0,i-1) index: 0 1 2 4 nums: [ 1, 2, 1, 3 ] sum: 0, 1, 3, 4, 7 补位0,num==k的场景
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: """求连续子数组的和,直接用暴力破解,穷举出所有子数组,算出和等于k即可。 如何求子数组的和sum(i,j)? 暴力法需要重复多次计算,而使用前缀和记录则是O(1) 即:sum(i,j) = sum(0,j) - sum(0,i-1) index: 0 1 2 4 nums: [ 1, 2, 1, 3 ] sum: 0, 1, 3, 4, 7 补位0,num==k的场景""" def subarraySum1(self, nums: List[int], k: int) -> int: """前缀和:会超时,仅提供思路""" ...
stack_v2_sparse_classes_36k_train_032132
1,897
no_license
[ { "docstring": "前缀和:会超时,仅提供思路", "name": "subarraySum1", "signature": "def subarraySum1(self, nums: List[int], k: int) -> int" }, { "docstring": "前缀和+hash表优化: 问题转化为: 求i<j,满足sum(i) = sum(j) - k 对于每个j,记录之前所有的presum,然后查找有多少个presum==sum(j)-k", "name": "subarraySum2", "signature": "def subarra...
2
stack_v2_sparse_classes_30k_train_000374
Implement the Python class `Solution` described below. Class description: 求连续子数组的和,直接用暴力破解,穷举出所有子数组,算出和等于k即可。 如何求子数组的和sum(i,j)? 暴力法需要重复多次计算,而使用前缀和记录则是O(1) 即:sum(i,j) = sum(0,j) - sum(0,i-1) index: 0 1 2 4 nums: [ 1, 2, 1, 3 ] sum: 0, 1, 3, 4, 7 补位0,num==k的场景 Method signatures and docstrings: - def subarraySum1(self, ...
Implement the Python class `Solution` described below. Class description: 求连续子数组的和,直接用暴力破解,穷举出所有子数组,算出和等于k即可。 如何求子数组的和sum(i,j)? 暴力法需要重复多次计算,而使用前缀和记录则是O(1) 即:sum(i,j) = sum(0,j) - sum(0,i-1) index: 0 1 2 4 nums: [ 1, 2, 1, 3 ] sum: 0, 1, 3, 4, 7 补位0,num==k的场景 Method signatures and docstrings: - def subarraySum1(self, ...
2bbb1640589aab34f2bc42489283033cc11fb885
<|skeleton|> class Solution: """求连续子数组的和,直接用暴力破解,穷举出所有子数组,算出和等于k即可。 如何求子数组的和sum(i,j)? 暴力法需要重复多次计算,而使用前缀和记录则是O(1) 即:sum(i,j) = sum(0,j) - sum(0,i-1) index: 0 1 2 4 nums: [ 1, 2, 1, 3 ] sum: 0, 1, 3, 4, 7 补位0,num==k的场景""" def subarraySum1(self, nums: List[int], k: int) -> int: """前缀和:会超时,仅提供思路""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: """求连续子数组的和,直接用暴力破解,穷举出所有子数组,算出和等于k即可。 如何求子数组的和sum(i,j)? 暴力法需要重复多次计算,而使用前缀和记录则是O(1) 即:sum(i,j) = sum(0,j) - sum(0,i-1) index: 0 1 2 4 nums: [ 1, 2, 1, 3 ] sum: 0, 1, 3, 4, 7 补位0,num==k的场景""" def subarraySum1(self, nums: List[int], k: int) -> int: """前缀和:会超时,仅提供思路""" sums = [0] ...
the_stack_v2_python_sparse
560_subarray-sum-equals-k.py
helloocc/algorithm
train
1
f5fb50d0ef37b2b9bf4de53a09c355740486895a
[ "inputs = np.random.rand(2, input_size, input_size, 3)\ntf.keras.backend.set_image_data_format('channels_last')\nbackbone = basnet_model.BASNetEncoder()\ndecoder = basnet_model.BASNetDecoder()\nrefinement = refunet.RefUnet()\nmodel = basnet_model.BASNetModel(backbone=backbone, decoder=decoder, refinement=refinement...
<|body_start_0|> inputs = np.random.rand(2, input_size, input_size, 3) tf.keras.backend.set_image_data_format('channels_last') backbone = basnet_model.BASNetEncoder() decoder = basnet_model.BASNetDecoder() refinement = refunet.RefUnet() model = basnet_model.BASNetModel(ba...
BASNetNetworkTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BASNetNetworkTest: def test_basnet_network_creation(self, input_size): """Test for creation of a segmentation network.""" <|body_0|> def test_serialize_deserialize(self): """Validate the network can be serialized and deserialized.""" <|body_1|> <|end_skeleto...
stack_v2_sparse_classes_36k_train_032133
2,356
permissive
[ { "docstring": "Test for creation of a segmentation network.", "name": "test_basnet_network_creation", "signature": "def test_basnet_network_creation(self, input_size)" }, { "docstring": "Validate the network can be serialized and deserialized.", "name": "test_serialize_deserialize", "si...
2
null
Implement the Python class `BASNetNetworkTest` described below. Class description: Implement the BASNetNetworkTest class. Method signatures and docstrings: - def test_basnet_network_creation(self, input_size): Test for creation of a segmentation network. - def test_serialize_deserialize(self): Validate the network ca...
Implement the Python class `BASNetNetworkTest` described below. Class description: Implement the BASNetNetworkTest class. Method signatures and docstrings: - def test_basnet_network_creation(self, input_size): Test for creation of a segmentation network. - def test_serialize_deserialize(self): Validate the network ca...
d3507b550a3ade40cade60a79eb5b8978b56c7ae
<|skeleton|> class BASNetNetworkTest: def test_basnet_network_creation(self, input_size): """Test for creation of a segmentation network.""" <|body_0|> def test_serialize_deserialize(self): """Validate the network can be serialized and deserialized.""" <|body_1|> <|end_skeleto...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BASNetNetworkTest: def test_basnet_network_creation(self, input_size): """Test for creation of a segmentation network.""" inputs = np.random.rand(2, input_size, input_size, 3) tf.keras.backend.set_image_data_format('channels_last') backbone = basnet_model.BASNetEncoder() ...
the_stack_v2_python_sparse
official/projects/basnet/modeling/basnet_model_test.py
jianzhnie/models
train
2
04947dc78c4c62c5ad3066f80a4a7181443c8d43
[ "if len(s) % 2 != 0:\n return False\nif len(s) == 0:\n return True\nss1 = ['(', ')', '{', '}', '[', ']']\nfor i in range(0, 6, 2):\n if s.count(ss1[i]) != s.count(ss1[i + 1]):\n return False\nwhile '()' in s or '[]' in s or '{}' in s:\n s = s.replace('()', '')\n s = s.replace('[]', '')\n s ...
<|body_start_0|> if len(s) % 2 != 0: return False if len(s) == 0: return True ss1 = ['(', ')', '{', '}', '[', ']'] for i in range(0, 6, 2): if s.count(ss1[i]) != s.count(ss1[i + 1]): return False while '()' in s or '[]' in s or ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isValid1(self, s): """:type s: str :rtype: bool""" <|body_0|> def isValid(self, s): """:type s: str :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> if len(s) % 2 != 0: return False if len(s) == 0: ...
stack_v2_sparse_classes_36k_train_032134
1,310
no_license
[ { "docstring": ":type s: str :rtype: bool", "name": "isValid1", "signature": "def isValid1(self, s)" }, { "docstring": ":type s: str :rtype: bool", "name": "isValid", "signature": "def isValid(self, s)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isValid1(self, s): :type s: str :rtype: bool - def isValid(self, s): :type s: str :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isValid1(self, s): :type s: str :rtype: bool - def isValid(self, s): :type s: str :rtype: bool <|skeleton|> class Solution: def isValid1(self, s): """:type s: s...
f1d780b7e8b91b4df704651514018143c6931f9d
<|skeleton|> class Solution: def isValid1(self, s): """:type s: str :rtype: bool""" <|body_0|> def isValid(self, s): """:type s: str :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def isValid1(self, s): """:type s: str :rtype: bool""" if len(s) % 2 != 0: return False if len(s) == 0: return True ss1 = ['(', ')', '{', '}', '[', ']'] for i in range(0, 6, 2): if s.count(ss1[i]) != s.count(ss1[i + 1]): ...
the_stack_v2_python_sparse
ProgramForLeetCode/LeetCode/20_isvalid.py
DQDH/Algorithm_Code
train
0
116910a56c9988d6690a9e57ded9f98de6908be2
[ "i, n, res = (0, len(nums), [])\nwhile i < n:\n if nums[i] != i + 1 and nums[i] != nums[nums[i] - 1]:\n temp = nums[i]\n nums[i] = nums[nums[i] - 1]\n nums[temp - 1] = temp\n else:\n i += 1\nfor i, num in enumerate(nums):\n if i + 1 != num:\n res.append(i + 1)\nreturn res...
<|body_start_0|> i, n, res = (0, len(nums), []) while i < n: if nums[i] != i + 1 and nums[i] != nums[nums[i] - 1]: temp = nums[i] nums[i] = nums[nums[i] - 1] nums[temp - 1] = temp else: i += 1 for i, num in e...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: """Swap numbers to be at their correct indices. Time: O(n) Space: O(1) excluding output list""" <|body_0|> def findDisappearedNumbers2(self, nums: List[int]) -> List[int]: """Sort and add numbe...
stack_v2_sparse_classes_36k_train_032135
1,581
no_license
[ { "docstring": "Swap numbers to be at their correct indices. Time: O(n) Space: O(1) excluding output list", "name": "findDisappearedNumbers", "signature": "def findDisappearedNumbers(self, nums: List[int]) -> List[int]" }, { "docstring": "Sort and add numbers that aren't in nums. Time: O(nlogn) ...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findDisappearedNumbers(self, nums: List[int]) -> List[int]: Swap numbers to be at their correct indices. Time: O(n) Space: O(1) excluding output list - def findDisappearedNum...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findDisappearedNumbers(self, nums: List[int]) -> List[int]: Swap numbers to be at their correct indices. Time: O(n) Space: O(1) excluding output list - def findDisappearedNum...
c14d8829c95f61ff6691816e8c0de76b9319f389
<|skeleton|> class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: """Swap numbers to be at their correct indices. Time: O(n) Space: O(1) excluding output list""" <|body_0|> def findDisappearedNumbers2(self, nums: List[int]) -> List[int]: """Sort and add numbe...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: """Swap numbers to be at their correct indices. Time: O(n) Space: O(1) excluding output list""" i, n, res = (0, len(nums), []) while i < n: if nums[i] != i + 1 and nums[i] != nums[nums[i] - 1]: ...
the_stack_v2_python_sparse
easy/find-all-numbers-disappeared-in-an-array/solution.py
hsuanhauliu/leetcode-solutions
train
0
226826158e2f6b8d9717a4ca44c6bc8690282af4
[ "try:\n self.request_control = request.RequestController(endopoint=accounting_endpoint)\nexcept Exception as e:\n raise exceptions.ConfigurationException('Accounting server configuration failed %s. ' % e.message)", "path = '/set_accounting'\nparameters = {'admin_token': admin_token, 'accounting': accounting...
<|body_start_0|> try: self.request_control = request.RequestController(endopoint=accounting_endpoint) except Exception as e: raise exceptions.ConfigurationException('Accounting server configuration failed %s. ' % e.message) <|end_body_0|> <|body_start_1|> path = '/set_ac...
Notification controller for batch systems.
BatchNotificationController
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BatchNotificationController: """Notification controller for batch systems.""" def __init__(self, accounting_endpoint): """Initialize the controller It set attributes and creates a Request controller by using the endpoint related to the accounting server. :param accounting_endpoint: :...
stack_v2_sparse_classes_36k_train_032136
29,683
permissive
[ { "docstring": "Initialize the controller It set attributes and creates a Request controller by using the endpoint related to the accounting server. :param accounting_endpoint: :return:", "name": "__init__", "signature": "def __init__(self, accounting_endpoint)" }, { "docstring": "Execute a PUT ...
2
stack_v2_sparse_classes_30k_train_021390
Implement the Python class `BatchNotificationController` described below. Class description: Notification controller for batch systems. Method signatures and docstrings: - def __init__(self, accounting_endpoint): Initialize the controller It set attributes and creates a Request controller by using the endpoint relate...
Implement the Python class `BatchNotificationController` described below. Class description: Notification controller for batch systems. Method signatures and docstrings: - def __init__(self, accounting_endpoint): Initialize the controller It set attributes and creates a Request controller by using the endpoint relate...
346f5bdd7a1ff6c705c30172661a93540d9f0985
<|skeleton|> class BatchNotificationController: """Notification controller for batch systems.""" def __init__(self, accounting_endpoint): """Initialize the controller It set attributes and creates a Request controller by using the endpoint related to the accounting server. :param accounting_endpoint: :...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BatchNotificationController: """Notification controller for batch systems.""" def __init__(self, accounting_endpoint): """Initialize the controller It set attributes and creates a Request controller by using the endpoint related to the accounting server. :param accounting_endpoint: :return:""" ...
the_stack_v2_python_sparse
bdocker/modules/batch.py
indigo-dc/bdocker
train
4
2973a96cc233a04d740c4c88e720cc72fcb2afe8
[ "query.add_extra({'_': 'akeys(\"%s\")' % attr}, None, None, None, None, None)\nresult = query.get_compiler(self.db).execute_sql(SINGLE)\nreturn result[0] if result else []", "query.add_extra({'_': '%s -> %%s' % attr}, [key], None, None, None, None)\nresult = query.get_compiler(self.db).execute_sql(SINGLE)\nif res...
<|body_start_0|> query.add_extra({'_': 'akeys("%s")' % attr}, None, None, None, None, None) result = query.get_compiler(self.db).execute_sql(SINGLE) return result[0] if result else [] <|end_body_0|> <|body_start_1|> query.add_extra({'_': '%s -> %%s' % attr}, [key], None, None, None, Non...
HStoreQuerysetMixin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HStoreQuerysetMixin: def hkeys(self, query, attr): """Enumerates the keys in the specified hstore.""" <|body_0|> def hpeek(self, query, attr, key): """Peeks at a value of the specified key.""" <|body_1|> def hslice(self, query, attr, keys): """Sl...
stack_v2_sparse_classes_36k_train_032137
22,243
no_license
[ { "docstring": "Enumerates the keys in the specified hstore.", "name": "hkeys", "signature": "def hkeys(self, query, attr)" }, { "docstring": "Peeks at a value of the specified key.", "name": "hpeek", "signature": "def hpeek(self, query, attr, key)" }, { "docstring": "Slices the ...
5
null
Implement the Python class `HStoreQuerysetMixin` described below. Class description: Implement the HStoreQuerysetMixin class. Method signatures and docstrings: - def hkeys(self, query, attr): Enumerates the keys in the specified hstore. - def hpeek(self, query, attr, key): Peeks at a value of the specified key. - def...
Implement the Python class `HStoreQuerysetMixin` described below. Class description: Implement the HStoreQuerysetMixin class. Method signatures and docstrings: - def hkeys(self, query, attr): Enumerates the keys in the specified hstore. - def hpeek(self, query, attr, key): Peeks at a value of the specified key. - def...
0ac6653219c2701c13c508c5c4fc9bc3437eea06
<|skeleton|> class HStoreQuerysetMixin: def hkeys(self, query, attr): """Enumerates the keys in the specified hstore.""" <|body_0|> def hpeek(self, query, attr, key): """Peeks at a value of the specified key.""" <|body_1|> def hslice(self, query, attr, keys): """Sl...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HStoreQuerysetMixin: def hkeys(self, query, attr): """Enumerates the keys in the specified hstore.""" query.add_extra({'_': 'akeys("%s")' % attr}, None, None, None, None, None) result = query.get_compiler(self.db).execute_sql(SINGLE) return result[0] if result else [] def ...
the_stack_v2_python_sparse
repoData/djangonauts-djorm-ext-hstore/allPythonContent.py
aCoffeeYin/pyreco
train
0
27445d915c623dd4455d27eccec82fd15c242a74
[ "self._query = query\nself._doc_fields = doc_fields\nself._usr_fields = usr_fields\nself._hparams = hparams\nself._mode = mode\nself.text_ftr_size = len(hparams.filter_window_sizes) * hparams.num_filters\nself.embedding = model_utils.init_word_embedding(self._hparams, self._mode)\nwith tf.variable_scope('cnn', dtyp...
<|body_start_0|> self._query = query self._doc_fields = doc_fields self._usr_fields = usr_fields self._hparams = hparams self._mode = mode self.text_ftr_size = len(hparams.filter_window_sizes) * hparams.num_filters self.embedding = model_utils.init_word_embedding(...
CnnModel
[ "BSD-2-Clause", "BSD-3-Clause", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CnnModel: def __init__(self, query, doc_fields, usr_fields, hparams, mode): """Applies CNN to convert text to a fix length embedding :param query: Tensor(dtype=tf.int) Shape=[batch_size, query_length] :param doc_fields: list(Tensor(dtype=int))/Tensor A list of document fields. Each has s...
stack_v2_sparse_classes_36k_train_032138
7,785
permissive
[ { "docstring": "Applies CNN to convert text to a fix length embedding :param query: Tensor(dtype=tf.int) Shape=[batch_size, query_length] :param doc_fields: list(Tensor(dtype=int))/Tensor A list of document fields. Each has shape= [batch_size, max_group_size, doc_field_length]. For online scoring, these fields ...
4
stack_v2_sparse_classes_30k_train_007429
Implement the Python class `CnnModel` described below. Class description: Implement the CnnModel class. Method signatures and docstrings: - def __init__(self, query, doc_fields, usr_fields, hparams, mode): Applies CNN to convert text to a fix length embedding :param query: Tensor(dtype=tf.int) Shape=[batch_size, quer...
Implement the Python class `CnnModel` described below. Class description: Implement the CnnModel class. Method signatures and docstrings: - def __init__(self, query, doc_fields, usr_fields, hparams, mode): Applies CNN to convert text to a fix length embedding :param query: Tensor(dtype=tf.int) Shape=[batch_size, quer...
38e7b74879debd8ae5f2685367c81cc3a8aa003b
<|skeleton|> class CnnModel: def __init__(self, query, doc_fields, usr_fields, hparams, mode): """Applies CNN to convert text to a fix length embedding :param query: Tensor(dtype=tf.int) Shape=[batch_size, query_length] :param doc_fields: list(Tensor(dtype=int))/Tensor A list of document fields. Each has s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CnnModel: def __init__(self, query, doc_fields, usr_fields, hparams, mode): """Applies CNN to convert text to a fix length embedding :param query: Tensor(dtype=tf.int) Shape=[batch_size, query_length] :param doc_fields: list(Tensor(dtype=int))/Tensor A list of document fields. Each has shape= [batch_s...
the_stack_v2_python_sparse
src/detext/model/cnn_model.py
naimmalek/detext
train
1
80e6d23d72bfca7d4581cdae011a0567d315b373
[ "primary = self.getPrimaryField()\nif primary:\n return primary.getRaw(self)\nelse:\n return ''", "histories = list(self.getHistories(1))\nif not histories:\n return None\nuser = histories[0][3].split(' ')[-1].strip()\nreturn user", "mTool = getToolByName(self, 'portal_membership')\nhistories = list(se...
<|body_start_0|> primary = self.getPrimaryField() if primary: return primary.getRaw(self) else: return '' <|end_body_0|> <|body_start_1|> histories = list(self.getHistories(1)) if not histories: return None user = histories[0][3].split...
History aware mixin class Shows a unified diff history of the content This mixin is using some low level functions of the ZODB to get the last transaction states (versions) of the current object. Older histories will disapear after packing the database so DO NOT rely on the history functionality. It's more a gimmick an...
HistoryAwareMixin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HistoryAwareMixin: """History aware mixin class Shows a unified diff history of the content This mixin is using some low level functions of the ZODB to get the last transaction states (versions) of the current object. Older histories will disapear after packing the database so DO NOT rely on the ...
stack_v2_sparse_classes_36k_train_032139
3,584
no_license
[ { "docstring": "get source for HistoryAwareMixin Must return a (raw) string", "name": "getHistorySource", "signature": "def getHistorySource(self)" }, { "docstring": "Returns the user name of the last editor. Returns None if no last editor is known.", "name": "getLastEditor", "signature"...
3
null
Implement the Python class `HistoryAwareMixin` described below. Class description: History aware mixin class Shows a unified diff history of the content This mixin is using some low level functions of the ZODB to get the last transaction states (versions) of the current object. Older histories will disapear after pack...
Implement the Python class `HistoryAwareMixin` described below. Class description: History aware mixin class Shows a unified diff history of the content This mixin is using some low level functions of the ZODB to get the last transaction states (versions) of the current object. Older histories will disapear after pack...
9c59626073daa97162c2b1d33a39a043f386cd8e
<|skeleton|> class HistoryAwareMixin: """History aware mixin class Shows a unified diff history of the content This mixin is using some low level functions of the ZODB to get the last transaction states (versions) of the current object. Older histories will disapear after packing the database so DO NOT rely on the ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HistoryAwareMixin: """History aware mixin class Shows a unified diff history of the content This mixin is using some low level functions of the ZODB to get the last transaction states (versions) of the current object. Older histories will disapear after packing the database so DO NOT rely on the history funct...
the_stack_v2_python_sparse
Products/ATContentTypes/lib/historyaware.py
plone/Products.ATContentTypes
train
1
05fd99b059a217e2030ac146acccfae954a3078b
[ "src_type, src_path = self.identify_type(src)\ndest_type, dest_path = self.identify_type(dest)\nformat_table = {'s3': self.s3_format, 'local': self.local_format}\ndir_op = parameters['dir_op']\nsrc_path = format_table[src_type](src_path, dir_op)[0]\ndest_path, use_src_name = format_table[dest_type](dest_path, dir_o...
<|body_start_0|> src_type, src_path = self.identify_type(src) dest_type, dest_path = self.identify_type(dest) format_table = {'s3': self.s3_format, 'local': self.local_format} dir_op = parameters['dir_op'] src_path = format_table[src_type](src_path, dir_op)[0] dest_path, ...
FileFormat
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FileFormat: def format(self, src, dest, parameters): """This function formats the source and destination path to the proper form for a file generator. Note that a file is designated as an s3 file if it begins with s3:// :param src: The path of the source :type src: string :param dest: Th...
stack_v2_sparse_classes_36k_train_032140
6,027
permissive
[ { "docstring": "This function formats the source and destination path to the proper form for a file generator. Note that a file is designated as an s3 file if it begins with s3:// :param src: The path of the source :type src: string :param dest: The path of the dest :type dest: string :param parameters: A dicti...
4
null
Implement the Python class `FileFormat` described below. Class description: Implement the FileFormat class. Method signatures and docstrings: - def format(self, src, dest, parameters): This function formats the source and destination path to the proper form for a file generator. Note that a file is designated as an s...
Implement the Python class `FileFormat` described below. Class description: Implement the FileFormat class. Method signatures and docstrings: - def format(self, src, dest, parameters): This function formats the source and destination path to the proper form for a file generator. Note that a file is designated as an s...
147d16dfdb72dc9cf362b676a57e46a49375afbd
<|skeleton|> class FileFormat: def format(self, src, dest, parameters): """This function formats the source and destination path to the proper form for a file generator. Note that a file is designated as an s3 file if it begins with s3:// :param src: The path of the source :type src: string :param dest: Th...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FileFormat: def format(self, src, dest, parameters): """This function formats the source and destination path to the proper form for a file generator. Note that a file is designated as an s3 file if it begins with s3:// :param src: The path of the source :type src: string :param dest: The path of the ...
the_stack_v2_python_sparse
awscli/customizations/s3/fileformat.py
aws/aws-cli
train
13,038
528c8b5d28b583c4a0e0d04572fdcf3a2e36fd38
[ "args = {}\nargs.update(cls.args_map_export())\nargs.update({'json_flat': False})\nreturn args", "super(Json, self).start(**kwargs)\nflat = self.get_arg_value('json_flat')\nself._first_row = True\nself.open_fd()\nbegin = '' if flat else '['\nself._fd.write(begin)", "super(Json, self).stop(**kwargs)\nflat = self...
<|body_start_0|> args = {} args.update(cls.args_map_export()) args.update({'json_flat': False}) return args <|end_body_0|> <|body_start_1|> super(Json, self).start(**kwargs) flat = self.get_arg_value('json_flat') self._first_row = True self.open_fd() ...
Callbacks for formatting asset data and exporting it in JSON format. Examples: Create a ``client`` using :obj:`axonius_api_client.connect.Connect` and assume ``apiobj`` is either ``client.devices`` or ``client.users`` >>> apiobj = client.devices # or client.users * :meth:`args_map` for callback generic arguments to for...
Json
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Json: """Callbacks for formatting asset data and exporting it in JSON format. Examples: Create a ``client`` using :obj:`axonius_api_client.connect.Connect` and assume ``apiobj`` is either ``client.devices`` or ``client.users`` >>> apiobj = client.devices # or client.users * :meth:`args_map` for c...
stack_v2_sparse_classes_36k_train_032141
4,497
permissive
[ { "docstring": "Get the custom argument names and their defaults for this callbacks object. Examples: Export the output to STDOUT. If ``export_file`` is not supplied, the default is to print the output to STDOUT. >>> assets = apiobj.get(export=\"json\") Export the output to a file in the default path :attr:`axo...
6
stack_v2_sparse_classes_30k_train_003949
Implement the Python class `Json` described below. Class description: Callbacks for formatting asset data and exporting it in JSON format. Examples: Create a ``client`` using :obj:`axonius_api_client.connect.Connect` and assume ``apiobj`` is either ``client.devices`` or ``client.users`` >>> apiobj = client.devices # o...
Implement the Python class `Json` described below. Class description: Callbacks for formatting asset data and exporting it in JSON format. Examples: Create a ``client`` using :obj:`axonius_api_client.connect.Connect` and assume ``apiobj`` is either ``client.devices`` or ``client.users`` >>> apiobj = client.devices # o...
be49566e590834df1b46494c8588651fa029b8c5
<|skeleton|> class Json: """Callbacks for formatting asset data and exporting it in JSON format. Examples: Create a ``client`` using :obj:`axonius_api_client.connect.Connect` and assume ``apiobj`` is either ``client.devices`` or ``client.users`` >>> apiobj = client.devices # or client.users * :meth:`args_map` for c...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Json: """Callbacks for formatting asset data and exporting it in JSON format. Examples: Create a ``client`` using :obj:`axonius_api_client.connect.Connect` and assume ``apiobj`` is either ``client.devices`` or ``client.users`` >>> apiobj = client.devices # or client.users * :meth:`args_map` for callback gener...
the_stack_v2_python_sparse
axonius_api_client/api/asset_callbacks/base_json.py
Axonius/axonius_api_client
train
17
0c5dc20af8517fcbf26c935fce8d1bc1a5ac746d
[ "assert number_rows > 0\nassert number_columns > 0\nsuper().__init__(self.PROBLEM_NAME)\nself.number_rows = number_rows\nself.number_columns = number_columns", "print('Solving {} problem ...'.format(self.PROBLEM_NAME))\nm = self.number_rows\nn = self.number_columns\npath_matrix = [[-1 for i in range(n)] for j in ...
<|body_start_0|> assert number_rows > 0 assert number_columns > 0 super().__init__(self.PROBLEM_NAME) self.number_rows = number_rows self.number_columns = number_columns <|end_body_0|> <|body_start_1|> print('Solving {} problem ...'.format(self.PROBLEM_NAME)) m =...
Unique Paths
UniquePaths
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UniquePaths: """Unique Paths""" def __init__(self, number_rows, number_columns): """Unique Paths Args: number_rows: Number of rows in the matrix number_columns: Number of columns in the matrix Returns: None Raises: None""" <|body_0|> def solve(self): """Solve the...
stack_v2_sparse_classes_36k_train_032142
1,885
no_license
[ { "docstring": "Unique Paths Args: number_rows: Number of rows in the matrix number_columns: Number of columns in the matrix Returns: None Raises: None", "name": "__init__", "signature": "def __init__(self, number_rows, number_columns)" }, { "docstring": "Solve the problem Note: O(mn) solution w...
2
null
Implement the Python class `UniquePaths` described below. Class description: Unique Paths Method signatures and docstrings: - def __init__(self, number_rows, number_columns): Unique Paths Args: number_rows: Number of rows in the matrix number_columns: Number of columns in the matrix Returns: None Raises: None - def s...
Implement the Python class `UniquePaths` described below. Class description: Unique Paths Method signatures and docstrings: - def __init__(self, number_rows, number_columns): Unique Paths Args: number_rows: Number of rows in the matrix number_columns: Number of columns in the matrix Returns: None Raises: None - def s...
11f4d25cb211740514c119a60962d075a0817abd
<|skeleton|> class UniquePaths: """Unique Paths""" def __init__(self, number_rows, number_columns): """Unique Paths Args: number_rows: Number of rows in the matrix number_columns: Number of columns in the matrix Returns: None Raises: None""" <|body_0|> def solve(self): """Solve the...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UniquePaths: """Unique Paths""" def __init__(self, number_rows, number_columns): """Unique Paths Args: number_rows: Number of rows in the matrix number_columns: Number of columns in the matrix Returns: None Raises: None""" assert number_rows > 0 assert number_columns > 0 s...
the_stack_v2_python_sparse
python/problems/dynamic_programming/unique_paths.py
santhosh-kumar/AlgorithmsAndDataStructures
train
2
a7af196c40923c3f22ed2facd7df2162b85ffe15
[ "super(FeatureFusionBlock_custom, self).__init__()\nself.deconv = deconv\nself.align_corners = align_corners\nself.groups = 1\nself.expand = expand\nout_features = features\nif self.expand == True:\n out_features = features // 2\nself.out_conv = nn.Conv2D(features, out_features, kernel_size=1, stride=1, padding=...
<|body_start_0|> super(FeatureFusionBlock_custom, self).__init__() self.deconv = deconv self.align_corners = align_corners self.groups = 1 self.expand = expand out_features = features if self.expand == True: out_features = features // 2 self.ou...
Feature fusion block.
FeatureFusionBlock_custom
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FeatureFusionBlock_custom: """Feature fusion block.""" def __init__(self, features, activation=nn.ReLU(), deconv=False, bn=False, expand=False, align_corners=True): """Init. Args: features (int): number of features""" <|body_0|> def forward(self, *xs): """Forward...
stack_v2_sparse_classes_36k_train_032143
7,931
permissive
[ { "docstring": "Init. Args: features (int): number of features", "name": "__init__", "signature": "def __init__(self, features, activation=nn.ReLU(), deconv=False, bn=False, expand=False, align_corners=True)" }, { "docstring": "Forward pass. Returns: tensor: output", "name": "forward", "...
2
null
Implement the Python class `FeatureFusionBlock_custom` described below. Class description: Feature fusion block. Method signatures and docstrings: - def __init__(self, features, activation=nn.ReLU(), deconv=False, bn=False, expand=False, align_corners=True): Init. Args: features (int): number of features - def forwar...
Implement the Python class `FeatureFusionBlock_custom` described below. Class description: Feature fusion block. Method signatures and docstrings: - def __init__(self, features, activation=nn.ReLU(), deconv=False, bn=False, expand=False, align_corners=True): Init. Args: features (int): number of features - def forwar...
b402610a6f0b382a978e82473b541ea1fc6cf09a
<|skeleton|> class FeatureFusionBlock_custom: """Feature fusion block.""" def __init__(self, features, activation=nn.ReLU(), deconv=False, bn=False, expand=False, align_corners=True): """Init. Args: features (int): number of features""" <|body_0|> def forward(self, *xs): """Forward...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FeatureFusionBlock_custom: """Feature fusion block.""" def __init__(self, features, activation=nn.ReLU(), deconv=False, bn=False, expand=False, align_corners=True): """Init. Args: features (int): number of features""" super(FeatureFusionBlock_custom, self).__init__() self.deconv =...
the_stack_v2_python_sparse
modules/image/semantic_segmentation/lseg/models/scratch.py
PaddlePaddle/PaddleHub
train
12,914
8f4a9be4611d012c6f8a05fe6183fda335c322e5
[ "self.nums = nums\nself.dicts = {}\n\ndef dfs(start, end):\n if start > end:\n return 0\n if (start, end) in self.dicts.keys():\n return self.dicts[start, end]\n if start == end:\n self.dicts[start, end] = self.nums[start]\n return self.nums[start]\n else:\n a = dfs(st...
<|body_start_0|> self.nums = nums self.dicts = {} def dfs(start, end): if start > end: return 0 if (start, end) in self.dicts.keys(): return self.dicts[start, end] if start == end: self.dicts[start, end] = self....
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def PredictTheWinner(self, nums): """:type nums: List[int] :rtype: bool 62ms""" <|body_0|> def PredictTheWinner_1(self, nums): """:type nums: List[int] :rtype: bool 32ms""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.nums = nums ...
stack_v2_sparse_classes_36k_train_032144
2,954
no_license
[ { "docstring": ":type nums: List[int] :rtype: bool 62ms", "name": "PredictTheWinner", "signature": "def PredictTheWinner(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: bool 32ms", "name": "PredictTheWinner_1", "signature": "def PredictTheWinner_1(self, nums)" } ]
2
stack_v2_sparse_classes_30k_train_013648
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def PredictTheWinner(self, nums): :type nums: List[int] :rtype: bool 62ms - def PredictTheWinner_1(self, nums): :type nums: List[int] :rtype: bool 32ms
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def PredictTheWinner(self, nums): :type nums: List[int] :rtype: bool 62ms - def PredictTheWinner_1(self, nums): :type nums: List[int] :rtype: bool 32ms <|skeleton|> class Soluti...
679a2b246b8b6bb7fc55ed1c8096d3047d6d4461
<|skeleton|> class Solution: def PredictTheWinner(self, nums): """:type nums: List[int] :rtype: bool 62ms""" <|body_0|> def PredictTheWinner_1(self, nums): """:type nums: List[int] :rtype: bool 32ms""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def PredictTheWinner(self, nums): """:type nums: List[int] :rtype: bool 62ms""" self.nums = nums self.dicts = {} def dfs(start, end): if start > end: return 0 if (start, end) in self.dicts.keys(): return self.di...
the_stack_v2_python_sparse
PredictTheWinner_MID_486.py
953250587/leetcode-python
train
2
a9a323d15c906da2be29e958fcc561740b986a22
[ "self.db = database\nself.cache = cache\nif auto_define:\n self.define_tables(migrate=migrate, fake_migrate=fake_migrate)\n self._get_settings()", "self.db.define_table('settings', Field('kkey'), Field('name'), Field('value', 'text'), Field('value_type'), Field('description', 'text'), Field('created_on', 'd...
<|body_start_0|> self.db = database self.cache = cache if auto_define: self.define_tables(migrate=migrate, fake_migrate=fake_migrate) self._get_settings() <|end_body_0|> <|body_start_1|> self.db.define_table('settings', Field('kkey'), Field('name'), Field('value'...
This class implements a configurable set of options for use in anything that needs settings that are to be stored in the database.
Configure
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Configure: """This class implements a configurable set of options for use in anything that needs settings that are to be stored in the database.""" def __init__(self, database, auto_define=True, migrate=True, fake_migrate=False, cache=None): """Initialize configure class. Keyword aru...
stack_v2_sparse_classes_36k_train_032145
6,588
no_license
[ { "docstring": "Initialize configure class. Keyword arugments: database -- web2py DAL instance auto_define -- auto define database tables (default: True) migrate -- migrate the database tables (default: True) cache -- cache object to use for pulling database settings, this is a tuple object consisting of cache ...
6
stack_v2_sparse_classes_30k_train_014231
Implement the Python class `Configure` described below. Class description: This class implements a configurable set of options for use in anything that needs settings that are to be stored in the database. Method signatures and docstrings: - def __init__(self, database, auto_define=True, migrate=True, fake_migrate=Fa...
Implement the Python class `Configure` described below. Class description: This class implements a configurable set of options for use in anything that needs settings that are to be stored in the database. Method signatures and docstrings: - def __init__(self, database, auto_define=True, migrate=True, fake_migrate=Fa...
44e9250a28ae3284bef242ad042624338e405fbb
<|skeleton|> class Configure: """This class implements a configurable set of options for use in anything that needs settings that are to be stored in the database.""" def __init__(self, database, auto_define=True, migrate=True, fake_migrate=False, cache=None): """Initialize configure class. Keyword aru...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Configure: """This class implements a configurable set of options for use in anything that needs settings that are to be stored in the database.""" def __init__(self, database, auto_define=True, migrate=True, fake_migrate=False, cache=None): """Initialize configure class. Keyword arugments: datab...
the_stack_v2_python_sparse
modules/web2py_utils/configure.py
Baffour/iapt-spring
train
1
c63d21c730744bed4915141c8afc7ac15d35c718
[ "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "conte...
<|body_start_0|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') <|end_body_0|> <|body_start_1|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not im...
A service that handles tenant management, including CRUD and enumeration.
TenantServiceServicer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TenantServiceServicer: """A service that handles tenant management, including CRUD and enumeration.""" def CreateTenant(self, request, context): """Creates a new tenant entity.""" <|body_0|> def GetTenant(self, request, context): """Retrieves specified tenant."""...
stack_v2_sparse_classes_36k_train_032146
6,155
permissive
[ { "docstring": "Creates a new tenant entity.", "name": "CreateTenant", "signature": "def CreateTenant(self, request, context)" }, { "docstring": "Retrieves specified tenant.", "name": "GetTenant", "signature": "def GetTenant(self, request, context)" }, { "docstring": "Updates spe...
5
null
Implement the Python class `TenantServiceServicer` described below. Class description: A service that handles tenant management, including CRUD and enumeration. Method signatures and docstrings: - def CreateTenant(self, request, context): Creates a new tenant entity. - def GetTenant(self, request, context): Retrieves...
Implement the Python class `TenantServiceServicer` described below. Class description: A service that handles tenant management, including CRUD and enumeration. Method signatures and docstrings: - def CreateTenant(self, request, context): Creates a new tenant entity. - def GetTenant(self, request, context): Retrieves...
d897d56bce03d1fda98b79afb08264e51d46c421
<|skeleton|> class TenantServiceServicer: """A service that handles tenant management, including CRUD and enumeration.""" def CreateTenant(self, request, context): """Creates a new tenant entity.""" <|body_0|> def GetTenant(self, request, context): """Retrieves specified tenant."""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TenantServiceServicer: """A service that handles tenant management, including CRUD and enumeration.""" def CreateTenant(self, request, context): """Creates a new tenant entity.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') ...
the_stack_v2_python_sparse
talent/google/cloud/talent_v4beta1/proto/tenant_service_pb2_grpc.py
tswast/google-cloud-python
train
1
36d7f35ff2d557ab4a3036d467a7da54ccacc7f1
[ "x = len(matrix)\ny = 0\nif x != 0:\n y = len(matrix[0])\nfor i in range(x):\n for j in range(y):\n left = 0\n top = 0\n leftTop = 0\n if j - 1 >= 0:\n left = matrix[i][j - 1]\n if i - 1 >= 0:\n top = matrix[i - 1][j]\n if i - 1 >= 0 and j - 1 >=...
<|body_start_0|> x = len(matrix) y = 0 if x != 0: y = len(matrix[0]) for i in range(x): for j in range(y): left = 0 top = 0 leftTop = 0 if j - 1 >= 0: left = matrix[i][j - 1] ...
NumMatrix
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NumMatrix: def __init__(self, matrix): """:type matrix: List[List[int]]""" <|body_0|> def sumRegion(self, row1, col1, row2, col2): """:type row1: int :type col1: int :type row2: int :type col2: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|>...
stack_v2_sparse_classes_36k_train_032147
1,387
no_license
[ { "docstring": ":type matrix: List[List[int]]", "name": "__init__", "signature": "def __init__(self, matrix)" }, { "docstring": ":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int", "name": "sumRegion", "signature": "def sumRegion(self, row1, col1, row2, col2)" ...
2
null
Implement the Python class `NumMatrix` described below. Class description: Implement the NumMatrix class. Method signatures and docstrings: - def __init__(self, matrix): :type matrix: List[List[int]] - def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:...
Implement the Python class `NumMatrix` described below. Class description: Implement the NumMatrix class. Method signatures and docstrings: - def __init__(self, matrix): :type matrix: List[List[int]] - def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:...
b890a5ea050cfe3886b5275cc26c1593b35b58db
<|skeleton|> class NumMatrix: def __init__(self, matrix): """:type matrix: List[List[int]]""" <|body_0|> def sumRegion(self, row1, col1, row2, col2): """:type row1: int :type col1: int :type row2: int :type col2: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NumMatrix: def __init__(self, matrix): """:type matrix: List[List[int]]""" x = len(matrix) y = 0 if x != 0: y = len(matrix[0]) for i in range(x): for j in range(y): left = 0 top = 0 leftTop = 0 ...
the_stack_v2_python_sparse
面试练习/304.py
QkqBeer/PythonSubject
train
4
9861268e721429a9d8da4a0385df2b1c08e517ef
[ "super().__init__(parent)\nself.figure_waveform = Figure()\nself.figure_spectrum = Figure()\nself.canvas_waveform = FigureCanvas(self.figure_waveform)\nself.canvas_spectrum = FigureCanvas(self.figure_spectrum)\nself.layout = QGridLayout(self)\nself.layout.addWidget(self.canvas_waveform, 0, 0)\nself.layout.addWidget...
<|body_start_0|> super().__init__(parent) self.figure_waveform = Figure() self.figure_spectrum = Figure() self.canvas_waveform = FigureCanvas(self.figure_waveform) self.canvas_spectrum = FigureCanvas(self.figure_spectrum) self.layout = QGridLayout(self) self.layou...
A QWidget that displays audio waveform and spectrum using Matplotlib.
AudioWidget
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AudioWidget: """A QWidget that displays audio waveform and spectrum using Matplotlib.""" def __init__(self, audio_path, parent=None): """Constructor for the AudioWidget class. Args: audio_path (str): Path to the audio file. parent (QWidget): Optional parent widget.""" <|body_...
stack_v2_sparse_classes_36k_train_032148
3,129
permissive
[ { "docstring": "Constructor for the AudioWidget class. Args: audio_path (str): Path to the audio file. parent (QWidget): Optional parent widget.", "name": "__init__", "signature": "def __init__(self, audio_path, parent=None)" }, { "docstring": "Plot the audio waveform and spectrum.", "name":...
3
stack_v2_sparse_classes_30k_train_011400
Implement the Python class `AudioWidget` described below. Class description: A QWidget that displays audio waveform and spectrum using Matplotlib. Method signatures and docstrings: - def __init__(self, audio_path, parent=None): Constructor for the AudioWidget class. Args: audio_path (str): Path to the audio file. par...
Implement the Python class `AudioWidget` described below. Class description: A QWidget that displays audio waveform and spectrum using Matplotlib. Method signatures and docstrings: - def __init__(self, audio_path, parent=None): Constructor for the AudioWidget class. Args: audio_path (str): Path to the audio file. par...
730f7dff2239ef716841390311b5b9250149acaf
<|skeleton|> class AudioWidget: """A QWidget that displays audio waveform and spectrum using Matplotlib.""" def __init__(self, audio_path, parent=None): """Constructor for the AudioWidget class. Args: audio_path (str): Path to the audio file. parent (QWidget): Optional parent widget.""" <|body_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AudioWidget: """A QWidget that displays audio waveform and spectrum using Matplotlib.""" def __init__(self, audio_path, parent=None): """Constructor for the AudioWidget class. Args: audio_path (str): Path to the audio file. parent (QWidget): Optional parent widget.""" super().__init__(par...
the_stack_v2_python_sparse
annolid/gui/widgets/audio.py
healthonrails/annolid
train
25
3b8c14b1c911048b737599c27dc773218fc4b61a
[ "super(DecoderRNN, self).__init__()\nself.embed = nn.Embedding(vocab_size, embed_size)\nself.lstm = nn.LSTM(embed_size, hidden_size, num_layers, batch_first=True)\nself.linear = nn.Linear(hidden_size, vocab_size)", "captions = captions[:, :-1]\nembeddings = self.embed(captions)\ninputs = torch.cat((features.unsqu...
<|body_start_0|> super(DecoderRNN, self).__init__() self.embed = nn.Embedding(vocab_size, embed_size) self.lstm = nn.LSTM(embed_size, hidden_size, num_layers, batch_first=True) self.linear = nn.Linear(hidden_size, vocab_size) <|end_body_0|> <|body_start_1|> captions = captions[:...
DecoderRNN
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DecoderRNN: def __init__(self, embed_size, hidden_size, vocab_size, num_layers=1): """Set the hyper-parameters and build the layers.""" <|body_0|> def forward(self, features, captions): """Decode image feature vectors and generates captions.""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_032149
4,303
permissive
[ { "docstring": "Set the hyper-parameters and build the layers.", "name": "__init__", "signature": "def __init__(self, embed_size, hidden_size, vocab_size, num_layers=1)" }, { "docstring": "Decode image feature vectors and generates captions.", "name": "forward", "signature": "def forward...
4
stack_v2_sparse_classes_30k_train_010957
Implement the Python class `DecoderRNN` described below. Class description: Implement the DecoderRNN class. Method signatures and docstrings: - def __init__(self, embed_size, hidden_size, vocab_size, num_layers=1): Set the hyper-parameters and build the layers. - def forward(self, features, captions): Decode image fe...
Implement the Python class `DecoderRNN` described below. Class description: Implement the DecoderRNN class. Method signatures and docstrings: - def __init__(self, embed_size, hidden_size, vocab_size, num_layers=1): Set the hyper-parameters and build the layers. - def forward(self, features, captions): Decode image fe...
2b558076dd7467acc2bcaf4c7480d48b129688a3
<|skeleton|> class DecoderRNN: def __init__(self, embed_size, hidden_size, vocab_size, num_layers=1): """Set the hyper-parameters and build the layers.""" <|body_0|> def forward(self, features, captions): """Decode image feature vectors and generates captions.""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DecoderRNN: def __init__(self, embed_size, hidden_size, vocab_size, num_layers=1): """Set the hyper-parameters and build the layers.""" super(DecoderRNN, self).__init__() self.embed = nn.Embedding(vocab_size, embed_size) self.lstm = nn.LSTM(embed_size, hidden_size, num_layers, ...
the_stack_v2_python_sparse
NIC/image_captioning/model.py
jomycs/Book-KnowledgeGraph-Recommendation
train
1
62ba06d61266d78b7ab6fc03e77c8d0a7fe8feed
[ "if n == 1:\n return k\ntwo_posts_back = k\none_post_back = k * k\nfor i in range(3, n + 1):\n curr = (k - 1) * (one_post_back + two_posts_back)\n two_posts_back = one_post_back\n one_post_back = curr\nreturn one_post_back", "if n == 1:\n return k\nif n == 2:\n return k * k\ndp = [0] * (n + 1)\n...
<|body_start_0|> if n == 1: return k two_posts_back = k one_post_back = k * k for i in range(3, n + 1): curr = (k - 1) * (one_post_back + two_posts_back) two_posts_back = one_post_back one_post_back = curr return one_post_back <|end...
Fence
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Fence: def number_of_ways_to_paint(self, n: int, k: int) -> int: """Approach: DP - Bottom Up (Constant Space) Time Complexity: O(N) Space Complexity: O(1) :param n: :param k: :return:""" <|body_0|> def number_of_ways_to_paint_(self, n: int, k: int) -> int: """Approac...
stack_v2_sparse_classes_36k_train_032150
1,833
no_license
[ { "docstring": "Approach: DP - Bottom Up (Constant Space) Time Complexity: O(N) Space Complexity: O(1) :param n: :param k: :return:", "name": "number_of_ways_to_paint", "signature": "def number_of_ways_to_paint(self, n: int, k: int) -> int" }, { "docstring": "Approach: DP - Bottom Up Time Comple...
3
null
Implement the Python class `Fence` described below. Class description: Implement the Fence class. Method signatures and docstrings: - def number_of_ways_to_paint(self, n: int, k: int) -> int: Approach: DP - Bottom Up (Constant Space) Time Complexity: O(N) Space Complexity: O(1) :param n: :param k: :return: - def numb...
Implement the Python class `Fence` described below. Class description: Implement the Fence class. Method signatures and docstrings: - def number_of_ways_to_paint(self, n: int, k: int) -> int: Approach: DP - Bottom Up (Constant Space) Time Complexity: O(N) Space Complexity: O(1) :param n: :param k: :return: - def numb...
65cc78b5afa0db064f9fe8f06597e3e120f7363d
<|skeleton|> class Fence: def number_of_ways_to_paint(self, n: int, k: int) -> int: """Approach: DP - Bottom Up (Constant Space) Time Complexity: O(N) Space Complexity: O(1) :param n: :param k: :return:""" <|body_0|> def number_of_ways_to_paint_(self, n: int, k: int) -> int: """Approac...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Fence: def number_of_ways_to_paint(self, n: int, k: int) -> int: """Approach: DP - Bottom Up (Constant Space) Time Complexity: O(N) Space Complexity: O(1) :param n: :param k: :return:""" if n == 1: return k two_posts_back = k one_post_back = k * k for i in r...
the_stack_v2_python_sparse
expedia/paint_fence.py
Shiv2157k/leet_code
train
1
3ef17ef6d07db3ad0d73923b1c598b17382b9274
[ "if version:\n if version == 4:\n return Command.executeIp(logger, IpConstant.IPV4, IpOption.RULE, IpAction.SHOW)\n elif version == 6:\n return Command.executeIp(logger, IpConstant.IPV6, IpOption.RULE, IpAction.SHOW)\nrc = Command.executeIp(logger, IpOption.RULE, IpAction.SHOW)\nreturn rc", "i...
<|body_start_0|> if version: if version == 4: return Command.executeIp(logger, IpConstant.IPV4, IpOption.RULE, IpAction.SHOW) elif version == 6: return Command.executeIp(logger, IpConstant.IPV6, IpOption.RULE, IpAction.SHOW) rc = Command.executeIp(...
IpRule
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IpRule: def showRules(logger, version=None): """This function list all rules Args: logger Return: tuple (rc, stdout, stderr) Raise: None""" <|body_0|> def addRule(logger, source, table, version=None): """This function inserts a new rule Args: logger source - select t...
stack_v2_sparse_classes_36k_train_032151
23,984
no_license
[ { "docstring": "This function list all rules Args: logger Return: tuple (rc, stdout, stderr) Raise: None", "name": "showRules", "signature": "def showRules(logger, version=None)" }, { "docstring": "This function inserts a new rule Args: logger source - select the source prefix to match. table - ...
4
null
Implement the Python class `IpRule` described below. Class description: Implement the IpRule class. Method signatures and docstrings: - def showRules(logger, version=None): This function list all rules Args: logger Return: tuple (rc, stdout, stderr) Raise: None - def addRule(logger, source, table, version=None): This...
Implement the Python class `IpRule` described below. Class description: Implement the IpRule class. Method signatures and docstrings: - def showRules(logger, version=None): This function list all rules Args: logger Return: tuple (rc, stdout, stderr) Raise: None - def addRule(logger, source, table, version=None): This...
81bcc74fe7c0ca036ec483f634d7be0bab19a6d0
<|skeleton|> class IpRule: def showRules(logger, version=None): """This function list all rules Args: logger Return: tuple (rc, stdout, stderr) Raise: None""" <|body_0|> def addRule(logger, source, table, version=None): """This function inserts a new rule Args: logger source - select t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class IpRule: def showRules(logger, version=None): """This function list all rules Args: logger Return: tuple (rc, stdout, stderr) Raise: None""" if version: if version == 4: return Command.executeIp(logger, IpConstant.IPV4, IpOption.RULE, IpAction.SHOW) elif ...
the_stack_v2_python_sparse
oscar/a/sys/net/lnx/route.py
afeset/miner2-tools
train
0
31c53490c06bfa0e3c5ccca769db2e318c4527ff
[ "super(SimpleNet, self).__init__()\nself.conv_layers = None\nself.fc_layers = None\nself.loss_criterion = None\nself.conv_layers = nn.Sequential(nn.Conv2d(1, 10, kernel_size=5, stride=1), nn.ReLU(), nn.MaxPool2d(3), nn.Conv2d(10, 20, kernel_size=5, stride=1), nn.ReLU(), nn.MaxPool2d(3))\nconv_out = int(20 * 5 * 5)\...
<|body_start_0|> super(SimpleNet, self).__init__() self.conv_layers = None self.fc_layers = None self.loss_criterion = None self.conv_layers = nn.Sequential(nn.Conv2d(1, 10, kernel_size=5, stride=1), nn.ReLU(), nn.MaxPool2d(3), nn.Conv2d(10, 20, kernel_size=5, stride=1), nn.ReLU(...
SimpleNet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SimpleNet: def __init__(self): """Constructor for SimpleNet class to define the layers and loss function. Note: Use 'mean' reduction in the loss_criterion. Read Pytorch's documention to understand what this means.""" <|body_0|> def forward(self, x: torch.Tensor) -> torch.Ten...
stack_v2_sparse_classes_36k_train_032152
2,210
no_license
[ { "docstring": "Constructor for SimpleNet class to define the layers and loss function. Note: Use 'mean' reduction in the loss_criterion. Read Pytorch's documention to understand what this means.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Perform the forward pass ...
2
stack_v2_sparse_classes_30k_train_001832
Implement the Python class `SimpleNet` described below. Class description: Implement the SimpleNet class. Method signatures and docstrings: - def __init__(self): Constructor for SimpleNet class to define the layers and loss function. Note: Use 'mean' reduction in the loss_criterion. Read Pytorch's documention to unde...
Implement the Python class `SimpleNet` described below. Class description: Implement the SimpleNet class. Method signatures and docstrings: - def __init__(self): Constructor for SimpleNet class to define the layers and loss function. Note: Use 'mean' reduction in the loss_criterion. Read Pytorch's documention to unde...
fd47764547131cb6382124b27fe7d428cbf4c64a
<|skeleton|> class SimpleNet: def __init__(self): """Constructor for SimpleNet class to define the layers and loss function. Note: Use 'mean' reduction in the loss_criterion. Read Pytorch's documention to understand what this means.""" <|body_0|> def forward(self, x: torch.Tensor) -> torch.Ten...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SimpleNet: def __init__(self): """Constructor for SimpleNet class to define the layers and loss function. Note: Use 'mean' reduction in the loss_criterion. Read Pytorch's documention to understand what this means.""" super(SimpleNet, self).__init__() self.conv_layers = None sel...
the_stack_v2_python_sparse
proj5/proj5_code/simple_net.py
pranavshenoykp/computerVision
train
2
4924ccdfd2b632022e21bf12fc5b2288190ba973
[ "stable = False\nwhile not stable:\n board, stable = self._crush(board)\n if not stable:\n board = self._drop(board)\nreturn board", "m, n = (len(board), len(board[0]))\ncrush = set()\nstable = True\nfor i in range(m):\n for j in range(1, n - 1):\n if board[i][j] == 0:\n continue...
<|body_start_0|> stable = False while not stable: board, stable = self._crush(board) if not stable: board = self._drop(board) return board <|end_body_0|> <|body_start_1|> m, n = (len(board), len(board[0])) crush = set() stable = Tr...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def candyCrush(self, board: List[List[int]]) -> List[List[int]]: """Array.""" <|body_0|> def _crush(self, board): """Running time: O(k) where k is the number of items in board.""" <|body_1|> def _drop(self, board): """Running time: O(k)...
stack_v2_sparse_classes_36k_train_032153
1,691
permissive
[ { "docstring": "Array.", "name": "candyCrush", "signature": "def candyCrush(self, board: List[List[int]]) -> List[List[int]]" }, { "docstring": "Running time: O(k) where k is the number of items in board.", "name": "_crush", "signature": "def _crush(self, board)" }, { "docstring"...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def candyCrush(self, board: List[List[int]]) -> List[List[int]]: Array. - def _crush(self, board): Running time: O(k) where k is the number of items in board. - def _drop(self, b...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def candyCrush(self, board: List[List[int]]) -> List[List[int]]: Array. - def _crush(self, board): Running time: O(k) where k is the number of items in board. - def _drop(self, b...
4a508a982b125a3a90ea893ae70863df7c99cc70
<|skeleton|> class Solution: def candyCrush(self, board: List[List[int]]) -> List[List[int]]: """Array.""" <|body_0|> def _crush(self, board): """Running time: O(k) where k is the number of items in board.""" <|body_1|> def _drop(self, board): """Running time: O(k)...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def candyCrush(self, board: List[List[int]]) -> List[List[int]]: """Array.""" stable = False while not stable: board, stable = self._crush(board) if not stable: board = self._drop(board) return board def _crush(self, board)...
the_stack_v2_python_sparse
solutions/723_candy_crush.py
YiqunPeng/leetcode_pro
train
0
1f253857a7da706aa6ef79334ea3cf5457783677
[ "searchMin = self.config.searchMin\nsearchMax = self.config.searchMax\nsearchStep = self.config.searchStep\nsearchNum = 1 + int(math.ceil((searchMax - searchMin) / searchStep))\nsearchVelocity = np.linspace(searchMin, searchMax, num=searchNum, endpoint=True)\nbeta = searchVelocity / const.c.to('km/s').value\ndopple...
<|body_start_0|> searchMin = self.config.searchMin searchMax = self.config.searchMax searchStep = self.config.searchStep searchNum = 1 + int(math.ceil((searchMax - searchMin) / searchStep)) searchVelocity = np.linspace(searchMin, searchMax, num=searchNum, endpoint=True) b...
Estimate the radial velocity.
EstimateRadialVelocityTask
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EstimateRadialVelocityTask: """Estimate the radial velocity.""" def run(self, spectrum: PfsFiberArray, modelSpectrum: PfsSimpleSpectrum) -> Struct: """Get the radial velocity of ``spectrum`` in comparison with ``modelSpectrum``. Parameters ---------- spectrum : `pfs.datamodel.pfsFibe...
stack_v2_sparse_classes_36k_train_032154
13,859
no_license
[ { "docstring": "Get the radial velocity of ``spectrum`` in comparison with ``modelSpectrum``. Parameters ---------- spectrum : `pfs.datamodel.pfsFiberArray.PfsFiberArray` Observed spectrum. It must be whitened (Continuum is 1.0 everywhere.) modelSpectrum : `pfs.datamodel.pfsSimpleSpectrum.PfsSimpleSpectrum` Mod...
2
stack_v2_sparse_classes_30k_train_002571
Implement the Python class `EstimateRadialVelocityTask` described below. Class description: Estimate the radial velocity. Method signatures and docstrings: - def run(self, spectrum: PfsFiberArray, modelSpectrum: PfsSimpleSpectrum) -> Struct: Get the radial velocity of ``spectrum`` in comparison with ``modelSpectrum``...
Implement the Python class `EstimateRadialVelocityTask` described below. Class description: Estimate the radial velocity. Method signatures and docstrings: - def run(self, spectrum: PfsFiberArray, modelSpectrum: PfsSimpleSpectrum) -> Struct: Get the radial velocity of ``spectrum`` in comparison with ``modelSpectrum``...
85602eea2485ac24e0831046dc74f1b2d1a3d89f
<|skeleton|> class EstimateRadialVelocityTask: """Estimate the radial velocity.""" def run(self, spectrum: PfsFiberArray, modelSpectrum: PfsSimpleSpectrum) -> Struct: """Get the radial velocity of ``spectrum`` in comparison with ``modelSpectrum``. Parameters ---------- spectrum : `pfs.datamodel.pfsFibe...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EstimateRadialVelocityTask: """Estimate the radial velocity.""" def run(self, spectrum: PfsFiberArray, modelSpectrum: PfsSimpleSpectrum) -> Struct: """Get the radial velocity of ``spectrum`` in comparison with ``modelSpectrum``. Parameters ---------- spectrum : `pfs.datamodel.pfsFiberArray.PfsFib...
the_stack_v2_python_sparse
python/pfs/drp/stella/estimateRadialVelocity.py
Subaru-PFS/drp_stella
train
3
0d7435c9c3f78fea8212d02288beb662458c31ff
[ "roles = get_list_or_404(Role)\nif request.GET.get('pagination'):\n pagination = request.GET.get('pagination')\n if pagination == 'true':\n paginator = AdministratorPagination()\n results = paginator.paginate_queryset(roles, request)\n serializer = RoleSerializer(results, many=True)\n ...
<|body_start_0|> roles = get_list_or_404(Role) if request.GET.get('pagination'): pagination = request.GET.get('pagination') if pagination == 'true': paginator = AdministratorPagination() results = paginator.paginate_queryset(roles, request) ...
RoleList
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RoleList: def get(self, request, format=None): """List all roles --- serializer: administrator.serializers.RoleSerializer parameters: - name: pagination required: false type: string paramType: query""" <|body_0|> def post(self, request, format=None): """Create new Ro...
stack_v2_sparse_classes_36k_train_032155
30,608
permissive
[ { "docstring": "List all roles --- serializer: administrator.serializers.RoleSerializer parameters: - name: pagination required: false type: string paramType: query", "name": "get", "signature": "def get(self, request, format=None)" }, { "docstring": "Create new Role --- serializer: administrato...
2
stack_v2_sparse_classes_30k_train_012502
Implement the Python class `RoleList` described below. Class description: Implement the RoleList class. Method signatures and docstrings: - def get(self, request, format=None): List all roles --- serializer: administrator.serializers.RoleSerializer parameters: - name: pagination required: false type: string paramType...
Implement the Python class `RoleList` described below. Class description: Implement the RoleList class. Method signatures and docstrings: - def get(self, request, format=None): List all roles --- serializer: administrator.serializers.RoleSerializer parameters: - name: pagination required: false type: string paramType...
73728463badb3bfd4413aa0f7aeb44a9606fdfea
<|skeleton|> class RoleList: def get(self, request, format=None): """List all roles --- serializer: administrator.serializers.RoleSerializer parameters: - name: pagination required: false type: string paramType: query""" <|body_0|> def post(self, request, format=None): """Create new Ro...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RoleList: def get(self, request, format=None): """List all roles --- serializer: administrator.serializers.RoleSerializer parameters: - name: pagination required: false type: string paramType: query""" roles = get_list_or_404(Role) if request.GET.get('pagination'): paginati...
the_stack_v2_python_sparse
administrator/views.py
belatrix/BackendAllStars
train
5
e6edd16db1a07b6eb96fe15c7c2147bbbac28d17
[ "super().__init__()\nself.low = low\nself.high = high\nself.seed = seed", "if self.seed:\n np.random.seed(self.seed)\nreturn np.random.randint(self.low, self.high)" ]
<|body_start_0|> super().__init__() self.low = low self.high = high self.seed = seed <|end_body_0|> <|body_start_1|> if self.seed: np.random.seed(self.seed) return np.random.randint(self.low, self.high) <|end_body_1|>
Derived class of HexHeuristic to quantify a state by generating random integers.
RandomHeuristic
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RandomHeuristic: """Derived class of HexHeuristic to quantify a state by generating random integers.""" def __init__(self, low, high, seed=None): """Initialize the Random heuristic with a low and high boundary for the random integer generation. For experimentation purposes a random s...
stack_v2_sparse_classes_36k_train_032156
13,925
permissive
[ { "docstring": "Initialize the Random heuristic with a low and high boundary for the random integer generation. For experimentation purposes a random seed can be provided. :param low: int Lower boundary for the random heuristic value :param high: int Upper boundary for the random heuristic value :param seed: in...
2
stack_v2_sparse_classes_30k_train_018883
Implement the Python class `RandomHeuristic` described below. Class description: Derived class of HexHeuristic to quantify a state by generating random integers. Method signatures and docstrings: - def __init__(self, low, high, seed=None): Initialize the Random heuristic with a low and high boundary for the random in...
Implement the Python class `RandomHeuristic` described below. Class description: Derived class of HexHeuristic to quantify a state by generating random integers. Method signatures and docstrings: - def __init__(self, low, high, seed=None): Initialize the Random heuristic with a low and high boundary for the random in...
78478c6a8a0f0e0e740159236d6cbb30a9396f5a
<|skeleton|> class RandomHeuristic: """Derived class of HexHeuristic to quantify a state by generating random integers.""" def __init__(self, low, high, seed=None): """Initialize the Random heuristic with a low and high boundary for the random integer generation. For experimentation purposes a random s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RandomHeuristic: """Derived class of HexHeuristic to quantify a state by generating random integers.""" def __init__(self, low, high, seed=None): """Initialize the Random heuristic with a low and high boundary for the random integer generation. For experimentation purposes a random seed can be pr...
the_stack_v2_python_sparse
Games/hex/legacy/hex_heuristics.py
frankbryce/muzero
train
1
16e917bb6ce255885127b76de3339f49cb5919b5
[ "n = len(height)\nif n < 3:\n return 0\nl_max = height[0]\nr_max = height[n - 1]\nleft, right = (1, n - 2)\nres = 0\nwhile left <= right:\n l_max = max(l_max, height[left])\n r_max = max(r_max, height[right])\n if l_max < r_max:\n res += l_max - height[left]\n left += 1\n else:\n ...
<|body_start_0|> n = len(height) if n < 3: return 0 l_max = height[0] r_max = height[n - 1] left, right = (1, n - 2) res = 0 while left <= right: l_max = max(l_max, height[left]) r_max = max(r_max, height[right]) if ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def trap(self, height): """:type height: List[int] :rtype: int 备忘录的方法用了两个数组, 但是发现其实每一次只需要用到第i次的值 因此可以边计算最大值边遍历, 考虑到左右两边,可以采用双指针""" <|body_0|> def trap0(self, height): """:type height: List[int] :rtype: int 因为每个位置我只需要知道它之前和之后的最大值, 所以可以用两个数组提前算好, 再遍历取对应的元素比较计...
stack_v2_sparse_classes_36k_train_032157
2,713
no_license
[ { "docstring": ":type height: List[int] :rtype: int 备忘录的方法用了两个数组, 但是发现其实每一次只需要用到第i次的值 因此可以边计算最大值边遍历, 考虑到左右两边,可以采用双指针", "name": "trap", "signature": "def trap(self, height)" }, { "docstring": ":type height: List[int] :rtype: int 因为每个位置我只需要知道它之前和之后的最大值, 所以可以用两个数组提前算好, 再遍历取对应的元素比较计算就好", "name":...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def trap(self, height): :type height: List[int] :rtype: int 备忘录的方法用了两个数组, 但是发现其实每一次只需要用到第i次的值 因此可以边计算最大值边遍历, 考虑到左右两边,可以采用双指针 - def trap0(self, height): :type height: List[int] :r...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def trap(self, height): :type height: List[int] :rtype: int 备忘录的方法用了两个数组, 但是发现其实每一次只需要用到第i次的值 因此可以边计算最大值边遍历, 考虑到左右两边,可以采用双指针 - def trap0(self, height): :type height: List[int] :r...
6e18c5d257840489cc3fb1079ae3804c743982a4
<|skeleton|> class Solution: def trap(self, height): """:type height: List[int] :rtype: int 备忘录的方法用了两个数组, 但是发现其实每一次只需要用到第i次的值 因此可以边计算最大值边遍历, 考虑到左右两边,可以采用双指针""" <|body_0|> def trap0(self, height): """:type height: List[int] :rtype: int 因为每个位置我只需要知道它之前和之后的最大值, 所以可以用两个数组提前算好, 再遍历取对应的元素比较计...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def trap(self, height): """:type height: List[int] :rtype: int 备忘录的方法用了两个数组, 但是发现其实每一次只需要用到第i次的值 因此可以边计算最大值边遍历, 考虑到左右两边,可以采用双指针""" n = len(height) if n < 3: return 0 l_max = height[0] r_max = height[n - 1] left, right = (1, n - 2) r...
the_stack_v2_python_sparse
out/production/leetcode/42.接雨水.py
yangyuxiang1996/leetcode
train
0
1867420c10cf52535175179e1a037af8095fb690
[ "doc, _ = self._to_xml_doc(frame_data, sasentry_attrs)\nif self.encoding is None:\n self.encoding = 'UTF-8'\nwith open(filename, 'wb') as file_ref:\n doc.write(file_ref, encoding=self.encoding, pretty_print=True, xml_declaration=True)", "valid_class = all([issubclass(data.__class__, Data1D) for data in fram...
<|body_start_0|> doc, _ = self._to_xml_doc(frame_data, sasentry_attrs) if self.encoding is None: self.encoding = 'UTF-8' with open(filename, 'wb') as file_ref: doc.write(file_ref, encoding=self.encoding, pretty_print=True, xml_declaration=True) <|end_body_0|> <|body_star...
CansasWriter
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CansasWriter: def write(self, filename, frame_data, sasentry_attrs=None): """Write the content of a Data1D as a CanSAS XML file :param filename: name of the file to write :param datainfo: Data1D object""" <|body_0|> def _to_xml_doc(self, frame_data, sasentry_attrs=None): ...
stack_v2_sparse_classes_36k_train_032158
4,460
permissive
[ { "docstring": "Write the content of a Data1D as a CanSAS XML file :param filename: name of the file to write :param datainfo: Data1D object", "name": "write", "signature": "def write(self, filename, frame_data, sasentry_attrs=None)" }, { "docstring": "Create an XML document to contain the conte...
3
stack_v2_sparse_classes_30k_test_001052
Implement the Python class `CansasWriter` described below. Class description: Implement the CansasWriter class. Method signatures and docstrings: - def write(self, filename, frame_data, sasentry_attrs=None): Write the content of a Data1D as a CanSAS XML file :param filename: name of the file to write :param datainfo:...
Implement the Python class `CansasWriter` described below. Class description: Implement the CansasWriter class. Method signatures and docstrings: - def write(self, filename, frame_data, sasentry_attrs=None): Write the content of a Data1D as a CanSAS XML file :param filename: name of the file to write :param datainfo:...
a5e91705b5a0d4b6c6bf6f4374418fd71c58dc8f
<|skeleton|> class CansasWriter: def write(self, filename, frame_data, sasentry_attrs=None): """Write the content of a Data1D as a CanSAS XML file :param filename: name of the file to write :param datainfo: Data1D object""" <|body_0|> def _to_xml_doc(self, frame_data, sasentry_attrs=None): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CansasWriter: def write(self, filename, frame_data, sasentry_attrs=None): """Write the content of a Data1D as a CanSAS XML file :param filename: name of the file to write :param datainfo: Data1D object""" doc, _ = self._to_xml_doc(frame_data, sasentry_attrs) if self.encoding is None: ...
the_stack_v2_python_sparse
src/sas/sascalc/file_converter/cansas_writer.py
m2cci-NMZ/sasview
train
0
f7d11a9f574ad5fb94f3a694e357c64cc75b4edc
[ "res = ''\nlength = len(s)\ni = 0\nwhile i < length:\n start = i\n while i < length and s[i] != ' ':\n i += 1\n for p in range(start, i)[::-1]:\n res += s[p]\n while i < length and s[i] == ' ':\n i += 1\n res += ' '\nreturn res", "strs = s.split(' ')\nres = []\nfor sub in s...
<|body_start_0|> res = '' length = len(s) i = 0 while i < length: start = i while i < length and s[i] != ' ': i += 1 for p in range(start, i)[::-1]: res += s[p] while i < length and s[i] == ' ': ...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def reverse_words(self, s: str) -> str: """单词反转 Args: arr: 字符串 Returns: 反转后字符串""" <|body_0|> def reverse_words2(self, s: str) -> str: """单词反转 Args: arr: 字符串 Returns: 反转后字符串""" <|body_1|> <|end_skeleton|> <|body_start_0|> res = '' l...
stack_v2_sparse_classes_36k_train_032159
2,076
permissive
[ { "docstring": "单词反转 Args: arr: 字符串 Returns: 反转后字符串", "name": "reverse_words", "signature": "def reverse_words(self, s: str) -> str" }, { "docstring": "单词反转 Args: arr: 字符串 Returns: 反转后字符串", "name": "reverse_words2", "signature": "def reverse_words2(self, s: str) -> str" } ]
2
stack_v2_sparse_classes_30k_train_001224
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverse_words(self, s: str) -> str: 单词反转 Args: arr: 字符串 Returns: 反转后字符串 - def reverse_words2(self, s: str) -> str: 单词反转 Args: arr: 字符串 Returns: 反转后字符串
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverse_words(self, s: str) -> str: 单词反转 Args: arr: 字符串 Returns: 反转后字符串 - def reverse_words2(self, s: str) -> str: 单词反转 Args: arr: 字符串 Returns: 反转后字符串 <|skeleton|> class Sol...
50f35eef6a0ad63173efed10df3c835b1dceaa3f
<|skeleton|> class Solution: def reverse_words(self, s: str) -> str: """单词反转 Args: arr: 字符串 Returns: 反转后字符串""" <|body_0|> def reverse_words2(self, s: str) -> str: """单词反转 Args: arr: 字符串 Returns: 反转后字符串""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def reverse_words(self, s: str) -> str: """单词反转 Args: arr: 字符串 Returns: 反转后字符串""" res = '' length = len(s) i = 0 while i < length: start = i while i < length and s[i] != ' ': i += 1 for p in range(start, i)[:...
the_stack_v2_python_sparse
src/leetcodepython/string/reverse_words_string_557.py
zhangyu345293721/leetcode
train
101
127b536d18395e0b543d55cd05265cf700cf6b83
[ "ENFORCER.enforce_call(action='identity:check_grant', build_target=functools.partial(_build_enforcement_target_attr, domain_id=domain_id, group_id=group_id, role_id=role_id))\nPROVIDERS.assignment_api.get_grant(domain_id=domain_id, group_id=group_id, role_id=role_id, inherited_to_projects=True)\nreturn (None, http_...
<|body_start_0|> ENFORCER.enforce_call(action='identity:check_grant', build_target=functools.partial(_build_enforcement_target_attr, domain_id=domain_id, group_id=group_id, role_id=role_id)) PROVIDERS.assignment_api.get_grant(domain_id=domain_id, group_id=group_id, role_id=role_id, inherited_to_projects...
OSInheritDomainGroupRolesResource
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OSInheritDomainGroupRolesResource: def get(self, domain_id, group_id, role_id): """Check for an inherited grant for a group on a domain. GET/HEAD /OS-INHERIT/domains/{domain_id}/groups/{group_id} /roles/{role_id}/inherited_to_projects""" <|body_0|> def put(self, domain_id, g...
stack_v2_sparse_classes_36k_train_032160
19,022
permissive
[ { "docstring": "Check for an inherited grant for a group on a domain. GET/HEAD /OS-INHERIT/domains/{domain_id}/groups/{group_id} /roles/{role_id}/inherited_to_projects", "name": "get", "signature": "def get(self, domain_id, group_id, role_id)" }, { "docstring": "Create an inherited grant for a g...
3
stack_v2_sparse_classes_30k_train_009843
Implement the Python class `OSInheritDomainGroupRolesResource` described below. Class description: Implement the OSInheritDomainGroupRolesResource class. Method signatures and docstrings: - def get(self, domain_id, group_id, role_id): Check for an inherited grant for a group on a domain. GET/HEAD /OS-INHERIT/domains/...
Implement the Python class `OSInheritDomainGroupRolesResource` described below. Class description: Implement the OSInheritDomainGroupRolesResource class. Method signatures and docstrings: - def get(self, domain_id, group_id, role_id): Check for an inherited grant for a group on a domain. GET/HEAD /OS-INHERIT/domains/...
03a0a8146a78682ede9eca12a5a7fdacde2035c8
<|skeleton|> class OSInheritDomainGroupRolesResource: def get(self, domain_id, group_id, role_id): """Check for an inherited grant for a group on a domain. GET/HEAD /OS-INHERIT/domains/{domain_id}/groups/{group_id} /roles/{role_id}/inherited_to_projects""" <|body_0|> def put(self, domain_id, g...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OSInheritDomainGroupRolesResource: def get(self, domain_id, group_id, role_id): """Check for an inherited grant for a group on a domain. GET/HEAD /OS-INHERIT/domains/{domain_id}/groups/{group_id} /roles/{role_id}/inherited_to_projects""" ENFORCER.enforce_call(action='identity:check_grant', bui...
the_stack_v2_python_sparse
keystone/api/os_inherit.py
sapcc/keystone
train
0
deebaff45b12c9ca011e660f33feb8bfd5b7bb35
[ "develop.initialize_options(self)\nself.no_npm = None\nself.with_doc_deps = None\nself.use_npm_cache = None", "if self.no_deps:\n develop.install_for_development(self)\n return\nself._run_pip(['install', '-e', '.'])\nself._run_pip(['install', '-r', 'dev-requirements.txt'])\nif self.with_doc_deps:\n self....
<|body_start_0|> develop.initialize_options(self) self.no_npm = None self.with_doc_deps = None self.use_npm_cache = None <|end_body_0|> <|body_start_1|> if self.no_deps: develop.install_for_development(self) return self._run_pip(['install', '-e', ...
Installs Review Board in developer mode. This will install all standard and development dependencies (using Python wheels and node.js packages from npm) and add the source tree to the Python module search path. That includes updating the versions of pip and setuptools on the system. To speed up subsequent runs, callers...
DevelopCommand
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DevelopCommand: """Installs Review Board in developer mode. This will install all standard and development dependencies (using Python wheels and node.js packages from npm) and add the source tree to the Python module search path. That includes updating the versions of pip and setuptools on the sy...
stack_v2_sparse_classes_36k_train_032161
14,185
permissive
[ { "docstring": "Initialize options for the command.", "name": "initialize_options", "signature": "def initialize_options(self)" }, { "docstring": "Install the package for development. This takes care of the work of installing all dependencies.", "name": "install_for_development", "signat...
3
stack_v2_sparse_classes_30k_train_021045
Implement the Python class `DevelopCommand` described below. Class description: Installs Review Board in developer mode. This will install all standard and development dependencies (using Python wheels and node.js packages from npm) and add the source tree to the Python module search path. That includes updating the v...
Implement the Python class `DevelopCommand` described below. Class description: Installs Review Board in developer mode. This will install all standard and development dependencies (using Python wheels and node.js packages from npm) and add the source tree to the Python module search path. That includes updating the v...
c3a991f1e9d7682239a1ab0e8661cee6da01d537
<|skeleton|> class DevelopCommand: """Installs Review Board in developer mode. This will install all standard and development dependencies (using Python wheels and node.js packages from npm) and add the source tree to the Python module search path. That includes updating the versions of pip and setuptools on the sy...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DevelopCommand: """Installs Review Board in developer mode. This will install all standard and development dependencies (using Python wheels and node.js packages from npm) and add the source tree to the Python module search path. That includes updating the versions of pip and setuptools on the system. To spee...
the_stack_v2_python_sparse
setup.py
reviewboard/reviewboard
train
1,141
c3f9f694d3276ac32d547368f54c637501f7a53a
[ "repo = repo.strip()\npath = os.path.join(os.getcwd(), path.strip())\n_ = {'ssh': '', 'name': 'name', 'email': 'name@gmail.com'}\n_.update(user)\nuser = _\nif not repo.startswith('git@'):\n raise Exception(f'Invalid checkout url: {repo}\\n\\nPlease use the valid ssh url with the following format:\\n `git@github....
<|body_start_0|> repo = repo.strip() path = os.path.join(os.getcwd(), path.strip()) _ = {'ssh': '', 'name': 'name', 'email': 'name@gmail.com'} _.update(user) user = _ if not repo.startswith('git@'): raise Exception(f'Invalid checkout url: {repo}\n\nPlease use ...
GitUtil
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GitUtil: def __init__(self, repo: str, user: dict, path: str=''): """initial method To use this class, first make sure you have set ssh private key and give the path in the following wapper. Save the wrapper as a bash script and give required permissions using "sudo chmod a+x /path/to/ss...
stack_v2_sparse_classes_36k_train_032162
4,122
permissive
[ { "docstring": "initial method To use this class, first make sure you have set ssh private key and give the path in the following wapper. Save the wrapper as a bash script and give required permissions using \"sudo chmod a+x /path/to/ssh_key\": #!/bin/bash ssh -i path/to/ssh/key -oIdentitiesOnly=yes -oStrictHos...
2
null
Implement the Python class `GitUtil` described below. Class description: Implement the GitUtil class. Method signatures and docstrings: - def __init__(self, repo: str, user: dict, path: str=''): initial method To use this class, first make sure you have set ssh private key and give the path in the following wapper. S...
Implement the Python class `GitUtil` described below. Class description: Implement the GitUtil class. Method signatures and docstrings: - def __init__(self, repo: str, user: dict, path: str=''): initial method To use this class, first make sure you have set ssh private key and give the path in the following wapper. S...
5ebec640c634ef57569d7ef4e1dc0dd1b188dcb3
<|skeleton|> class GitUtil: def __init__(self, repo: str, user: dict, path: str=''): """initial method To use this class, first make sure you have set ssh private key and give the path in the following wapper. Save the wrapper as a bash script and give required permissions using "sudo chmod a+x /path/to/ss...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GitUtil: def __init__(self, repo: str, user: dict, path: str=''): """initial method To use this class, first make sure you have set ssh private key and give the path in the following wapper. Save the wrapper as a bash script and give required permissions using "sudo chmod a+x /path/to/ssh_key": #!/bin...
the_stack_v2_python_sparse
openiti/git/git_util.py
OpenITI/openiti
train
10
fd94796047c557b42d455180121d18b4c96ee72f
[ "from scoop.content.models import Attachment\nuuid = self.value\nlink = Attachment.objects.get_link_by_uuid(uuid)\nreturn {'link': link}", "base = super(AttachmentInline, self).get_template_name()[0]\npath = 'content/{}'.format(base)\nreturn path" ]
<|body_start_0|> from scoop.content.models import Attachment uuid = self.value link = Attachment.objects.get_link_by_uuid(uuid) return {'link': link} <|end_body_0|> <|body_start_1|> base = super(AttachmentInline, self).get_template_name()[0] path = 'content/{}'.format(ba...
Inline d'insertion de pièces jointes Format : {{attachment uuid}}
AttachmentInline
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AttachmentInline: """Inline d'insertion de pièces jointes Format : {{attachment uuid}}""" def get_context(self): """Renvoyer le contexte de rendu de l'inline""" <|body_0|> def get_template_name(self): """Renvoyer le chemin du template""" <|body_1|> <|end...
stack_v2_sparse_classes_36k_train_032163
6,816
no_license
[ { "docstring": "Renvoyer le contexte de rendu de l'inline", "name": "get_context", "signature": "def get_context(self)" }, { "docstring": "Renvoyer le chemin du template", "name": "get_template_name", "signature": "def get_template_name(self)" } ]
2
stack_v2_sparse_classes_30k_train_003124
Implement the Python class `AttachmentInline` described below. Class description: Inline d'insertion de pièces jointes Format : {{attachment uuid}} Method signatures and docstrings: - def get_context(self): Renvoyer le contexte de rendu de l'inline - def get_template_name(self): Renvoyer le chemin du template
Implement the Python class `AttachmentInline` described below. Class description: Inline d'insertion de pièces jointes Format : {{attachment uuid}} Method signatures and docstrings: - def get_context(self): Renvoyer le contexte de rendu de l'inline - def get_template_name(self): Renvoyer le chemin du template <|skel...
8cef6f6e89c1990e2b25f83e54e0c3481d83b6d7
<|skeleton|> class AttachmentInline: """Inline d'insertion de pièces jointes Format : {{attachment uuid}}""" def get_context(self): """Renvoyer le contexte de rendu de l'inline""" <|body_0|> def get_template_name(self): """Renvoyer le chemin du template""" <|body_1|> <|end...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AttachmentInline: """Inline d'insertion de pièces jointes Format : {{attachment uuid}}""" def get_context(self): """Renvoyer le contexte de rendu de l'inline""" from scoop.content.models import Attachment uuid = self.value link = Attachment.objects.get_link_by_uuid(uuid) ...
the_stack_v2_python_sparse
scoop/content/util/inlines.py
artscoop/scoop
train
0
445e81ce4a6ada54c133f22d1ba751d188a29f17
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn IosDeviceFeaturesConfiguration()", "from .apple_device_features_configuration_base import AppleDeviceFeaturesConfigurationBase\nfrom .ios_home_screen_item import IosHomeScreenItem\nfrom .ios_home_screen_page import IosHomeScreenPage\nf...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return IosDeviceFeaturesConfiguration() <|end_body_0|> <|body_start_1|> from .apple_device_features_configuration_base import AppleDeviceFeaturesConfigurationBase from .ios_home_screen_item imp...
iOS Device Features Configuration Profile.
IosDeviceFeaturesConfiguration
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IosDeviceFeaturesConfiguration: """iOS Device Features Configuration Profile.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosDeviceFeaturesConfiguration: """Creates a new instance of the appropriate class based on discriminator value Args: parse_no...
stack_v2_sparse_classes_36k_train_032164
4,709
permissive
[ { "docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: IosDeviceFeaturesConfiguration", "name": "create_from_discriminator_value", "signature": "def create_from_di...
3
null
Implement the Python class `IosDeviceFeaturesConfiguration` described below. Class description: iOS Device Features Configuration Profile. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosDeviceFeaturesConfiguration: Creates a new instance of the appr...
Implement the Python class `IosDeviceFeaturesConfiguration` described below. Class description: iOS Device Features Configuration Profile. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosDeviceFeaturesConfiguration: Creates a new instance of the appr...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class IosDeviceFeaturesConfiguration: """iOS Device Features Configuration Profile.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosDeviceFeaturesConfiguration: """Creates a new instance of the appropriate class based on discriminator value Args: parse_no...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class IosDeviceFeaturesConfiguration: """iOS Device Features Configuration Profile.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosDeviceFeaturesConfiguration: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse...
the_stack_v2_python_sparse
msgraph/generated/models/ios_device_features_configuration.py
microsoftgraph/msgraph-sdk-python
train
135
478a11221eb3e26ef4fb53042ae055876d5bc868
[ "try:\n self.stream = Stream._member_map_[data.get('stream', 'PRINT').upper()]\nexcept KeyError:\n raise ValueError(f\"invalid stream specifier: {data['stream']}\")\nself.binary = binary\nself.payload = data.get('payload', '{command}')\nself.args = data.get('args', [])\nself.suid = data.get('suid', None)\nsel...
<|body_start_0|> try: self.stream = Stream._member_map_[data.get('stream', 'PRINT').upper()] except KeyError: raise ValueError(f"invalid stream specifier: {data['stream']}") self.binary = binary self.payload = data.get('payload', '{command}') self.args = d...
Abstract method class built from the JSON database
Method
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Method: """Abstract method class built from the JSON database""" def __init__(self, binary: 'Binary', cap: Capability, data: Dict[str, Any]): """Create a new method associated with the given binary.""" <|body_0|> def sudo_args(self, binary_path: str, spec: str) -> bool: ...
stack_v2_sparse_classes_36k_train_032165
17,537
permissive
[ { "docstring": "Create a new method associated with the given binary.", "name": "__init__", "signature": "def __init__(self, binary: 'Binary', cap: Capability, data: Dict[str, Any])" }, { "docstring": "Check if this method is compatible with the given sudo command spec. It will evaluate whether ...
3
null
Implement the Python class `Method` described below. Class description: Abstract method class built from the JSON database Method signatures and docstrings: - def __init__(self, binary: 'Binary', cap: Capability, data: Dict[str, Any]): Create a new method associated with the given binary. - def sudo_args(self, binary...
Implement the Python class `Method` described below. Class description: Abstract method class built from the JSON database Method signatures and docstrings: - def __init__(self, binary: 'Binary', cap: Capability, data: Dict[str, Any]): Create a new method associated with the given binary. - def sudo_args(self, binary...
37f04d4e16ff47c7fd70e95162f9fccd327cca7e
<|skeleton|> class Method: """Abstract method class built from the JSON database""" def __init__(self, binary: 'Binary', cap: Capability, data: Dict[str, Any]): """Create a new method associated with the given binary.""" <|body_0|> def sudo_args(self, binary_path: str, spec: str) -> bool: ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Method: """Abstract method class built from the JSON database""" def __init__(self, binary: 'Binary', cap: Capability, data: Dict[str, Any]): """Create a new method associated with the given binary.""" try: self.stream = Stream._member_map_[data.get('stream', 'PRINT').upper()]...
the_stack_v2_python_sparse
pwncat/gtfobins.py
calebstewart/pwncat
train
2,177
13e51e95931398f9d7cfd0d2043d004ed6f4e878
[ "self.V = V\nself.D = D\nself.W = np.random.randn(self.V, self.D)\nself.W /= 100\nself.x = None", "if W is not None:\n self.W = W\nself.x = x\nreturn self.W[x]", "if self.x is None:\n raise 'forward pass must occur before backward pass'\ngrad_W = np.zeros(self.W.shape)\nnp.add.at(grad_W, self.x, grad_out)...
<|body_start_0|> self.V = V self.D = D self.W = np.random.randn(self.V, self.D) self.W /= 100 self.x = None <|end_body_0|> <|body_start_1|> if W is not None: self.W = W self.x = x return self.W[x] <|end_body_1|> <|body_start_2|> if se...
Word embedding layer represents words using vectors. Each word of the vocabulary be associated with a vector and these vectors will be learned jointly with the rest of the system.
WordEmbeddingLayer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WordEmbeddingLayer: """Word embedding layer represents words using vectors. Each word of the vocabulary be associated with a vector and these vectors will be learned jointly with the rest of the system.""" def __init__(self, V, D): """Args: V (int): Number of words in the dictionary....
stack_v2_sparse_classes_36k_train_032166
2,635
no_license
[ { "docstring": "Args: V (int): Number of words in the dictionary. D (int): Dimension of the desired word vector.", "name": "__init__", "signature": "def __init__(self, V, D)" }, { "docstring": "Forward pass for word embedding layer. This function operates on mini-batch of size N where each seque...
4
null
Implement the Python class `WordEmbeddingLayer` described below. Class description: Word embedding layer represents words using vectors. Each word of the vocabulary be associated with a vector and these vectors will be learned jointly with the rest of the system. Method signatures and docstrings: - def __init__(self,...
Implement the Python class `WordEmbeddingLayer` described below. Class description: Word embedding layer represents words using vectors. Each word of the vocabulary be associated with a vector and these vectors will be learned jointly with the rest of the system. Method signatures and docstrings: - def __init__(self,...
7da789ef34d5e5bcf9033cfbe0ff5df607b2437a
<|skeleton|> class WordEmbeddingLayer: """Word embedding layer represents words using vectors. Each word of the vocabulary be associated with a vector and these vectors will be learned jointly with the rest of the system.""" def __init__(self, V, D): """Args: V (int): Number of words in the dictionary....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WordEmbeddingLayer: """Word embedding layer represents words using vectors. Each word of the vocabulary be associated with a vector and these vectors will be learned jointly with the rest of the system.""" def __init__(self, V, D): """Args: V (int): Number of words in the dictionary. D (int): Dim...
the_stack_v2_python_sparse
recurrent_neural_networks/rnn/word_embedding_layer.py
calvinfeng/machine-learning-notebook
train
38
fd115993a258640a5f69874c5d7cd34822113baa
[ "super(APConnect, self).__init__()\nself.nodes = nodes\nreturn", "self.logger.info(\"Connecting '{0}' to SSID: '{1}'\".format(parameters.nodes.parameters, parameters.ssids.parameters))\nself.nodes[parameters.nodes.parameters].connect(parameters.ssids.parameters)\nreturn" ]
<|body_start_0|> super(APConnect, self).__init__() self.nodes = nodes return <|end_body_0|> <|body_start_1|> self.logger.info("Connecting '{0}' to SSID: '{1}'".format(parameters.nodes.parameters, parameters.ssids.parameters)) self.nodes[parameters.nodes.parameters].connect(param...
A class to connect a device to an AP
APConnect
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class APConnect: """A class to connect a device to an AP""" def __init__(self, nodes): """:param: - `nodes`: dictionary of id:device pairs""" <|body_0|> def __call__(self, parameters): """:param: - `parameters`: a named tuple with `nodes.parameters` and `ssids.paramete...
stack_v2_sparse_classes_36k_train_032167
970
permissive
[ { "docstring": ":param: - `nodes`: dictionary of id:device pairs", "name": "__init__", "signature": "def __init__(self, nodes)" }, { "docstring": ":param: - `parameters`: a named tuple with `nodes.parameters` and `ssids.parameters` attributes", "name": "__call__", "signature": "def __cal...
2
stack_v2_sparse_classes_30k_test_000136
Implement the Python class `APConnect` described below. Class description: A class to connect a device to an AP Method signatures and docstrings: - def __init__(self, nodes): :param: - `nodes`: dictionary of id:device pairs - def __call__(self, parameters): :param: - `parameters`: a named tuple with `nodes.parameters...
Implement the Python class `APConnect` described below. Class description: A class to connect a device to an AP Method signatures and docstrings: - def __init__(self, nodes): :param: - `nodes`: dictionary of id:device pairs - def __call__(self, parameters): :param: - `parameters`: a named tuple with `nodes.parameters...
b4d1c77e1d611fe2b30768b42bdc7493afb0ea95
<|skeleton|> class APConnect: """A class to connect a device to an AP""" def __init__(self, nodes): """:param: - `nodes`: dictionary of id:device pairs""" <|body_0|> def __call__(self, parameters): """:param: - `parameters`: a named tuple with `nodes.parameters` and `ssids.paramete...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class APConnect: """A class to connect a device to an AP""" def __init__(self, nodes): """:param: - `nodes`: dictionary of id:device pairs""" super(APConnect, self).__init__() self.nodes = nodes return def __call__(self, parameters): """:param: - `parameters`: a nam...
the_stack_v2_python_sparse
apetools/affectors/apconnect.py
russell-n/oldape
train
0
7219e6eda24c85b742be0a2092d97eceb8dde47a
[ "np.random.seed(12345)\nN, M = image.shape\ndata = np.zeros((int(N * M / B / B), B * B))\nfor i in range(N // B):\n for j in range(M // B):\n data[i * M // B + j] = image[i * B:(i + 1) * B, j * B:(j + 1) * B].reshape(-1)\ncluster = KMeans(n_clusters=K)\ncluster.fit(data)\ncodebook = cluster.cluster_center...
<|body_start_0|> np.random.seed(12345) N, M = image.shape data = np.zeros((int(N * M / B / B), B * B)) for i in range(N // B): for j in range(M // B): data[i * M // B + j] = image[i * B:(i + 1) * B, j * B:(j + 1) * B].reshape(-1) cluster = KMeans(n_clu...
Question2
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Question2: def trainVQ(self, image, B, K): """Generate a codebook for vector quantization. You can use the KMeans function from the sklearn package. **For grading purposes only:** Do NOT change the random seed, otherwise we are not able to grade your code! Please flatten any matrix in *r...
stack_v2_sparse_classes_36k_train_032168
15,694
no_license
[ { "docstring": "Generate a codebook for vector quantization. You can use the KMeans function from the sklearn package. **For grading purposes only:** Do NOT change the random seed, otherwise we are not able to grade your code! Please flatten any matrix in *row-major* order. If you prefer, you can use np.flatten...
3
null
Implement the Python class `Question2` described below. Class description: Implement the Question2 class. Method signatures and docstrings: - def trainVQ(self, image, B, K): Generate a codebook for vector quantization. You can use the KMeans function from the sklearn package. **For grading purposes only:** Do NOT cha...
Implement the Python class `Question2` described below. Class description: Implement the Question2 class. Method signatures and docstrings: - def trainVQ(self, image, B, K): Generate a codebook for vector quantization. You can use the KMeans function from the sklearn package. **For grading purposes only:** Do NOT cha...
adcb6b47164a909fe8b3cd3969c8bc3f3696893a
<|skeleton|> class Question2: def trainVQ(self, image, B, K): """Generate a codebook for vector quantization. You can use the KMeans function from the sklearn package. **For grading purposes only:** Do NOT change the random seed, otherwise we are not able to grade your code! Please flatten any matrix in *r...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Question2: def trainVQ(self, image, B, K): """Generate a codebook for vector quantization. You can use the KMeans function from the sklearn package. **For grading purposes only:** Do NOT change the random seed, otherwise we are not able to grade your code! Please flatten any matrix in *row-major* orde...
the_stack_v2_python_sparse
ECE365/ML/lab4/main.py
RickyL-2000/ZJUI-lib
train
1
bf99336bd2c29ad714006bdfb35a6ce2bc7dcc2e
[ "self.license_key = license_key\nself.signed_by_user = signed_by_user\nself.signed_time = signed_time\nself.signed_version = signed_version", "if dictionary is None:\n return None\nlicense_key = dictionary.get('licenseKey')\nsigned_by_user = dictionary.get('signedByUser')\nsigned_time = dictionary.get('signedT...
<|body_start_0|> self.license_key = license_key self.signed_by_user = signed_by_user self.signed_time = signed_time self.signed_version = signed_version <|end_body_0|> <|body_start_1|> if dictionary is None: return None license_key = dictionary.get('licenseKe...
Implementation of the 'EulaConfig' model. Specifies the End User License Agreement acceptance information. Attributes: license_key (string, required): Specifies the license key. signed_by_user (string): Specifies the login account name for the Cohesity user who accepted the End User License Agreement. signed_time (long...
EulaConfig
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EulaConfig: """Implementation of the 'EulaConfig' model. Specifies the End User License Agreement acceptance information. Attributes: license_key (string, required): Specifies the license key. signed_by_user (string): Specifies the login account name for the Cohesity user who accepted the End Use...
stack_v2_sparse_classes_36k_train_032169
2,344
permissive
[ { "docstring": "Constructor for the EulaConfig class", "name": "__init__", "signature": "def __init__(self, license_key=None, signed_by_user=None, signed_time=None, signed_version=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dicti...
2
null
Implement the Python class `EulaConfig` described below. Class description: Implementation of the 'EulaConfig' model. Specifies the End User License Agreement acceptance information. Attributes: license_key (string, required): Specifies the license key. signed_by_user (string): Specifies the login account name for the...
Implement the Python class `EulaConfig` described below. Class description: Implementation of the 'EulaConfig' model. Specifies the End User License Agreement acceptance information. Attributes: license_key (string, required): Specifies the license key. signed_by_user (string): Specifies the login account name for the...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class EulaConfig: """Implementation of the 'EulaConfig' model. Specifies the End User License Agreement acceptance information. Attributes: license_key (string, required): Specifies the license key. signed_by_user (string): Specifies the login account name for the Cohesity user who accepted the End Use...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EulaConfig: """Implementation of the 'EulaConfig' model. Specifies the End User License Agreement acceptance information. Attributes: license_key (string, required): Specifies the license key. signed_by_user (string): Specifies the login account name for the Cohesity user who accepted the End User License Agr...
the_stack_v2_python_sparse
cohesity_management_sdk/models/eula_config.py
cohesity/management-sdk-python
train
24
924db1e689a1e67ca2cd0b7a1e9b1ce183cdb833
[ "create_l7policy_flow = linear_flow.Flow(constants.CREATE_L7POLICY_FLOW)\ncreate_l7policy_flow.add(lifecycle_tasks.L7PolicyToErrorOnRevertTask(requires=[constants.L7POLICY, constants.LISTENERS, constants.LOADBALANCER_ID]))\ncreate_l7policy_flow.add(database_tasks.MarkL7PolicyPendingCreateInDB(requires=constants.L7P...
<|body_start_0|> create_l7policy_flow = linear_flow.Flow(constants.CREATE_L7POLICY_FLOW) create_l7policy_flow.add(lifecycle_tasks.L7PolicyToErrorOnRevertTask(requires=[constants.L7POLICY, constants.LISTENERS, constants.LOADBALANCER_ID])) create_l7policy_flow.add(database_tasks.MarkL7PolicyPendin...
L7PolicyFlows
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class L7PolicyFlows: def get_create_l7policy_flow(self): """Create a flow to create an L7 policy :returns: The flow for creating an L7 policy""" <|body_0|> def get_delete_l7policy_flow(self): """Create a flow to delete an L7 policy :returns: The flow for deleting an L7 pol...
stack_v2_sparse_classes_36k_train_032170
4,109
permissive
[ { "docstring": "Create a flow to create an L7 policy :returns: The flow for creating an L7 policy", "name": "get_create_l7policy_flow", "signature": "def get_create_l7policy_flow(self)" }, { "docstring": "Create a flow to delete an L7 policy :returns: The flow for deleting an L7 policy", "na...
3
null
Implement the Python class `L7PolicyFlows` described below. Class description: Implement the L7PolicyFlows class. Method signatures and docstrings: - def get_create_l7policy_flow(self): Create a flow to create an L7 policy :returns: The flow for creating an L7 policy - def get_delete_l7policy_flow(self): Create a flo...
Implement the Python class `L7PolicyFlows` described below. Class description: Implement the L7PolicyFlows class. Method signatures and docstrings: - def get_create_l7policy_flow(self): Create a flow to create an L7 policy :returns: The flow for creating an L7 policy - def get_delete_l7policy_flow(self): Create a flo...
0426285a41464a5015494584f109eed35a0d44db
<|skeleton|> class L7PolicyFlows: def get_create_l7policy_flow(self): """Create a flow to create an L7 policy :returns: The flow for creating an L7 policy""" <|body_0|> def get_delete_l7policy_flow(self): """Create a flow to delete an L7 policy :returns: The flow for deleting an L7 pol...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class L7PolicyFlows: def get_create_l7policy_flow(self): """Create a flow to create an L7 policy :returns: The flow for creating an L7 policy""" create_l7policy_flow = linear_flow.Flow(constants.CREATE_L7POLICY_FLOW) create_l7policy_flow.add(lifecycle_tasks.L7PolicyToErrorOnRevertTask(requir...
the_stack_v2_python_sparse
octavia/controller/worker/v2/flows/l7policy_flows.py
openstack/octavia
train
147
6418721c19ed2fbed5bacacf0555ad2ddfd5ce07
[ "self.S = S\nscore = 0\ni = 0\nwhile i < len(S):\n subscore, i = self._get_score(i)\n score += subscore\nreturn score", "if i_start >= len(self.S):\n return [0, len(self.S)]\nscore = 0\ni = i_start + 1\nwhile i < len(self.S) and self.S[i] != ')':\n sub_score, i = self._get_score(i)\n score += sub_s...
<|body_start_0|> self.S = S score = 0 i = 0 while i < len(S): subscore, i = self._get_score(i) score += subscore return score <|end_body_0|> <|body_start_1|> if i_start >= len(self.S): return [0, len(self.S)] score = 0 ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def scoreOfParentheses(self, S: str) -> int: """Time complexity. Each symbol is read once and processed in O(1) manner, so total complexity is O(n) Space complexity: O(1) without stacking memory, O(max depth) with stacking memory.""" <|body_0|> def _get_score(self,...
stack_v2_sparse_classes_36k_train_032171
2,047
no_license
[ { "docstring": "Time complexity. Each symbol is read once and processed in O(1) manner, so total complexity is O(n) Space complexity: O(1) without stacking memory, O(max depth) with stacking memory.", "name": "scoreOfParentheses", "signature": "def scoreOfParentheses(self, S: str) -> int" }, { "...
2
stack_v2_sparse_classes_30k_train_015999
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def scoreOfParentheses(self, S: str) -> int: Time complexity. Each symbol is read once and processed in O(1) manner, so total complexity is O(n) Space complexity: O(1) without st...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def scoreOfParentheses(self, S: str) -> int: Time complexity. Each symbol is read once and processed in O(1) manner, so total complexity is O(n) Space complexity: O(1) without st...
ee8237b66975fb5584a3d68b311e762c0462c8aa
<|skeleton|> class Solution: def scoreOfParentheses(self, S: str) -> int: """Time complexity. Each symbol is read once and processed in O(1) manner, so total complexity is O(n) Space complexity: O(1) without stacking memory, O(max depth) with stacking memory.""" <|body_0|> def _get_score(self,...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def scoreOfParentheses(self, S: str) -> int: """Time complexity. Each symbol is read once and processed in O(1) manner, so total complexity is O(n) Space complexity: O(1) without stacking memory, O(max depth) with stacking memory.""" self.S = S score = 0 i = 0 ...
the_stack_v2_python_sparse
LC856-Score-of-Parentheses.py
kate-melnykova/LeetCode-solutions
train
2
21bbcf03a738abc709bbc3e54ed0c46b913fbe44
[ "super(ObservationPadEnv, self).__init__(env)\nself._padded_shape = padded_shape\nself._center = center\nold_space = self.observation_space\nself.observation_space = gym.spaces.Box(low=self.observation(old_space.low), high=self.observation(old_space.high), dtype=old_space.dtype)", "total_pads = tuple((target - cu...
<|body_start_0|> super(ObservationPadEnv, self).__init__(env) self._padded_shape = padded_shape self._center = center old_space = self.observation_space self.observation_space = gym.spaces.Box(low=self.observation(old_space.low), high=self.observation(old_space.high), dtype=old_s...
An environment that zero-pads the observation. Supports any Box observation space.
ObservationPadEnv
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ObservationPadEnv: """An environment that zero-pads the observation. Supports any Box observation space.""" def __init__(self, env, padded_shape, center=True): """Create a padded environment. Args: env: the environment to wrap. padded_shape: the shape after padding. center: if True, ...
stack_v2_sparse_classes_36k_train_032172
2,666
permissive
[ { "docstring": "Create a padded environment. Args: env: the environment to wrap. padded_shape: the shape after padding. center: if True, attempt to center the original observation in the padded one. Otherwise, put the original image at the beginning of the padded image (e.g. the top-left corner).", "name": ...
2
stack_v2_sparse_classes_30k_train_005665
Implement the Python class `ObservationPadEnv` described below. Class description: An environment that zero-pads the observation. Supports any Box observation space. Method signatures and docstrings: - def __init__(self, env, padded_shape, center=True): Create a padded environment. Args: env: the environment to wrap....
Implement the Python class `ObservationPadEnv` described below. Class description: An environment that zero-pads the observation. Supports any Box observation space. Method signatures and docstrings: - def __init__(self, env, padded_shape, center=True): Create a padded environment. Args: env: the environment to wrap....
bba80d7049fc1586a42c05905bae75c271657761
<|skeleton|> class ObservationPadEnv: """An environment that zero-pads the observation. Supports any Box observation space.""" def __init__(self, env, padded_shape, center=True): """Create a padded environment. Args: env: the environment to wrap. padded_shape: the shape after padding. center: if True, ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ObservationPadEnv: """An environment that zero-pads the observation. Supports any Box observation space.""" def __init__(self, env, padded_shape, center=True): """Create a padded environment. Args: env: the environment to wrap. padded_shape: the shape after padding. center: if True, attempt to ce...
the_stack_v2_python_sparse
anyrl-py/anyrl/envs/wrappers/padding.py
onursahin93/sonic_contest
train
0
b4f2bf194cce2fd88682429504a88de29c1b1245
[ "ctxt = context.get_admin_context()\nservices = db.service_get_all(ctxt)\nprint_format = '%-16s %-36s %-16s %-10s %-5s %-10s'\nprint(print_format % (_('Binary'), _('Host'), _('Zone'), _('Status'), _('State'), _('Updated At')))\nfor svc in services:\n alive = utils.service_is_up(svc)\n art = ':-)' if alive els...
<|body_start_0|> ctxt = context.get_admin_context() services = db.service_get_all(ctxt) print_format = '%-16s %-36s %-16s %-10s %-5s %-10s' print(print_format % (_('Binary'), _('Host'), _('Zone'), _('Status'), _('State'), _('Updated At'))) for svc in services: alive =...
Methods for managing services.
ServiceCommands
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ServiceCommands: """Methods for managing services.""" def list(self): """Show a list of all manila services.""" <|body_0|> def cleanup(self): """Remove manila services reporting as 'down'.""" <|body_1|> <|end_skeleton|> <|body_start_0|> ctxt = c...
stack_v2_sparse_classes_36k_train_032173
19,425
permissive
[ { "docstring": "Show a list of all manila services.", "name": "list", "signature": "def list(self)" }, { "docstring": "Remove manila services reporting as 'down'.", "name": "cleanup", "signature": "def cleanup(self)" } ]
2
stack_v2_sparse_classes_30k_train_015811
Implement the Python class `ServiceCommands` described below. Class description: Methods for managing services. Method signatures and docstrings: - def list(self): Show a list of all manila services. - def cleanup(self): Remove manila services reporting as 'down'.
Implement the Python class `ServiceCommands` described below. Class description: Methods for managing services. Method signatures and docstrings: - def list(self): Show a list of all manila services. - def cleanup(self): Remove manila services reporting as 'down'. <|skeleton|> class ServiceCommands: """Methods f...
a93a844398a11a8a85f204782fb9456f7caccdbe
<|skeleton|> class ServiceCommands: """Methods for managing services.""" def list(self): """Show a list of all manila services.""" <|body_0|> def cleanup(self): """Remove manila services reporting as 'down'.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ServiceCommands: """Methods for managing services.""" def list(self): """Show a list of all manila services.""" ctxt = context.get_admin_context() services = db.service_get_all(ctxt) print_format = '%-16s %-36s %-16s %-10s %-5s %-10s' print(print_format % (_('Binar...
the_stack_v2_python_sparse
manila/cmd/manage.py
openstack/manila
train
178
2c6c8d7866a60ca28a31866c8b738eaf043934ca
[ "supported_hashes = ', '.join(cls._SUPPORTED_HASHES)\nargument_group.add_argument('--nsrlsvr-hash', '--nsrlsvr_hash', dest='nsrlsvr_hash', type=str, action='store', choices=cls._SUPPORTED_HASHES, default=cls._DEFAULT_HASH, metavar='HASH', help=f'Type of hash to use to query nsrlsvr instance, the default is: {cls._D...
<|body_start_0|> supported_hashes = ', '.join(cls._SUPPORTED_HASHES) argument_group.add_argument('--nsrlsvr-hash', '--nsrlsvr_hash', dest='nsrlsvr_hash', type=str, action='store', choices=cls._SUPPORTED_HASHES, default=cls._DEFAULT_HASH, metavar='HASH', help=f'Type of hash to use to query nsrlsvr instan...
Nsrlsvr analysis plugin CLI arguments helper.
NsrlsvrAnalysisArgumentsHelper
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NsrlsvrAnalysisArgumentsHelper: """Nsrlsvr analysis plugin CLI arguments helper.""" def AddArguments(cls, argument_group): """Adds command line arguments the helper supports to an argument group. This function takes an argument parser or an argument group object and adds to it all th...
stack_v2_sparse_classes_36k_train_032174
3,840
permissive
[ { "docstring": "Adds command line arguments the helper supports to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args: argument_group (argparse._ArgumentGroup|argparse.ArgumentParser): group to append arg...
2
null
Implement the Python class `NsrlsvrAnalysisArgumentsHelper` described below. Class description: Nsrlsvr analysis plugin CLI arguments helper. Method signatures and docstrings: - def AddArguments(cls, argument_group): Adds command line arguments the helper supports to an argument group. This function takes an argument...
Implement the Python class `NsrlsvrAnalysisArgumentsHelper` described below. Class description: Nsrlsvr analysis plugin CLI arguments helper. Method signatures and docstrings: - def AddArguments(cls, argument_group): Adds command line arguments the helper supports to an argument group. This function takes an argument...
d6022f8cfebfddf2d08ab2d300a41b61f3349933
<|skeleton|> class NsrlsvrAnalysisArgumentsHelper: """Nsrlsvr analysis plugin CLI arguments helper.""" def AddArguments(cls, argument_group): """Adds command line arguments the helper supports to an argument group. This function takes an argument parser or an argument group object and adds to it all th...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NsrlsvrAnalysisArgumentsHelper: """Nsrlsvr analysis plugin CLI arguments helper.""" def AddArguments(cls, argument_group): """Adds command line arguments the helper supports to an argument group. This function takes an argument parser or an argument group object and adds to it all the command lin...
the_stack_v2_python_sparse
plaso/cli/helpers/nsrlsvr_analysis.py
log2timeline/plaso
train
1,506
988321bb3f0f3978f5f741829432c2bfdde4be58
[ "if token.base_form == '*':\n return WordRepr(token.surface, token.surface)\nelse:\n return WordRepr(token.surface, token.base_form)", "base_form = token_detail.feature.base_form\nif base_form == '*':\n return WordRepr(token_detail.surface, token_detail.surface)\nelse:\n return WordRepr(token_detail.s...
<|body_start_0|> if token.base_form == '*': return WordRepr(token.surface, token.surface) else: return WordRepr(token.surface, token.base_form) <|end_body_0|> <|body_start_1|> base_form = token_detail.feature.base_form if base_form == '*': return Word...
単語の表現情報 Attributes: surface (str): 表層形 base_form (str): 原形
WordRepr
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WordRepr: """単語の表現情報 Attributes: surface (str): 表層形 base_form (str): 原形""" def from_token(cls, token: Token): """TokenインスタンスからWordReprインスタンスを作成 Args: token (Token): Tokenインスタンス Returns: WordReprインスタンス""" <|body_0|> def from_token_detail(cls, token_detail: TokenDetail): ...
stack_v2_sparse_classes_36k_train_032175
12,296
no_license
[ { "docstring": "TokenインスタンスからWordReprインスタンスを作成 Args: token (Token): Tokenインスタンス Returns: WordReprインスタンス", "name": "from_token", "signature": "def from_token(cls, token: Token)" }, { "docstring": "TokenDetailインスタンスからWordReprインスタンスを作成 Args: token_detail (TokenDetail): TokenDetailインスタンス Returns: Wo...
2
stack_v2_sparse_classes_30k_train_010639
Implement the Python class `WordRepr` described below. Class description: 単語の表現情報 Attributes: surface (str): 表層形 base_form (str): 原形 Method signatures and docstrings: - def from_token(cls, token: Token): TokenインスタンスからWordReprインスタンスを作成 Args: token (Token): Tokenインスタンス Returns: WordReprインスタンス - def from_token_detail(cl...
Implement the Python class `WordRepr` described below. Class description: 単語の表現情報 Attributes: surface (str): 表層形 base_form (str): 原形 Method signatures and docstrings: - def from_token(cls, token: Token): TokenインスタンスからWordReprインスタンスを作成 Args: token (Token): Tokenインスタンス Returns: WordReprインスタンス - def from_token_detail(cl...
a4c6334b779a94814b7798a0fbfe9a148bf18d3a
<|skeleton|> class WordRepr: """単語の表現情報 Attributes: surface (str): 表層形 base_form (str): 原形""" def from_token(cls, token: Token): """TokenインスタンスからWordReprインスタンスを作成 Args: token (Token): Tokenインスタンス Returns: WordReprインスタンス""" <|body_0|> def from_token_detail(cls, token_detail: TokenDetail): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WordRepr: """単語の表現情報 Attributes: surface (str): 表層形 base_form (str): 原形""" def from_token(cls, token: Token): """TokenインスタンスからWordReprインスタンスを作成 Args: token (Token): Tokenインスタンス Returns: WordReprインスタンス""" if token.base_form == '*': return WordRepr(token.surface, token.surface) ...
the_stack_v2_python_sparse
src/review_research/nlp/nlp_types.py
S38knt-ks/ReviewResearch
train
0
5a835443cd21a6f169a9dd6c125659a8acc8016b
[ "if self.source_port is not None:\n return self.source_port.is_local\nreturn True", "if self.dest_port is not None:\n return self.dest_port.is_local\nreturn True", "super(FlowClassifier, self).validate()\nif self.source_port is None and self.dest_port is None:\n raise errors.ValidationError('One of sou...
<|body_start_0|> if self.source_port is not None: return self.source_port.is_local return True <|end_body_0|> <|body_start_1|> if self.dest_port is not None: return self.dest_port.is_local return True <|end_body_1|> <|body_start_2|> super(FlowClassifier,...
FlowClassifier
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FlowClassifier: def is_classification_local(self): """Should the flow classifier classification flows be installed locally For classification on source lport, we match using reg6, which is available only after classification app sets it, so there is no use installing it on other hosts. F...
stack_v2_sparse_classes_36k_train_032176
5,427
permissive
[ { "docstring": "Should the flow classifier classification flows be installed locally For classification on source lport, we match using reg6, which is available only after classification app sets it, so there is no use installing it on other hosts. For classification on dest lport, we match using reg7. reg7 is ...
3
stack_v2_sparse_classes_30k_test_000816
Implement the Python class `FlowClassifier` described below. Class description: Implement the FlowClassifier class. Method signatures and docstrings: - def is_classification_local(self): Should the flow classifier classification flows be installed locally For classification on source lport, we match using reg6, which...
Implement the Python class `FlowClassifier` described below. Class description: Implement the FlowClassifier class. Method signatures and docstrings: - def is_classification_local(self): Should the flow classifier classification flows be installed locally For classification on source lport, we match using reg6, which...
0f154d4f794b02ac5b7fd61a3417d89e7b10912d
<|skeleton|> class FlowClassifier: def is_classification_local(self): """Should the flow classifier classification flows be installed locally For classification on source lport, we match using reg6, which is available only after classification app sets it, so there is no use installing it on other hosts. F...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FlowClassifier: def is_classification_local(self): """Should the flow classifier classification flows be installed locally For classification on source lport, we match using reg6, which is available only after classification app sets it, so there is no use installing it on other hosts. For classificat...
the_stack_v2_python_sparse
dragonflow/db/models/sfc.py
qianyuqiao/dragonflow
train
0
567a387287bf9c62c3cd299a59c85a542af781f5
[ "self.serializer_class = CommentSerializer\nimage_id = self.kwargs.get('image_id')\nif not image_id:\n return JsonResponse({'status': 'fail', 'code': 406, 'data': None, 'messages': ['Error: No image id provided!']})\nqueryset_list = Comment.objects.filter(image__pk=image_id)\nreturn queryset_list", "self.seria...
<|body_start_0|> self.serializer_class = CommentSerializer image_id = self.kwargs.get('image_id') if not image_id: return JsonResponse({'status': 'fail', 'code': 406, 'data': None, 'messages': ['Error: No image id provided!']}) queryset_list = Comment.objects.filter(image__pk...
Класа која се користи за креирање коментара и за добављање листе свих коментара слике репрезентованих у JSON формату
CreateGetCommentsAPI
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CreateGetCommentsAPI: """Класа која се користи за креирање коментара и за добављање листе свих коментара слике репрезентованих у JSON формату""" def get_queryset(self, *args, **kwargs): """Mетода помоћу које се добављају сви подаци :param args: :param kwargs: image_id :return: QueryS...
stack_v2_sparse_classes_36k_train_032177
6,327
no_license
[ { "docstring": "Mетода помоћу које се добављају сви подаци :param args: :param kwargs: image_id :return: QuerySet", "name": "get_queryset", "signature": "def get_queryset(self, *args, **kwargs)" }, { "docstring": "Mетода помоћу које се врши креирање :param request: :param args: :param kwargs: im...
2
stack_v2_sparse_classes_30k_train_002529
Implement the Python class `CreateGetCommentsAPI` described below. Class description: Класа која се користи за креирање коментара и за добављање листе свих коментара слике репрезентованих у JSON формату Method signatures and docstrings: - def get_queryset(self, *args, **kwargs): Mетода помоћу које се добављају сви по...
Implement the Python class `CreateGetCommentsAPI` described below. Class description: Класа која се користи за креирање коментара и за добављање листе свих коментара слике репрезентованих у JSON формату Method signatures and docstrings: - def get_queryset(self, *args, **kwargs): Mетода помоћу које се добављају сви по...
9b49cdfdcfbbc911cec23ed30ded30f6c4042522
<|skeleton|> class CreateGetCommentsAPI: """Класа која се користи за креирање коментара и за добављање листе свих коментара слике репрезентованих у JSON формату""" def get_queryset(self, *args, **kwargs): """Mетода помоћу које се добављају сви подаци :param args: :param kwargs: image_id :return: QueryS...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CreateGetCommentsAPI: """Класа која се користи за креирање коментара и за добављање листе свих коментара слике репрезентованих у JSON формату""" def get_queryset(self, *args, **kwargs): """Mетода помоћу које се добављају сви подаци :param args: :param kwargs: image_id :return: QuerySet""" ...
the_stack_v2_python_sparse
src/comments/api/views.py
milosb793/django-gallery-api
train
0
76636a1200484ae7d2ef3113785f4f033cdaf370
[ "links = response.xpath('//a[@class=\"product-title-link\"]/@href').extract()\nfor link in links:\n yield response.follow('https://www.labirint.ru' + link, callback=self.parse_item)\nnext_page = response.xpath('//a[@class=\"pagination-next__text\"]/@href').extract_first()\nif next_page:\n yield response.follo...
<|body_start_0|> links = response.xpath('//a[@class="product-title-link"]/@href').extract() for link in links: yield response.follow('https://www.labirint.ru' + link, callback=self.parse_item) next_page = response.xpath('//a[@class="pagination-next__text"]/@href').extract_first() ...
Labirint.ru spider.
LabirintruSpider
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LabirintruSpider: """Labirint.ru spider.""" def parse(self, response): """Novelty page parser.""" <|body_0|> def parse_item(self, response: HtmlResponse): """Book item parser.""" <|body_1|> <|end_skeleton|> <|body_start_0|> links = response.xpat...
stack_v2_sparse_classes_36k_train_032178
1,756
no_license
[ { "docstring": "Novelty page parser.", "name": "parse", "signature": "def parse(self, response)" }, { "docstring": "Book item parser.", "name": "parse_item", "signature": "def parse_item(self, response: HtmlResponse)" } ]
2
stack_v2_sparse_classes_30k_test_001166
Implement the Python class `LabirintruSpider` described below. Class description: Labirint.ru spider. Method signatures and docstrings: - def parse(self, response): Novelty page parser. - def parse_item(self, response: HtmlResponse): Book item parser.
Implement the Python class `LabirintruSpider` described below. Class description: Labirint.ru spider. Method signatures and docstrings: - def parse(self, response): Novelty page parser. - def parse_item(self, response: HtmlResponse): Book item parser. <|skeleton|> class LabirintruSpider: """Labirint.ru spider.""...
69488f0e788578722bf4f1cf171508f1e5624145
<|skeleton|> class LabirintruSpider: """Labirint.ru spider.""" def parse(self, response): """Novelty page parser.""" <|body_0|> def parse_item(self, response: HtmlResponse): """Book item parser.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LabirintruSpider: """Labirint.ru spider.""" def parse(self, response): """Novelty page parser.""" links = response.xpath('//a[@class="product-title-link"]/@href').extract() for link in links: yield response.follow('https://www.labirint.ru' + link, callback=self.parse_i...
the_stack_v2_python_sparse
lesson_6/bookparser/spiders/labirintru.py
IInvasion/collecting_and_processing_web_data
train
0
83b027bbe9a384bab501f1ad937396ebf4515b3f
[ "logger.info('Checking Appfollow API connection...')\ntry:\n ext_id = config['ext_id']\n cid = config['cid']\n api_secret = config['api_secret']\n response = requests.get(f'https://api.appfollow.io/ratings?ext_id={ext_id}&cid={cid}', auth=HTTPBasicAuth(api_secret, api_secret))\n if response.status_co...
<|body_start_0|> logger.info('Checking Appfollow API connection...') try: ext_id = config['ext_id'] cid = config['cid'] api_secret = config['api_secret'] response = requests.get(f'https://api.appfollow.io/ratings?ext_id={ext_id}&cid={cid}', auth=HTTPBasicA...
SourceAppfollow
[ "MIT", "Apache-2.0", "BSD-3-Clause", "Elastic-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SourceAppfollow: def check_connection(self, logger, config) -> Tuple[bool, any]: """A connection check to validate that the user-provided config can be used to connect to the underlying API :param config: the user-input config object conforming to the connector's spec.yaml :param logger:...
stack_v2_sparse_classes_36k_train_032179
3,806
permissive
[ { "docstring": "A connection check to validate that the user-provided config can be used to connect to the underlying API :param config: the user-input config object conforming to the connector's spec.yaml :param logger: logger object :return Tuple[bool, any]: (True, None) if the input config can be used to con...
2
stack_v2_sparse_classes_30k_train_007124
Implement the Python class `SourceAppfollow` described below. Class description: Implement the SourceAppfollow class. Method signatures and docstrings: - def check_connection(self, logger, config) -> Tuple[bool, any]: A connection check to validate that the user-provided config can be used to connect to the underlyin...
Implement the Python class `SourceAppfollow` described below. Class description: Implement the SourceAppfollow class. Method signatures and docstrings: - def check_connection(self, logger, config) -> Tuple[bool, any]: A connection check to validate that the user-provided config can be used to connect to the underlyin...
8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6
<|skeleton|> class SourceAppfollow: def check_connection(self, logger, config) -> Tuple[bool, any]: """A connection check to validate that the user-provided config can be used to connect to the underlying API :param config: the user-input config object conforming to the connector's spec.yaml :param logger:...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SourceAppfollow: def check_connection(self, logger, config) -> Tuple[bool, any]: """A connection check to validate that the user-provided config can be used to connect to the underlying API :param config: the user-input config object conforming to the connector's spec.yaml :param logger: logger object...
the_stack_v2_python_sparse
dts/airbyte/airbyte-integrations/connectors/source-appfollow/source_appfollow/source.py
alldatacenter/alldata
train
774
7aa0653bafc11b065bb47d21a55d0c4e8f3ba002
[ "def find(parent, i):\n \"\"\"\n find the \"root\" node which is connected to i\n \"\"\"\n while parent[i] != i:\n i = parent[i]\n return parent[i]\nN = len(edges)\nparent = [0] * (N + 1)\nA, B = ([], [])\nfor i in range(N):\n u, v = edges[i]\n if parent[v] == 0:\n ...
<|body_start_0|> def find(parent, i): """ find the "root" node which is connected to i """ while parent[i] != i: i = parent[i] return parent[i] N = len(edges) parent = [0] * (N + 1) A, B = ([], []...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findRedundantDirectedConnection(self, edges): """:type edges: List[List[int]] :rtype: List[int]""" <|body_0|> def findRedundantDirectedConnection2(self, edges): """:type edges: List[List[int]] :rtype: List[int]""" <|body_1|> <|end_skeleton|> <...
stack_v2_sparse_classes_36k_train_032180
7,752
no_license
[ { "docstring": ":type edges: List[List[int]] :rtype: List[int]", "name": "findRedundantDirectedConnection", "signature": "def findRedundantDirectedConnection(self, edges)" }, { "docstring": ":type edges: List[List[int]] :rtype: List[int]", "name": "findRedundantDirectedConnection2", "sig...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findRedundantDirectedConnection(self, edges): :type edges: List[List[int]] :rtype: List[int] - def findRedundantDirectedConnection2(self, edges): :type edges: List[List[int]]...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findRedundantDirectedConnection(self, edges): :type edges: List[List[int]] :rtype: List[int] - def findRedundantDirectedConnection2(self, edges): :type edges: List[List[int]]...
635af6e22aa8eef8e7920a585d43a45a891a8157
<|skeleton|> class Solution: def findRedundantDirectedConnection(self, edges): """:type edges: List[List[int]] :rtype: List[int]""" <|body_0|> def findRedundantDirectedConnection2(self, edges): """:type edges: List[List[int]] :rtype: List[int]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def findRedundantDirectedConnection(self, edges): """:type edges: List[List[int]] :rtype: List[int]""" def find(parent, i): """ find the "root" node which is connected to i """ while parent[i] != i: i = p...
the_stack_v2_python_sparse
code685RedundantConnectionII.py
cybelewang/leetcode-python
train
0
f187006e01fc57789e714d7778b7868779b7bbe4
[ "try:\n comment = self.update_order_comment()\nexcept Exception:\n return HttpResponseBadRequest()\nelse:\n return JsonResponse({'comment': comment})", "product_id = self.request.POST['product_id']\ncomment = self.request.POST['comment']\nproduct = get_object_or_404(BaseProduct, id=product_id)\nreturn mo...
<|body_start_0|> try: comment = self.update_order_comment() except Exception: return HttpResponseBadRequest() else: return JsonResponse({'comment': comment}) <|end_body_0|> <|body_start_1|> product_id = self.request.POST['product_id'] comment ...
View for setting re-order comments.
SetOrderComment
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SetOrderComment: """View for setting re-order comments.""" def post(self, *args, **kwargs): """Update re-order comment.""" <|body_0|> def update_order_comment(self): """Update re-order comment.""" <|body_1|> <|end_skeleton|> <|body_start_0|> try...
stack_v2_sparse_classes_36k_train_032181
6,889
no_license
[ { "docstring": "Update re-order comment.", "name": "post", "signature": "def post(self, *args, **kwargs)" }, { "docstring": "Update re-order comment.", "name": "update_order_comment", "signature": "def update_order_comment(self)" } ]
2
stack_v2_sparse_classes_30k_train_018647
Implement the Python class `SetOrderComment` described below. Class description: View for setting re-order comments. Method signatures and docstrings: - def post(self, *args, **kwargs): Update re-order comment. - def update_order_comment(self): Update re-order comment.
Implement the Python class `SetOrderComment` described below. Class description: View for setting re-order comments. Method signatures and docstrings: - def post(self, *args, **kwargs): Update re-order comment. - def update_order_comment(self): Update re-order comment. <|skeleton|> class SetOrderComment: """View...
ba51d4e304b1aeb296fa2fe16611c892fcdbd471
<|skeleton|> class SetOrderComment: """View for setting re-order comments.""" def post(self, *args, **kwargs): """Update re-order comment.""" <|body_0|> def update_order_comment(self): """Update re-order comment.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SetOrderComment: """View for setting re-order comments.""" def post(self, *args, **kwargs): """Update re-order comment.""" try: comment = self.update_order_comment() except Exception: return HttpResponseBadRequest() else: return JsonResp...
the_stack_v2_python_sparse
restock/views.py
stcstores/stcadmin
train
0
b4cc6bcb27a43d153bc09ea98392be10defb41b1
[ "cluster = self.get_object_or_404(objects.Cluster, cluster_id)\nself.check_net_provider(cluster)\nreturn self.serializer.serialize_for_cluster(cluster)", "data = jsonutils.loads(web.data())\ncluster = self.get_object_or_404(objects.Cluster, cluster_id)\nself.check_net_provider(cluster)\nself.check_if_network_conf...
<|body_start_0|> cluster = self.get_object_or_404(objects.Cluster, cluster_id) self.check_net_provider(cluster) return self.serializer.serialize_for_cluster(cluster) <|end_body_0|> <|body_start_1|> data = jsonutils.loads(web.data()) cluster = self.get_object_or_404(objects.Clust...
Neutron Network configuration handler
NeutronNetworkConfigurationHandler
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NeutronNetworkConfigurationHandler: """Neutron Network configuration handler""" def GET(self, cluster_id): """:returns: JSONized network configuration for cluster. :http: * 200 (OK) * 404 (cluster not found in db)""" <|body_0|> def PUT(self, cluster_id): """:retu...
stack_v2_sparse_classes_36k_train_032182
8,763
permissive
[ { "docstring": ":returns: JSONized network configuration for cluster. :http: * 200 (OK) * 404 (cluster not found in db)", "name": "GET", "signature": "def GET(self, cluster_id)" }, { "docstring": ":returns: JSONized Task object. :http: * 200 (task successfully executed) * 202 (network checking t...
2
null
Implement the Python class `NeutronNetworkConfigurationHandler` described below. Class description: Neutron Network configuration handler Method signatures and docstrings: - def GET(self, cluster_id): :returns: JSONized network configuration for cluster. :http: * 200 (OK) * 404 (cluster not found in db) - def PUT(sel...
Implement the Python class `NeutronNetworkConfigurationHandler` described below. Class description: Neutron Network configuration handler Method signatures and docstrings: - def GET(self, cluster_id): :returns: JSONized network configuration for cluster. :http: * 200 (OK) * 404 (cluster not found in db) - def PUT(sel...
976baf842242a5f97c95bdc3e20328fa0558bf69
<|skeleton|> class NeutronNetworkConfigurationHandler: """Neutron Network configuration handler""" def GET(self, cluster_id): """:returns: JSONized network configuration for cluster. :http: * 200 (OK) * 404 (cluster not found in db)""" <|body_0|> def PUT(self, cluster_id): """:retu...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NeutronNetworkConfigurationHandler: """Neutron Network configuration handler""" def GET(self, cluster_id): """:returns: JSONized network configuration for cluster. :http: * 200 (OK) * 404 (cluster not found in db)""" cluster = self.get_object_or_404(objects.Cluster, cluster_id) se...
the_stack_v2_python_sparse
nailgun/nailgun/api/v1/handlers/network_configuration.py
nebril/fuel-web
train
1
3a710c6f39d176e199527f6694694b0639a7e78c
[ "super().__init__(model, step_type, predictor_kwargs=predictor_kwargs)\nself.model = model\nself.hidden_size = hidden_size\nself.num_samples = num_samples\nself.mc_dropout = mc_dropout\nself.weight_decay = weight_decay\nself.prior_scale = prior_scale\nself.data_length = data_length\nself.mc_dropout_layer = nn.Dropo...
<|body_start_0|> super().__init__(model, step_type, predictor_kwargs=predictor_kwargs) self.model = model self.hidden_size = hidden_size self.num_samples = num_samples self.mc_dropout = mc_dropout self.weight_decay = weight_decay self.prior_scale = prior_scale ...
Recoding mechanism that bases its recoding on the predictive uncertainty of the decoder, where the uncertainty is estimate using MC Dropout [1]. [1] http://proceedings.mlr.press/v48/gal16.pdf
MCDropoutMechanism
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MCDropoutMechanism: """Recoding mechanism that bases its recoding on the predictive uncertainty of the decoder, where the uncertainty is estimate using MC Dropout [1]. [1] http://proceedings.mlr.press/v48/gal16.pdf""" def __init__(self, model: AbstractRNN, hidden_size: int, num_samples: int,...
stack_v2_sparse_classes_36k_train_032183
5,682
no_license
[ { "docstring": "Initialize the mechanism. Parameters ---------- model: AbstractRNN Model the mechanism is being applied to. hidden_size: int Dimensionality of hidden activations. num_samples: int Number of samples used to estimate uncertainty. mc_dropout: float Dropout probability used to estimate uncertainty. ...
4
stack_v2_sparse_classes_30k_train_018693
Implement the Python class `MCDropoutMechanism` described below. Class description: Recoding mechanism that bases its recoding on the predictive uncertainty of the decoder, where the uncertainty is estimate using MC Dropout [1]. [1] http://proceedings.mlr.press/v48/gal16.pdf Method signatures and docstrings: - def __...
Implement the Python class `MCDropoutMechanism` described below. Class description: Recoding mechanism that bases its recoding on the predictive uncertainty of the decoder, where the uncertainty is estimate using MC Dropout [1]. [1] http://proceedings.mlr.press/v48/gal16.pdf Method signatures and docstrings: - def __...
6443bea8d325fa948e117b32a063e5383db2de14
<|skeleton|> class MCDropoutMechanism: """Recoding mechanism that bases its recoding on the predictive uncertainty of the decoder, where the uncertainty is estimate using MC Dropout [1]. [1] http://proceedings.mlr.press/v48/gal16.pdf""" def __init__(self, model: AbstractRNN, hidden_size: int, num_samples: int,...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MCDropoutMechanism: """Recoding mechanism that bases its recoding on the predictive uncertainty of the decoder, where the uncertainty is estimate using MC Dropout [1]. [1] http://proceedings.mlr.press/v48/gal16.pdf""" def __init__(self, model: AbstractRNN, hidden_size: int, num_samples: int, mc_dropout: ...
the_stack_v2_python_sparse
src/recoding/mc_dropout.py
Kaleidophon/tenacious-toucan
train
0
b8a2e0b8e6fcc9ed26aea820e37dec857fabdd56
[ "keyword = data.get('keyword')\ndescription = data.get('description')\n_keyword = Keyword(keyword)\nfunction_name = _keyword.get_function_name_from_source()\ndata = {'name': function_name, 'description': description, 'keyword': keyword}\nmodel = KeywordModel(**data)\ndb.session.add(model)\ndb.session.commit()\nretu...
<|body_start_0|> keyword = data.get('keyword') description = data.get('description') _keyword = Keyword(keyword) function_name = _keyword.get_function_name_from_source() data = {'name': function_name, 'description': description, 'keyword': keyword} model = KeywordModel(**...
KeywordService
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KeywordService: def create(self, data): """# 暂时没有前端页面 -- SQL暂时不更换 # 这里需要先提取函数名,然后关键字用函数名进行索引,存到数据库。 # 如果数据库中函数名已经存在怎么办,是否需要先查询,重复则失败? :param data: :return:""" <|body_0|> def delete(self, data): """:param data: :return:""" <|body_1|> def update(self, data...
stack_v2_sparse_classes_36k_train_032184
3,159
permissive
[ { "docstring": "# 暂时没有前端页面 -- SQL暂时不更换 # 这里需要先提取函数名,然后关键字用函数名进行索引,存到数据库。 # 如果数据库中函数名已经存在怎么办,是否需要先查询,重复则失败? :param data: :return:", "name": "create", "signature": "def create(self, data)" }, { "docstring": ":param data: :return:", "name": "delete", "signature": "def delete(self, data)" ...
5
stack_v2_sparse_classes_30k_train_003011
Implement the Python class `KeywordService` described below. Class description: Implement the KeywordService class. Method signatures and docstrings: - def create(self, data): # 暂时没有前端页面 -- SQL暂时不更换 # 这里需要先提取函数名,然后关键字用函数名进行索引,存到数据库。 # 如果数据库中函数名已经存在怎么办,是否需要先查询,重复则失败? :param data: :return: - def delete(self, data): :pa...
Implement the Python class `KeywordService` described below. Class description: Implement the KeywordService class. Method signatures and docstrings: - def create(self, data): # 暂时没有前端页面 -- SQL暂时不更换 # 这里需要先提取函数名,然后关键字用函数名进行索引,存到数据库。 # 如果数据库中函数名已经存在怎么办,是否需要先查询,重复则失败? :param data: :return: - def delete(self, data): :pa...
54dc4000263ab9e8873f0d429a7fe48b11fb727a
<|skeleton|> class KeywordService: def create(self, data): """# 暂时没有前端页面 -- SQL暂时不更换 # 这里需要先提取函数名,然后关键字用函数名进行索引,存到数据库。 # 如果数据库中函数名已经存在怎么办,是否需要先查询,重复则失败? :param data: :return:""" <|body_0|> def delete(self, data): """:param data: :return:""" <|body_1|> def update(self, data...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class KeywordService: def create(self, data): """# 暂时没有前端页面 -- SQL暂时不更换 # 这里需要先提取函数名,然后关键字用函数名进行索引,存到数据库。 # 如果数据库中函数名已经存在怎么办,是否需要先查询,重复则失败? :param data: :return:""" keyword = data.get('keyword') description = data.get('description') _keyword = Keyword(keyword) function_name =...
the_stack_v2_python_sparse
clover/keyword/service.py
taoyanli0808/clover
train
18
3dc14a6646dc4003095a61985af6e816f58b3fd6
[ "try:\n word_value = Word_Counter.objects.get(pk=pk)\n serializer = WordCounterSerializer(word_value, context={'request': request})\n return Response(serializer.data)\nexcept Exception as ex:\n return HttpResponseServerError(ex)", "word_values = self.request.query_params.get('word_values')\nif word_va...
<|body_start_0|> try: word_value = Word_Counter.objects.get(pk=pk) serializer = WordCounterSerializer(word_value, context={'request': request}) return Response(serializer.data) except Exception as ex: return HttpResponseServerError(ex) <|end_body_0|> <|bo...
Words_Counter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Words_Counter: def retrieve(self, request, pk=None): """Handle GET requests for single word Returns: Response -- JSON serialized word instance""" <|body_0|> def list(self, request): """Handle GET requests to words resource Returns: Response -- JSON serialized list of...
stack_v2_sparse_classes_36k_train_032185
2,351
no_license
[ { "docstring": "Handle GET requests for single word Returns: Response -- JSON serialized word instance", "name": "retrieve", "signature": "def retrieve(self, request, pk=None)" }, { "docstring": "Handle GET requests to words resource Returns: Response -- JSON serialized list of words", "name...
2
stack_v2_sparse_classes_30k_train_009840
Implement the Python class `Words_Counter` described below. Class description: Implement the Words_Counter class. Method signatures and docstrings: - def retrieve(self, request, pk=None): Handle GET requests for single word Returns: Response -- JSON serialized word instance - def list(self, request): Handle GET reque...
Implement the Python class `Words_Counter` described below. Class description: Implement the Words_Counter class. Method signatures and docstrings: - def retrieve(self, request, pk=None): Handle GET requests for single word Returns: Response -- JSON serialized word instance - def list(self, request): Handle GET reque...
582048dafa7e354fffdc0478ec68088e8bbf42b1
<|skeleton|> class Words_Counter: def retrieve(self, request, pk=None): """Handle GET requests for single word Returns: Response -- JSON serialized word instance""" <|body_0|> def list(self, request): """Handle GET requests to words resource Returns: Response -- JSON serialized list of...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Words_Counter: def retrieve(self, request, pk=None): """Handle GET requests for single word Returns: Response -- JSON serialized word instance""" try: word_value = Word_Counter.objects.get(pk=pk) serializer = WordCounterSerializer(word_value, context={'request': request...
the_stack_v2_python_sparse
genieioapp/views/words_counter.py
cherkesky/GenieIO
train
1
011c2c4de5f89e0f33ce9287fc819cfd630ace89
[ "self._num_gaussians = len(sigma_list)\nself._sigmas_scaled = np.array(sigma_list) / pixel_scale\nif supersampling_convolution is True:\n self._sigmas_scaled *= supersampling_factor\nself._fraction_list = fraction_list / np.sum(fraction_list)\nassert len(self._sigmas_scaled) == len(self._fraction_list)\nself._tr...
<|body_start_0|> self._num_gaussians = len(sigma_list) self._sigmas_scaled = np.array(sigma_list) / pixel_scale if supersampling_convolution is True: self._sigmas_scaled *= supersampling_factor self._fraction_list = fraction_list / np.sum(fraction_list) assert len(sel...
class to perform a convolution consisting of multiple 2d Gaussians This is aimed to lead to a speed-up without significant loss of accuracy do to the simplified convolution kernel relative to a pixelized kernel.
MultiGaussianConvolution
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiGaussianConvolution: """class to perform a convolution consisting of multiple 2d Gaussians This is aimed to lead to a speed-up without significant loss of accuracy do to the simplified convolution kernel relative to a pixelized kernel.""" def __init__(self, sigma_list, fraction_list, pi...
stack_v2_sparse_classes_36k_train_032186
15,375
permissive
[ { "docstring": ":param sigma_list: list of std value of Gaussian kernel :param fraction_list: fraction of flux to be convoled with each Gaussian kernel :param pixel_scale: scale of pixel width (to convert sigmas into units of pixels) :param truncation: float. Truncate the filter at this many standard deviations...
4
null
Implement the Python class `MultiGaussianConvolution` described below. Class description: class to perform a convolution consisting of multiple 2d Gaussians This is aimed to lead to a speed-up without significant loss of accuracy do to the simplified convolution kernel relative to a pixelized kernel. Method signature...
Implement the Python class `MultiGaussianConvolution` described below. Class description: class to perform a convolution consisting of multiple 2d Gaussians This is aimed to lead to a speed-up without significant loss of accuracy do to the simplified convolution kernel relative to a pixelized kernel. Method signature...
73c9645f26f6983fe7961104075ebe8bf7a4b54c
<|skeleton|> class MultiGaussianConvolution: """class to perform a convolution consisting of multiple 2d Gaussians This is aimed to lead to a speed-up without significant loss of accuracy do to the simplified convolution kernel relative to a pixelized kernel.""" def __init__(self, sigma_list, fraction_list, pi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MultiGaussianConvolution: """class to perform a convolution consisting of multiple 2d Gaussians This is aimed to lead to a speed-up without significant loss of accuracy do to the simplified convolution kernel relative to a pixelized kernel.""" def __init__(self, sigma_list, fraction_list, pixel_scale, su...
the_stack_v2_python_sparse
lenstronomy/ImSim/Numerics/convolution.py
lenstronomy/lenstronomy
train
41
d45662f4dd4be5a127e11579b8d510877b610a82
[ "self.ss = ss\nself.n_step = n_step\nself.mu = mu\nself.sigma = sigma\nself.step_time = step_time\nself.saw_time = saw_time / delta_t", "step_vector = np.abs([round(gauss(self.mu, self.sigma), 1) for _ in range(self.n_step)])\nstep_vector[0] = self.ss\nu = np.zeros(shape=dim)\nj = 0\nramp_Step = self.saw_time\nco...
<|body_start_0|> self.ss = ss self.n_step = n_step self.mu = mu self.sigma = sigma self.step_time = step_time self.saw_time = saw_time / delta_t <|end_body_0|> <|body_start_1|> step_vector = np.abs([round(gauss(self.mu, self.sigma), 1) for _ in range(self.n_step)...
SawGaussStep
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SawGaussStep: def __init__(self, step_time, saw_time, delta_t, mu=None, sigma=None, n_step=None, ss=None): """Settings for a random step sequence Args: step_time: Time to perform step change n_step (int): Number of steps""" <|body_0|> def out(self, t: any, dim=(None, None)) ...
stack_v2_sparse_classes_36k_train_032187
8,036
no_license
[ { "docstring": "Settings for a random step sequence Args: step_time: Time to perform step change n_step (int): Number of steps", "name": "__init__", "signature": "def __init__(self, step_time, saw_time, delta_t, mu=None, sigma=None, n_step=None, ss=None)" }, { "docstring": "Generate a random seq...
2
stack_v2_sparse_classes_30k_train_008396
Implement the Python class `SawGaussStep` described below. Class description: Implement the SawGaussStep class. Method signatures and docstrings: - def __init__(self, step_time, saw_time, delta_t, mu=None, sigma=None, n_step=None, ss=None): Settings for a random step sequence Args: step_time: Time to perform step cha...
Implement the Python class `SawGaussStep` described below. Class description: Implement the SawGaussStep class. Method signatures and docstrings: - def __init__(self, step_time, saw_time, delta_t, mu=None, sigma=None, n_step=None, ss=None): Settings for a random step sequence Args: step_time: Time to perform step cha...
cf548475295f25407ba968546c2fc85c26f9343c
<|skeleton|> class SawGaussStep: def __init__(self, step_time, saw_time, delta_t, mu=None, sigma=None, n_step=None, ss=None): """Settings for a random step sequence Args: step_time: Time to perform step change n_step (int): Number of steps""" <|body_0|> def out(self, t: any, dim=(None, None)) ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SawGaussStep: def __init__(self, step_time, saw_time, delta_t, mu=None, sigma=None, n_step=None, ss=None): """Settings for a random step sequence Args: step_time: Time to perform step change n_step (int): Number of steps""" self.ss = ss self.n_step = n_step self.mu = mu ...
the_stack_v2_python_sparse
SourceCode/simulation/signal.py
martin-bachorik/Master-Thesis-Project
train
0
99c18086dc0c85ef0eb1cc727aa1f7d3b8e629ff
[ "stack = [root]\nrAns = [str(root.val)]\nwhile stack:\n temp = stack.pop(0)\n if temp.left and temp.right:\n stack.append(temp.left)\n stack.append(temp.right)\n rAns.append(str(temp.left.val))\n rAns.append(str(temp.right.val))\n elif not temp.left and temp.right:\n stac...
<|body_start_0|> stack = [root] rAns = [str(root.val)] while stack: temp = stack.pop(0) if temp.left and temp.right: stack.append(temp.left) stack.append(temp.right) rAns.append(str(temp.left.val)) rAns.appen...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_36k_train_032188
2,440
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
stack_v2_sparse_classes_30k_train_007634
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
7ee9e603b0ef612193a522a32bb150781c6bb416
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" stack = [root] rAns = [str(root.val)] while stack: temp = stack.pop(0) if temp.left and temp.right: stack.append(temp.left) ...
the_stack_v2_python_sparse
pySolution/Codec.py
Qanora/leetcode
train
0
71d85026ba072ce67091fcdd952249e861ee28fb
[ "self.state_list = state_list\nself.domain = domain\nself.start_state = start_state\nself.acceptor_states = acceptor_states\nself.state_transition_table = state_transition_table", "current_state = self.start_state\nfor char in input_string:\n if not current_state in self.state_list:\n return 'REJECT'\n ...
<|body_start_0|> self.state_list = state_list self.domain = domain self.start_state = start_state self.acceptor_states = acceptor_states self.state_transition_table = state_transition_table <|end_body_0|> <|body_start_1|> current_state = self.start_state for char...
Class containing functions for defining finite state automata and running finite state machines using textual input
Finite_State_Automata
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Finite_State_Automata: """Class containing functions for defining finite state automata and running finite state machines using textual input""" def __init__(self, state_list, domain, start_state, acceptor_states, state_transition_table): """Initialize an FSA by its own definition Pa...
stack_v2_sparse_classes_36k_train_032189
5,491
no_license
[ { "docstring": "Initialize an FSA by its own definition Parameters --- state_list -> List of all possible states domain -> Domain of all symbols that the machine can accept start_state -> The starting state of the machine acceptor_states -> list of states that are defined as the final accepting states state_tra...
3
stack_v2_sparse_classes_30k_train_008187
Implement the Python class `Finite_State_Automata` described below. Class description: Class containing functions for defining finite state automata and running finite state machines using textual input Method signatures and docstrings: - def __init__(self, state_list, domain, start_state, acceptor_states, state_tran...
Implement the Python class `Finite_State_Automata` described below. Class description: Class containing functions for defining finite state automata and running finite state machines using textual input Method signatures and docstrings: - def __init__(self, state_list, domain, start_state, acceptor_states, state_tran...
1f7dd50123b5b69d8268bc071a4adc5b3b8a76e6
<|skeleton|> class Finite_State_Automata: """Class containing functions for defining finite state automata and running finite state machines using textual input""" def __init__(self, state_list, domain, start_state, acceptor_states, state_transition_table): """Initialize an FSA by its own definition Pa...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Finite_State_Automata: """Class containing functions for defining finite state automata and running finite state machines using textual input""" def __init__(self, state_list, domain, start_state, acceptor_states, state_transition_table): """Initialize an FSA by its own definition Parameters --- ...
the_stack_v2_python_sparse
state_machine.py
lzambella/csc470-proj1
train
0
5e7b52ecb441c4972fd4855ac4edcc1747d8f79f
[ "super(SegNet_1, self).__init__()\nself.layer_1 = SegnetLayer_Encoder(in_channels, 64, 2)\nself.layer_2 = SegnetLayer_Encoder(64, 128, 2)\nself.layer_3 = SegnetLayer_Encoder(128, 256, 3)\nself.layer_4 = SegnetLayer_Encoder(256, 512, 3)\nself.layer_5 = SegnetLayer_Encoder(512, 1024, 3)\nself.layer_6 = SegnetLayer_En...
<|body_start_0|> super(SegNet_1, self).__init__() self.layer_1 = SegnetLayer_Encoder(in_channels, 64, 2) self.layer_2 = SegnetLayer_Encoder(64, 128, 2) self.layer_3 = SegnetLayer_Encoder(128, 256, 3) self.layer_4 = SegnetLayer_Encoder(256, 512, 3) self.layer_5 = SegnetLay...
Derived Class to define a Segnet Architecture of NN Attributes ---------- in_channels : int The input size of the network. n_classes : int The output size of the network. References ---------- SegNet: A Deep Convolutional Encoder-Decoder Architecture for Image Segmentation Vijay Badrinarayanan, Alex Kendall, Roberto Ci...
SegNet_1
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SegNet_1: """Derived Class to define a Segnet Architecture of NN Attributes ---------- in_channels : int The input size of the network. n_classes : int The output size of the network. References ---------- SegNet: A Deep Convolutional Encoder-Decoder Architecture for Image Segmentation Vijay Badr...
stack_v2_sparse_classes_36k_train_032190
20,094
no_license
[ { "docstring": "Sequential Instanciation of the different Layers", "name": "__init__", "signature": "def __init__(self, in_channels=3, n_classes=21)" }, { "docstring": "Sequential Computation, see nn.Module.forward methods PyTorch", "name": "forward", "signature": "def forward(self, inpu...
2
stack_v2_sparse_classes_30k_train_019076
Implement the Python class `SegNet_1` described below. Class description: Derived Class to define a Segnet Architecture of NN Attributes ---------- in_channels : int The input size of the network. n_classes : int The output size of the network. References ---------- SegNet: A Deep Convolutional Encoder-Decoder Archite...
Implement the Python class `SegNet_1` described below. Class description: Derived Class to define a Segnet Architecture of NN Attributes ---------- in_channels : int The input size of the network. n_classes : int The output size of the network. References ---------- SegNet: A Deep Convolutional Encoder-Decoder Archite...
3b63f360e67013d5962082e57fb36ebfb37d8920
<|skeleton|> class SegNet_1: """Derived Class to define a Segnet Architecture of NN Attributes ---------- in_channels : int The input size of the network. n_classes : int The output size of the network. References ---------- SegNet: A Deep Convolutional Encoder-Decoder Architecture for Image Segmentation Vijay Badr...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SegNet_1: """Derived Class to define a Segnet Architecture of NN Attributes ---------- in_channels : int The input size of the network. n_classes : int The output size of the network. References ---------- SegNet: A Deep Convolutional Encoder-Decoder Architecture for Image Segmentation Vijay Badrinarayanan, A...
the_stack_v2_python_sparse
segmentation/models/nn.py
Kivo0/vibotorch
train
0
74740fad7b96eeb46118e5d97bf81abef5df8f6e
[ "super().__init__(coordinator, device, 'delivery', 'Energy delivery', f'delivery_{dev_type}')\nself._type = dev_type\nself._attr_name = f'Energy delivery {dev_type}'", "if self.coordinator.data.delivery_meter is None:\n return None\nreturn getattr(self.coordinator.data.delivery_meter, f'_{self._type}', None)" ...
<|body_start_0|> super().__init__(coordinator, device, 'delivery', 'Energy delivery', f'delivery_{dev_type}') self._type = dev_type self._attr_name = f'Energy delivery {dev_type}' <|end_body_0|> <|body_start_1|> if self.coordinator.data.delivery_meter is None: return None ...
The Youless delivery meter value sensor.
DeliveryMeterSensor
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DeliveryMeterSensor: """The Youless delivery meter value sensor.""" def __init__(self, coordinator: DataUpdateCoordinator[YoulessAPI], device: str, dev_type: str) -> None: """Instantiate a delivery meter sensor.""" <|body_0|> def get_sensor(self) -> YoulessSensor | None:...
stack_v2_sparse_classes_36k_train_032191
11,812
permissive
[ { "docstring": "Instantiate a delivery meter sensor.", "name": "__init__", "signature": "def __init__(self, coordinator: DataUpdateCoordinator[YoulessAPI], device: str, dev_type: str) -> None" }, { "docstring": "Get the sensor for providing the value.", "name": "get_sensor", "signature":...
2
null
Implement the Python class `DeliveryMeterSensor` described below. Class description: The Youless delivery meter value sensor. Method signatures and docstrings: - def __init__(self, coordinator: DataUpdateCoordinator[YoulessAPI], device: str, dev_type: str) -> None: Instantiate a delivery meter sensor. - def get_senso...
Implement the Python class `DeliveryMeterSensor` described below. Class description: The Youless delivery meter value sensor. Method signatures and docstrings: - def __init__(self, coordinator: DataUpdateCoordinator[YoulessAPI], device: str, dev_type: str) -> None: Instantiate a delivery meter sensor. - def get_senso...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class DeliveryMeterSensor: """The Youless delivery meter value sensor.""" def __init__(self, coordinator: DataUpdateCoordinator[YoulessAPI], device: str, dev_type: str) -> None: """Instantiate a delivery meter sensor.""" <|body_0|> def get_sensor(self) -> YoulessSensor | None:...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DeliveryMeterSensor: """The Youless delivery meter value sensor.""" def __init__(self, coordinator: DataUpdateCoordinator[YoulessAPI], device: str, dev_type: str) -> None: """Instantiate a delivery meter sensor.""" super().__init__(coordinator, device, 'delivery', 'Energy delivery', f'del...
the_stack_v2_python_sparse
homeassistant/components/youless/sensor.py
home-assistant/core
train
35,501
19c9bcf19d67e868f2b5c68808f5f8201bfd4dc7
[ "try:\n return (int(key[0] // 16), int(key[1] // 16), int(key[2] // 16))\nexcept ValueError:\n return KeyError(\"Key %s isn't usable here!\" % repr(key))", "minx, innerx = divmod(key[0], 16)\nminy, innery = divmod(key[1], 16)\nminz, innerz = divmod(key[2], 16)\nminx = int(minx)\nminy = int(miny)\nminz = int...
<|body_start_0|> try: return (int(key[0] // 16), int(key[1] // 16), int(key[2] // 16)) except ValueError: return KeyError("Key %s isn't usable here!" % repr(key)) <|end_body_0|> <|body_start_1|> minx, innerx = divmod(key[0], 16) miny, innery = divmod(key[1], 16) ...
Class for tracking blocks in the XZ-plane.
Block3DSpatialDict
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Block3DSpatialDict: """Class for tracking blocks in the XZ-plane.""" def key_for_bucket(self, key): """Partition keys into chunk-sized buckets.""" <|body_0|> def keys_near(self, key, radius): """Get all bucket keys "near" this key. This method may return a genera...
stack_v2_sparse_classes_36k_train_032192
5,213
permissive
[ { "docstring": "Partition keys into chunk-sized buckets.", "name": "key_for_bucket", "signature": "def key_for_bucket(self, key)" }, { "docstring": "Get all bucket keys \"near\" this key. This method may return a generator.", "name": "keys_near", "signature": "def keys_near(self, key, ra...
2
stack_v2_sparse_classes_30k_train_012028
Implement the Python class `Block3DSpatialDict` described below. Class description: Class for tracking blocks in the XZ-plane. Method signatures and docstrings: - def key_for_bucket(self, key): Partition keys into chunk-sized buckets. - def keys_near(self, key, radius): Get all bucket keys "near" this key. This metho...
Implement the Python class `Block3DSpatialDict` described below. Class description: Class for tracking blocks in the XZ-plane. Method signatures and docstrings: - def key_for_bucket(self, key): Partition keys into chunk-sized buckets. - def keys_near(self, key, radius): Get all bucket keys "near" this key. This metho...
7be5d792871a8447499911fa1502c6a7c1437dc3
<|skeleton|> class Block3DSpatialDict: """Class for tracking blocks in the XZ-plane.""" def key_for_bucket(self, key): """Partition keys into chunk-sized buckets.""" <|body_0|> def keys_near(self, key, radius): """Get all bucket keys "near" this key. This method may return a genera...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Block3DSpatialDict: """Class for tracking blocks in the XZ-plane.""" def key_for_bucket(self, key): """Partition keys into chunk-sized buckets.""" try: return (int(key[0] // 16), int(key[1] // 16), int(key[2] // 16)) except ValueError: return KeyError("Key ...
the_stack_v2_python_sparse
bravo/utilities/spatial.py
CyberFlameGO/bravo
train
0
32d8973b1b805ce5e395966c008f30e5c9649e33
[ "self.str_a = str_a\nself.str_b = str_b\nself.ratio = distance_ratio\nself.author_a = None\nself.author_b = None\nself.work_a = None\nself.work_b = None\nself.subwork_a = None\nself.subwork_b = None\nself.text_n_a = None\nself.text_n_b = None\nself.language_a = None\nself.language_b = None\nreturn", "if 'author' ...
<|body_start_0|> self.str_a = str_a self.str_b = str_b self.ratio = distance_ratio self.author_a = None self.author_b = None self.work_a = None self.work_b = None self.subwork_a = None self.subwork_b = None self.text_n_a = None self...
A class to increase ease of working with text reuse data.
Comparison
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Comparison: """A class to increase ease of working with text reuse data.""" def __init__(self, str_a, str_b, distance_ratio): """Initialize class with compared strings and ratio of comparison :param str_a: str :param str_b: str :param distance_ratio: float""" <|body_0|> ...
stack_v2_sparse_classes_36k_train_032193
7,939
permissive
[ { "docstring": "Initialize class with compared strings and ratio of comparison :param str_a: str :param str_b: str :param distance_ratio: float", "name": "__init__", "signature": "def __init__(self, str_a, str_b, distance_ratio)" }, { "docstring": "Set the reference values related to the str_a c...
3
null
Implement the Python class `Comparison` described below. Class description: A class to increase ease of working with text reuse data. Method signatures and docstrings: - def __init__(self, str_a, str_b, distance_ratio): Initialize class with compared strings and ratio of comparison :param str_a: str :param str_b: str...
Implement the Python class `Comparison` described below. Class description: A class to increase ease of working with text reuse data. Method signatures and docstrings: - def __init__(self, str_a, str_b, distance_ratio): Initialize class with compared strings and ratio of comparison :param str_a: str :param str_b: str...
085420eaed7055fbcb311714eebb67861fd1b241
<|skeleton|> class Comparison: """A class to increase ease of working with text reuse data.""" def __init__(self, str_a, str_b, distance_ratio): """Initialize class with compared strings and ratio of comparison :param str_a: str :param str_b: str :param distance_ratio: float""" <|body_0|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Comparison: """A class to increase ease of working with text reuse data.""" def __init__(self, str_a, str_b, distance_ratio): """Initialize class with compared strings and ratio of comparison :param str_a: str :param str_b: str :param distance_ratio: float""" self.str_a = str_a se...
the_stack_v2_python_sparse
cltk/text_reuse/comparison.py
jerryfrancis-97/cltk
train
1
60fe1647f69d4d734dee6722d20fb0df14b30295
[ "super().__init__(**kwargs)\nself.rnn = rnn\nself.reducer = reducer\nself.bidirectional = bidirectional\nif bidirectional:\n self.rnn = tf.keras.layers.Bidirectional(self.rnn, merge_mode=None)", "outputs = self.rnn(*args, **kwargs)\nif self.bidirectional:\n sequences = outputs[0:2]\n states = outputs[2:]...
<|body_start_0|> super().__init__(**kwargs) self.rnn = rnn self.reducer = reducer self.bidirectional = bidirectional if bidirectional: self.rnn = tf.keras.layers.Bidirectional(self.rnn, merge_mode=None) <|end_body_0|> <|body_start_1|> outputs = self.rnn(*args...
Extend a RNN layer to possibly make it bidirectional and format its outputs.
_RNNWrapper
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _RNNWrapper: """Extend a RNN layer to possibly make it bidirectional and format its outputs.""" def __init__(self, rnn, bidirectional=False, reducer=reducer_lib.ConcatReducer(), **kwargs): """Initializes the layer. Args: rnn: The RNN layer to extend, built with ``return_sequences`` a...
stack_v2_sparse_classes_36k_train_032194
9,747
permissive
[ { "docstring": "Initializes the layer. Args: rnn: The RNN layer to extend, built with ``return_sequences`` and ``return_state`` enabled. bidirectional: Make this layer bidirectional. reducer: A :class:`opennmt.layers.Reducer` instance to merge bidirectional states and outputs. **kwargs: Additional layer argumen...
2
null
Implement the Python class `_RNNWrapper` described below. Class description: Extend a RNN layer to possibly make it bidirectional and format its outputs. Method signatures and docstrings: - def __init__(self, rnn, bidirectional=False, reducer=reducer_lib.ConcatReducer(), **kwargs): Initializes the layer. Args: rnn: T...
Implement the Python class `_RNNWrapper` described below. Class description: Extend a RNN layer to possibly make it bidirectional and format its outputs. Method signatures and docstrings: - def __init__(self, rnn, bidirectional=False, reducer=reducer_lib.ConcatReducer(), **kwargs): Initializes the layer. Args: rnn: T...
6f3b952ebb973dec31250a806bf0f56ff730d0b5
<|skeleton|> class _RNNWrapper: """Extend a RNN layer to possibly make it bidirectional and format its outputs.""" def __init__(self, rnn, bidirectional=False, reducer=reducer_lib.ConcatReducer(), **kwargs): """Initializes the layer. Args: rnn: The RNN layer to extend, built with ``return_sequences`` a...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _RNNWrapper: """Extend a RNN layer to possibly make it bidirectional and format its outputs.""" def __init__(self, rnn, bidirectional=False, reducer=reducer_lib.ConcatReducer(), **kwargs): """Initializes the layer. Args: rnn: The RNN layer to extend, built with ``return_sequences`` and ``return_s...
the_stack_v2_python_sparse
opennmt/layers/rnn.py
OpenNMT/OpenNMT-tf
train
1,487
61777ce76fa0aa407cfce3f0c6fc81db02d04523
[ "super(WeightQuantizerGF, self).__init__()\nself.k = k\nfor i in range(1, k + 1):\n self.register_buffer(f'v{i}', torch.tensor([0.0] * size))", "if self.training:\n vs, x_q = quantization.quantizer_gf(x, k=self.k)\n for i in range(self.k):\n getattr(self, f'v{i + 1}').copy_(vs[i])\nelse:\n vs =...
<|body_start_0|> super(WeightQuantizerGF, self).__init__() self.k = k for i in range(1, k + 1): self.register_buffer(f'v{i}', torch.tensor([0.0] * size)) <|end_body_0|> <|body_start_1|> if self.training: vs, x_q = quantization.quantizer_gf(x, k=self.k) ...
Weight greedy foldable quantizer. In training mode, the optimal scalars are computed and cached. In eval mode, the cached scalars are used to compute the quantization.
WeightQuantizerGF
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WeightQuantizerGF: """Weight greedy foldable quantizer. In training mode, the optimal scalars are computed and cached. In eval mode, the cached scalars are used to compute the quantization.""" def __init__(self, size: int, k: int) -> None: """Construct a greedy-foldable quantizer wit...
stack_v2_sparse_classes_36k_train_032195
4,037
no_license
[ { "docstring": "Construct a greedy-foldable quantizer with `k`-bits.", "name": "__init__", "signature": "def __init__(self, size: int, k: int) -> None" }, { "docstring": "Forward pass of greedy foldable quantizer with `k`-bits.", "name": "forward", "signature": "def forward(self, x: torc...
2
stack_v2_sparse_classes_30k_train_005115
Implement the Python class `WeightQuantizerGF` described below. Class description: Weight greedy foldable quantizer. In training mode, the optimal scalars are computed and cached. In eval mode, the cached scalars are used to compute the quantization. Method signatures and docstrings: - def __init__(self, size: int, k...
Implement the Python class `WeightQuantizerGF` described below. Class description: Weight greedy foldable quantizer. In training mode, the optimal scalars are computed and cached. In eval mode, the cached scalars are used to compute the quantization. Method signatures and docstrings: - def __init__(self, size: int, k...
39197b5f54cd84ff35022c851dd2dcb753ca6b89
<|skeleton|> class WeightQuantizerGF: """Weight greedy foldable quantizer. In training mode, the optimal scalars are computed and cached. In eval mode, the cached scalars are used to compute the quantization.""" def __init__(self, size: int, k: int) -> None: """Construct a greedy-foldable quantizer wit...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WeightQuantizerGF: """Weight greedy foldable quantizer. In training mode, the optimal scalars are computed and cached. In eval mode, the cached scalars are used to compute the quantization.""" def __init__(self, size: int, k: int) -> None: """Construct a greedy-foldable quantizer with `k`-bits.""...
the_stack_v2_python_sparse
quant/binary/weight_quantization.py
mikechen66/ml-quant
train
0
06c9deea268d960d8d0ee98a1bfd9a07619be465
[ "self.n = int(n)\nself.p = float(p)\nif data is None:\n if self.n < 1:\n raise ValueError('n must be a positive value')\n elif self.p <= 0 or self.p >= 1:\n raise ValueError('p must be greater than 0 and less than 1')\nelif isinstance(data, list):\n if len(data) > 1:\n self.data = data...
<|body_start_0|> self.n = int(n) self.p = float(p) if data is None: if self.n < 1: raise ValueError('n must be a positive value') elif self.p <= 0 or self.p >= 1: raise ValueError('p must be greater than 0 and less than 1') elif isi...
Class Binomial
Binomial
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Binomial: """Class Binomial""" def __init__(self, data=None, n=1, p=0.5): """Initializes the distribution. Args: data (list): distribution data n (int): Bernoulli number. p (float): success probability.""" <|body_0|> def pmf(self, k): """Calculates the pmf at a g...
stack_v2_sparse_classes_36k_train_032196
2,389
no_license
[ { "docstring": "Initializes the distribution. Args: data (list): distribution data n (int): Bernoulli number. p (float): success probability.", "name": "__init__", "signature": "def __init__(self, data=None, n=1, p=0.5)" }, { "docstring": "Calculates the pmf at a given k Args: k (int): point to ...
3
stack_v2_sparse_classes_30k_train_011654
Implement the Python class `Binomial` described below. Class description: Class Binomial Method signatures and docstrings: - def __init__(self, data=None, n=1, p=0.5): Initializes the distribution. Args: data (list): distribution data n (int): Bernoulli number. p (float): success probability. - def pmf(self, k): Calc...
Implement the Python class `Binomial` described below. Class description: Class Binomial Method signatures and docstrings: - def __init__(self, data=None, n=1, p=0.5): Initializes the distribution. Args: data (list): distribution data n (int): Bernoulli number. p (float): success probability. - def pmf(self, k): Calc...
5aff923277cfe9f2b5324a773e4e5c3cac810a0c
<|skeleton|> class Binomial: """Class Binomial""" def __init__(self, data=None, n=1, p=0.5): """Initializes the distribution. Args: data (list): distribution data n (int): Bernoulli number. p (float): success probability.""" <|body_0|> def pmf(self, k): """Calculates the pmf at a g...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Binomial: """Class Binomial""" def __init__(self, data=None, n=1, p=0.5): """Initializes the distribution. Args: data (list): distribution data n (int): Bernoulli number. p (float): success probability.""" self.n = int(n) self.p = float(p) if data is None: if s...
the_stack_v2_python_sparse
math/0x03-probability/binomial.py
cmmolanos1/holbertonschool-machine_learning
train
1
368f3d65b3dcbbfb9b9ff08b82a8748cb8826381
[ "super().setUp()\nself.login(self.CURRICULUM_ADMIN_EMAIL, is_super_admin=True)\ncsrf_token = self.get_new_csrf_token()\nself.post_json('/adminhandler', {'action': 'reload_exploration', 'exploration_id': '3'}, csrf_token=csrf_token)\nself.logout()", "library_groups = summary_services.get_library_groups([])\nexpect...
<|body_start_0|> super().setUp() self.login(self.CURRICULUM_ADMIN_EMAIL, is_super_admin=True) csrf_token = self.get_new_csrf_token() self.post_json('/adminhandler', {'action': 'reload_exploration', 'exploration_id': '3'}, csrf_token=csrf_token) self.logout() <|end_body_0|> <|bod...
Test functions for getting summary dicts for library groups.
LibraryGroupsTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LibraryGroupsTest: """Test functions for getting summary dicts for library groups.""" def setUp(self) -> None: """Populate the database of explorations and their summaries. The sequence of events is: - (1) Admin logs in. - (2) Admin access admin page. - (3) Admin reloads exploration ...
stack_v2_sparse_classes_36k_train_032197
47,358
permissive
[ { "docstring": "Populate the database of explorations and their summaries. The sequence of events is: - (1) Admin logs in. - (2) Admin access admin page. - (3) Admin reloads exploration with id '3'. - (4) Admin logs out.", "name": "setUp", "signature": "def setUp(self) -> None" }, { "docstring":...
2
stack_v2_sparse_classes_30k_train_015085
Implement the Python class `LibraryGroupsTest` described below. Class description: Test functions for getting summary dicts for library groups. Method signatures and docstrings: - def setUp(self) -> None: Populate the database of explorations and their summaries. The sequence of events is: - (1) Admin logs in. - (2) ...
Implement the Python class `LibraryGroupsTest` described below. Class description: Test functions for getting summary dicts for library groups. Method signatures and docstrings: - def setUp(self) -> None: Populate the database of explorations and their summaries. The sequence of events is: - (1) Admin logs in. - (2) ...
d16fdf23d790eafd63812bd7239532256e30a21d
<|skeleton|> class LibraryGroupsTest: """Test functions for getting summary dicts for library groups.""" def setUp(self) -> None: """Populate the database of explorations and their summaries. The sequence of events is: - (1) Admin logs in. - (2) Admin access admin page. - (3) Admin reloads exploration ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LibraryGroupsTest: """Test functions for getting summary dicts for library groups.""" def setUp(self) -> None: """Populate the database of explorations and their summaries. The sequence of events is: - (1) Admin logs in. - (2) Admin access admin page. - (3) Admin reloads exploration with id '3'. ...
the_stack_v2_python_sparse
core/domain/summary_services_test.py
oppia/oppia
train
6,172
c8c24ab8b6e196d8eb0c64920251021a94acfa9e
[ "event_columns_string = QueryHelper.get_columns_string(EventMapping, 'events')\nevent_type_columns_string = QueryHelper.get_columns_string(EventTypeMapping, 'event_types')\ndog_columns_string = QueryHelper.get_columns_string(DogMapping, 'dogs')\nstmt = text('SELECT {event_columns}, {event_type_columns}, {dog_column...
<|body_start_0|> event_columns_string = QueryHelper.get_columns_string(EventMapping, 'events') event_type_columns_string = QueryHelper.get_columns_string(EventTypeMapping, 'event_types') dog_columns_string = QueryHelper.get_columns_string(DogMapping, 'dogs') stmt = text('SELECT {event_co...
EventRepository
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EventRepository: def get_events_by_expenditure_id(cls, expenditure_id: int): """Gets all events by expenditure id, joined with dog and type""" <|body_0|> def get_event_by_id(cls, event_id: int): """Get event by id""" <|body_1|> def add_new_event(cls, eve...
stack_v2_sparse_classes_36k_train_032198
7,079
no_license
[ { "docstring": "Gets all events by expenditure id, joined with dog and type", "name": "get_events_by_expenditure_id", "signature": "def get_events_by_expenditure_id(cls, expenditure_id: int)" }, { "docstring": "Get event by id", "name": "get_event_by_id", "signature": "def get_event_by_i...
4
stack_v2_sparse_classes_30k_train_001236
Implement the Python class `EventRepository` described below. Class description: Implement the EventRepository class. Method signatures and docstrings: - def get_events_by_expenditure_id(cls, expenditure_id: int): Gets all events by expenditure id, joined with dog and type - def get_event_by_id(cls, event_id: int): G...
Implement the Python class `EventRepository` described below. Class description: Implement the EventRepository class. Method signatures and docstrings: - def get_events_by_expenditure_id(cls, expenditure_id: int): Gets all events by expenditure id, joined with dog and type - def get_event_by_id(cls, event_id: int): G...
d5e383a3a703c973d038627f35d405e716cfd25c
<|skeleton|> class EventRepository: def get_events_by_expenditure_id(cls, expenditure_id: int): """Gets all events by expenditure id, joined with dog and type""" <|body_0|> def get_event_by_id(cls, event_id: int): """Get event by id""" <|body_1|> def add_new_event(cls, eve...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EventRepository: def get_events_by_expenditure_id(cls, expenditure_id: int): """Gets all events by expenditure id, joined with dog and type""" event_columns_string = QueryHelper.get_columns_string(EventMapping, 'events') event_type_columns_string = QueryHelper.get_columns_string(EventT...
the_stack_v2_python_sparse
app/events/repository.py
Innodogs/Innodogs
train
0
c6e1b2e3f9b1b14f4881ee9baa0e1999835e5ac2
[ "cube = set_up_variable_cube(np.zeros((2, 2), dtype=np.float32), name='lwe_thickness_of_precipitation_amount', units='m', time=dt(2017, 1, 10, 4, 0), frt=dt(2017, 1, 10, 3, 0))\nself.cube = add_coordinate(cube, [dt(2017, 1, 10, 3, 0), dt(2017, 1, 10, 4, 0)], 'time', is_datetime=True)\ndata = np.array([[[1.0, 1.0], ...
<|body_start_0|> cube = set_up_variable_cube(np.zeros((2, 2), dtype=np.float32), name='lwe_thickness_of_precipitation_amount', units='m', time=dt(2017, 1, 10, 4, 0), frt=dt(2017, 1, 10, 3, 0)) self.cube = add_coordinate(cube, [dt(2017, 1, 10, 3, 0), dt(2017, 1, 10, 4, 0)], 'time', is_datetime=True) ...
Tests for the process method in ChooseDefaultWeightsTriangular.
Test_process
[ "BSD-3-Clause", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Test_process: """Tests for the process method in ChooseDefaultWeightsTriangular.""" def setUp(self): """Set up cubes used in unit tests""" <|body_0|> def test_same_units(self): """Test plugin produces the correct weights when the parameters for the triangle are i...
stack_v2_sparse_classes_36k_train_032199
13,166
permissive
[ { "docstring": "Set up cubes used in unit tests", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Test plugin produces the correct weights when the parameters for the triangle are in the same units as the input cube's coordinate", "name": "test_same_units", "signature"...
4
stack_v2_sparse_classes_30k_train_003089
Implement the Python class `Test_process` described below. Class description: Tests for the process method in ChooseDefaultWeightsTriangular. Method signatures and docstrings: - def setUp(self): Set up cubes used in unit tests - def test_same_units(self): Test plugin produces the correct weights when the parameters f...
Implement the Python class `Test_process` described below. Class description: Tests for the process method in ChooseDefaultWeightsTriangular. Method signatures and docstrings: - def setUp(self): Set up cubes used in unit tests - def test_same_units(self): Test plugin produces the correct weights when the parameters f...
cd2c9019944345df1e703bf8f625db537ad9f559
<|skeleton|> class Test_process: """Tests for the process method in ChooseDefaultWeightsTriangular.""" def setUp(self): """Set up cubes used in unit tests""" <|body_0|> def test_same_units(self): """Test plugin produces the correct weights when the parameters for the triangle are i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Test_process: """Tests for the process method in ChooseDefaultWeightsTriangular.""" def setUp(self): """Set up cubes used in unit tests""" cube = set_up_variable_cube(np.zeros((2, 2), dtype=np.float32), name='lwe_thickness_of_precipitation_amount', units='m', time=dt(2017, 1, 10, 4, 0), f...
the_stack_v2_python_sparse
improver_tests/blending/weights/test_ChooseDefaultWeightsTriangular.py
metoppv/improver
train
101