blob_id
stringlengths
40
40
bodies
listlengths
2
6
bodies_text
stringlengths
196
7.73k
class_docstring
stringlengths
0
700
class_name
stringlengths
1
86
detected_licenses
listlengths
0
45
format_version
stringclasses
1 value
full_text
stringlengths
378
8.64k
id
stringlengths
44
44
length_bytes
int64
505
50k
license_type
stringclasses
2 values
methods
listlengths
2
6
n_methods
int64
2
6
original_id
stringlengths
38
40
prompt
stringlengths
153
4.88k
prompted_full_text
stringlengths
565
12.5k
revision_id
stringlengths
40
40
skeleton
stringlengths
162
5.05k
snapshot_name
stringclasses
1 value
snapshot_source_dir
stringclasses
1 value
snapshot_total_rows
int64
75.8k
75.8k
solution
stringlengths
242
8.3k
source
stringclasses
1 value
source_path
stringlengths
4
177
source_repo
stringlengths
6
110
split
stringclasses
1 value
star_events_count
int64
0
209k
09ceeff88db61da4ecf6a84878bedc5302bdf39a
[ "if self.request.version == 'v6':\n return ScanDetailsSerializerV6\nelif self.request.version == 'v7':\n return ScanDetailsSerializerV6", "if request.version == 'v6':\n return self._post_v6(request, scan_id)\nelif request.version == 'v7':\n return self._post_v6(request, scan_id)\nraise Http404()", "...
<|body_start_0|> if self.request.version == 'v6': return ScanDetailsSerializerV6 elif self.request.version == 'v7': return ScanDetailsSerializerV6 <|end_body_0|> <|body_start_1|> if request.version == 'v6': return self._post_v6(request, scan_id) elif ...
This view is the endpoint for launching a scan execution to ingest
ScansProcessView
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "LicenseRef-scancode-public-domain" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ScansProcessView: """This view is the endpoint for launching a scan execution to ingest""" def get_serializer_class(self): """Returns the appropriate serializer based off the requests version of the REST API.""" <|body_0|> def post(self, request, scan_id=None): "...
stack_v2_sparse_classes_75kplus_train_006600
30,689
permissive
[ { "docstring": "Returns the appropriate serializer based off the requests version of the REST API.", "name": "get_serializer_class", "signature": "def get_serializer_class(self)" }, { "docstring": "Launches a scan to ingest from an existing scan model instance :param request: the HTTP POST reque...
3
stack_v2_sparse_classes_30k_train_005625
Implement the Python class `ScansProcessView` described below. Class description: This view is the endpoint for launching a scan execution to ingest Method signatures and docstrings: - def get_serializer_class(self): Returns the appropriate serializer based off the requests version of the REST API. - def post(self, r...
Implement the Python class `ScansProcessView` described below. Class description: This view is the endpoint for launching a scan execution to ingest Method signatures and docstrings: - def get_serializer_class(self): Returns the appropriate serializer based off the requests version of the REST API. - def post(self, r...
28618aee07ceed9e4a6eb7b8d0e6f05b31d8fd6b
<|skeleton|> class ScansProcessView: """This view is the endpoint for launching a scan execution to ingest""" def get_serializer_class(self): """Returns the appropriate serializer based off the requests version of the REST API.""" <|body_0|> def post(self, request, scan_id=None): "...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ScansProcessView: """This view is the endpoint for launching a scan execution to ingest""" def get_serializer_class(self): """Returns the appropriate serializer based off the requests version of the REST API.""" if self.request.version == 'v6': return ScanDetailsSerializerV6 ...
the_stack_v2_python_sparse
scale/ingest/views.py
kfconsultant/scale
train
0
f68750e963e0ed6e9b737dab1df13ed511131b6a
[ "self.model = model\nself.NX = self.model.NX()\nself.NZ = self.model.NZ()\nself.NU = self.model.NU()\nself.NP = self.model.NP()\nself.NY = self.model.NY()\nself.xk = x0\nself.zk = z0 if z0 is not None else DM.zeros((self.NZ, 1))\nself.w_mean = process_noise_mean if process_noise_mean is not None else np.zeros(self....
<|body_start_0|> self.model = model self.NX = self.model.NX() self.NZ = self.model.NZ() self.NU = self.model.NU() self.NP = self.model.NP() self.NY = self.model.NY() self.xk = x0 self.zk = z0 if z0 is not None else DM.zeros((self.NZ, 1)) self.w_mea...
CarouselSimulator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CarouselSimulator: def __init__(self, model: CarouselModel, x0: DM, z0: DM=None, process_noise_mean: DM=None, process_noise_covar: DM=None, measurement_noise_mean: DM=None, measurement_noise_covar: DM=None, jit: bool=False, expand: bool=True) -> None: """Carousel_Simulator simulates the ...
stack_v2_sparse_classes_75kplus_train_006601
4,440
no_license
[ { "docstring": "Carousel_Simulator simulates the carousel whitebox model xdot = f(x,z,u,p) + w 0 = g(x,z,u,p) y = h(x,z,u,p) + v :param model: The model to simulate :param x0: The initial (differential) state :param z0: The initial (algebraic) state (optional) :param process_noise_mean: The process noise mean (...
2
stack_v2_sparse_classes_30k_train_031411
Implement the Python class `CarouselSimulator` described below. Class description: Implement the CarouselSimulator class. Method signatures and docstrings: - def __init__(self, model: CarouselModel, x0: DM, z0: DM=None, process_noise_mean: DM=None, process_noise_covar: DM=None, measurement_noise_mean: DM=None, measur...
Implement the Python class `CarouselSimulator` described below. Class description: Implement the CarouselSimulator class. Method signatures and docstrings: - def __init__(self, model: CarouselModel, x0: DM, z0: DM=None, process_noise_mean: DM=None, process_noise_covar: DM=None, measurement_noise_mean: DM=None, measur...
bb1a800612a1f046d2184ae42e00ed5ec0425b06
<|skeleton|> class CarouselSimulator: def __init__(self, model: CarouselModel, x0: DM, z0: DM=None, process_noise_mean: DM=None, process_noise_covar: DM=None, measurement_noise_mean: DM=None, measurement_noise_covar: DM=None, jit: bool=False, expand: bool=True) -> None: """Carousel_Simulator simulates the ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CarouselSimulator: def __init__(self, model: CarouselModel, x0: DM, z0: DM=None, process_noise_mean: DM=None, process_noise_covar: DM=None, measurement_noise_mean: DM=None, measurement_noise_covar: DM=None, jit: bool=False, expand: bool=True) -> None: """Carousel_Simulator simulates the carousel white...
the_stack_v2_python_sparse
src/thesis_code/simulator.py
Duam/python-master-thesis-code
train
1
404141f8499f629060a22da177643388ec37459b
[ "super(CustomSchedule, self).__init__()\nself.d_model = tf.cast(d_model, tf.float32)\nself.warmup_steps = warmup_steps", "arg1 = tf.math.rsqrt(step)\narg2 = step * self.warmup_steps ** (-1.5)\nreturn tf.math.rsqrt(self.d_model) * tf.math.minimum(arg1, arg2)" ]
<|body_start_0|> super(CustomSchedule, self).__init__() self.d_model = tf.cast(d_model, tf.float32) self.warmup_steps = warmup_steps <|end_body_0|> <|body_start_1|> arg1 = tf.math.rsqrt(step) arg2 = step * self.warmup_steps ** (-1.5) return tf.math.rsqrt(self.d_model) * ...
calculate learning rate for optimizers
CustomSchedule
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CustomSchedule: """calculate learning rate for optimizers""" def __init__(self, d_model, warmup_steps=4000): """constructor""" <|body_0|> def __call__(self, step): """initialize class""" <|body_1|> <|end_skeleton|> <|body_start_0|> super(CustomS...
stack_v2_sparse_classes_75kplus_train_006602
3,770
no_license
[ { "docstring": "constructor", "name": "__init__", "signature": "def __init__(self, d_model, warmup_steps=4000)" }, { "docstring": "initialize class", "name": "__call__", "signature": "def __call__(self, step)" } ]
2
stack_v2_sparse_classes_30k_train_026138
Implement the Python class `CustomSchedule` described below. Class description: calculate learning rate for optimizers Method signatures and docstrings: - def __init__(self, d_model, warmup_steps=4000): constructor - def __call__(self, step): initialize class
Implement the Python class `CustomSchedule` described below. Class description: calculate learning rate for optimizers Method signatures and docstrings: - def __init__(self, d_model, warmup_steps=4000): constructor - def __call__(self, step): initialize class <|skeleton|> class CustomSchedule: """calculate learn...
bda9efa60075afa834433ff1b5179db80f2487ae
<|skeleton|> class CustomSchedule: """calculate learning rate for optimizers""" def __init__(self, d_model, warmup_steps=4000): """constructor""" <|body_0|> def __call__(self, step): """initialize class""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CustomSchedule: """calculate learning rate for optimizers""" def __init__(self, d_model, warmup_steps=4000): """constructor""" super(CustomSchedule, self).__init__() self.d_model = tf.cast(d_model, tf.float32) self.warmup_steps = warmup_steps def __call__(self, step):...
the_stack_v2_python_sparse
supervised_learning/0x12-transformer_apps/5-train.py
vandeldiegoc/holbertonschool-machine_learning
train
0
240065eb9b2e89471cf43ddd03b90af970ba33b1
[ "super(DCGANDiscriminator, self).__init__(name=name)\nif filters_spec == 'small':\n filters = [64, 64, 96, 96]\nelif filters_spec == 'med':\n filters = [32, 64, 128, 128, 128]\nelif filters_spec == 'big':\n filters = None\nself._patchGAN = patchGAN\nif regularizer_weight:\n self._regularizers = {'w': tf...
<|body_start_0|> super(DCGANDiscriminator, self).__init__(name=name) if filters_spec == 'small': filters = [64, 64, 96, 96] elif filters_spec == 'med': filters = [32, 64, 128, 128, 128] elif filters_spec == 'big': filters = None self._patchGAN ...
A multilayer, fully-connected discriminator.
DCGANDiscriminator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DCGANDiscriminator: """A multilayer, fully-connected discriminator.""" def __init__(self, filters_spec='big', name='dcgan_discriminator', patchGAN=False, regularizer_weight=0): """Constructs a DCGANDiscriminator.""" <|body_0|> def _build(self, input, is_training=True): ...
stack_v2_sparse_classes_75kplus_train_006603
3,752
no_license
[ { "docstring": "Constructs a DCGANDiscriminator.", "name": "__init__", "signature": "def __init__(self, filters_spec='big', name='dcgan_discriminator', patchGAN=False, regularizer_weight=0)" }, { "docstring": "Adds the network into the graph.", "name": "_build", "signature": "def _build(...
2
stack_v2_sparse_classes_30k_train_016607
Implement the Python class `DCGANDiscriminator` described below. Class description: A multilayer, fully-connected discriminator. Method signatures and docstrings: - def __init__(self, filters_spec='big', name='dcgan_discriminator', patchGAN=False, regularizer_weight=0): Constructs a DCGANDiscriminator. - def _build(s...
Implement the Python class `DCGANDiscriminator` described below. Class description: A multilayer, fully-connected discriminator. Method signatures and docstrings: - def __init__(self, filters_spec='big', name='dcgan_discriminator', patchGAN=False, regularizer_weight=0): Constructs a DCGANDiscriminator. - def _build(s...
358a09d491aab0794df9cc7f3f8064430a78fbc3
<|skeleton|> class DCGANDiscriminator: """A multilayer, fully-connected discriminator.""" def __init__(self, filters_spec='big', name='dcgan_discriminator', patchGAN=False, regularizer_weight=0): """Constructs a DCGANDiscriminator.""" <|body_0|> def _build(self, input, is_training=True): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DCGANDiscriminator: """A multilayer, fully-connected discriminator.""" def __init__(self, filters_spec='big', name='dcgan_discriminator', patchGAN=False, regularizer_weight=0): """Constructs a DCGANDiscriminator.""" super(DCGANDiscriminator, self).__init__(name=name) if filters_sp...
the_stack_v2_python_sparse
architectures/discriminators.py
zwbgood6/temporal-hierarchy
train
0
d9920ada7a4bba8ec492cc044db20ea001290a10
[ "t = Timex()\nif node.hasAttribute('tid'):\n t.id = int(node.getAttribute('tid')[1:])\nif node.hasAttribute('value'):\n t.value = node.getAttribute('value')\nif node.hasAttribute('mod'):\n t.mod = node.getAttribute('mod')\nif node.hasAttribute('type'):\n t.type = node.getAttribute('type')\nif node.hasAt...
<|body_start_0|> t = Timex() if node.hasAttribute('tid'): t.id = int(node.getAttribute('tid')[1:]) if node.hasAttribute('value'): t.value = node.getAttribute('value') if node.hasAttribute('mod'): t.mod = node.getAttribute('mod') if node.hasAttr...
A class which takes any random XML document and adds TIMEX3 tags to it. Suitable for use with Timebank, which contains many superfluous tags that aren't in the TimeML spec, even though it claims to be TimeML.
Timex3XmlDocument
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Timex3XmlDocument: """A class which takes any random XML document and adds TIMEX3 tags to it. Suitable for use with Timebank, which contains many superfluous tags that aren't in the TimeML spec, even though it claims to be TimeML.""" def _timex_from_node(self, node): """Given a node ...
stack_v2_sparse_classes_75kplus_train_006604
3,167
permissive
[ { "docstring": "Given a node representing a TIMEX3 element, return a timex object representing it", "name": "_timex_from_node", "signature": "def _timex_from_node(self, node)" }, { "docstring": "Add attributes to this TIMEX3 node", "name": "_annotate_node_from_timex", "signature": "def _...
2
stack_v2_sparse_classes_30k_train_005606
Implement the Python class `Timex3XmlDocument` described below. Class description: A class which takes any random XML document and adds TIMEX3 tags to it. Suitable for use with Timebank, which contains many superfluous tags that aren't in the TimeML spec, even though it claims to be TimeML. Method signatures and docs...
Implement the Python class `Timex3XmlDocument` described below. Class description: A class which takes any random XML document and adds TIMEX3 tags to it. Suitable for use with Timebank, which contains many superfluous tags that aren't in the TimeML spec, even though it claims to be TimeML. Method signatures and docs...
e2e1fd101e230951e17431dff3af4cdb6c1270d1
<|skeleton|> class Timex3XmlDocument: """A class which takes any random XML document and adds TIMEX3 tags to it. Suitable for use with Timebank, which contains many superfluous tags that aren't in the TimeML spec, even though it claims to be TimeML.""" def _timex_from_node(self, node): """Given a node ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Timex3XmlDocument: """A class which takes any random XML document and adds TIMEX3 tags to it. Suitable for use with Timebank, which contains many superfluous tags that aren't in the TimeML spec, even though it claims to be TimeML.""" def _timex_from_node(self, node): """Given a node representing ...
the_stack_v2_python_sparse
ternip/formats/timex3.py
jo-fu/TimeLineCurator
train
63
4b5138967c1399153a6017b312fffa391e733bdc
[ "cube = set_up_variable_cube(np.ones((12, 12), dtype=np.float32), time=datetime(2017, 2, 17, 6, 0), frt=datetime(2017, 2, 17, 6, 0))\ncube.remove_coord('forecast_period')\nself.time_points = np.arange(1487311200, 1487354400, 3600).astype(np.int64)\nself.cube = add_coordinate(cube, self.time_points, 'time', dtype=np...
<|body_start_0|> cube = set_up_variable_cube(np.ones((12, 12), dtype=np.float32), time=datetime(2017, 2, 17, 6, 0), frt=datetime(2017, 2, 17, 6, 0)) cube.remove_coord('forecast_period') self.time_points = np.arange(1487311200, 1487354400, 3600).astype(np.int64) self.cube = add_coordinate...
Test construction of an iris.Constraint from a python datetime object.
Test_datetime_constraint
[ "BSD-3-Clause", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Test_datetime_constraint: """Test construction of an iris.Constraint from a python datetime object.""" def setUp(self): """Set up test cubes""" <|body_0|> def test_constraint_list_equality(self): """Check a list of constraints is as expected.""" <|body_1|...
stack_v2_sparse_classes_75kplus_train_006605
19,622
permissive
[ { "docstring": "Set up test cubes", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Check a list of constraints is as expected.", "name": "test_constraint_list_equality", "signature": "def test_constraint_list_equality(self)" }, { "docstring": "Check type is ir...
5
stack_v2_sparse_classes_30k_train_024538
Implement the Python class `Test_datetime_constraint` described below. Class description: Test construction of an iris.Constraint from a python datetime object. Method signatures and docstrings: - def setUp(self): Set up test cubes - def test_constraint_list_equality(self): Check a list of constraints is as expected....
Implement the Python class `Test_datetime_constraint` described below. Class description: Test construction of an iris.Constraint from a python datetime object. Method signatures and docstrings: - def setUp(self): Set up test cubes - def test_constraint_list_equality(self): Check a list of constraints is as expected....
cd2c9019944345df1e703bf8f625db537ad9f559
<|skeleton|> class Test_datetime_constraint: """Test construction of an iris.Constraint from a python datetime object.""" def setUp(self): """Set up test cubes""" <|body_0|> def test_constraint_list_equality(self): """Check a list of constraints is as expected.""" <|body_1|...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Test_datetime_constraint: """Test construction of an iris.Constraint from a python datetime object.""" def setUp(self): """Set up test cubes""" cube = set_up_variable_cube(np.ones((12, 12), dtype=np.float32), time=datetime(2017, 2, 17, 6, 0), frt=datetime(2017, 2, 17, 6, 0)) cube....
the_stack_v2_python_sparse
improver_tests/utilities/temporal/test_temporal.py
metoppv/improver
train
101
27646f08e8387d7860dd80b7e475c112cb4b4be7
[ "assert self.base_url is not None, '`base_url` is required!'\nassert self.item_loader_xpath is not None, '`item_loader_xpath` is required!'\nself.start_urls = tuple((self.base_url + word for word in kwargs.values()))\nname = self.__class__.__name__ if self.name is None else self.name\nsuper(BaseSpider, self).__init...
<|body_start_0|> assert self.base_url is not None, '`base_url` is required!' assert self.item_loader_xpath is not None, '`item_loader_xpath` is required!' self.start_urls = tuple((self.base_url + word for word in kwargs.values())) name = self.__class__.__name__ if self.name is None else ...
BaseSpider
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseSpider: def __init__(self, **kwargs): """:param kwargs:""" <|body_0|> def start_requests(self): """:return:""" <|body_1|> def parse(self, response, **kwargs): """response.xpath("//span[contains(@class, 'Head')]//text()").getall() :param respo...
stack_v2_sparse_classes_75kplus_train_006606
2,554
no_license
[ { "docstring": ":param kwargs:", "name": "__init__", "signature": "def __init__(self, **kwargs)" }, { "docstring": ":return:", "name": "start_requests", "signature": "def start_requests(self)" }, { "docstring": "response.xpath(\"//span[contains(@class, 'Head')]//text()\").getall(...
3
stack_v2_sparse_classes_30k_train_033742
Implement the Python class `BaseSpider` described below. Class description: Implement the BaseSpider class. Method signatures and docstrings: - def __init__(self, **kwargs): :param kwargs: - def start_requests(self): :return: - def parse(self, response, **kwargs): response.xpath("//span[contains(@class, 'Head')]//tex...
Implement the Python class `BaseSpider` described below. Class description: Implement the BaseSpider class. Method signatures and docstrings: - def __init__(self, **kwargs): :param kwargs: - def start_requests(self): :return: - def parse(self, response, **kwargs): response.xpath("//span[contains(@class, 'Head')]//tex...
90e839b3cd9dce90288dcd55a92c4ffa80a6c380
<|skeleton|> class BaseSpider: def __init__(self, **kwargs): """:param kwargs:""" <|body_0|> def start_requests(self): """:return:""" <|body_1|> def parse(self, response, **kwargs): """response.xpath("//span[contains(@class, 'Head')]//text()").getall() :param respo...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BaseSpider: def __init__(self, **kwargs): """:param kwargs:""" assert self.base_url is not None, '`base_url` is required!' assert self.item_loader_xpath is not None, '`item_loader_xpath` is required!' self.start_urls = tuple((self.base_url + word for word in kwargs.values())) ...
the_stack_v2_python_sparse
dictionary_crawlers/dictionary_crawlers/spiders/base.py
mohammadmasoumi/dictionary_crawlers
train
2
e0880581d64c978acf267852b35dd723a4c6b0f3
[ "super().__init__()\nself.session = requests.Session()\nlogin_page = self.session.get('https://ers.cr.usgs.gov/login/')\nhtml_root = html.fromstring(login_page.content)\ncsrf, = html_root.xpath('//*[@id=\"csrf_token\"]')\nncforminfo, = html_root.xpath('//*[@id=\"loginForm\"]/input[2]')\ncsrf_token = csrf.get('value...
<|body_start_0|> super().__init__() self.session = requests.Session() login_page = self.session.get('https://ers.cr.usgs.gov/login/') html_root = html.fromstring(login_page.content) csrf, = html_root.xpath('//*[@id="csrf_token"]') ncforminfo, = html_root.xpath('//*[@id="l...
USGSCrawler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class USGSCrawler: def __init__(self): """login is required to download files from USGS. we are simulating a login with session here""" <|body_0|> def crawl(self, target_date: date) -> Optional[str]: """this func will download a single file :param target_date: date :return...
stack_v2_sparse_classes_75kplus_train_006607
3,922
no_license
[ { "docstring": "login is required to download files from USGS. we are simulating a login with session here", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "this func will download a single file :param target_date: date :return: full-path of downloaded file. None if not ...
2
stack_v2_sparse_classes_30k_train_008174
Implement the Python class `USGSCrawler` described below. Class description: Implement the USGSCrawler class. Method signatures and docstrings: - def __init__(self): login is required to download files from USGS. we are simulating a login with session here - def crawl(self, target_date: date) -> Optional[str]: this f...
Implement the Python class `USGSCrawler` described below. Class description: Implement the USGSCrawler class. Method signatures and docstrings: - def __init__(self): login is required to download files from USGS. we are simulating a login with session here - def crawl(self, target_date: date) -> Optional[str]: this f...
9d0dc17e0e5a60fc0507475cd5ef0975beb8b397
<|skeleton|> class USGSCrawler: def __init__(self): """login is required to download files from USGS. we are simulating a login with session here""" <|body_0|> def crawl(self, target_date: date) -> Optional[str]: """this func will download a single file :param target_date: date :return...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class USGSCrawler: def __init__(self): """login is required to download files from USGS. we are simulating a login with session here""" super().__init__() self.session = requests.Session() login_page = self.session.get('https://ers.cr.usgs.gov/login/') html_root = html.fromst...
the_stack_v2_python_sparse
backend/data_preparation/crawler/usgs_crawler.py
totemprotocol/Wildfires
train
0
5e487f6d77b5629efb1084439719aca626b42be6
[ "self.profiling_parameters = {}\nself._use_default_metrics_configs = False\nself._use_one_config_for_all_metrics = False\nself._use_custom_metrics_configs = False\nself._process_trace_file_parameters(local_path, file_max_size, file_close_interval, file_open_fail_threshold)\nuse_custom_metrics_configs = self._proces...
<|body_start_0|> self.profiling_parameters = {} self._use_default_metrics_configs = False self._use_one_config_for_all_metrics = False self._use_custom_metrics_configs = False self._process_trace_file_parameters(local_path, file_max_size, file_close_interval, file_open_fail_thres...
Sets up the profiling configuration for framework metrics. Validates user inputs and fills in default values if no input is provided. There are three main profiling options to choose from: :class:`~sagemaker.debugger.metrics_config.DetailedProfilingConfig`, :class:`~sagemaker.debugger.metrics_config.DataloaderProfiling...
FrameworkProfile
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FrameworkProfile: """Sets up the profiling configuration for framework metrics. Validates user inputs and fills in default values if no input is provided. There are three main profiling options to choose from: :class:`~sagemaker.debugger.metrics_config.DetailedProfilingConfig`, :class:`~sagemaker...
stack_v2_sparse_classes_75kplus_train_006608
12,642
permissive
[ { "docstring": "Initialize the FrameworkProfile class object. Args: detailed_profiling_config (DetailedProfilingConfig): The configuration for detailed profiling. Configure it using the :class:`~sagemaker.debugger.metrics_config.DetailedProfilingConfig` class. Pass ``DetailedProfilingConfig()`` to use the defau...
5
stack_v2_sparse_classes_30k_train_042369
Implement the Python class `FrameworkProfile` described below. Class description: Sets up the profiling configuration for framework metrics. Validates user inputs and fills in default values if no input is provided. There are three main profiling options to choose from: :class:`~sagemaker.debugger.metrics_config.Detai...
Implement the Python class `FrameworkProfile` described below. Class description: Sets up the profiling configuration for framework metrics. Validates user inputs and fills in default values if no input is provided. There are three main profiling options to choose from: :class:`~sagemaker.debugger.metrics_config.Detai...
8d5d7fd8ae1a917ed3e2b988d5e533bce244fd85
<|skeleton|> class FrameworkProfile: """Sets up the profiling configuration for framework metrics. Validates user inputs and fills in default values if no input is provided. There are three main profiling options to choose from: :class:`~sagemaker.debugger.metrics_config.DetailedProfilingConfig`, :class:`~sagemaker...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FrameworkProfile: """Sets up the profiling configuration for framework metrics. Validates user inputs and fills in default values if no input is provided. There are three main profiling options to choose from: :class:`~sagemaker.debugger.metrics_config.DetailedProfilingConfig`, :class:`~sagemaker.debugger.met...
the_stack_v2_python_sparse
src/sagemaker/debugger/framework_profile.py
aws/sagemaker-python-sdk
train
2,050
4de8fd18d0508f60aa64475032d14150fa7abd4d
[ "all_actions = [[0, 0], [1, 0], [2, 0], [0, 1], [0, 2], [1, 1]]\npossible_actions = []\nif state[2]:\n x = -1\nelse:\n x = 1\nfor i in all_actions:\n circles_left = state[0][0] - i[0] * x\n polys_left = state[0][1] - i[1] * x\n circles_right = state[1][0] + i[0] * x\n polys_right = state[1][1] + i...
<|body_start_0|> all_actions = [[0, 0], [1, 0], [2, 0], [0, 1], [0, 2], [1, 1]] possible_actions = [] if state[2]: x = -1 else: x = 1 for i in all_actions: circles_left = state[0][0] - i[0] * x polys_left = state[0][1] - i[1] * x ...
A class for the Flatland problem using the Problem class from search.py.
Flatland_Problem
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Flatland_Problem: """A class for the Flatland problem using the Problem class from search.py.""" def actions(self, state): """Return the actions that can be executed in the given state. The result would typically be a list, but if there are many actions, consider yielding them one at...
stack_v2_sparse_classes_75kplus_train_006609
9,376
no_license
[ { "docstring": "Return the actions that can be executed in the given state. The result would typically be a list, but if there are many actions, consider yielding them one at a time in an iterator, rather than building them all at once. Parameters ---------- state : list The current state of Flatland. Returns -...
3
stack_v2_sparse_classes_30k_train_005617
Implement the Python class `Flatland_Problem` described below. Class description: A class for the Flatland problem using the Problem class from search.py. Method signatures and docstrings: - def actions(self, state): Return the actions that can be executed in the given state. The result would typically be a list, but...
Implement the Python class `Flatland_Problem` described below. Class description: A class for the Flatland problem using the Problem class from search.py. Method signatures and docstrings: - def actions(self, state): Return the actions that can be executed in the given state. The result would typically be a list, but...
c23fa01a9145d3896c2f2782f7340808761f4c88
<|skeleton|> class Flatland_Problem: """A class for the Flatland problem using the Problem class from search.py.""" def actions(self, state): """Return the actions that can be executed in the given state. The result would typically be a list, but if there are many actions, consider yielding them one at...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Flatland_Problem: """A class for the Flatland problem using the Problem class from search.py.""" def actions(self, state): """Return the actions that can be executed in the given state. The result would typically be a list, but if there are many actions, consider yielding them one at a time in an...
the_stack_v2_python_sparse
homework_5/revolutionizing_flatland.py
kojirowilliam/advanced_topics
train
0
426e72b2400e3dd5ecbb847d33ba1b02dca5c0aa
[ "super(sub_graph_parallel, self).__init__()\nself.adj_sub = adj_sub\nself.in_features = in_features\nself.out_features = out_features\nself.DEVICE = device\nself.linear = nn.Linear(adj_sub.shape[1] * self.out_features, self.out_features)\nself.linear_in_edge_sub = nn.Linear(1, in_features)\nself.weight = nn.Paramet...
<|body_start_0|> super(sub_graph_parallel, self).__init__() self.adj_sub = adj_sub self.in_features = in_features self.out_features = out_features self.DEVICE = device self.linear = nn.Linear(adj_sub.shape[1] * self.out_features, self.out_features) self.linear_in_...
并行化计算子图 GCN of the sub_graph
sub_graph_parallel
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class sub_graph_parallel: """并行化计算子图 GCN of the sub_graph""" def __init__(self, adj_sub, in_features, out_features, device): """:param in_features:num of channels in the input sequence :param out_features:num of channels in the output sequence :param device:""" <|body_0|> def ...
stack_v2_sparse_classes_75kplus_train_006610
2,223
no_license
[ { "docstring": ":param in_features:num of channels in the input sequence :param out_features:num of channels in the output sequence :param device:", "name": "__init__", "signature": "def __init__(self, adj_sub, in_features, out_features, device)" }, { "docstring": "The subgraphs of different nod...
2
null
Implement the Python class `sub_graph_parallel` described below. Class description: 并行化计算子图 GCN of the sub_graph Method signatures and docstrings: - def __init__(self, adj_sub, in_features, out_features, device): :param in_features:num of channels in the input sequence :param out_features:num of channels in the outpu...
Implement the Python class `sub_graph_parallel` described below. Class description: 并行化计算子图 GCN of the sub_graph Method signatures and docstrings: - def __init__(self, adj_sub, in_features, out_features, device): :param in_features:num of channels in the input sequence :param out_features:num of channels in the outpu...
5175789012d1fe74f866edd05789a9e73c19e782
<|skeleton|> class sub_graph_parallel: """并行化计算子图 GCN of the sub_graph""" def __init__(self, adj_sub, in_features, out_features, device): """:param in_features:num of channels in the input sequence :param out_features:num of channels in the output sequence :param device:""" <|body_0|> def ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class sub_graph_parallel: """并行化计算子图 GCN of the sub_graph""" def __init__(self, adj_sub, in_features, out_features, device): """:param in_features:num of channels in the input sequence :param out_features:num of channels in the output sequence :param device:""" super(sub_graph_parallel, self)._...
the_stack_v2_python_sparse
model/Subgraph.py
I-am-YuLang/MADGCN
train
0
5eed5363b98b3707e1981688a8eeda7e232fed7b
[ "self.text = text\nself.tokens = str.split(text)\nassert len(self.tokens) == len(token_weights), 'Token count does not match.'\nself.token_weights = token_weights\ntop_k_value = math.ceil(len(self.tokens) * top_k_ratio)\nself.top_k_ids = np.argsort(token_weights)[-top_k_value:]\nself.top_k_ids = list(reversed(self....
<|body_start_0|> self.text = text self.tokens = str.split(text) assert len(self.tokens) == len(token_weights), 'Token count does not match.' self.token_weights = token_weights top_k_value = math.ceil(len(self.tokens) * top_k_ratio) self.top_k_ids = np.argsort(token_weight...
A text with a rationale explanation.
TextRationale
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TextRationale: """A text with a rationale explanation.""" def __init__(self, text: str, token_weights: list[float], top_k_ratio: float=TOP_K_AVG_RATIO): """Initializes with a text and a list of token weights. Args: text: A full-text input to a classifier with tokens separated with ' ...
stack_v2_sparse_classes_75kplus_train_006611
4,299
permissive
[ { "docstring": "Initializes with a text and a list of token weights. Args: text: A full-text input to a classifier with tokens separated with ' '. token_weights: A list of token weights (in the token position order). top_k_ratio: Rationale size in tokens is defined proportional to the input length (in tokens). ...
3
stack_v2_sparse_classes_30k_train_037429
Implement the Python class `TextRationale` described below. Class description: A text with a rationale explanation. Method signatures and docstrings: - def __init__(self, text: str, token_weights: list[float], top_k_ratio: float=TOP_K_AVG_RATIO): Initializes with a text and a list of token weights. Args: text: A full...
Implement the Python class `TextRationale` described below. Class description: A text with a rationale explanation. Method signatures and docstrings: - def __init__(self, text: str, token_weights: list[float], top_k_ratio: float=TOP_K_AVG_RATIO): Initializes with a text and a list of token weights. Args: text: A full...
a41130960d6ccb92acf6ffc603377eaecce8a62b
<|skeleton|> class TextRationale: """A text with a rationale explanation.""" def __init__(self, text: str, token_weights: list[float], top_k_ratio: float=TOP_K_AVG_RATIO): """Initializes with a text and a list of token weights. Args: text: A full-text input to a classifier with tokens separated with ' ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TextRationale: """A text with a rationale explanation.""" def __init__(self, text: str, token_weights: list[float], top_k_ratio: float=TOP_K_AVG_RATIO): """Initializes with a text and a list of token weights. Args: text: A full-text input to a classifier with tokens separated with ' '. token_weig...
the_stack_v2_python_sparse
lit_nlp/components/citrus/helpers.py
PAIR-code/lit
train
3,201
b601b0fd8c0a11b9cf0413e7f0c39a1a0f62453a
[ "print('\\nrunning test method:{}'.format(inspect.stack()[0][3]))\nreal_result = MathOperation(10, 2).division()\nexcept_result = 5\nmsg = '两个正数相除失败'\ntry:\n self.assertEqual(except_result, real_result, msg=msg)\nexcept AssertionError as e:\n print('具体异常为:{}'.format(e))\n file.write('{},执行结果为:{}\\n具体异常为:{}...
<|body_start_0|> print('\nrunning test method:{}'.format(inspect.stack()[0][3])) real_result = MathOperation(10, 2).division() except_result = 5 msg = '两个正数相除失败' try: self.assertEqual(except_result, real_result, msg=msg) except AssertionError as e: ...
测试两数相乘
TestDivide
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestDivide: """测试两数相乘""" def test_two_pos_divide(self): """1.两个正数相除 :return:""" <|body_0|> def test_two_neg_divide(self): """2.两个负数相除 :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> print('\nrunning test method:{}'.format(inspect.stack(...
stack_v2_sparse_classes_75kplus_train_006612
7,546
no_license
[ { "docstring": "1.两个正数相除 :return:", "name": "test_two_pos_divide", "signature": "def test_two_pos_divide(self)" }, { "docstring": "2.两个负数相除 :return:", "name": "test_two_neg_divide", "signature": "def test_two_neg_divide(self)" } ]
2
stack_v2_sparse_classes_30k_train_004371
Implement the Python class `TestDivide` described below. Class description: 测试两数相乘 Method signatures and docstrings: - def test_two_pos_divide(self): 1.两个正数相除 :return: - def test_two_neg_divide(self): 2.两个负数相除 :return:
Implement the Python class `TestDivide` described below. Class description: 测试两数相乘 Method signatures and docstrings: - def test_two_pos_divide(self): 1.两个正数相除 :return: - def test_two_neg_divide(self): 2.两个负数相除 :return: <|skeleton|> class TestDivide: """测试两数相乘""" def test_two_pos_divide(self): """1.两...
09d6bf79f46002b590289fdb94cbf1febe891184
<|skeleton|> class TestDivide: """测试两数相乘""" def test_two_pos_divide(self): """1.两个正数相除 :return:""" <|body_0|> def test_two_neg_divide(self): """2.两个负数相除 :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestDivide: """测试两数相乘""" def test_two_pos_divide(self): """1.两个正数相除 :return:""" print('\nrunning test method:{}'.format(inspect.stack()[0][3])) real_result = MathOperation(10, 2).division() except_result = 5 msg = '两个正数相除失败' try: self.assertEqua...
the_stack_v2_python_sparse
pythonbase_class_1/Class_11_Unittest_start_end_handle.py
2353501820/erp
train
0
5e979f0b17c07e64bdf52808dcdc16fe2b2671b6
[ "data_type_dict = {'base_station_set': BaseStation, 'mec_set': Mec, 'hmds_set': VrHMD}\nprint(f'\\n*** decoding {str(data_type_dict[data_type])} objects ***')\nfor key, value in data_set[data_type].items():\n data_type_object = data_type_dict[data_type].from_dict(value)\n data_set[data_type][key] = data_type_...
<|body_start_0|> data_type_dict = {'base_station_set': BaseStation, 'mec_set': Mec, 'hmds_set': VrHMD} print(f'\n*** decoding {str(data_type_dict[data_type])} objects ***') for key, value in data_set[data_type].items(): data_type_object = data_type_dict[data_type].from_dict(value) ...
provides methods to decoding json data
DecoderController
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DecoderController: """provides methods to decoding json data""" def decoder_to_dict_objects(data_set: dict, data_type: str) -> None: """decodes a dict of json objects into BaseStations, Mecs, or VrHMD objects""" <|body_0|> def decoding_to_dict(data_directory: str, file_n...
stack_v2_sparse_classes_75kplus_train_006613
4,620
no_license
[ { "docstring": "decodes a dict of json objects into BaseStations, Mecs, or VrHMD objects", "name": "decoder_to_dict_objects", "signature": "def decoder_to_dict_objects(data_set: dict, data_type: str) -> None" }, { "docstring": "decodes a file of json objects into dict of BaseStations, Mecs, or V...
5
stack_v2_sparse_classes_30k_train_020256
Implement the Python class `DecoderController` described below. Class description: provides methods to decoding json data Method signatures and docstrings: - def decoder_to_dict_objects(data_set: dict, data_type: str) -> None: decodes a dict of json objects into BaseStations, Mecs, or VrHMD objects - def decoding_to_...
Implement the Python class `DecoderController` described below. Class description: provides methods to decoding json data Method signatures and docstrings: - def decoder_to_dict_objects(data_set: dict, data_type: str) -> None: decodes a dict of json objects into BaseStations, Mecs, or VrHMD objects - def decoding_to_...
e3e022a14058936619f1d79d11dbbb4f6f48d531
<|skeleton|> class DecoderController: """provides methods to decoding json data""" def decoder_to_dict_objects(data_set: dict, data_type: str) -> None: """decodes a dict of json objects into BaseStations, Mecs, or VrHMD objects""" <|body_0|> def decoding_to_dict(data_directory: str, file_n...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DecoderController: """provides methods to decoding json data""" def decoder_to_dict_objects(data_set: dict, data_type: str) -> None: """decodes a dict of json objects into BaseStations, Mecs, or VrHMD objects""" data_type_dict = {'base_station_set': BaseStation, 'mec_set': Mec, 'hmds_set'...
the_stack_v2_python_sparse
controllers/json_controller.py
alissonpmedeiros/scg
train
0
763ddcd301c33c42b80db42bcb708b64ba4bafa2
[ "super().__init__()\nself.poly_order = poly_order\nself.diff_order = diff_order", "prediction, data = input\npoly_list = []\nderiv_list = []\ntime_deriv_list = []\nfor output in np.arange(prediction.shape[1]):\n time_deriv, du = library_deriv(data, prediction[:, output:output + 1], self.diff_order)\n u = li...
<|body_start_0|> super().__init__() self.poly_order = poly_order self.diff_order = diff_order <|end_body_0|> <|body_start_1|> prediction, data = input poly_list = [] deriv_list = [] time_deriv_list = [] for output in np.arange(prediction.shape[1]): ...
Library1D
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Library1D: def __init__(self, poly_order: int, diff_order: int) -> None: """Calculates the temporal derivative a library/feature matrix consisting of 1) polynomials up to order poly_order, i.e. u, u^2... 2) derivatives up to order diff_order, i.e. u_x, u_xx 3) cross terms of 1) and 2), i...
stack_v2_sparse_classes_75kplus_train_006614
7,619
permissive
[ { "docstring": "Calculates the temporal derivative a library/feature matrix consisting of 1) polynomials up to order poly_order, i.e. u, u^2... 2) derivatives up to order diff_order, i.e. u_x, u_xx 3) cross terms of 1) and 2), i.e. $uu_x$, $u^2u_xx$ Order of terms is derivative first, i.e. [$1, u_x, u, uu_x, u^...
2
stack_v2_sparse_classes_30k_train_009631
Implement the Python class `Library1D` described below. Class description: Implement the Library1D class. Method signatures and docstrings: - def __init__(self, poly_order: int, diff_order: int) -> None: Calculates the temporal derivative a library/feature matrix consisting of 1) polynomials up to order poly_order, i...
Implement the Python class `Library1D` described below. Class description: Implement the Library1D class. Method signatures and docstrings: - def __init__(self, poly_order: int, diff_order: int) -> None: Calculates the temporal derivative a library/feature matrix consisting of 1) polynomials up to order poly_order, i...
47c33667b6d89b5ca65d9e950773d8ac4a3ca0b9
<|skeleton|> class Library1D: def __init__(self, poly_order: int, diff_order: int) -> None: """Calculates the temporal derivative a library/feature matrix consisting of 1) polynomials up to order poly_order, i.e. u, u^2... 2) derivatives up to order diff_order, i.e. u_x, u_xx 3) cross terms of 1) and 2), i...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Library1D: def __init__(self, poly_order: int, diff_order: int) -> None: """Calculates the temporal derivative a library/feature matrix consisting of 1) polynomials up to order poly_order, i.e. u, u^2... 2) derivatives up to order diff_order, i.e. u_x, u_xx 3) cross terms of 1) and 2), i.e. $uu_x$, $u...
the_stack_v2_python_sparse
src/deepymod/model/library.py
PhIMaL/DeePyMoD
train
36
d5dce3505201f7e23b768316eb3c515f8107dace
[ "def _generateTrees(start: int, end: int) -> List[Union[TreeNode, None]]:\n ans = []\n if start > end:\n ans.append(None)\n return ans\n for i in range(start, end + 1):\n left = _generateTrees(start, i - 1)\n right = _generateTrees(i + 1, end)\n for ln in left:\n ...
<|body_start_0|> def _generateTrees(start: int, end: int) -> List[Union[TreeNode, None]]: ans = [] if start > end: ans.append(None) return ans for i in range(start, end + 1): left = _generateTrees(start, i - 1) r...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def generateTrees1(self, n: int) -> List[TreeNode]: """递归法 :param n: :return:""" <|body_0|> def generateTrees2(self, n: int) -> List[TreeNode]: """递归改dp :param n: :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> def _generateTrees(...
stack_v2_sparse_classes_75kplus_train_006615
2,149
no_license
[ { "docstring": "递归法 :param n: :return:", "name": "generateTrees1", "signature": "def generateTrees1(self, n: int) -> List[TreeNode]" }, { "docstring": "递归改dp :param n: :return:", "name": "generateTrees2", "signature": "def generateTrees2(self, n: int) -> List[TreeNode]" } ]
2
stack_v2_sparse_classes_30k_train_000261
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def generateTrees1(self, n: int) -> List[TreeNode]: 递归法 :param n: :return: - def generateTrees2(self, n: int) -> List[TreeNode]: 递归改dp :param n: :return:
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def generateTrees1(self, n: int) -> List[TreeNode]: 递归法 :param n: :return: - def generateTrees2(self, n: int) -> List[TreeNode]: 递归改dp :param n: :return: <|skeleton|> class Solu...
25f2795b6e7f9f68833f2fddc6cc4f4d977121a6
<|skeleton|> class Solution: def generateTrees1(self, n: int) -> List[TreeNode]: """递归法 :param n: :return:""" <|body_0|> def generateTrees2(self, n: int) -> List[TreeNode]: """递归改dp :param n: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def generateTrees1(self, n: int) -> List[TreeNode]: """递归法 :param n: :return:""" def _generateTrees(start: int, end: int) -> List[Union[TreeNode, None]]: ans = [] if start > end: ans.append(None) return ans for i in ...
the_stack_v2_python_sparse
95.py
Darkxiete/leetcode_python
train
0
d44bebf2262a95c1571c2393768b4c22004f2fc0
[ "result = empty_result()\nresult['data'] = {'linknets': []}\nwith sqla_session() as session:\n instance = session.query(Linknet).filter(Linknet.id == linknet_id).one_or_none()\n if instance:\n result['data']['linknets'].append(instance.as_dict())\n else:\n return (empty_result('error', 'Linkn...
<|body_start_0|> result = empty_result() result['data'] = {'linknets': []} with sqla_session() as session: instance = session.query(Linknet).filter(Linknet.id == linknet_id).one_or_none() if instance: result['data']['linknets'].append(instance.as_dict()) ...
LinknetByIdApi
[ "BSD-2-Clause-Views", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LinknetByIdApi: def get(self, linknet_id): """Get a single specified linknet""" <|body_0|> def delete(self, linknet_id): """Remove a linknet""" <|body_1|> def put(self, linknet_id): """Update data on existing linknet""" <|body_2|> <|end_...
stack_v2_sparse_classes_75kplus_train_006616
11,188
permissive
[ { "docstring": "Get a single specified linknet", "name": "get", "signature": "def get(self, linknet_id)" }, { "docstring": "Remove a linknet", "name": "delete", "signature": "def delete(self, linknet_id)" }, { "docstring": "Update data on existing linknet", "name": "put", ...
3
stack_v2_sparse_classes_30k_train_047776
Implement the Python class `LinknetByIdApi` described below. Class description: Implement the LinknetByIdApi class. Method signatures and docstrings: - def get(self, linknet_id): Get a single specified linknet - def delete(self, linknet_id): Remove a linknet - def put(self, linknet_id): Update data on existing linkne...
Implement the Python class `LinknetByIdApi` described below. Class description: Implement the LinknetByIdApi class. Method signatures and docstrings: - def get(self, linknet_id): Get a single specified linknet - def delete(self, linknet_id): Remove a linknet - def put(self, linknet_id): Update data on existing linkne...
d755dfed69bebe0c7bea66ad1802cba2cd89fec8
<|skeleton|> class LinknetByIdApi: def get(self, linknet_id): """Get a single specified linknet""" <|body_0|> def delete(self, linknet_id): """Remove a linknet""" <|body_1|> def put(self, linknet_id): """Update data on existing linknet""" <|body_2|> <|end_...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LinknetByIdApi: def get(self, linknet_id): """Get a single specified linknet""" result = empty_result() result['data'] = {'linknets': []} with sqla_session() as session: instance = session.query(Linknet).filter(Linknet.id == linknet_id).one_or_none() if ...
the_stack_v2_python_sparse
src/cnaas_nms/api/linknet.py
SUNET/cnaas-nms
train
67
4c9a9affa7add5d8a4ce7f303ed690a03d3fe072
[ "zeroPad = 0\nres = 0\nnum1 = num1[::-1]\nnum2 = num2[::-1]\nfor i in num1:\n res += self.multiplyHelp(num2, i, zeroPad)\n zeroPad += 1\nreturn '{}'.format(res)", "res = ['0'] * pos\nmultiplier = int(actor)\nnext_q = 0\nfor i in target:\n x = int(i)\n product = multiplier * x + next_q\n next_q = 0\...
<|body_start_0|> zeroPad = 0 res = 0 num1 = num1[::-1] num2 = num2[::-1] for i in num1: res += self.multiplyHelp(num2, i, zeroPad) zeroPad += 1 return '{}'.format(res) <|end_body_0|> <|body_start_1|> res = ['0'] * pos multiplier = ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def multiply(self, num1: str, num2: str) -> str: """:param num1: the first number as a string :param num2: the second number as a string :return: the product as a string working theory: zeroPad: the power of 10 to muliply by at every stage res = result as an integer; it is bett...
stack_v2_sparse_classes_75kplus_train_006617
2,336
no_license
[ { "docstring": ":param num1: the first number as a string :param num2: the second number as a string :return: the product as a string working theory: zeroPad: the power of 10 to muliply by at every stage res = result as an integer; it is better because string conversion will only happen once and direct addition...
2
stack_v2_sparse_classes_30k_train_053458
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def multiply(self, num1: str, num2: str) -> str: :param num1: the first number as a string :param num2: the second number as a string :return: the product as a string working the...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def multiply(self, num1: str, num2: str) -> str: :param num1: the first number as a string :param num2: the second number as a string :return: the product as a string working the...
9d8dfd05f6367ea2b5e2b1c490f09a18fa5e8a14
<|skeleton|> class Solution: def multiply(self, num1: str, num2: str) -> str: """:param num1: the first number as a string :param num2: the second number as a string :return: the product as a string working theory: zeroPad: the power of 10 to muliply by at every stage res = result as an integer; it is bett...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def multiply(self, num1: str, num2: str) -> str: """:param num1: the first number as a string :param num2: the second number as a string :return: the product as a string working theory: zeroPad: the power of 10 to muliply by at every stage res = result as an integer; it is better because str...
the_stack_v2_python_sparse
multiply strings.py
rehoboth23/leetcode-base
train
1
407a5cc2239767789366aac65dc362cc9f6001bf
[ "self.current_usage_gib = current_usage_gib\nself.feature_name = feature_name\nself.num_vm = num_vm", "if dictionary is None:\n return None\ncurrent_usage_gib = dictionary.get('currentUsageGiB')\nfeature_name = dictionary.get('featureName')\nnum_vm = dictionary.get('numVm')\nreturn cls(current_usage_gib, featu...
<|body_start_0|> self.current_usage_gib = current_usage_gib self.feature_name = feature_name self.num_vm = num_vm <|end_body_0|> <|body_start_1|> if dictionary is None: return None current_usage_gib = dictionary.get('currentUsageGiB') feature_name = dictionar...
Implementation of the 'FeatureUsage' model. TODO: type description here. Attributes: current_usage_gib (long|int): Feature usage by the cluster. feature_name (string): Name of feature. num_vm (long|int): Number of VM spinned.
FeatureUsage
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FeatureUsage: """Implementation of the 'FeatureUsage' model. TODO: type description here. Attributes: current_usage_gib (long|int): Feature usage by the cluster. feature_name (string): Name of feature. num_vm (long|int): Number of VM spinned.""" def __init__(self, current_usage_gib=None, fea...
stack_v2_sparse_classes_75kplus_train_006618
1,804
permissive
[ { "docstring": "Constructor for the FeatureUsage class", "name": "__init__", "signature": "def __init__(self, current_usage_gib=None, feature_name=None, num_vm=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation...
2
stack_v2_sparse_classes_30k_train_050169
Implement the Python class `FeatureUsage` described below. Class description: Implementation of the 'FeatureUsage' model. TODO: type description here. Attributes: current_usage_gib (long|int): Feature usage by the cluster. feature_name (string): Name of feature. num_vm (long|int): Number of VM spinned. Method signatu...
Implement the Python class `FeatureUsage` described below. Class description: Implementation of the 'FeatureUsage' model. TODO: type description here. Attributes: current_usage_gib (long|int): Feature usage by the cluster. feature_name (string): Name of feature. num_vm (long|int): Number of VM spinned. Method signatu...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class FeatureUsage: """Implementation of the 'FeatureUsage' model. TODO: type description here. Attributes: current_usage_gib (long|int): Feature usage by the cluster. feature_name (string): Name of feature. num_vm (long|int): Number of VM spinned.""" def __init__(self, current_usage_gib=None, fea...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FeatureUsage: """Implementation of the 'FeatureUsage' model. TODO: type description here. Attributes: current_usage_gib (long|int): Feature usage by the cluster. feature_name (string): Name of feature. num_vm (long|int): Number of VM spinned.""" def __init__(self, current_usage_gib=None, feature_name=Non...
the_stack_v2_python_sparse
cohesity_management_sdk/models/feature_usage.py
cohesity/management-sdk-python
train
24
3c1ae498137ca0bb073c5755c2674f823f34626c
[ "super().__init__(*args, category=CATEGORY_SENSOR)\nstate = self.hass.states.get(self.entity_id)\nself.create_services()\nself.async_update_state(state)", "serv_air_quality = self.add_preload_service(SERV_AIR_QUALITY_SENSOR, [CHAR_AIR_PARTICULATE_DENSITY])\nself.char_quality = serv_air_quality.configure_char(CHAR...
<|body_start_0|> super().__init__(*args, category=CATEGORY_SENSOR) state = self.hass.states.get(self.entity_id) self.create_services() self.async_update_state(state) <|end_body_0|> <|body_start_1|> serv_air_quality = self.add_preload_service(SERV_AIR_QUALITY_SENSOR, [CHAR_AIR_PA...
Generate a AirQualitySensor accessory as air quality sensor.
AirQualitySensor
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AirQualitySensor: """Generate a AirQualitySensor accessory as air quality sensor.""" def __init__(self, *args): """Initialize a AirQualitySensor accessory object.""" <|body_0|> def create_services(self): """Initialize a AirQualitySensor accessory object.""" ...
stack_v2_sparse_classes_75kplus_train_006619
17,041
permissive
[ { "docstring": "Initialize a AirQualitySensor accessory object.", "name": "__init__", "signature": "def __init__(self, *args)" }, { "docstring": "Initialize a AirQualitySensor accessory object.", "name": "create_services", "signature": "def create_services(self)" }, { "docstring"...
3
stack_v2_sparse_classes_30k_train_053851
Implement the Python class `AirQualitySensor` described below. Class description: Generate a AirQualitySensor accessory as air quality sensor. Method signatures and docstrings: - def __init__(self, *args): Initialize a AirQualitySensor accessory object. - def create_services(self): Initialize a AirQualitySensor acces...
Implement the Python class `AirQualitySensor` described below. Class description: Generate a AirQualitySensor accessory as air quality sensor. Method signatures and docstrings: - def __init__(self, *args): Initialize a AirQualitySensor accessory object. - def create_services(self): Initialize a AirQualitySensor acces...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class AirQualitySensor: """Generate a AirQualitySensor accessory as air quality sensor.""" def __init__(self, *args): """Initialize a AirQualitySensor accessory object.""" <|body_0|> def create_services(self): """Initialize a AirQualitySensor accessory object.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AirQualitySensor: """Generate a AirQualitySensor accessory as air quality sensor.""" def __init__(self, *args): """Initialize a AirQualitySensor accessory object.""" super().__init__(*args, category=CATEGORY_SENSOR) state = self.hass.states.get(self.entity_id) self.create_...
the_stack_v2_python_sparse
homeassistant/components/homekit/type_sensors.py
home-assistant/core
train
35,501
5e6a836d786744b5f8ddac0ee8af62a32cdf8af3
[ "student_list = self.get_queryset()\nserializer = self.get_serializer(instance=student_list, many=True)\nreturn Response(serializer.data)", "serializer = self.get_serializer(data=request.data)\nserializer.is_valid(raise_exception=True)\ninstance = serializer.save()\nreturn Response(serializer.data)" ]
<|body_start_0|> student_list = self.get_queryset() serializer = self.get_serializer(instance=student_list, many=True) return Response(serializer.data) <|end_body_0|> <|body_start_1|> serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) ...
Student4GenericAPIView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Student4GenericAPIView: def get(self, request): """获取所有数据""" <|body_0|> def post(self, request): """添加数据""" <|body_1|> <|end_skeleton|> <|body_start_0|> student_list = self.get_queryset() serializer = self.get_serializer(instance=student_lis...
stack_v2_sparse_classes_75kplus_train_006620
8,431
no_license
[ { "docstring": "获取所有数据", "name": "get", "signature": "def get(self, request)" }, { "docstring": "添加数据", "name": "post", "signature": "def post(self, request)" } ]
2
null
Implement the Python class `Student4GenericAPIView` described below. Class description: Implement the Student4GenericAPIView class. Method signatures and docstrings: - def get(self, request): 获取所有数据 - def post(self, request): 添加数据
Implement the Python class `Student4GenericAPIView` described below. Class description: Implement the Student4GenericAPIView class. Method signatures and docstrings: - def get(self, request): 获取所有数据 - def post(self, request): 添加数据 <|skeleton|> class Student4GenericAPIView: def get(self, request): """获取所...
8de49ae37ea869975cc394abff5e68c3d067debb
<|skeleton|> class Student4GenericAPIView: def get(self, request): """获取所有数据""" <|body_0|> def post(self, request): """添加数据""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Student4GenericAPIView: def get(self, request): """获取所有数据""" student_list = self.get_queryset() serializer = self.get_serializer(instance=student_list, many=True) return Response(serializer.data) def post(self, request): """添加数据""" serializer = self.get_ser...
the_stack_v2_python_sparse
drf/req/views.py
0429ren/Django_restframework
train
0
0cf76373175d21c7baf916bcc696a347544e9a99
[ "wx.Panel.__init__(self, parent=parent)\nself.frame = parent\nsizer = wx.BoxSizer(wx.VERTICAL)\nhSizer = wx.BoxSizer(wx.HORIZONTAL)\nfor num in range(4):\n label = 'Button %s' % num\n btn = wx.Button(self, label=label)\n sizer.Add(btn, 0, wx.ALL, 5)\nhSizer.Add((1, 1), 1, wx.EXPAND)\nhSizer.Add(sizer, 0, w...
<|body_start_0|> wx.Panel.__init__(self, parent=parent) self.frame = parent sizer = wx.BoxSizer(wx.VERTICAL) hSizer = wx.BoxSizer(wx.HORIZONTAL) for num in range(4): label = 'Button %s' % num btn = wx.Button(self, label=label) sizer.Add(btn, 0,...
MainPanel
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MainPanel: def __init__(self, parent): """Constructor""" <|body_0|> def OnEraseBackground(self, evt): """Add a picture to the background""" <|body_1|> <|end_skeleton|> <|body_start_0|> wx.Panel.__init__(self, parent=parent) self.frame = pare...
stack_v2_sparse_classes_75kplus_train_006621
1,515
no_license
[ { "docstring": "Constructor", "name": "__init__", "signature": "def __init__(self, parent)" }, { "docstring": "Add a picture to the background", "name": "OnEraseBackground", "signature": "def OnEraseBackground(self, evt)" } ]
2
null
Implement the Python class `MainPanel` described below. Class description: Implement the MainPanel class. Method signatures and docstrings: - def __init__(self, parent): Constructor - def OnEraseBackground(self, evt): Add a picture to the background
Implement the Python class `MainPanel` described below. Class description: Implement the MainPanel class. Method signatures and docstrings: - def __init__(self, parent): Constructor - def OnEraseBackground(self, evt): Add a picture to the background <|skeleton|> class MainPanel: def __init__(self, parent): ...
ebe43e870b1057c6252671d8739e8ce7bad424fe
<|skeleton|> class MainPanel: def __init__(self, parent): """Constructor""" <|body_0|> def OnEraseBackground(self, evt): """Add a picture to the background""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MainPanel: def __init__(self, parent): """Constructor""" wx.Panel.__init__(self, parent=parent) self.frame = parent sizer = wx.BoxSizer(wx.VERTICAL) hSizer = wx.BoxSizer(wx.HORIZONTAL) for num in range(4): label = 'Button %s' % num btn = ...
the_stack_v2_python_sparse
wxPython_recipes_book_code-master/chapter_2_working_with_images/recipe_2_3_put_background_image_on_panel/main.py
canderson71/python
train
0
29e80ecbd55e38b9e35b16fbef9a747a4d35a73d
[ "try:\n cls.abrir_conexion()\n sql = 'SELECT mat_ins.cantidad,mat_ins.idMaterial FROM mat_ins WHERE idInsumo = {};'.format(id)\n cls.cursor.execute(sql)\n cantmats_ = cls.cursor.fetchall()\n cantmats = []\n for m in cantmats_:\n cantmat = CantMaterial...
<|body_start_0|> try: cls.abrir_conexion() sql = 'SELECT mat_ins.cantidad,mat_ins.idMaterial FROM mat_ins WHERE idInsumo = {};'.format(id) cls.cursor.execute(sql) cantmats_ = cls.cursor.fetchall() cantmats = [] ...
DatosCantMaterial
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DatosCantMaterial: def get_from_Insid(cls, id, noClose=False): """Obtiene los materiales que componen un insumo de la BD""" <|body_0|> def addComponente(cls, idMat, idIns, cant): """Registra una cantidad de un material requerido para la produccion de un insumo.""" ...
stack_v2_sparse_classes_75kplus_train_006622
5,360
no_license
[ { "docstring": "Obtiene los materiales que componen un insumo de la BD", "name": "get_from_Insid", "signature": "def get_from_Insid(cls, id, noClose=False)" }, { "docstring": "Registra una cantidad de un material requerido para la produccion de un insumo.", "name": "addComponente", "sign...
6
stack_v2_sparse_classes_30k_train_016384
Implement the Python class `DatosCantMaterial` described below. Class description: Implement the DatosCantMaterial class. Method signatures and docstrings: - def get_from_Insid(cls, id, noClose=False): Obtiene los materiales que componen un insumo de la BD - def addComponente(cls, idMat, idIns, cant): Registra una ca...
Implement the Python class `DatosCantMaterial` described below. Class description: Implement the DatosCantMaterial class. Method signatures and docstrings: - def get_from_Insid(cls, id, noClose=False): Obtiene los materiales que componen un insumo de la BD - def addComponente(cls, idMat, idIns, cant): Registra una ca...
57ca674dba4dabd2526c450ba7210933240f19c5
<|skeleton|> class DatosCantMaterial: def get_from_Insid(cls, id, noClose=False): """Obtiene los materiales que componen un insumo de la BD""" <|body_0|> def addComponente(cls, idMat, idIns, cant): """Registra una cantidad de un material requerido para la produccion de un insumo.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DatosCantMaterial: def get_from_Insid(cls, id, noClose=False): """Obtiene los materiales que componen un insumo de la BD""" try: cls.abrir_conexion() sql = 'SELECT mat_ins.cantidad,mat_ins.idMaterial FROM mat_ins WHERE idInsumo = ...
the_stack_v2_python_sparse
data/data_cant_material.py
JoaquinCardonaRuiz/proyecto-final
train
0
21aab0f0ab96927ad0a1027e61b0df1dfbe24d5f
[ "super().__init__(RotatingMAB(*args, **kwargs))\nself.observation_space = Discrete(2)\nself._last_reward = False", "s, r, done, info = super().step(action)\nself._last_reward = r > 0.0\nreturn (int(self._last_reward), r, done, info)" ]
<|body_start_0|> super().__init__(RotatingMAB(*args, **kwargs)) self.observation_space = Discrete(2) self._last_reward = False <|end_body_0|> <|body_start_1|> s, r, done, info = super().step(action) self._last_reward = r > 0.0 return (int(self._last_reward), r, done, inf...
Non-Markovian Rotating MAB.
NonMarkovianRotatingMAB
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NonMarkovianRotatingMAB: """Non-Markovian Rotating MAB.""" def __init__(self, *args, **kwargs): """Initialize the environment.""" <|body_0|> def step(self, action): """Do a step.""" <|body_1|> <|end_skeleton|> <|body_start_0|> super().__init__(R...
stack_v2_sparse_classes_75kplus_train_006623
3,899
no_license
[ { "docstring": "Initialize the environment.", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "Do a step.", "name": "step", "signature": "def step(self, action)" } ]
2
stack_v2_sparse_classes_30k_train_043430
Implement the Python class `NonMarkovianRotatingMAB` described below. Class description: Non-Markovian Rotating MAB. Method signatures and docstrings: - def __init__(self, *args, **kwargs): Initialize the environment. - def step(self, action): Do a step.
Implement the Python class `NonMarkovianRotatingMAB` described below. Class description: Non-Markovian Rotating MAB. Method signatures and docstrings: - def __init__(self, *args, **kwargs): Initialize the environment. - def step(self, action): Do a step. <|skeleton|> class NonMarkovianRotatingMAB: """Non-Markovi...
b516ffa46e9df6a67fbda7546f9128c23920c460
<|skeleton|> class NonMarkovianRotatingMAB: """Non-Markovian Rotating MAB.""" def __init__(self, *args, **kwargs): """Initialize the environment.""" <|body_0|> def step(self, action): """Do a step.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NonMarkovianRotatingMAB: """Non-Markovian Rotating MAB.""" def __init__(self, *args, **kwargs): """Initialize the environment.""" super().__init__(RotatingMAB(*args, **kwargs)) self.observation_space = Discrete(2) self._last_reward = False def step(self, action): ...
the_stack_v2_python_sparse
src/envs/rotating_mab.py
marcofavorito/PAC-RDPs-code
train
2
1a3f2350e08643506ab97436b3bac296f297cd0e
[ "body = eval(response_self.request.body)\nuser_id = str(body['userId'])\ndata = str(body['data'])\nif judgeIfPermiss(user_id=user_id, mode=1, page='systemUserTeam') == False:\n return {'status': 0, 'errorInfo': '用户没有权限设置'}\nelse:\n return self.insertInMysql(data)", "try:\n data = eval(data)\nexcept:\n ...
<|body_start_0|> body = eval(response_self.request.body) user_id = str(body['userId']) data = str(body['data']) if judgeIfPermiss(user_id=user_id, mode=1, page='systemUserTeam') == False: return {'status': 0, 'errorInfo': '用户没有权限设置'} else: return self.inse...
添加一个用户,前端发送来的信息为: "userId": "admin", "data": { "name": "用户组三", "description": "巴拉巴拉", } 本函数接收该信息,判断userId用户是否拥有该权限并根据结果将其添加入库,返回: { "status": 1, #1表示成功,0表示失败 "errorInfo": "用户没有权限设置", #status为0时,前端展示errorinfo }
AddOneUserTeam
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AddOneUserTeam: """添加一个用户,前端发送来的信息为: "userId": "admin", "data": { "name": "用户组三", "description": "巴拉巴拉", } 本函数接收该信息,判断userId用户是否拥有该权限并根据结果将其添加入库,返回: { "status": 1, #1表示成功,0表示失败 "errorInfo": "用户没有权限设置", #status为0时,前端展示errorinfo }""" def entry(self, response_self): """response为tornado下...
stack_v2_sparse_classes_75kplus_train_006624
2,571
no_license
[ { "docstring": "response为tornado下get函数接收到前端数据后的self", "name": "entry", "signature": "def entry(self, response_self)" }, { "docstring": "对前端发来的data进行校验", "name": "judgePara", "signature": "def judgePara(self, data)" }, { "docstring": "将data中用户组信息入库", "name": "insertInMysql", ...
3
stack_v2_sparse_classes_30k_train_049985
Implement the Python class `AddOneUserTeam` described below. Class description: 添加一个用户,前端发送来的信息为: "userId": "admin", "data": { "name": "用户组三", "description": "巴拉巴拉", } 本函数接收该信息,判断userId用户是否拥有该权限并根据结果将其添加入库,返回: { "status": 1, #1表示成功,0表示失败 "errorInfo": "用户没有权限设置", #status为0时,前端展示errorinfo } Method signatures and docstr...
Implement the Python class `AddOneUserTeam` described below. Class description: 添加一个用户,前端发送来的信息为: "userId": "admin", "data": { "name": "用户组三", "description": "巴拉巴拉", } 本函数接收该信息,判断userId用户是否拥有该权限并根据结果将其添加入库,返回: { "status": 1, #1表示成功,0表示失败 "errorInfo": "用户没有权限设置", #status为0时,前端展示errorinfo } Method signatures and docstr...
a31364869894c72349e3587944ecb4fda018e020
<|skeleton|> class AddOneUserTeam: """添加一个用户,前端发送来的信息为: "userId": "admin", "data": { "name": "用户组三", "description": "巴拉巴拉", } 本函数接收该信息,判断userId用户是否拥有该权限并根据结果将其添加入库,返回: { "status": 1, #1表示成功,0表示失败 "errorInfo": "用户没有权限设置", #status为0时,前端展示errorinfo }""" def entry(self, response_self): """response为tornado下...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AddOneUserTeam: """添加一个用户,前端发送来的信息为: "userId": "admin", "data": { "name": "用户组三", "description": "巴拉巴拉", } 本函数接收该信息,判断userId用户是否拥有该权限并根据结果将其添加入库,返回: { "status": 1, #1表示成功,0表示失败 "errorInfo": "用户没有权限设置", #status为0时,前端展示errorinfo }""" def entry(self, response_self): """response为tornado下get函数接收到前端数据后...
the_stack_v2_python_sparse
tornado/system/add_one_user_team.py
fxrc/care-system
train
1
6c794ff211cd9aa5e0584f7f386aeeb28763e008
[ "if tracing_attributes is None:\n tracing_attributes = {}\nspan_shell: Callable = distributed_trace(name_of_span=name_of_span, tracing_attributes=tracing_attributes, kind=kind)\nspan = span_shell(invoker)\nreturn span()", "if tracing_attributes is None:\n tracing_attributes = {}\nspan_shell: Callable = dist...
<|body_start_0|> if tracing_attributes is None: tracing_attributes = {} span_shell: Callable = distributed_trace(name_of_span=name_of_span, tracing_attributes=tracing_attributes, kind=kind) span = span_shell(invoker) return span() <|end_body_0|> <|body_start_1|> if t...
Invoker class for telemetry
MonitoredActivity
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MonitoredActivity: """Invoker class for telemetry""" def invoke(invoker: Callable[[], T], name_of_span: str=None, tracing_attributes=None, kind: str=SpanKind.INTERNAL) -> T: """Runs the span on given function""" <|body_0|> async def invoke_async(invoker: Callable[[], T],...
stack_v2_sparse_classes_75kplus_train_006625
4,896
permissive
[ { "docstring": "Runs the span on given function", "name": "invoke", "signature": "def invoke(invoker: Callable[[], T], name_of_span: str=None, tracing_attributes=None, kind: str=SpanKind.INTERNAL) -> T" }, { "docstring": "Runs a span on given function", "name": "invoke_async", "signature...
2
null
Implement the Python class `MonitoredActivity` described below. Class description: Invoker class for telemetry Method signatures and docstrings: - def invoke(invoker: Callable[[], T], name_of_span: str=None, tracing_attributes=None, kind: str=SpanKind.INTERNAL) -> T: Runs the span on given function - async def invoke...
Implement the Python class `MonitoredActivity` described below. Class description: Invoker class for telemetry Method signatures and docstrings: - def invoke(invoker: Callable[[], T], name_of_span: str=None, tracing_attributes=None, kind: str=SpanKind.INTERNAL) -> T: Runs the span on given function - async def invoke...
59e263b17716b1499e596d667c1137598b98aac0
<|skeleton|> class MonitoredActivity: """Invoker class for telemetry""" def invoke(invoker: Callable[[], T], name_of_span: str=None, tracing_attributes=None, kind: str=SpanKind.INTERNAL) -> T: """Runs the span on given function""" <|body_0|> async def invoke_async(invoker: Callable[[], T],...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MonitoredActivity: """Invoker class for telemetry""" def invoke(invoker: Callable[[], T], name_of_span: str=None, tracing_attributes=None, kind: str=SpanKind.INTERNAL) -> T: """Runs the span on given function""" if tracing_attributes is None: tracing_attributes = {} sp...
the_stack_v2_python_sparse
azure-kusto-data/azure/kusto/data/_telemetry.py
Azure/azure-kusto-python
train
176
a8956c6aa972fc14b6b6f6c51bfd00d7af6d708a
[ "self.generic = config.get('generic', False)\nwrap = config.get('tex_inline_wrap', ['\\\\(', '\\\\)'])\nself.wrap = wrap[0] + '%s' + wrap[1]\nself.preview = config.get('preview', True)\nPattern.__init__(self, pattern)", "if self.preview:\n el = md_util.etree.Element('span')\n preview = md_util.etree.SubElem...
<|body_start_0|> self.generic = config.get('generic', False) wrap = config.get('tex_inline_wrap', ['\\(', '\\)']) self.wrap = wrap[0] + '%s' + wrap[1] self.preview = config.get('preview', True) Pattern.__init__(self, pattern) <|end_body_0|> <|body_start_1|> if self.previ...
Arithmatex inline pattern handler.
InlineArithmatexPattern
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InlineArithmatexPattern: """Arithmatex inline pattern handler.""" def __init__(self, pattern, config): """Initialize.""" <|body_0|> def mathjax_output(self, math): """Default MathJax output.""" <|body_1|> def generic_output(self, math): """Ge...
stack_v2_sparse_classes_75kplus_train_006626
9,236
permissive
[ { "docstring": "Initialize.", "name": "__init__", "signature": "def __init__(self, pattern, config)" }, { "docstring": "Default MathJax output.", "name": "mathjax_output", "signature": "def mathjax_output(self, math)" }, { "docstring": "Generic output.", "name": "generic_outp...
4
stack_v2_sparse_classes_30k_train_021276
Implement the Python class `InlineArithmatexPattern` described below. Class description: Arithmatex inline pattern handler. Method signatures and docstrings: - def __init__(self, pattern, config): Initialize. - def mathjax_output(self, math): Default MathJax output. - def generic_output(self, math): Generic output. -...
Implement the Python class `InlineArithmatexPattern` described below. Class description: Arithmatex inline pattern handler. Method signatures and docstrings: - def __init__(self, pattern, config): Initialize. - def mathjax_output(self, math): Default MathJax output. - def generic_output(self, math): Generic output. -...
0e7796a61d4391ba51e3a9e21d3cdcd64a0ba8a4
<|skeleton|> class InlineArithmatexPattern: """Arithmatex inline pattern handler.""" def __init__(self, pattern, config): """Initialize.""" <|body_0|> def mathjax_output(self, math): """Default MathJax output.""" <|body_1|> def generic_output(self, math): """Ge...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class InlineArithmatexPattern: """Arithmatex inline pattern handler.""" def __init__(self, pattern, config): """Initialize.""" self.generic = config.get('generic', False) wrap = config.get('tex_inline_wrap', ['\\(', '\\)']) self.wrap = wrap[0] + '%s' + wrap[1] self.previ...
the_stack_v2_python_sparse
thirdparty/pymdownx/arithmatex.py
cxsjclassroom/webserver
train
5
b20e2f095ea4c83726ce383fef8d9c46a5455798
[ "rc = []\nfor test in tests:\n try:\n testmethod = getattr(SCR_Test_Runtime, test)\n if callable(testmethod):\n rc.append(testmethod())\n else:\n print('SCR_Test_Runtime: ERROR: ' + test + ' is defined but is not a test method.')\n except AttributeError as e:\n ...
<|body_start_0|> rc = [] for test in tests: try: testmethod = getattr(SCR_Test_Runtime, test) if callable(testmethod): rc.append(testmethod()) else: print('SCR_Test_Runtime: ERROR: ' + test + ' is defined...
SCR_Test_Runtime class contains methods to determine whether we should launch with SCR This class contains methods to test the environment, to ensure SCR will be able to function. These tests are called in scr_prerun.py, immediately after checking if scr is enabled. Not all methods are appropriate to test in every envi...
SCR_Test_Runtime
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SCR_Test_Runtime: """SCR_Test_Runtime class contains methods to determine whether we should launch with SCR This class contains methods to test the environment, to ensure SCR will be able to function. These tests are called in scr_prerun.py, immediately after checking if scr is enabled. Not all m...
stack_v2_sparse_classes_75kplus_train_006627
5,626
permissive
[ { "docstring": "This method collects the return codes of all static methods declared in SCR_Test_Runtime This method receives a list. Each element is a string and is the name of a method of the SCR_Test_Runtime class Returns ------- This method returns an integer. This method does not return an instance of a cl...
3
stack_v2_sparse_classes_30k_train_032104
Implement the Python class `SCR_Test_Runtime` described below. Class description: SCR_Test_Runtime class contains methods to determine whether we should launch with SCR This class contains methods to test the environment, to ensure SCR will be able to function. These tests are called in scr_prerun.py, immediately afte...
Implement the Python class `SCR_Test_Runtime` described below. Class description: SCR_Test_Runtime class contains methods to determine whether we should launch with SCR This class contains methods to test the environment, to ensure SCR will be able to function. These tests are called in scr_prerun.py, immediately afte...
1d78ff0bccd02a9443ad07844c4ca75129a537a1
<|skeleton|> class SCR_Test_Runtime: """SCR_Test_Runtime class contains methods to determine whether we should launch with SCR This class contains methods to test the environment, to ensure SCR will be able to function. These tests are called in scr_prerun.py, immediately after checking if scr is enabled. Not all m...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SCR_Test_Runtime: """SCR_Test_Runtime class contains methods to determine whether we should launch with SCR This class contains methods to test the environment, to ensure SCR will be able to function. These tests are called in scr_prerun.py, immediately after checking if scr is enabled. Not all methods are ap...
the_stack_v2_python_sparse
scripts/python/scrjob/scr_test_runtime.py
LLNL/scr
train
84
1ce82c17072a0efa1c946a3b3ecaa27de0476c14
[ "nums_island = 0\nif len(gird) == 0 or len(gird[0]) == 0:\n return nums_island\nacross_length = len(gird)\nvertical_length = len(gird[0])\nfor across in range(across_length):\n for vertical in range(vertical_length):\n if gird[across][vertical] == '1':\n nums_island += 1\n gird[ac...
<|body_start_0|> nums_island = 0 if len(gird) == 0 or len(gird[0]) == 0: return nums_island across_length = len(gird) vertical_length = len(gird[0]) for across in range(across_length): for vertical in range(vertical_length): if gird[across]...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def numIslands(self, gird: [[str]]) -> int: """get the islands nums in the two-dimensional matrix :param gird: :return:""" <|body_0|> def __dfs(self, across: int, vertical: int, across_length: int, vertical_length: int, grid: [[str]]) -> None: """depth firs...
stack_v2_sparse_classes_75kplus_train_006628
2,465
no_license
[ { "docstring": "get the islands nums in the two-dimensional matrix :param gird: :return:", "name": "numIslands", "signature": "def numIslands(self, gird: [[str]]) -> int" }, { "docstring": "depth first search the \"1\" which in the two-dimensional matrix, and then change the \"1\" to the \"0\" :...
2
stack_v2_sparse_classes_30k_train_011448
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def numIslands(self, gird: [[str]]) -> int: get the islands nums in the two-dimensional matrix :param gird: :return: - def __dfs(self, across: int, vertical: int, across_length: ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def numIslands(self, gird: [[str]]) -> int: get the islands nums in the two-dimensional matrix :param gird: :return: - def __dfs(self, across: int, vertical: int, across_length: ...
37710292b2cfc6060098363c8d5f8881a4c22b26
<|skeleton|> class Solution: def numIslands(self, gird: [[str]]) -> int: """get the islands nums in the two-dimensional matrix :param gird: :return:""" <|body_0|> def __dfs(self, across: int, vertical: int, across_length: int, vertical_length: int, grid: [[str]]) -> None: """depth firs...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def numIslands(self, gird: [[str]]) -> int: """get the islands nums in the two-dimensional matrix :param gird: :return:""" nums_island = 0 if len(gird) == 0 or len(gird[0]) == 0: return nums_island across_length = len(gird) vertical_length = len(gi...
the_stack_v2_python_sparse
python/pyleetcode/queue_and_stack/numIslandsII.py
yudongnan23/algorithmRoad
train
0
76c03b352734bc4a5e64026dda27edffe5138419
[ "self.path = path\nself.path_to_models_csv = join(path, 'production.csv')\nself.df = pandas.read_csv(self.path_to_models_csv)\nself.df.index = self.df['allele']\nself.supported_alleles = list(sorted(self.df.allele))\nself.predictors_cache = {}", "allele_name = normalize_allele_name(allele_name)\nif allele_name no...
<|body_start_0|> self.path = path self.path_to_models_csv = join(path, 'production.csv') self.df = pandas.read_csv(self.path_to_models_csv) self.df.index = self.df['allele'] self.supported_alleles = list(sorted(self.df.allele)) self.predictors_cache = {} <|end_body_0|> <...
Factory for Class1BindingPredictor instances that are stored on disk using this directory structure: production.csv - Manifest file giving information on all models models/ - directory of models with names given in the manifest file MODEL-BAR.pickle MODEL-FOO.pickle ...
Class1AlleleSpecificPredictorLoader
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Class1AlleleSpecificPredictorLoader: """Factory for Class1BindingPredictor instances that are stored on disk using this directory structure: production.csv - Manifest file giving information on all models models/ - directory of models with names given in the manifest file MODEL-BAR.pickle MODEL-F...
stack_v2_sparse_classes_75kplus_train_006629
3,933
permissive
[ { "docstring": "Parameters ---------- path : string Path to directory containing manifest and models", "name": "__init__", "signature": "def __init__(self, path)" }, { "docstring": "Load a predictor for an allele. Parameters ---------- allele_name : class I allele name Returns ---------- Class1B...
2
stack_v2_sparse_classes_30k_train_053086
Implement the Python class `Class1AlleleSpecificPredictorLoader` described below. Class description: Factory for Class1BindingPredictor instances that are stored on disk using this directory structure: production.csv - Manifest file giving information on all models models/ - directory of models with names given in the...
Implement the Python class `Class1AlleleSpecificPredictorLoader` described below. Class description: Factory for Class1BindingPredictor instances that are stored on disk using this directory structure: production.csv - Manifest file giving information on all models models/ - directory of models with names given in the...
9493286baef94ec43b6c419126181417a5699410
<|skeleton|> class Class1AlleleSpecificPredictorLoader: """Factory for Class1BindingPredictor instances that are stored on disk using this directory structure: production.csv - Manifest file giving information on all models models/ - directory of models with names given in the manifest file MODEL-BAR.pickle MODEL-F...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Class1AlleleSpecificPredictorLoader: """Factory for Class1BindingPredictor instances that are stored on disk using this directory structure: production.csv - Manifest file giving information on all models models/ - directory of models with names given in the manifest file MODEL-BAR.pickle MODEL-FOO.pickle ......
the_stack_v2_python_sparse
mhcflurry/class1_allele_specific/load.py
alexanderwhatley/mhcflurry
train
0
91ff1f496b8b073141bfdc71f965b0187e3a2488
[ "try:\n self._cur.execute('COMMIT')\n self._cur.execute(query)\n return str(self._cur.fetchall())\nexcept DatabaseError:\n return None", "query = query.strip(' ;\\n')\nif not query:\n return 0\norig_checksum = self._result_checksum(query)\nif not orig_checksum:\n return 0\ntokens = query.split()...
<|body_start_0|> try: self._cur.execute('COMMIT') self._cur.execute(query) return str(self._cur.fetchall()) except DatabaseError: return None <|end_body_0|> <|body_start_1|> query = query.strip(' ;\n') if not query: return 0 ...
AllPartsEssential
[ "Apache-2.0", "BSD-2-Clause", "CC0-1.0", "BSD-3-Clause", "MPL-2.0", "0BSD", "PostgreSQL", "GPL-1.0-or-later", "GPL-2.0-only", "MIT", "BUSL-1.1" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AllPartsEssential: def _result_checksum(self, query: str) -> Optional[str]: """Execute the query and return a 'checksum' of the result. In this implementation, the checksum is simply the serialization of the entire result set""" <|body_0|> def fitness(self, query: str) -> fl...
stack_v2_sparse_classes_75kplus_train_006630
2,632
permissive
[ { "docstring": "Execute the query and return a 'checksum' of the result. In this implementation, the checksum is simply the serialization of the entire result set", "name": "_result_checksum", "signature": "def _result_checksum(self, query: str) -> Optional[str]" }, { "docstring": "Test if all p...
2
stack_v2_sparse_classes_30k_train_032022
Implement the Python class `AllPartsEssential` described below. Class description: Implement the AllPartsEssential class. Method signatures and docstrings: - def _result_checksum(self, query: str) -> Optional[str]: Execute the query and return a 'checksum' of the result. In this implementation, the checksum is simply...
Implement the Python class `AllPartsEssential` described below. Class description: Implement the AllPartsEssential class. Method signatures and docstrings: - def _result_checksum(self, query: str) -> Optional[str]: Execute the query and return a 'checksum' of the result. In this implementation, the checksum is simply...
cb9d59d2f1c0eaee33b864982f22b7b3b9ba8759
<|skeleton|> class AllPartsEssential: def _result_checksum(self, query: str) -> Optional[str]: """Execute the query and return a 'checksum' of the result. In this implementation, the checksum is simply the serialization of the entire result set""" <|body_0|> def fitness(self, query: str) -> fl...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AllPartsEssential: def _result_checksum(self, query: str) -> Optional[str]: """Execute the query and return a 'checksum' of the result. In this implementation, the checksum is simply the serialization of the entire result set""" try: self._cur.execute('COMMIT') self._cu...
the_stack_v2_python_sparse
misc/python/materialize/query_fitness/all_parts_essential.py
nisarhassan12/materialize
train
0
1e7e8816ec6e1760bde7146bfade6b18b9c66402
[ "dp = [0] * (num + 1)\ndp[0] = 0\nfor i in range(1, num + 1):\n dp[i] = dp[i - 2 ** floor(log2(i))] + 1\nreturn dp", "dp = [0] * (num + 1)\ndp[0] = 0\nfor i in range(1, num + 1):\n tmp = i\n j = 0\n while tmp >= 2:\n j += 1\n tmp = tmp >> 1\n dp[i] = dp[i - 2 ** j] + 1\nreturn dp" ]
<|body_start_0|> dp = [0] * (num + 1) dp[0] = 0 for i in range(1, num + 1): dp[i] = dp[i - 2 ** floor(log2(i))] + 1 return dp <|end_body_0|> <|body_start_1|> dp = [0] * (num + 1) dp[0] = 0 for i in range(1, num + 1): tmp = i j ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def countBits(self, num: int) -> List[int]: """DP, Time: O(n), Space: O(n)""" <|body_0|> def countBits(self, num: int) -> List[int]: """Without build in log2""" <|body_1|> <|end_skeleton|> <|body_start_0|> dp = [0] * (num + 1) dp[0...
stack_v2_sparse_classes_75kplus_train_006631
1,033
no_license
[ { "docstring": "DP, Time: O(n), Space: O(n)", "name": "countBits", "signature": "def countBits(self, num: int) -> List[int]" }, { "docstring": "Without build in log2", "name": "countBits", "signature": "def countBits(self, num: int) -> List[int]" } ]
2
stack_v2_sparse_classes_30k_train_027316
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countBits(self, num: int) -> List[int]: DP, Time: O(n), Space: O(n) - def countBits(self, num: int) -> List[int]: Without build in log2
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countBits(self, num: int) -> List[int]: DP, Time: O(n), Space: O(n) - def countBits(self, num: int) -> List[int]: Without build in log2 <|skeleton|> class Solution: def...
72136e3487d239f5b37e2d6393e034262a6bf599
<|skeleton|> class Solution: def countBits(self, num: int) -> List[int]: """DP, Time: O(n), Space: O(n)""" <|body_0|> def countBits(self, num: int) -> List[int]: """Without build in log2""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def countBits(self, num: int) -> List[int]: """DP, Time: O(n), Space: O(n)""" dp = [0] * (num + 1) dp[0] = 0 for i in range(1, num + 1): dp[i] = dp[i - 2 ** floor(log2(i))] + 1 return dp def countBits(self, num: int) -> List[int]: """W...
the_stack_v2_python_sparse
python/338-Counting Bits.py
cwza/leetcode
train
0
296f9e6210a14ad96edd1c6ccba151a89a822c2c
[ "self.tree = [0] * (2 * self.MAX_ARRAY_SIZE)\nn = len(input_array)\nself.n = n\nfor i in range(n):\n self.tree[n + i] = input_array[i]\nfor i in range(n - 1, 0, -1):\n self.tree[i] = self.tree[i << 1] + self.tree[i << 1 | 1]", "self.tree[index + self.n] = value\nindex = index + self.n\ni = index\nwhile i > ...
<|body_start_0|> self.tree = [0] * (2 * self.MAX_ARRAY_SIZE) n = len(input_array) self.n = n for i in range(n): self.tree[n + i] = input_array[i] for i in range(n - 1, 0, -1): self.tree[i] = self.tree[i << 1] + self.tree[i << 1 | 1] <|end_body_0|> <|body_...
An implementation of Segment Tree
SegmentTree
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SegmentTree: """An implementation of Segment Tree""" def __init__(self, input_array): """init Segment Tree Args: input_array: Input array Returns: None Raises: None""" <|body_0|> def update(self, index, value): """Update Args: index: to update value: new value Re...
stack_v2_sparse_classes_75kplus_train_006632
2,356
no_license
[ { "docstring": "init Segment Tree Args: input_array: Input array Returns: None Raises: None", "name": "__init__", "signature": "def __init__(self, input_array)" }, { "docstring": "Update Args: index: to update value: new value Returns: None Raises: None", "name": "update", "signature": "...
3
stack_v2_sparse_classes_30k_train_046832
Implement the Python class `SegmentTree` described below. Class description: An implementation of Segment Tree Method signatures and docstrings: - def __init__(self, input_array): init Segment Tree Args: input_array: Input array Returns: None Raises: None - def update(self, index, value): Update Args: index: to updat...
Implement the Python class `SegmentTree` described below. Class description: An implementation of Segment Tree Method signatures and docstrings: - def __init__(self, input_array): init Segment Tree Args: input_array: Input array Returns: None Raises: None - def update(self, index, value): Update Args: index: to updat...
11f4d25cb211740514c119a60962d075a0817abd
<|skeleton|> class SegmentTree: """An implementation of Segment Tree""" def __init__(self, input_array): """init Segment Tree Args: input_array: Input array Returns: None Raises: None""" <|body_0|> def update(self, index, value): """Update Args: index: to update value: new value Re...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SegmentTree: """An implementation of Segment Tree""" def __init__(self, input_array): """init Segment Tree Args: input_array: Input array Returns: None Raises: None""" self.tree = [0] * (2 * self.MAX_ARRAY_SIZE) n = len(input_array) self.n = n for i in range(n): ...
the_stack_v2_python_sparse
python/common/segment_tree.py
santhosh-kumar/AlgorithmsAndDataStructures
train
2
56595d8ed021a6775b47003f9f8f957b22bb9720
[ "print('\\nGenerating simple sine wave ...')\nfreq = RelPitch.valid_freq(note)\ndur = RelTime.valid_beatsec(dur).samps()\namp = inpt_validate(amp, 'flt', allowed=[0, 2])\narr = BaseGenerator.wave(dur, freq.get_period(rate), shift=0, amp=amp)\nsource_block = {'type': 'generator', 'name': sys._getframe().f_code.co_na...
<|body_start_0|> print('\nGenerating simple sine wave ...') freq = RelPitch.valid_freq(note) dur = RelTime.valid_beatsec(dur).samps() amp = inpt_validate(amp, 'flt', allowed=[0, 2]) arr = BaseGenerator.wave(dur, freq.get_period(rate), shift=0, amp=amp) source_block = {'ty...
SimpleWave
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SimpleWave: def sine(note, dur, amp=0.1, rate=44100, name=None): """sine wave generator freqency (Hz) duration (secs) amplitude (0-1) 0.1 default returns Recording obj""" <|body_0|> def square(note, dur, amp=0.05, rate=44100, name=None): """freqency (Hz) duration (se...
stack_v2_sparse_classes_75kplus_train_006633
6,937
no_license
[ { "docstring": "sine wave generator freqency (Hz) duration (secs) amplitude (0-1) 0.1 default returns Recording obj", "name": "sine", "signature": "def sine(note, dur, amp=0.1, rate=44100, name=None)" }, { "docstring": "freqency (Hz) duration (secs) amplitude (0-1) 0.05 default rate (sps) 44100"...
4
stack_v2_sparse_classes_30k_train_039442
Implement the Python class `SimpleWave` described below. Class description: Implement the SimpleWave class. Method signatures and docstrings: - def sine(note, dur, amp=0.1, rate=44100, name=None): sine wave generator freqency (Hz) duration (secs) amplitude (0-1) 0.1 default returns Recording obj - def square(note, du...
Implement the Python class `SimpleWave` described below. Class description: Implement the SimpleWave class. Method signatures and docstrings: - def sine(note, dur, amp=0.1, rate=44100, name=None): sine wave generator freqency (Hz) duration (secs) amplitude (0-1) 0.1 default returns Recording obj - def square(note, du...
f52f4f9aab6b9bc1a3c9bf9f351e2fb07a448278
<|skeleton|> class SimpleWave: def sine(note, dur, amp=0.1, rate=44100, name=None): """sine wave generator freqency (Hz) duration (secs) amplitude (0-1) 0.1 default returns Recording obj""" <|body_0|> def square(note, dur, amp=0.05, rate=44100, name=None): """freqency (Hz) duration (se...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SimpleWave: def sine(note, dur, amp=0.1, rate=44100, name=None): """sine wave generator freqency (Hz) duration (secs) amplitude (0-1) 0.1 default returns Recording obj""" print('\nGenerating simple sine wave ...') freq = RelPitch.valid_freq(note) dur = RelTime.valid_beatsec(dur...
the_stack_v2_python_sparse
src/generators.py
JRice15/relativism
train
2
659fd75fe7a1f37389859e7eeedbcc0c234a9eae
[ "self.snapshot_task_start_time_usecs = snapshot_task_start_time_usecs\nself.archive_task_uid = archive_task_uid\nself.error = error\nself.expiry_time_usecs = expiry_time_usecs\nself.job_run_id = job_run_id\nself.progress_monitor_task = progress_monitor_task\nself.snapshot_task_end_time_usecs = snapshot_task_end_tim...
<|body_start_0|> self.snapshot_task_start_time_usecs = snapshot_task_start_time_usecs self.archive_task_uid = archive_task_uid self.error = error self.expiry_time_usecs = expiry_time_usecs self.job_run_id = job_run_id self.progress_monitor_task = progress_monitor_task ...
Implementation of the 'RemoteRestoreSnapshotStatus' model. Specifies the status of a restore Snapshot task. Attributes: snapshot_task_start_time_usecs (long|int): Specifies when the snapshot task started. This time is recorded as a Unix epoch Timestamp (in microseconds). archive_task_uid (UniversalId): Specifies the gl...
RemoteRestoreSnapshotStatus
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RemoteRestoreSnapshotStatus: """Implementation of the 'RemoteRestoreSnapshotStatus' model. Specifies the status of a restore Snapshot task. Attributes: snapshot_task_start_time_usecs (long|int): Specifies when the snapshot task started. This time is recorded as a Unix epoch Timestamp (in microsec...
stack_v2_sparse_classes_75kplus_train_006634
5,677
permissive
[ { "docstring": "Constructor for the RemoteRestoreSnapshotStatus class", "name": "__init__", "signature": "def __init__(self, snapshot_task_start_time_usecs=None, archive_task_uid=None, error=None, expiry_time_usecs=None, job_run_id=None, progress_monitor_task=None, snapshot_task_end_time_usecs=None, sna...
2
null
Implement the Python class `RemoteRestoreSnapshotStatus` described below. Class description: Implementation of the 'RemoteRestoreSnapshotStatus' model. Specifies the status of a restore Snapshot task. Attributes: snapshot_task_start_time_usecs (long|int): Specifies when the snapshot task started. This time is recorded...
Implement the Python class `RemoteRestoreSnapshotStatus` described below. Class description: Implementation of the 'RemoteRestoreSnapshotStatus' model. Specifies the status of a restore Snapshot task. Attributes: snapshot_task_start_time_usecs (long|int): Specifies when the snapshot task started. This time is recorded...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class RemoteRestoreSnapshotStatus: """Implementation of the 'RemoteRestoreSnapshotStatus' model. Specifies the status of a restore Snapshot task. Attributes: snapshot_task_start_time_usecs (long|int): Specifies when the snapshot task started. This time is recorded as a Unix epoch Timestamp (in microsec...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RemoteRestoreSnapshotStatus: """Implementation of the 'RemoteRestoreSnapshotStatus' model. Specifies the status of a restore Snapshot task. Attributes: snapshot_task_start_time_usecs (long|int): Specifies when the snapshot task started. This time is recorded as a Unix epoch Timestamp (in microseconds). archiv...
the_stack_v2_python_sparse
cohesity_management_sdk/models/remote_restore_snapshot_status.py
cohesity/management-sdk-python
train
24
77dd90e7970c52cd4b1718ab5b5df6245fa21104
[ "super(MHA, self).__init__()\nself.H = H\nself.local_attn_size = local_attn_size\nself.fwd_attn = fwd_attn\nself.device = device\nself.scores = None\nself.W_q = nn.Linear(D_embed, Q * H)\nself.W_k = nn.Linear(D_embed, Q * H)\nself.W_v = nn.Linear(D_embed, V * H)\nself.smax = nn.Softmax(dim=-1)\nself.W_o = nn.Linear...
<|body_start_0|> super(MHA, self).__init__() self.H = H self.local_attn_size = local_attn_size self.fwd_attn = fwd_attn self.device = device self.scores = None self.W_q = nn.Linear(D_embed, Q * H) self.W_k = nn.Linear(D_embed, Q * H) self.W_v = nn....
Multi-Head Attention model based on 'Attention Is All You Need' paper. Generates self-attention tensor given requisite Query, Key, Value tensors.
MHA
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MHA: """Multi-Head Attention model based on 'Attention Is All You Need' paper. Generates self-attention tensor given requisite Query, Key, Value tensors.""" def __init__(self, D_embed, Q, V, H, local_attn_size=None, fwd_attn=True, device=None): """params D_embed (scalar): input embed...
stack_v2_sparse_classes_75kplus_train_006635
3,274
no_license
[ { "docstring": "params D_embed (scalar): input embedding feature dimension Q (scalar): query matrix dimension V (scalar): value matrix dimension H (scalar): number of heads local_attn_size: number of prior local elements attention will consider fwd_attn: indicator for whether to include forward attention mask d...
2
stack_v2_sparse_classes_30k_train_042996
Implement the Python class `MHA` described below. Class description: Multi-Head Attention model based on 'Attention Is All You Need' paper. Generates self-attention tensor given requisite Query, Key, Value tensors. Method signatures and docstrings: - def __init__(self, D_embed, Q, V, H, local_attn_size=None, fwd_attn...
Implement the Python class `MHA` described below. Class description: Multi-Head Attention model based on 'Attention Is All You Need' paper. Generates self-attention tensor given requisite Query, Key, Value tensors. Method signatures and docstrings: - def __init__(self, D_embed, Q, V, H, local_attn_size=None, fwd_attn...
274ff8db17271106155e34725ae69b1a35c962b2
<|skeleton|> class MHA: """Multi-Head Attention model based on 'Attention Is All You Need' paper. Generates self-attention tensor given requisite Query, Key, Value tensors.""" def __init__(self, D_embed, Q, V, H, local_attn_size=None, fwd_attn=True, device=None): """params D_embed (scalar): input embed...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MHA: """Multi-Head Attention model based on 'Attention Is All You Need' paper. Generates self-attention tensor given requisite Query, Key, Value tensors.""" def __init__(self, D_embed, Q, V, H, local_attn_size=None, fwd_attn=True, device=None): """params D_embed (scalar): input embedding feature ...
the_stack_v2_python_sparse
ml/models/MHA.py
gravaman/fleishco
train
0
51730351bb2b1f6246ec3394f4bbf2fe59e79256
[ "self.config = validateDict(config, self.default)\nself.sequence = self.config['sequence']\nself.duration = self.config['duration']\nself.frames = self.config['frames'][self.sequence[0]:self.sequence[-1] + 1]\npg.sprite.Sprite.__init__(self)\nself.pointer = 0\nself.image = self.frames[self.pointer]\nself.framecount...
<|body_start_0|> self.config = validateDict(config, self.default) self.sequence = self.config['sequence'] self.duration = self.config['duration'] self.frames = self.config['frames'][self.sequence[0]:self.sequence[-1] + 1] pg.sprite.Sprite.__init__(self) self.pointer = 0 ...
An animated sprite class.
Animation
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Animation: """An animated sprite class.""" def __init__(self, config={}): """Constructor.""" <|body_0|> def update(self): """Updating the pointer's position. The active frame is always drawn to the animation image surface.""" <|body_1|> def nextFrame...
stack_v2_sparse_classes_75kplus_train_006636
1,571
no_license
[ { "docstring": "Constructor.", "name": "__init__", "signature": "def __init__(self, config={})" }, { "docstring": "Updating the pointer's position. The active frame is always drawn to the animation image surface.", "name": "update", "signature": "def update(self)" }, { "docstring...
3
stack_v2_sparse_classes_30k_train_036036
Implement the Python class `Animation` described below. Class description: An animated sprite class. Method signatures and docstrings: - def __init__(self, config={}): Constructor. - def update(self): Updating the pointer's position. The active frame is always drawn to the animation image surface. - def nextFrame(sel...
Implement the Python class `Animation` described below. Class description: An animated sprite class. Method signatures and docstrings: - def __init__(self, config={}): Constructor. - def update(self): Updating the pointer's position. The active frame is always drawn to the animation image surface. - def nextFrame(sel...
c0c971af9cb4da9d4e00c98f065ee845f1cd9330
<|skeleton|> class Animation: """An animated sprite class.""" def __init__(self, config={}): """Constructor.""" <|body_0|> def update(self): """Updating the pointer's position. The active frame is always drawn to the animation image surface.""" <|body_1|> def nextFrame...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Animation: """An animated sprite class.""" def __init__(self, config={}): """Constructor.""" self.config = validateDict(config, self.default) self.sequence = self.config['sequence'] self.duration = self.config['duration'] self.frames = self.config['frames'][self.se...
the_stack_v2_python_sparse
animation.py
IveBeatenTetris/pygo
train
0
05aa1ba5649a2a1294cbbe9c1581a33ab3936ae9
[ "self.parametersDict = parametersDict\nself.parameter_list = []\nself.build_parameter_list()", "for parameterDict in self.parametersDict:\n if parameterDict['type'] == 'ManningN':\n currParameter = pyHMT2D.Calibration.Parameter_ManningN(parameterDict)\n self.parameter_list.append(currParameter)\n...
<|body_start_0|> self.parametersDict = parametersDict self.parameter_list = [] self.build_parameter_list() <|end_body_0|> <|body_start_1|> for parameterDict in self.parametersDict: if parameterDict['type'] == 'ManningN': currParameter = pyHMT2D.Calibration.Pa...
Calibration parameter collection class A "Parameters" object is a list of "Parameter" objects. Attributes ----------
Parameters
[ "MIT", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-generic-cla" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Parameters: """Calibration parameter collection class A "Parameters" object is a list of "Parameter" objects. Attributes ----------""" def __init__(self, parametersDict): """Objectives class constructor Parameters ---------- parametersDict : dict a dictionary contains the information...
stack_v2_sparse_classes_75kplus_train_006637
5,710
permissive
[ { "docstring": "Objectives class constructor Parameters ---------- parametersDict : dict a dictionary contains the information about calibration parameters", "name": "__init__", "signature": "def __init__(self, parametersDict)" }, { "docstring": "Build parameter_list Returns -------", "name"...
3
stack_v2_sparse_classes_30k_train_043951
Implement the Python class `Parameters` described below. Class description: Calibration parameter collection class A "Parameters" object is a list of "Parameter" objects. Attributes ---------- Method signatures and docstrings: - def __init__(self, parametersDict): Objectives class constructor Parameters ---------- pa...
Implement the Python class `Parameters` described below. Class description: Calibration parameter collection class A "Parameters" object is a list of "Parameter" objects. Attributes ---------- Method signatures and docstrings: - def __init__(self, parametersDict): Objectives class constructor Parameters ---------- pa...
b3254c257723aa4d00ebdd17bfa11c3d13429748
<|skeleton|> class Parameters: """Calibration parameter collection class A "Parameters" object is a list of "Parameter" objects. Attributes ----------""" def __init__(self, parametersDict): """Objectives class constructor Parameters ---------- parametersDict : dict a dictionary contains the information...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Parameters: """Calibration parameter collection class A "Parameters" object is a list of "Parameter" objects. Attributes ----------""" def __init__(self, parametersDict): """Objectives class constructor Parameters ---------- parametersDict : dict a dictionary contains the information about calibr...
the_stack_v2_python_sparse
pyHMT2D/Calibration/Parameters.py
hiter-joe/pyHMT2D
train
0
a93d2d689109b36239173c0104826ff19bb3c541
[ "error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError}\nerror_map.update(kwargs.pop('error_map', {}) or {})\n_headers = case_insensitive_dict(kwargs.pop('headers', {}) or {})\n_params = case_insensitive_dict(kwargs.pop('params', {}) or {})\napi_version = kwargs.pop('api_...
<|body_start_0|> error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {}) or {}) _headers = case_insensitive_dict(kwargs.pop('headers', {}) or {}) _params = case_insensitive_dict(kwargs.pop('params', {...
AuthenticationOperations
[ "LicenseRef-scancode-generic-cla", "MIT", "LGPL-2.1-or-later" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AuthenticationOperations: async def exchange_aad_access_token_for_acr_refresh_token(self, grant_type: Union[str, '_models.PostContentSchemaGrantType'], service: str, tenant: Optional[str]=None, refresh_token: Optional[str]=None, access_token: Optional[str]=None, **kwargs: Any) -> _models.AcrRefr...
stack_v2_sparse_classes_75kplus_train_006638
8,679
permissive
[ { "docstring": "Exchange AAD tokens for an ACR refresh Token. :param grant_type: Can take a value of access_token_refresh_token, or access_token, or refresh_token. :type grant_type: str or ~container_registry.models.PostContentSchemaGrantType :param service: Indicates the name of your Azure container registry. ...
2
stack_v2_sparse_classes_30k_train_030479
Implement the Python class `AuthenticationOperations` described below. Class description: Implement the AuthenticationOperations class. Method signatures and docstrings: - async def exchange_aad_access_token_for_acr_refresh_token(self, grant_type: Union[str, '_models.PostContentSchemaGrantType'], service: str, tenant...
Implement the Python class `AuthenticationOperations` described below. Class description: Implement the AuthenticationOperations class. Method signatures and docstrings: - async def exchange_aad_access_token_for_acr_refresh_token(self, grant_type: Union[str, '_models.PostContentSchemaGrantType'], service: str, tenant...
c2ca191e736bb06bfbbbc9493e8325763ba990bb
<|skeleton|> class AuthenticationOperations: async def exchange_aad_access_token_for_acr_refresh_token(self, grant_type: Union[str, '_models.PostContentSchemaGrantType'], service: str, tenant: Optional[str]=None, refresh_token: Optional[str]=None, access_token: Optional[str]=None, **kwargs: Any) -> _models.AcrRefr...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AuthenticationOperations: async def exchange_aad_access_token_for_acr_refresh_token(self, grant_type: Union[str, '_models.PostContentSchemaGrantType'], service: str, tenant: Optional[str]=None, refresh_token: Optional[str]=None, access_token: Optional[str]=None, **kwargs: Any) -> _models.AcrRefreshToken: ...
the_stack_v2_python_sparse
sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/operations/_patch.py
Azure/azure-sdk-for-python
train
4,046
20efd32f30e3046f1a2ae2e9045be9413bbdfb95
[ "user_id = request.user.id\ndate = json.loads(request.body.decode())\nsku_id = date.get('sku_id')\ntry:\n SKU.objects.get(pk=sku_id)\nexcept SKU.DoesNotExist:\n return http.HttpResponseBadRequest('sku不存在')\nredis_conn = get_redis_connection('history')\npl = redis_conn.pipeline()\npl.lrem('history_%s' % user_i...
<|body_start_0|> user_id = request.user.id date = json.loads(request.body.decode()) sku_id = date.get('sku_id') try: SKU.objects.get(pk=sku_id) except SKU.DoesNotExist: return http.HttpResponseBadRequest('sku不存在') redis_conn = get_redis_connection(...
UserBrowseHistory
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserBrowseHistory: def post(self, request): """# 1.接受数据(user_id,date,sku_id) # 2.通过sku_id获取对象中所有数据,在判断数据是否存在 # 3.保存浏览数据 # 3.1.链接数据库 # 3.2创建管道实例 # 3.3去重 [lrem(key,重复次数,value)] # 3.4存储 # 3.5最后截取[ltrim(key,截取区间)] # 4.返回响应 :param request: 访问详情页面 :return: sku_id 用户信息""" <|body_0|> ...
stack_v2_sparse_classes_75kplus_train_006639
28,561
permissive
[ { "docstring": "# 1.接受数据(user_id,date,sku_id) # 2.通过sku_id获取对象中所有数据,在判断数据是否存在 # 3.保存浏览数据 # 3.1.链接数据库 # 3.2创建管道实例 # 3.3去重 [lrem(key,重复次数,value)] # 3.4存储 # 3.5最后截取[ltrim(key,截取区间)] # 4.返回响应 :param request: 访问详情页面 :return: sku_id 用户信息", "name": "post", "signature": "def post(self, request)" }, { "d...
2
null
Implement the Python class `UserBrowseHistory` described below. Class description: Implement the UserBrowseHistory class. Method signatures and docstrings: - def post(self, request): # 1.接受数据(user_id,date,sku_id) # 2.通过sku_id获取对象中所有数据,在判断数据是否存在 # 3.保存浏览数据 # 3.1.链接数据库 # 3.2创建管道实例 # 3.3去重 [lrem(key,重复次数,value)] # 3.4存储...
Implement the Python class `UserBrowseHistory` described below. Class description: Implement the UserBrowseHistory class. Method signatures and docstrings: - def post(self, request): # 1.接受数据(user_id,date,sku_id) # 2.通过sku_id获取对象中所有数据,在判断数据是否存在 # 3.保存浏览数据 # 3.1.链接数据库 # 3.2创建管道实例 # 3.3去重 [lrem(key,重复次数,value)] # 3.4存储...
3f21773d2d98204400ea2c3738969ac2a593b242
<|skeleton|> class UserBrowseHistory: def post(self, request): """# 1.接受数据(user_id,date,sku_id) # 2.通过sku_id获取对象中所有数据,在判断数据是否存在 # 3.保存浏览数据 # 3.1.链接数据库 # 3.2创建管道实例 # 3.3去重 [lrem(key,重复次数,value)] # 3.4存储 # 3.5最后截取[ltrim(key,截取区间)] # 4.返回响应 :param request: 访问详情页面 :return: sku_id 用户信息""" <|body_0|> ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UserBrowseHistory: def post(self, request): """# 1.接受数据(user_id,date,sku_id) # 2.通过sku_id获取对象中所有数据,在判断数据是否存在 # 3.保存浏览数据 # 3.1.链接数据库 # 3.2创建管道实例 # 3.3去重 [lrem(key,重复次数,value)] # 3.4存储 # 3.5最后截取[ltrim(key,截取区间)] # 4.返回响应 :param request: 访问详情页面 :return: sku_id 用户信息""" user_id = request.user.id ...
the_stack_v2_python_sparse
meiduo_mall02/apps/users/views.py
hongyinwang/meiduo_project02
train
0
c1fada0bbae0bbaaf95b7c95f61fee954cd24db6
[ "from sktime.distances._distance_alignment_paths import compute_min_return_path\nfrom sktime.distances._erp_numba import _erp_cost_matrix\nfrom sktime.distances.lower_bounding import resolve_bounding_matrix\nfrom sktime.utils.numba.njit import njit\n_bounding_matrix = resolve_bounding_matrix(x, y, window, itakura_m...
<|body_start_0|> from sktime.distances._distance_alignment_paths import compute_min_return_path from sktime.distances._erp_numba import _erp_cost_matrix from sktime.distances.lower_bounding import resolve_bounding_matrix from sktime.utils.numba.njit import njit _bounding_matrix =...
Edit distance with real penalty (erp) between two time series.
_ErpDistance
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _ErpDistance: """Edit distance with real penalty (erp) between two time series.""" def _distance_alignment_path_factory(self, x: np.ndarray, y: np.ndarray, return_cost_matrix: bool=False, window: float=None, itakura_max_slope: float=None, bounding_matrix: np.ndarray=None, g: float=0.0, **kwa...
stack_v2_sparse_classes_75kplus_train_006640
6,760
permissive
[ { "docstring": "Create a no_python compiled erp distance alignment path callable. Similar to LCSS with a different penalty. Series should be shape (d, m), where d is the number of dimensions, m the series length. Series can be different lengths. Parameters ---------- x: np.ndarray (2d array of shape (d,m1)). Fi...
2
stack_v2_sparse_classes_30k_test_002179
Implement the Python class `_ErpDistance` described below. Class description: Edit distance with real penalty (erp) between two time series. Method signatures and docstrings: - def _distance_alignment_path_factory(self, x: np.ndarray, y: np.ndarray, return_cost_matrix: bool=False, window: float=None, itakura_max_slop...
Implement the Python class `_ErpDistance` described below. Class description: Edit distance with real penalty (erp) between two time series. Method signatures and docstrings: - def _distance_alignment_path_factory(self, x: np.ndarray, y: np.ndarray, return_cost_matrix: bool=False, window: float=None, itakura_max_slop...
70b2bfaaa597eb31bc3a1032366dcc0e1f4c8a9f
<|skeleton|> class _ErpDistance: """Edit distance with real penalty (erp) between two time series.""" def _distance_alignment_path_factory(self, x: np.ndarray, y: np.ndarray, return_cost_matrix: bool=False, window: float=None, itakura_max_slope: float=None, bounding_matrix: np.ndarray=None, g: float=0.0, **kwa...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class _ErpDistance: """Edit distance with real penalty (erp) between two time series.""" def _distance_alignment_path_factory(self, x: np.ndarray, y: np.ndarray, return_cost_matrix: bool=False, window: float=None, itakura_max_slope: float=None, bounding_matrix: np.ndarray=None, g: float=0.0, **kwargs: Any) -> ...
the_stack_v2_python_sparse
sktime/distances/_erp.py
sktime/sktime
train
1,117
2a50d35ad5af8f9be6d5438a05bc04fa903d3869
[ "n, m = (len(s), len(p))\np = sorted(p)\nres = []\nfor i in range(n):\n if s[i] in p:\n if sorted(s[i:i + m]) == p:\n res.append(i)\nreturn res", "from collections import defaultdict\nneed = defaultdict(int)\nfor i in p:\n need[i] += 1\nwindow = {}\nn, m = (len(s), len(p))\nleft, right = (...
<|body_start_0|> n, m = (len(s), len(p)) p = sorted(p) res = [] for i in range(n): if s[i] in p: if sorted(s[i:i + m]) == p: res.append(i) return res <|end_body_0|> <|body_start_1|> from collections import defaultdict ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findAnagrams0(self, s, p): """:type s: str :type p: str :rtype: List[int] 暴力解法,超时""" <|body_0|> def findAnagrams(self, s, p): """:type s: str :type p: str :rtype: List[int] 滑动窗口""" <|body_1|> <|end_skeleton|> <|body_start_0|> n, m = (l...
stack_v2_sparse_classes_75kplus_train_006641
1,695
no_license
[ { "docstring": ":type s: str :type p: str :rtype: List[int] 暴力解法,超时", "name": "findAnagrams0", "signature": "def findAnagrams0(self, s, p)" }, { "docstring": ":type s: str :type p: str :rtype: List[int] 滑动窗口", "name": "findAnagrams", "signature": "def findAnagrams(self, s, p)" } ]
2
stack_v2_sparse_classes_30k_train_047278
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findAnagrams0(self, s, p): :type s: str :type p: str :rtype: List[int] 暴力解法,超时 - def findAnagrams(self, s, p): :type s: str :type p: str :rtype: List[int] 滑动窗口
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findAnagrams0(self, s, p): :type s: str :type p: str :rtype: List[int] 暴力解法,超时 - def findAnagrams(self, s, p): :type s: str :type p: str :rtype: List[int] 滑动窗口 <|skeleton|> ...
6e18c5d257840489cc3fb1079ae3804c743982a4
<|skeleton|> class Solution: def findAnagrams0(self, s, p): """:type s: str :type p: str :rtype: List[int] 暴力解法,超时""" <|body_0|> def findAnagrams(self, s, p): """:type s: str :type p: str :rtype: List[int] 滑动窗口""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def findAnagrams0(self, s, p): """:type s: str :type p: str :rtype: List[int] 暴力解法,超时""" n, m = (len(s), len(p)) p = sorted(p) res = [] for i in range(n): if s[i] in p: if sorted(s[i:i + m]) == p: res.append(i) ...
the_stack_v2_python_sparse
438.找到字符串中所有字母异位词.py
yangyuxiang1996/leetcode
train
0
830b634409d806bb3bca6de828a57ae82e6476d2
[ "self.consumer_group = consumer_group\nself.consumer_group_generation_id = consumer_group_generation_id\nself.consumer_id = consumer_id\nself._reqs = defaultdict(dict)\nfor t in partition_requests:\n self._reqs[t.topic_name][t.partition_id] = (t.offset, t.timestamp, t.metadata)", "size = self.HEADER_LEN + 2 + ...
<|body_start_0|> self.consumer_group = consumer_group self.consumer_group_generation_id = consumer_group_generation_id self.consumer_id = consumer_id self._reqs = defaultdict(dict) for t in partition_requests: self._reqs[t.topic_name][t.partition_id] = (t.offset, t.ti...
An offset commit request Specification:: OffsetCommitRequest => ConsumerGroupId ConsumerGroupGenerationId ConsumerId [TopicName [Partition Offset TimeStamp Metadata]] ConsumerGroupId => string ConsumerGroupGenerationId => int32 ConsumerId => string TopicName => string Partition => int32 Offset => int64 TimeStamp => int...
OffsetCommitRequest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OffsetCommitRequest: """An offset commit request Specification:: OffsetCommitRequest => ConsumerGroupId ConsumerGroupGenerationId ConsumerId [TopicName [Partition Offset TimeStamp Metadata]] ConsumerGroupId => string ConsumerGroupGenerationId => int32 ConsumerId => string TopicName => string Part...
stack_v2_sparse_classes_75kplus_train_006642
12,832
permissive
[ { "docstring": "Create a new offset commit request :param partition_requests: Iterable of :class:`kafka.pykafka.protocol.PartitionOffsetCommitRequest` for this request", "name": "__init__", "signature": "def __init__(self, consumer_group, consumer_group_generation_id, consumer_id, partition_requests=[])...
3
stack_v2_sparse_classes_30k_train_024935
Implement the Python class `OffsetCommitRequest` described below. Class description: An offset commit request Specification:: OffsetCommitRequest => ConsumerGroupId ConsumerGroupGenerationId ConsumerId [TopicName [Partition Offset TimeStamp Metadata]] ConsumerGroupId => string ConsumerGroupGenerationId => int32 Consum...
Implement the Python class `OffsetCommitRequest` described below. Class description: An offset commit request Specification:: OffsetCommitRequest => ConsumerGroupId ConsumerGroupGenerationId ConsumerId [TopicName [Partition Offset TimeStamp Metadata]] ConsumerGroupId => string ConsumerGroupGenerationId => int32 Consum...
c7054bd05b127385b8c6f56a4e2241d92ff42ab4
<|skeleton|> class OffsetCommitRequest: """An offset commit request Specification:: OffsetCommitRequest => ConsumerGroupId ConsumerGroupGenerationId ConsumerId [TopicName [Partition Offset TimeStamp Metadata]] ConsumerGroupId => string ConsumerGroupGenerationId => int32 ConsumerId => string TopicName => string Part...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class OffsetCommitRequest: """An offset commit request Specification:: OffsetCommitRequest => ConsumerGroupId ConsumerGroupGenerationId ConsumerId [TopicName [Partition Offset TimeStamp Metadata]] ConsumerGroupId => string ConsumerGroupGenerationId => int32 ConsumerId => string TopicName => string Partition => int3...
the_stack_v2_python_sparse
py_kafk/tar/pykafka-2.8.1-dev.1/pykafka/protocol/offset_commit.py
liuansen/python-utils-class
train
3
72edcdf99f2acf4130917b530d7be7a117ffe091
[ "self.inputFile = inputFile\nself.logLevel = logLevel\nlogging.basicConfig(level=self.logLevel)\nself.dConditions = {}\ntry:\n self.filehandle = open(self.inputFile, 'r')\nexcept Exception as e:\n logging.error(e)\n sys.exit(1)", "for idx, line in enumerate(self.filehandle):\n currentLine = line.strip...
<|body_start_0|> self.inputFile = inputFile self.logLevel = logLevel logging.basicConfig(level=self.logLevel) self.dConditions = {} try: self.filehandle = open(self.inputFile, 'r') except Exception as e: logging.error(e) sys.exit(1) <|e...
ExpNucFileParser
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExpNucFileParser: def __init__(self, inputFile='', logLevel='ERROR'): """Constructor""" <|body_0|> def parse(self): """parse file""" <|body_1|> def getlLabels(self): """return list of labels""" <|body_2|> def getlConditions(self): ...
stack_v2_sparse_classes_75kplus_train_006643
2,378
no_license
[ { "docstring": "Constructor", "name": "__init__", "signature": "def __init__(self, inputFile='', logLevel='ERROR')" }, { "docstring": "parse file", "name": "parse", "signature": "def parse(self)" }, { "docstring": "return list of labels", "name": "getlLabels", "signature"...
6
stack_v2_sparse_classes_30k_train_001602
Implement the Python class `ExpNucFileParser` described below. Class description: Implement the ExpNucFileParser class. Method signatures and docstrings: - def __init__(self, inputFile='', logLevel='ERROR'): Constructor - def parse(self): parse file - def getlLabels(self): return list of labels - def getlConditions(s...
Implement the Python class `ExpNucFileParser` described below. Class description: Implement the ExpNucFileParser class. Method signatures and docstrings: - def __init__(self, inputFile='', logLevel='ERROR'): Constructor - def parse(self): parse file - def getlLabels(self): return list of labels - def getlConditions(s...
ee0be5513d6a429b07b057d0ddd3fd617a1073d7
<|skeleton|> class ExpNucFileParser: def __init__(self, inputFile='', logLevel='ERROR'): """Constructor""" <|body_0|> def parse(self): """parse file""" <|body_1|> def getlLabels(self): """return list of labels""" <|body_2|> def getlConditions(self): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ExpNucFileParser: def __init__(self, inputFile='', logLevel='ERROR'): """Constructor""" self.inputFile = inputFile self.logLevel = logLevel logging.basicConfig(level=self.logLevel) self.dConditions = {} try: self.filehandle = open(self.inputFile, 'r'...
the_stack_v2_python_sparse
MSTS/Parser/ExpNucFileParser.py
nlapalu/MSTS
train
0
43ad6498ff3815c9f66c9145e63b5c8a6d23ac5b
[ "super().__init__(items, embeddings)\nself.PAD = pad\nself.UNK = unk", "if word not in self._dict:\n return self.__getitem__(self.UNK)\nreturn super().__getitem__(word)" ]
<|body_start_0|> super().__init__(items, embeddings) self.PAD = pad self.UNK = unk <|end_body_0|> <|body_start_1|> if word not in self._dict: return self.__getitem__(self.UNK) return super().__getitem__(word) <|end_body_1|>
Class for collection of word embeddings. Attributes: PAD (str): Label for the padding token UNK (str): Label for the unknown token
WordEmbeddings
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WordEmbeddings: """Class for collection of word embeddings. Attributes: PAD (str): Label for the padding token UNK (str): Label for the unknown token""" def __init__(self, words, embeddings, pad='<pad>', unk='<unk>'): """Initialize word embeddings Args: words (list): Words embeddings...
stack_v2_sparse_classes_75kplus_train_006644
12,577
permissive
[ { "docstring": "Initialize word embeddings Args: words (list): Words embeddings (ndarray): Word embeddings (vectors) pad (str, optional): Label for the padding token, usually filled in empty places in a string having fewer words than the required sequence length unk (str, optional): Label for the unknown tokens...
2
stack_v2_sparse_classes_30k_train_017935
Implement the Python class `WordEmbeddings` described below. Class description: Class for collection of word embeddings. Attributes: PAD (str): Label for the padding token UNK (str): Label for the unknown token Method signatures and docstrings: - def __init__(self, words, embeddings, pad='<pad>', unk='<unk>'): Initia...
Implement the Python class `WordEmbeddings` described below. Class description: Class for collection of word embeddings. Attributes: PAD (str): Label for the padding token UNK (str): Label for the unknown token Method signatures and docstrings: - def __init__(self, words, embeddings, pad='<pad>', unk='<unk>'): Initia...
4b7f027f339d5c4c20d0f215e6c770ce7296069c
<|skeleton|> class WordEmbeddings: """Class for collection of word embeddings. Attributes: PAD (str): Label for the padding token UNK (str): Label for the unknown token""" def __init__(self, words, embeddings, pad='<pad>', unk='<unk>'): """Initialize word embeddings Args: words (list): Words embeddings...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class WordEmbeddings: """Class for collection of word embeddings. Attributes: PAD (str): Label for the padding token UNK (str): Label for the unknown token""" def __init__(self, words, embeddings, pad='<pad>', unk='<unk>'): """Initialize word embeddings Args: words (list): Words embeddings (ndarray): W...
the_stack_v2_python_sparse
core/representations.py
fairhopeweb/pqai
train
0
5b8421a3b4c6cf55660d2c08c367e9e10d34dde9
[ "super().__init__()\nself.conv = nn.Conv2d(in_channels, out_channels, bias=False, **kwargs)\nself.bn = nn.BatchNorm2d(out_channels, eps=0.001)", "x = self.conv(x)\nx = self.bn(x)\nreturn F.relu(x)" ]
<|body_start_0|> super().__init__() self.conv = nn.Conv2d(in_channels, out_channels, bias=False, **kwargs) self.bn = nn.BatchNorm2d(out_channels, eps=0.001) <|end_body_0|> <|body_start_1|> x = self.conv(x) x = self.bn(x) return F.relu(x) <|end_body_1|>
Wrapper around conv + batchnorm + relu. `nn.Sequential` not used because of compatibility with pretrained network.
BasicConv2d
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BasicConv2d: """Wrapper around conv + batchnorm + relu. `nn.Sequential` not used because of compatibility with pretrained network.""" def __init__(self, in_channels, out_channels, **kwargs): """Init Convolutional Block.""" <|body_0|> def forward(self, x): """Forw...
stack_v2_sparse_classes_75kplus_train_006645
6,541
permissive
[ { "docstring": "Init Convolutional Block.", "name": "__init__", "signature": "def __init__(self, in_channels, out_channels, **kwargs)" }, { "docstring": "Forward propagation through convolutional block.", "name": "forward", "signature": "def forward(self, x)" } ]
2
stack_v2_sparse_classes_30k_train_003705
Implement the Python class `BasicConv2d` described below. Class description: Wrapper around conv + batchnorm + relu. `nn.Sequential` not used because of compatibility with pretrained network. Method signatures and docstrings: - def __init__(self, in_channels, out_channels, **kwargs): Init Convolutional Block. - def f...
Implement the Python class `BasicConv2d` described below. Class description: Wrapper around conv + batchnorm + relu. `nn.Sequential` not used because of compatibility with pretrained network. Method signatures and docstrings: - def __init__(self, in_channels, out_channels, **kwargs): Init Convolutional Block. - def f...
7a452e581edcd57ef5f0fa78c3a3d47224c80577
<|skeleton|> class BasicConv2d: """Wrapper around conv + batchnorm + relu. `nn.Sequential` not used because of compatibility with pretrained network.""" def __init__(self, in_channels, out_channels, **kwargs): """Init Convolutional Block.""" <|body_0|> def forward(self, x): """Forw...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BasicConv2d: """Wrapper around conv + batchnorm + relu. `nn.Sequential` not used because of compatibility with pretrained network.""" def __init__(self, in_channels, out_channels, **kwargs): """Init Convolutional Block.""" super().__init__() self.conv = nn.Conv2d(in_channels, out_...
the_stack_v2_python_sparse
crnns4captions/encoders/image_encoder.py
JackeyWang777/Deep-Representations-of-Visual-Descriptions
train
0
4b4063884185b7b4704e362fea7287d34b604f31
[ "super(RunGeneralTrampolineTest, self).setUp()\nrun.trampoline.PLATFORM = 'MY_PLATFORM'\nrun.trampoline.CONFIG = 'MY_CONFIG'", "expected_output = 'python starboard/tools/example/app_launcher_client.py --platform MY_PLATFORM --config MY_CONFIG --target_name cobalt'\ncmd_str = run._ResolveTrampoline(argv=['cobalt']...
<|body_start_0|> super(RunGeneralTrampolineTest, self).setUp() run.trampoline.PLATFORM = 'MY_PLATFORM' run.trampoline.CONFIG = 'MY_CONFIG' <|end_body_0|> <|body_start_1|> expected_output = 'python starboard/tools/example/app_launcher_client.py --platform MY_PLATFORM --config MY_CONFIG -...
Tests trampoline substitutions for run_cobalt.py.
RunGeneralTrampolineTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RunGeneralTrampolineTest: """Tests trampoline substitutions for run_cobalt.py.""" def setUp(self): """Change the trampoline internals for testing purposes.""" <|body_0|> def testOneTarget(self): """Tests that one target gets resolved.""" <|body_1|> d...
stack_v2_sparse_classes_75kplus_train_006646
2,430
permissive
[ { "docstring": "Change the trampoline internals for testing purposes.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Tests that one target gets resolved.", "name": "testOneTarget", "signature": "def testOneTarget(self)" }, { "docstring": "Tests that two targ...
4
stack_v2_sparse_classes_30k_train_050844
Implement the Python class `RunGeneralTrampolineTest` described below. Class description: Tests trampoline substitutions for run_cobalt.py. Method signatures and docstrings: - def setUp(self): Change the trampoline internals for testing purposes. - def testOneTarget(self): Tests that one target gets resolved. - def t...
Implement the Python class `RunGeneralTrampolineTest` described below. Class description: Tests trampoline substitutions for run_cobalt.py. Method signatures and docstrings: - def setUp(self): Change the trampoline internals for testing purposes. - def testOneTarget(self): Tests that one target gets resolved. - def t...
0b72f93b07285f3af3c8452ae2ceaf5860ca7c72
<|skeleton|> class RunGeneralTrampolineTest: """Tests trampoline substitutions for run_cobalt.py.""" def setUp(self): """Change the trampoline internals for testing purposes.""" <|body_0|> def testOneTarget(self): """Tests that one target gets resolved.""" <|body_1|> d...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RunGeneralTrampolineTest: """Tests trampoline substitutions for run_cobalt.py.""" def setUp(self): """Change the trampoline internals for testing purposes.""" super(RunGeneralTrampolineTest, self).setUp() run.trampoline.PLATFORM = 'MY_PLATFORM' run.trampoline.CONFIG = 'MY_...
the_stack_v2_python_sparse
src/cobalt/build/cobalt_archive_content/__cobalt_archive/run/impl/run_test.py
blockspacer/cobalt-clone-cab7770533804d582eaa66c713a1582f361182d3
train
1
fc41a59e80bb2035ac5532394e3796729040c759
[ "result = {'code': '1000', 'data': '', 'error': ''}\nif not check_login(token=request.query_params.get('token')):\n result['code'] = '1001'\n result['error'] = 'not valid token!'\n return Response(data=result)\ncollectives = Collective.objects.all()\ncollectives_data = CollectiveModelSerializer(instance=co...
<|body_start_0|> result = {'code': '1000', 'data': '', 'error': ''} if not check_login(token=request.query_params.get('token')): result['code'] = '1001' result['error'] = 'not valid token!' return Response(data=result) collectives = Collective.objects.all() ...
CollectiveView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CollectiveView: def get(self, request): """获取所有collective""" <|body_0|> def post(self, request): """添加collecitve""" <|body_1|> def put(self, request): """修改机柜""" <|body_2|> def delete(self, request): """删除机房""" <|body...
stack_v2_sparse_classes_75kplus_train_006647
2,693
no_license
[ { "docstring": "获取所有collective", "name": "get", "signature": "def get(self, request)" }, { "docstring": "添加collecitve", "name": "post", "signature": "def post(self, request)" }, { "docstring": "修改机柜", "name": "put", "signature": "def put(self, request)" }, { "docs...
4
null
Implement the Python class `CollectiveView` described below. Class description: Implement the CollectiveView class. Method signatures and docstrings: - def get(self, request): 获取所有collective - def post(self, request): 添加collecitve - def put(self, request): 修改机柜 - def delete(self, request): 删除机房
Implement the Python class `CollectiveView` described below. Class description: Implement the CollectiveView class. Method signatures and docstrings: - def get(self, request): 获取所有collective - def post(self, request): 添加collecitve - def put(self, request): 修改机柜 - def delete(self, request): 删除机房 <|skeleton|> class Co...
75565e674355cb5f8d558e0bb8ef1c2c9b289340
<|skeleton|> class CollectiveView: def get(self, request): """获取所有collective""" <|body_0|> def post(self, request): """添加collecitve""" <|body_1|> def put(self, request): """修改机柜""" <|body_2|> def delete(self, request): """删除机房""" <|body...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CollectiveView: def get(self, request): """获取所有collective""" result = {'code': '1000', 'data': '', 'error': ''} if not check_login(token=request.query_params.get('token')): result['code'] = '1001' result['error'] = 'not valid token!' return Response(...
the_stack_v2_python_sparse
api/views/collective_views.py
Sweetbob/om_backend
train
0
8e90ccbc1d636dbbc6ad35c03bf49577bbbdde39
[ "cls = self.model\nattr_list = cls._meta.get_all_field_names()\nreturn attr_list", "cls = self.model\nattr_list = cls._meta.get_fields()\nattr_str_list = []\nfor attr in attr_list:\n if isinstance(attr, models.ForeignKey):\n attr_str = '%s_id' % attr.name\n attr_str_list.append(attr_str)\n els...
<|body_start_0|> cls = self.model attr_list = cls._meta.get_all_field_names() return attr_list <|end_body_0|> <|body_start_1|> cls = self.model attr_list = cls._meta.get_fields() attr_str_list = [] for attr in attr_list: if isinstance(attr, models.For...
模型管理器类抽象基类
BaseModelManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseModelManager: """模型管理器类抽象基类""" def get_all_valid_fields(self): """获取模型管理器对象所在模型类的属性列表""" <|body_0|> def get_all_valid_fields2(self): """获取模型管理器对象所在模型类的属性列表""" <|body_1|> def create_one_object(self, **kwargs): """往数据库中插入一条模型管理器对象所在的模型类数据""...
stack_v2_sparse_classes_75kplus_train_006648
2,914
no_license
[ { "docstring": "获取模型管理器对象所在模型类的属性列表", "name": "get_all_valid_fields", "signature": "def get_all_valid_fields(self)" }, { "docstring": "获取模型管理器对象所在模型类的属性列表", "name": "get_all_valid_fields2", "signature": "def get_all_valid_fields2(self)" }, { "docstring": "往数据库中插入一条模型管理器对象所在的模型类数据...
5
stack_v2_sparse_classes_30k_train_034210
Implement the Python class `BaseModelManager` described below. Class description: 模型管理器类抽象基类 Method signatures and docstrings: - def get_all_valid_fields(self): 获取模型管理器对象所在模型类的属性列表 - def get_all_valid_fields2(self): 获取模型管理器对象所在模型类的属性列表 - def create_one_object(self, **kwargs): 往数据库中插入一条模型管理器对象所在的模型类数据 - def get_one_ob...
Implement the Python class `BaseModelManager` described below. Class description: 模型管理器类抽象基类 Method signatures and docstrings: - def get_all_valid_fields(self): 获取模型管理器对象所在模型类的属性列表 - def get_all_valid_fields2(self): 获取模型管理器对象所在模型类的属性列表 - def create_one_object(self, **kwargs): 往数据库中插入一条模型管理器对象所在的模型类数据 - def get_one_ob...
ac01a1cba0e0068cd33d30bfd60d2a5df6bc5114
<|skeleton|> class BaseModelManager: """模型管理器类抽象基类""" def get_all_valid_fields(self): """获取模型管理器对象所在模型类的属性列表""" <|body_0|> def get_all_valid_fields2(self): """获取模型管理器对象所在模型类的属性列表""" <|body_1|> def create_one_object(self, **kwargs): """往数据库中插入一条模型管理器对象所在的模型类数据""...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BaseModelManager: """模型管理器类抽象基类""" def get_all_valid_fields(self): """获取模型管理器对象所在模型类的属性列表""" cls = self.model attr_list = cls._meta.get_all_field_names() return attr_list def get_all_valid_fields2(self): """获取模型管理器对象所在模型类的属性列表""" cls = self.model ...
the_stack_v2_python_sparse
salesmindData/db/base_manager.py
piaoxue85/salesmindData
train
0
8d81bb9c8b41ab14b36a03783502ac168b695308
[ "if x == 0:\n return x\nif x > 0:\n str_x = str(x)\n reverse_str_x = str_x[::-1]\n reverse_x = int(reverse_str_x)\n if reverse_x < (-2) ** 31 or reverse_x > 2 ** 31 - 1:\n return 0\nelse:\n str_x = str(x)\n reverse_str_x = str_x[::-1]\n reverse_str_x = '-' + reverse_str_x.replace('-',...
<|body_start_0|> if x == 0: return x if x > 0: str_x = str(x) reverse_str_x = str_x[::-1] reverse_x = int(reverse_str_x) if reverse_x < (-2) ** 31 or reverse_x > 2 ** 31 - 1: return 0 else: str_x = str(x) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def reverse(self, x): """这个思路是将int转成str""" <|body_0|> def reverse2(self, x): """取余再除以10向下取整,这样可以逆序获取数字的各个位,再迭代乘以10就能计算出逆序数了""" <|body_1|> <|end_skeleton|> <|body_start_0|> if x == 0: return x if x > 0: str_x...
stack_v2_sparse_classes_75kplus_train_006649
1,691
no_license
[ { "docstring": "这个思路是将int转成str", "name": "reverse", "signature": "def reverse(self, x)" }, { "docstring": "取余再除以10向下取整,这样可以逆序获取数字的各个位,再迭代乘以10就能计算出逆序数了", "name": "reverse2", "signature": "def reverse2(self, x)" } ]
2
stack_v2_sparse_classes_30k_test_001403
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverse(self, x): 这个思路是将int转成str - def reverse2(self, x): 取余再除以10向下取整,这样可以逆序获取数字的各个位,再迭代乘以10就能计算出逆序数了
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverse(self, x): 这个思路是将int转成str - def reverse2(self, x): 取余再除以10向下取整,这样可以逆序获取数字的各个位,再迭代乘以10就能计算出逆序数了 <|skeleton|> class Solution: def reverse(self, x): """这个思路...
86e4a46de635c74d7c80c3d186d21d79cfb7a640
<|skeleton|> class Solution: def reverse(self, x): """这个思路是将int转成str""" <|body_0|> def reverse2(self, x): """取余再除以10向下取整,这样可以逆序获取数字的各个位,再迭代乘以10就能计算出逆序数了""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def reverse(self, x): """这个思路是将int转成str""" if x == 0: return x if x > 0: str_x = str(x) reverse_str_x = str_x[::-1] reverse_x = int(reverse_str_x) if reverse_x < (-2) ** 31 or reverse_x > 2 ** 31 - 1: ...
the_stack_v2_python_sparse
leetcode/02整数反转.py
fairypeng/a_python_note
train
0
7ca2ffee369143d1e082a433f1239bdd4071a83f
[ "if cls._instance is None:\n cls._instance = super(SQLConfig, cls).__new__(cls)\nreturn cls._instance", "uri = ConfigurationManager().get_value('core', 'catalog_database_uri')\nself.engine = create_engine(uri)\nself.session = scoped_session(sessionmaker(bind=self.engine))" ]
<|body_start_0|> if cls._instance is None: cls._instance = super(SQLConfig, cls).__new__(cls) return cls._instance <|end_body_0|> <|body_start_1|> uri = ConfigurationManager().get_value('core', 'catalog_database_uri') self.engine = create_engine(uri) self.session = s...
Singleton class for configuring connection to the database. Attributes: _instance: stores the singleton instance of the class.
SQLConfig
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SQLConfig: """Singleton class for configuring connection to the database. Attributes: _instance: stores the singleton instance of the class.""" def __new__(cls): """Overrides the default __new__ method. Returns the existing instance or creates a new one if an instance does not exist....
stack_v2_sparse_classes_75kplus_train_006650
1,746
permissive
[ { "docstring": "Overrides the default __new__ method. Returns the existing instance or creates a new one if an instance does not exist. Returns: An instance of the class.", "name": "__new__", "signature": "def __new__(cls)" }, { "docstring": "Initializes the engine and session for database opera...
2
null
Implement the Python class `SQLConfig` described below. Class description: Singleton class for configuring connection to the database. Attributes: _instance: stores the singleton instance of the class. Method signatures and docstrings: - def __new__(cls): Overrides the default __new__ method. Returns the existing ins...
Implement the Python class `SQLConfig` described below. Class description: Singleton class for configuring connection to the database. Attributes: _instance: stores the singleton instance of the class. Method signatures and docstrings: - def __new__(cls): Overrides the default __new__ method. Returns the existing ins...
6462881e30a2b26756d315a02be17260bf5e184e
<|skeleton|> class SQLConfig: """Singleton class for configuring connection to the database. Attributes: _instance: stores the singleton instance of the class.""" def __new__(cls): """Overrides the default __new__ method. Returns the existing instance or creates a new one if an instance does not exist....
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SQLConfig: """Singleton class for configuring connection to the database. Attributes: _instance: stores the singleton instance of the class.""" def __new__(cls): """Overrides the default __new__ method. Returns the existing instance or creates a new one if an instance does not exist. Returns: An ...
the_stack_v2_python_sparse
eva/catalog/sql_config.py
jarulraj/eva
train
1
9ad801a0a1a8d9928fd4ff38598bd752efce7cfa
[ "self.working_directory = working_directory\nself.num_epochs = num_epochs\nself.batch_size = batch_size\nself.lr = lr\nself.wd = wd\nself.drop_prob = drop_prob\nself.debug = debug\nself.scheme = scheme\nself.warmstart_dir = warmstart_dir\nself.dataset = dataset\nself.n_workers = n_workers\nself.data_path = 'data/ti...
<|body_start_0|> self.working_directory = working_directory self.num_epochs = num_epochs self.batch_size = batch_size self.lr = lr self.wd = wd self.drop_prob = drop_prob self.debug = debug self.scheme = scheme self.warmstart_dir = warmstart_dir ...
DARTSWorker
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DARTSWorker: def __init__(self, working_directory, num_epochs, batch_size, *args, scheme='nes_re', dataset='fmnist', warmstart_dir=None, debug=False, n_workers=4, only_predict=False, lr=0.025, wd=0.0003, drop_prob=0.3, anchor=False, anch_coeff=1, full_train=False, n_datapoints=None, oneshot=Fals...
stack_v2_sparse_classes_75kplus_train_006651
7,772
permissive
[ { "docstring": "Args: working_directory (str): directory where results are written num_epochs (int): number of total epochs to train the baselearner batch_size (int): mini-batch size during training scheme (str): scheme name dataset (str): dataset name warmstart_dir (str): directory where previous results are s...
3
stack_v2_sparse_classes_30k_test_001939
Implement the Python class `DARTSWorker` described below. Class description: Implement the DARTSWorker class. Method signatures and docstrings: - def __init__(self, working_directory, num_epochs, batch_size, *args, scheme='nes_re', dataset='fmnist', warmstart_dir=None, debug=False, n_workers=4, only_predict=False, lr...
Implement the Python class `DARTSWorker` described below. Class description: Implement the DARTSWorker class. Method signatures and docstrings: - def __init__(self, working_directory, num_epochs, batch_size, *args, scheme='nes_re', dataset='fmnist', warmstart_dir=None, debug=False, n_workers=4, only_predict=False, lr...
1c54786c30acd6e19eb9708204bffc86b58ea272
<|skeleton|> class DARTSWorker: def __init__(self, working_directory, num_epochs, batch_size, *args, scheme='nes_re', dataset='fmnist', warmstart_dir=None, debug=False, n_workers=4, only_predict=False, lr=0.025, wd=0.0003, drop_prob=0.3, anchor=False, anch_coeff=1, full_train=False, n_datapoints=None, oneshot=Fals...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DARTSWorker: def __init__(self, working_directory, num_epochs, batch_size, *args, scheme='nes_re', dataset='fmnist', warmstart_dir=None, debug=False, n_workers=4, only_predict=False, lr=0.025, wd=0.0003, drop_prob=0.3, anchor=False, anch_coeff=1, full_train=False, n_datapoints=None, oneshot=False, saved_model...
the_stack_v2_python_sparse
nes/darts/worker.py
automl/nes
train
33
ae24b7eea7a73b587ec50156b601339ef5e3ae8d
[ "parameters = json_parameters()\nbytes_param = param_get(parameters, 'bytes')\ntry:\n set_global_account_limit(account=account, rse_expression=rse_expression, bytes_=bytes_param, issuer=request.environ.get('issuer'), vo=request.environ.get('vo'))\nexcept AccessDenied as error:\n return generate_http_error_fla...
<|body_start_0|> parameters = json_parameters() bytes_param = param_get(parameters, 'bytes') try: set_global_account_limit(account=account, rse_expression=rse_expression, bytes_=bytes_param, issuer=request.environ.get('issuer'), vo=request.environ.get('vo')) except AccessDeni...
GlobalAccountLimit
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GlobalAccountLimit: def post(self, account, rse_expression): """--- summary: Create or update a global account limit tags: - Account Limit parameters: - name: account in: path description: The account for the accountlimit. schema: type: string style: simple - name: rse_expression in: pat...
stack_v2_sparse_classes_75kplus_train_006652
7,826
permissive
[ { "docstring": "--- summary: Create or update a global account limit tags: - Account Limit parameters: - name: account in: path description: The account for the accountlimit. schema: type: string style: simple - name: rse_expression in: path description: The rse expression for the accountlimit. schema: type: st...
2
stack_v2_sparse_classes_30k_train_029967
Implement the Python class `GlobalAccountLimit` described below. Class description: Implement the GlobalAccountLimit class. Method signatures and docstrings: - def post(self, account, rse_expression): --- summary: Create or update a global account limit tags: - Account Limit parameters: - name: account in: path descr...
Implement the Python class `GlobalAccountLimit` described below. Class description: Implement the GlobalAccountLimit class. Method signatures and docstrings: - def post(self, account, rse_expression): --- summary: Create or update a global account limit tags: - Account Limit parameters: - name: account in: path descr...
7f0d229ac0b3bc7dec12c6e158bea2b82d414a3b
<|skeleton|> class GlobalAccountLimit: def post(self, account, rse_expression): """--- summary: Create or update a global account limit tags: - Account Limit parameters: - name: account in: path description: The account for the accountlimit. schema: type: string style: simple - name: rse_expression in: pat...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GlobalAccountLimit: def post(self, account, rse_expression): """--- summary: Create or update a global account limit tags: - Account Limit parameters: - name: account in: path description: The account for the accountlimit. schema: type: string style: simple - name: rse_expression in: path description:...
the_stack_v2_python_sparse
lib/rucio/web/rest/flaskapi/v1/accountlimits.py
rucio/rucio
train
232
6cc4ec51c925de0573ce6257b0ee58f69178311f
[ "item = Event.get_by_id(item_id)\nif item is None:\n abort(404)\nreturn item", "item = Event.get_by_id(item_id)\nif item is None:\n abort(404)\nblp.check_etag(item, EventSchema)\nitem.delete()" ]
<|body_start_0|> item = Event.get_by_id(item_id) if item is None: abort(404) return item <|end_body_0|> <|body_start_1|> item = Event.get_by_id(item_id) if item is None: abort(404) blp.check_etag(item, EventSchema) item.delete() <|end_body...
EventsByIdViews
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EventsByIdViews: def get(self, item_id): """Get en event by its ID""" <|body_0|> def delete(self, item_id): """Delete an event""" <|body_1|> <|end_skeleton|> <|body_start_0|> item = Event.get_by_id(item_id) if item is None: abort...
stack_v2_sparse_classes_75kplus_train_006653
3,771
no_license
[ { "docstring": "Get en event by its ID", "name": "get", "signature": "def get(self, item_id)" }, { "docstring": "Delete an event", "name": "delete", "signature": "def delete(self, item_id)" } ]
2
stack_v2_sparse_classes_30k_train_035883
Implement the Python class `EventsByIdViews` described below. Class description: Implement the EventsByIdViews class. Method signatures and docstrings: - def get(self, item_id): Get en event by its ID - def delete(self, item_id): Delete an event
Implement the Python class `EventsByIdViews` described below. Class description: Implement the EventsByIdViews class. Method signatures and docstrings: - def get(self, item_id): Get en event by its ID - def delete(self, item_id): Delete an event <|skeleton|> class EventsByIdViews: def get(self, item_id): ...
96768e453c2714085bb4cb8ae2253139bd61f9a3
<|skeleton|> class EventsByIdViews: def get(self, item_id): """Get en event by its ID""" <|body_0|> def delete(self, item_id): """Delete an event""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EventsByIdViews: def get(self, item_id): """Get en event by its ID""" item = Event.get_by_id(item_id) if item is None: abort(404) return item def delete(self, item_id): """Delete an event""" item = Event.get_by_id(item_id) if item is Non...
the_stack_v2_python_sparse
bemserver/app/api/resources/events/routes.py
Nobatek/bemserver
train
0
f3fd0dfd6d99cefce7a892b028188061fa4bf2ef
[ "if context is None:\n context = {}\nif not date:\n date = time.strftime('%Y-%m-%d')\nperiod_ids = self.find(cr, uid, date, context=context)\ndo = [('special', '=', False), ('id', 'in', period_ids)]\ndemo_enabled = self.pool.get('ir.module.module').search(cr, uid, [('name', '=', 'base'), ('demo', '=', True)])...
<|body_start_0|> if context is None: context = {} if not date: date = time.strftime('%Y-%m-%d') period_ids = self.find(cr, uid, date, context=context) do = [('special', '=', False), ('id', 'in', period_ids)] demo_enabled = self.pool.get('ir.module.module')...
AccountPeriod
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AccountPeriod: def _find_fortnight(self, cr, uid, date=None, context=None): """This Function returns a tuple composed of *) period for the asked dt (int) *) fortnight for the asked dt (boolean): -) False: for the 1st. fortnight -) True: for the 2nd. fortnight. Example: (3,True) => a peri...
stack_v2_sparse_classes_75kplus_train_006654
5,861
no_license
[ { "docstring": "This Function returns a tuple composed of *) period for the asked dt (int) *) fortnight for the asked dt (boolean): -) False: for the 1st. fortnight -) True: for the 2nd. fortnight. Example: (3,True) => a period whose id is 3 in the second fortnight", "name": "_find_fortnight", "signatur...
2
stack_v2_sparse_classes_30k_train_029934
Implement the Python class `AccountPeriod` described below. Class description: Implement the AccountPeriod class. Method signatures and docstrings: - def _find_fortnight(self, cr, uid, date=None, context=None): This Function returns a tuple composed of *) period for the asked dt (int) *) fortnight for the asked dt (b...
Implement the Python class `AccountPeriod` described below. Class description: Implement the AccountPeriod class. Method signatures and docstrings: - def _find_fortnight(self, cr, uid, date=None, context=None): This Function returns a tuple composed of *) period for the asked dt (int) *) fortnight for the asked dt (b...
718327d01e5b4408add58682c5ad1901fa35b450
<|skeleton|> class AccountPeriod: def _find_fortnight(self, cr, uid, date=None, context=None): """This Function returns a tuple composed of *) period for the asked dt (int) *) fortnight for the asked dt (boolean): -) False: for the 1st. fortnight -) True: for the 2nd. fortnight. Example: (3,True) => a peri...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AccountPeriod: def _find_fortnight(self, cr, uid, date=None, context=None): """This Function returns a tuple composed of *) period for the asked dt (int) *) fortnight for the asked dt (boolean): -) False: for the 1st. fortnight -) True: for the 2nd. fortnight. Example: (3,True) => a period whose id is...
the_stack_v2_python_sparse
l10n_ve_withholding/model/account.py
Vauxoo/odoo-venezuela
train
15
4eec6083dc452e480ebafcef060e9d214589a7eb
[ "super(ServerFromVolumeWithAttachmentsMigrateTests, cls).setUpClass()\ncls.create_server()\ncls.resources.add(cls.server.id, cls.confirm_server_deleted)\nnum_volumes_to_attach = 2\ncls.attached_volumes = list()\nfor i in range(num_volumes_to_attach):\n volume = cls.compute_integration.volumes.behaviors.create_av...
<|body_start_0|> super(ServerFromVolumeWithAttachmentsMigrateTests, cls).setUpClass() cls.create_server() cls.resources.add(cls.server.id, cls.confirm_server_deleted) num_volumes_to_attach = 2 cls.attached_volumes = list() for i in range(num_volumes_to_attach): ...
ServerFromVolumeWithAttachmentsMigrateTests
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ServerFromVolumeWithAttachmentsMigrateTests: def setUpClass(cls): """Create and migrate a server from volume with multiple attachments The following resources are created during this setup: - Create an active server.""" <|body_0|> def confirm_server_deleted(cls, server_id): ...
stack_v2_sparse_classes_75kplus_train_006655
6,345
permissive
[ { "docstring": "Create and migrate a server from volume with multiple attachments The following resources are created during this setup: - Create an active server.", "name": "setUpClass", "signature": "def setUpClass(cls)" }, { "docstring": "Confirm the server resource has been deleted This meth...
4
null
Implement the Python class `ServerFromVolumeWithAttachmentsMigrateTests` described below. Class description: Implement the ServerFromVolumeWithAttachmentsMigrateTests class. Method signatures and docstrings: - def setUpClass(cls): Create and migrate a server from volume with multiple attachments The following resourc...
Implement the Python class `ServerFromVolumeWithAttachmentsMigrateTests` described below. Class description: Implement the ServerFromVolumeWithAttachmentsMigrateTests class. Method signatures and docstrings: - def setUpClass(cls): Create and migrate a server from volume with multiple attachments The following resourc...
30f0e64672676c3f90b4a582fe90fac6621475b3
<|skeleton|> class ServerFromVolumeWithAttachmentsMigrateTests: def setUpClass(cls): """Create and migrate a server from volume with multiple attachments The following resources are created during this setup: - Create an active server.""" <|body_0|> def confirm_server_deleted(cls, server_id): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ServerFromVolumeWithAttachmentsMigrateTests: def setUpClass(cls): """Create and migrate a server from volume with multiple attachments The following resources are created during this setup: - Create an active server.""" super(ServerFromVolumeWithAttachmentsMigrateTests, cls).setUpClass() ...
the_stack_v2_python_sparse
cloudroast/compute/integration/volumes/boot_from_volume/admin_api/v2/test_migrate_server_with_attachments.py
RULCSoft/cloudroast
train
1
23cd1e03fabbd2a8eced9dd99fa6edf183dbf6a3
[ "n = len(nums)\npairs = set()\nfor i in range(n - 1):\n for j in range(i + 1, n):\n if nums[i] > nums[j]:\n pair = (nums[i], nums[j])\n else:\n pair = (nums[j], nums[i])\n if abs(nums[j] - nums[i]) == k and pair not in pairs:\n pairs.add(pair)\nreturn len(pai...
<|body_start_0|> n = len(nums) pairs = set() for i in range(n - 1): for j in range(i + 1, n): if nums[i] > nums[j]: pair = (nums[i], nums[j]) else: pair = (nums[j], nums[i]) if abs(nums[j] - nums[...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def find_pairs_brute(self, nums, k): """Returns number of unique k-diff pairs(i, j) such as |i - j| = k. Naive algorithm. Checks all possible pairs of i, j, adds it to the set of unique pairs, where each pair is a tuple(min int, max int). Time complexity: O(n ^ 2). Space comple...
stack_v2_sparse_classes_75kplus_train_006656
2,909
no_license
[ { "docstring": "Returns number of unique k-diff pairs(i, j) such as |i - j| = k. Naive algorithm. Checks all possible pairs of i, j, adds it to the set of unique pairs, where each pair is a tuple(min int, max int). Time complexity: O(n ^ 2). Space complexity: O(n), where n is len(nums).", "name": "find_pair...
4
stack_v2_sparse_classes_30k_train_003064
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def find_pairs_brute(self, nums, k): Returns number of unique k-diff pairs(i, j) such as |i - j| = k. Naive algorithm. Checks all possible pairs of i, j, adds it to the set of un...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def find_pairs_brute(self, nums, k): Returns number of unique k-diff pairs(i, j) such as |i - j| = k. Naive algorithm. Checks all possible pairs of i, j, adds it to the set of un...
71b722ddfe8da04572e527b055cf8723d5c87bbf
<|skeleton|> class Solution: def find_pairs_brute(self, nums, k): """Returns number of unique k-diff pairs(i, j) such as |i - j| = k. Naive algorithm. Checks all possible pairs of i, j, adds it to the set of unique pairs, where each pair is a tuple(min int, max int). Time complexity: O(n ^ 2). Space comple...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def find_pairs_brute(self, nums, k): """Returns number of unique k-diff pairs(i, j) such as |i - j| = k. Naive algorithm. Checks all possible pairs of i, j, adds it to the set of unique pairs, where each pair is a tuple(min int, max int). Time complexity: O(n ^ 2). Space complexity: O(n), wh...
the_stack_v2_python_sparse
Arrays/kdiff_pairs.py
vladn90/Algorithms
train
0
bc6136c8d3d0334ffae535b8adb6cbcf6b89ea1d
[ "uglys = [1]\nugly2 = ugly3 = ugly5 = 0\nwhile len(uglys) < n:\n ugnext2, ugnext3, ugnext5 = (uglys[ugly2] * 2, uglys[ugly3] * 3, uglys[ugly5] * 5)\n if ugnext2 <= ugnext3 and ugnext2 <= ugnext5:\n ugly2 += 1\n if ugnext2 not in uglys:\n uglys.append(ugnext2)\n continue\n if...
<|body_start_0|> uglys = [1] ugly2 = ugly3 = ugly5 = 0 while len(uglys) < n: ugnext2, ugnext3, ugnext5 = (uglys[ugly2] * 2, uglys[ugly3] * 3, uglys[ugly5] * 5) if ugnext2 <= ugnext3 and ugnext2 <= ugnext5: ugly2 += 1 if ugnext2 not in uglys...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def nthUglyNumber(self, n): """:type n: int :rtype: int""" <|body_0|> def nthUglyNumber2(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> uglys = [1] ugly2 = ugly3 = ugly5 = 0 while len(...
stack_v2_sparse_classes_75kplus_train_006657
1,534
no_license
[ { "docstring": ":type n: int :rtype: int", "name": "nthUglyNumber", "signature": "def nthUglyNumber(self, n)" }, { "docstring": ":type n: int :rtype: int", "name": "nthUglyNumber2", "signature": "def nthUglyNumber2(self, n)" } ]
2
stack_v2_sparse_classes_30k_train_040971
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def nthUglyNumber(self, n): :type n: int :rtype: int - def nthUglyNumber2(self, n): :type n: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def nthUglyNumber(self, n): :type n: int :rtype: int - def nthUglyNumber2(self, n): :type n: int :rtype: int <|skeleton|> class Solution: def nthUglyNumber(self, n): ...
0fc4c7af59246e3064db41989a45d9db413a624b
<|skeleton|> class Solution: def nthUglyNumber(self, n): """:type n: int :rtype: int""" <|body_0|> def nthUglyNumber2(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def nthUglyNumber(self, n): """:type n: int :rtype: int""" uglys = [1] ugly2 = ugly3 = ugly5 = 0 while len(uglys) < n: ugnext2, ugnext3, ugnext5 = (uglys[ugly2] * 2, uglys[ugly3] * 3, uglys[ugly5] * 5) if ugnext2 <= ugnext3 and ugnext2 <= ugnex...
the_stack_v2_python_sparse
264. Ugly Number II/ugly2.py
Macielyoung/LeetCode
train
1
90f663bc6908576487452747db412406e0607c97
[ "a = 4.2\nb = 2.1\nself.fail('Write a single line expression')\nself.assertEqual(float(c), 6.3)", "a = 1.3\nb = 1.7\nself.fail('Do the calculation and round the result')\nself.assertEqual(float(c), 0.765)" ]
<|body_start_0|> a = 4.2 b = 2.1 self.fail('Write a single line expression') self.assertEqual(float(c), 6.3) <|end_body_0|> <|body_start_1|> a = 1.3 b = 1.7 self.fail('Do the calculation and round the result') self.assertEqual(float(c), 0.765) <|end_body_...
PerformingAccurateDecimalCalculationsTest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PerformingAccurateDecimalCalculationsTest: def test_perform_accurate_calculation(self): """Hint: add the variables together but note that adding them as floats will not give the desired result due to floating point inaccuracies.""" <|body_0|> def test_divide_a_by_b_and_round...
stack_v2_sparse_classes_75kplus_train_006658
8,669
no_license
[ { "docstring": "Hint: add the variables together but note that adding them as floats will not give the desired result due to floating point inaccuracies.", "name": "test_perform_accurate_calculation", "signature": "def test_perform_accurate_calculation(self)" }, { "docstring": "Hint: don't use f...
2
null
Implement the Python class `PerformingAccurateDecimalCalculationsTest` described below. Class description: Implement the PerformingAccurateDecimalCalculationsTest class. Method signatures and docstrings: - def test_perform_accurate_calculation(self): Hint: add the variables together but note that adding them as float...
Implement the Python class `PerformingAccurateDecimalCalculationsTest` described below. Class description: Implement the PerformingAccurateDecimalCalculationsTest class. Method signatures and docstrings: - def test_perform_accurate_calculation(self): Hint: add the variables together but note that adding them as float...
b0b47df00aac7423b91f196ec7e041fac1937aef
<|skeleton|> class PerformingAccurateDecimalCalculationsTest: def test_perform_accurate_calculation(self): """Hint: add the variables together but note that adding them as floats will not give the desired result due to floating point inaccuracies.""" <|body_0|> def test_divide_a_by_b_and_round...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PerformingAccurateDecimalCalculationsTest: def test_perform_accurate_calculation(self): """Hint: add the variables together but note that adding them as floats will not give the desired result due to floating point inaccuracies.""" a = 4.2 b = 2.1 self.fail('Write a single line...
the_stack_v2_python_sparse
pythoncookbook/chapter3_tests.py
wkeeling/kata
train
1
a0b315d5a1255de285c4c34f43247624c1f616d0
[ "polling_interval = kwargs.pop('_polling_interval', 5)\nsas_parameter = self._models.SASTokenParameter(storage_resource_uri=blob_storage_url, token=sas_token)\ncontinuation_token = kwargs.pop('continuation_token', None)\nstatus_response = None\nif continuation_token:\n status_url = base64.b64decode(continuation_...
<|body_start_0|> polling_interval = kwargs.pop('_polling_interval', 5) sas_parameter = self._models.SASTokenParameter(storage_resource_uri=blob_storage_url, token=sas_token) continuation_token = kwargs.pop('continuation_token', None) status_response = None if continuation_token: ...
Performs Key Vault backup and restore operations. :param str vault_url: URL of the vault on which the client will operate. This is also called the vault's "DNS Name". You should validate that this URL references a valid Key Vault or Managed HSM resource. See https://aka.ms/azsdk/blog/vault-uri for details. :param crede...
KeyVaultBackupClient
[ "LicenseRef-scancode-generic-cla", "MIT", "LGPL-2.1-or-later" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KeyVaultBackupClient: """Performs Key Vault backup and restore operations. :param str vault_url: URL of the vault on which the client will operate. This is also called the vault's "DNS Name". You should validate that this URL references a valid Key Vault or Managed HSM resource. See https://aka.m...
stack_v2_sparse_classes_75kplus_train_006659
8,812
permissive
[ { "docstring": "Begin a full backup of the Key Vault. :param str blob_storage_url: URL of the blob storage container in which the backup will be stored, for example https://<account>.blob.core.windows.net/backup :param str sas_token: a Shared Access Signature (SAS) token authorizing access to the blob storage r...
2
null
Implement the Python class `KeyVaultBackupClient` described below. Class description: Performs Key Vault backup and restore operations. :param str vault_url: URL of the vault on which the client will operate. This is also called the vault's "DNS Name". You should validate that this URL references a valid Key Vault or ...
Implement the Python class `KeyVaultBackupClient` described below. Class description: Performs Key Vault backup and restore operations. :param str vault_url: URL of the vault on which the client will operate. This is also called the vault's "DNS Name". You should validate that this URL references a valid Key Vault or ...
c2ca191e736bb06bfbbbc9493e8325763ba990bb
<|skeleton|> class KeyVaultBackupClient: """Performs Key Vault backup and restore operations. :param str vault_url: URL of the vault on which the client will operate. This is also called the vault's "DNS Name". You should validate that this URL references a valid Key Vault or Managed HSM resource. See https://aka.m...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class KeyVaultBackupClient: """Performs Key Vault backup and restore operations. :param str vault_url: URL of the vault on which the client will operate. This is also called the vault's "DNS Name". You should validate that this URL references a valid Key Vault or Managed HSM resource. See https://aka.ms/azsdk/blog/...
the_stack_v2_python_sparse
sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/aio/_backup_client.py
Azure/azure-sdk-for-python
train
4,046
bec069374fa8aeccb9c709d91a59229897697fa3
[ "self.deal = deal\nself.action = action\nself.bet = bet\nself.player = player", "if self.player == CHANCE:\n return ', '.join((INT2STRING_CARD[c] for c in self.deal))\nelse:\n return INT2STRING_ACTION[self.action]" ]
<|body_start_0|> self.deal = deal self.action = action self.bet = bet self.player = player <|end_body_0|> <|body_start_1|> if self.player == CHANCE: return ', '.join((INT2STRING_CARD[c] for c in self.deal)) else: return INT2STRING_ACTION[self.acti...
Action object of env: Texas Hold'em.
Action
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Action: """Action object of env: Texas Hold'em.""" def __init__(self, deal=None, action=None, bet=0, player=-1): """Init the action instance.""" <|body_0|> def to_string(self): """Return a string representing this action.""" <|body_1|> <|end_skeleton|> ...
stack_v2_sparse_classes_75kplus_train_006660
10,184
no_license
[ { "docstring": "Init the action instance.", "name": "__init__", "signature": "def __init__(self, deal=None, action=None, bet=0, player=-1)" }, { "docstring": "Return a string representing this action.", "name": "to_string", "signature": "def to_string(self)" } ]
2
stack_v2_sparse_classes_30k_train_016365
Implement the Python class `Action` described below. Class description: Action object of env: Texas Hold'em. Method signatures and docstrings: - def __init__(self, deal=None, action=None, bet=0, player=-1): Init the action instance. - def to_string(self): Return a string representing this action.
Implement the Python class `Action` described below. Class description: Action object of env: Texas Hold'em. Method signatures and docstrings: - def __init__(self, deal=None, action=None, bet=0, player=-1): Init the action instance. - def to_string(self): Return a string representing this action. <|skeleton|> class ...
3514a0ea315b36dd9545bd2cfe36bd6c099ee1d7
<|skeleton|> class Action: """Action object of env: Texas Hold'em.""" def __init__(self, deal=None, action=None, bet=0, player=-1): """Init the action instance.""" <|body_0|> def to_string(self): """Return a string representing this action.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Action: """Action object of env: Texas Hold'em.""" def __init__(self, deal=None, action=None, bet=0, player=-1): """Init the action instance.""" self.deal = deal self.action = action self.bet = bet self.player = player def to_string(self): """Return a ...
the_stack_v2_python_sparse
env/texas_holdem/texas_holdem_char.py
orange9426/FOGs
train
1
4a827327ad662616764ffd6e385900e37a073311
[ "n = 3\nU1 = random_interferometer(n)\nU2 = random_interferometer(n)\nint1 = ops.Interferometer(U1)\nint1inv = ops.Interferometer(U1.conj().T)\nint2 = ops.Interferometer(U2)\nassert int1.merge(int1inv) is None\nassert np.allclose(int1.merge(int2).p[0].x, U2 @ U1, atol=tol, rtol=0)", "prog = sf.Program(2)\nG = ops...
<|body_start_0|> n = 3 U1 = random_interferometer(n) U2 = random_interferometer(n) int1 = ops.Interferometer(U1) int1inv = ops.Interferometer(U1.conj().T) int2 = ops.Interferometer(U2) assert int1.merge(int1inv) is None assert np.allclose(int1.merge(int2)....
Tests for the interferometer quantum operation
TestInterferometer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestInterferometer: """Tests for the interferometer quantum operation""" def test_merge(self, tol): """Test that two interferometers merge: U = U1 @ U2""" <|body_0|> def test_identity(self): """Test that nothing is done if the unitary is the identity""" <...
stack_v2_sparse_classes_75kplus_train_006661
18,974
permissive
[ { "docstring": "Test that two interferometers merge: U = U1 @ U2", "name": "test_merge", "signature": "def test_merge(self, tol)" }, { "docstring": "Test that nothing is done if the unitary is the identity", "name": "test_identity", "signature": "def test_identity(self)" }, { "do...
3
null
Implement the Python class `TestInterferometer` described below. Class description: Tests for the interferometer quantum operation Method signatures and docstrings: - def test_merge(self, tol): Test that two interferometers merge: U = U1 @ U2 - def test_identity(self): Test that nothing is done if the unitary is the ...
Implement the Python class `TestInterferometer` described below. Class description: Tests for the interferometer quantum operation Method signatures and docstrings: - def test_merge(self, tol): Test that two interferometers merge: U = U1 @ U2 - def test_identity(self): Test that nothing is done if the unitary is the ...
0c1c805fd5dfce465a8955ee3faf81037023a23e
<|skeleton|> class TestInterferometer: """Tests for the interferometer quantum operation""" def test_merge(self, tol): """Test that two interferometers merge: U = U1 @ U2""" <|body_0|> def test_identity(self): """Test that nothing is done if the unitary is the identity""" <...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestInterferometer: """Tests for the interferometer quantum operation""" def test_merge(self, tol): """Test that two interferometers merge: U = U1 @ U2""" n = 3 U1 = random_interferometer(n) U2 = random_interferometer(n) int1 = ops.Interferometer(U1) int1in...
the_stack_v2_python_sparse
artifacts/old_dataset_versions/minimal_commits_v02/strawberryfields/strawberryfields#90/after/test_ops_decompositions.py
MattePalte/Bugs-Quantum-Computing-Platforms
train
4
e7db9f3933cff09ba49a0b98e5843a5906529f0c
[ "super().__init__(estimator, slices, estimator_i)\nif estimator_n is None:\n self.estimator_n = list(range(len(estimator)))\nelse:\n self.estimator_n = estimator_n\nassert len(self.estimator) >= 2\nassert len(self.estimator_n) >= 2\nself.n_jobs = n_jobs", "slices = [tuple(_) for _ in self.slices]\nif not pr...
<|body_start_0|> super().__init__(estimator, slices, estimator_i) if estimator_n is None: self.estimator_n = list(range(len(estimator))) else: self.estimator_n = estimator_n assert len(self.estimator) >= 2 assert len(self.estimator_n) >= 2 self.n_j...
union grouping selection calculate the predict_y on node, for each base estimator calculate the distance of predict_y, for each base estimator cluster the nodes by distance and get groups, for each base estimator unite groups of base estimators to tournament groups select the candidate nodes in each groups with penalty...
UGS
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UGS: """union grouping selection calculate the predict_y on node, for each base estimator calculate the distance of predict_y, for each base estimator cluster the nodes by distance and get groups, for each base estimator unite groups of base estimators to tournament groups select the candidate no...
stack_v2_sparse_classes_75kplus_train_006662
24,066
permissive
[ { "docstring": "Parameters ---------- estimator : list list of base estimator or GridSearchCV from sklearn slices: list the lists of the index of feature subsets, each feature subset is a node,each int is the index of X Examples 3 nodes [[1,4,5],[1,4,6],[1,2,7]] estimator_n: list default indexes of estimator", ...
3
stack_v2_sparse_classes_30k_train_030920
Implement the Python class `UGS` described below. Class description: union grouping selection calculate the predict_y on node, for each base estimator calculate the distance of predict_y, for each base estimator cluster the nodes by distance and get groups, for each base estimator unite groups of base estimators to to...
Implement the Python class `UGS` described below. Class description: union grouping selection calculate the predict_y on node, for each base estimator calculate the distance of predict_y, for each base estimator cluster the nodes by distance and get groups, for each base estimator unite groups of base estimators to to...
92863075410ba308b3e19aefaaae2a4077764eb0
<|skeleton|> class UGS: """union grouping selection calculate the predict_y on node, for each base estimator calculate the distance of predict_y, for each base estimator cluster the nodes by distance and get groups, for each base estimator unite groups of base estimators to tournament groups select the candidate no...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UGS: """union grouping selection calculate the predict_y on node, for each base estimator calculate the distance of predict_y, for each base estimator cluster the nodes by distance and get groups, for each base estimator unite groups of base estimators to tournament groups select the candidate nodes in each g...
the_stack_v2_python_sparse
featurebox/selection/ugs.py
ghayth82/featurebox
train
0
ef3e807b11976a760c758e129939ce6e437ffae1
[ "super(LDASynthesis, self).__init__(name=name)\nself.estimators = pickle.loads(params)\nself.nb_bins = len(self.estimators)\nself.select = select", "frame = frame.reshape((1, -1))\nreco = np.empty(self.nb_bins)\nfor spec_bin, est in enumerate(self.estimators):\n reco[spec_bin] = est.predict(frame[:, self.selec...
<|body_start_0|> super(LDASynthesis, self).__init__(name=name) self.estimators = pickle.loads(params) self.nb_bins = len(self.estimators) self.select = select <|end_body_0|> <|body_start_1|> frame = frame.reshape((1, -1)) reco = np.empty(self.nb_bins) for spec_bi...
Predict quantized units based on LDA estimators
LDASynthesis
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LDASynthesis: """Predict quantized units based on LDA estimators""" def __init__(self, params, select, name='LDASynthesis'): """Initializing all linear models for each spectral bin""" <|body_0|> def add_data(self, frame, data_id=0): """Reconstruct quantized bins ...
stack_v2_sparse_classes_75kplus_train_006663
836
no_license
[ { "docstring": "Initializing all linear models for each spectral bin", "name": "__init__", "signature": "def __init__(self, params, select, name='LDASynthesis')" }, { "docstring": "Reconstruct quantized bins based on an ECoG frame", "name": "add_data", "signature": "def add_data(self, fr...
2
null
Implement the Python class `LDASynthesis` described below. Class description: Predict quantized units based on LDA estimators Method signatures and docstrings: - def __init__(self, params, select, name='LDASynthesis'): Initializing all linear models for each spectral bin - def add_data(self, frame, data_id=0): Recons...
Implement the Python class `LDASynthesis` described below. Class description: Predict quantized units based on LDA estimators Method signatures and docstrings: - def __init__(self, params, select, name='LDASynthesis'): Initializing all linear models for each spectral bin - def add_data(self, frame, data_id=0): Recons...
f80da4527490d7c172a9d29d86480f9e47cb30b9
<|skeleton|> class LDASynthesis: """Predict quantized units based on LDA estimators""" def __init__(self, params, select, name='LDASynthesis'): """Initializing all linear models for each spectral bin""" <|body_0|> def add_data(self, frame, data_id=0): """Reconstruct quantized bins ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LDASynthesis: """Predict quantized units based on LDA estimators""" def __init__(self, params, select, name='LDASynthesis'): """Initializing all linear models for each spectral bin""" super(LDASynthesis, self).__init__(name=name) self.estimators = pickle.loads(params) self...
the_stack_v2_python_sparse
livenodes/LDASynthesis.py
neuralinterfacinglab/closed-loop-seeg-speech-synthesis
train
1
37dee392f9239671b672ab6211d081c495c53d85
[ "self.x_0s = [[211, 184, 1], [190, 257, 1], [231, 319, 1], [198, 397, 1], [181, 569, 1], [316, 513, 1], [113, 270, 1], [140, 213, 1], [244, 180, 1], [158, 319, 1]]\nself.x_1s = [[194.0, 31, 1], [106, 154, 1], [137, 286, 1], [58, 401, 1], [52, 581, 1], [254, 536, 1], [24, 150, 1], [103, 66, 1], [248, 34, 1], [57, 24...
<|body_start_0|> self.x_0s = [[211, 184, 1], [190, 257, 1], [231, 319, 1], [198, 397, 1], [181, 569, 1], [316, 513, 1], [113, 270, 1], [140, 213, 1], [244, 180, 1], [158, 319, 1]] self.x_1s = [[194.0, 31, 1], [106, 154, 1], [137, 286, 1], [58, 401, 1], [52, 581, 1], [254, 536, 1], [24, 150, 1], [103, 66...
Second example with real example.
TestFundamentalMatrix3
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestFundamentalMatrix3: """Second example with real example.""" def setUp(self): """Create F for testing, corresponding to real data.""" <|body_0|> def test_least_squares_optimize(self): """Test optimize with LM, needs 9 points.""" <|body_1|> def tes...
stack_v2_sparse_classes_75kplus_train_006664
6,788
no_license
[ { "docstring": "Create F for testing, corresponding to real data.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Test optimize with LM, needs 9 points.", "name": "test_least_squares_optimize", "signature": "def test_least_squares_optimize(self)" }, { "docstr...
3
null
Implement the Python class `TestFundamentalMatrix3` described below. Class description: Second example with real example. Method signatures and docstrings: - def setUp(self): Create F for testing, corresponding to real data. - def test_least_squares_optimize(self): Test optimize with LM, needs 9 points. - def test_si...
Implement the Python class `TestFundamentalMatrix3` described below. Class description: Second example with real example. Method signatures and docstrings: - def setUp(self): Create F for testing, corresponding to real data. - def test_least_squares_optimize(self): Test optimize with LM, needs 9 points. - def test_si...
2de4374f46065e8d7e0bd372e5a682c8b7ac0cf4
<|skeleton|> class TestFundamentalMatrix3: """Second example with real example.""" def setUp(self): """Create F for testing, corresponding to real data.""" <|body_0|> def test_least_squares_optimize(self): """Test optimize with LM, needs 9 points.""" <|body_1|> def tes...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestFundamentalMatrix3: """Second example with real example.""" def setUp(self): """Create F for testing, corresponding to real data.""" self.x_0s = [[211, 184, 1], [190, 257, 1], [231, 319, 1], [198, 397, 1], [181, 569, 1], [316, 513, 1], [113, 270, 1], [140, 213, 1], [244, 180, 1], [158...
the_stack_v2_python_sparse
Python/HW2/proj2_unit_tests/test_fundamental_matrix.py
wwy305756464/Computer-Vision
train
5
4bfd142068029bfeb46d9965f6b0f59b1a568102
[ "self.vec = vec2d\nself.row = 0\nself.col = 0", "tem = self.vec[self.row][self.col]\nself.col += 1\nreturn tem", "if not self.vec:\n return False\nwhile self.col >= len(self.vec[self.row]):\n self.col = 0\n self.row += 1\n if self.row >= len(self.vec):\n return False\nreturn True" ]
<|body_start_0|> self.vec = vec2d self.row = 0 self.col = 0 <|end_body_0|> <|body_start_1|> tem = self.vec[self.row][self.col] self.col += 1 return tem <|end_body_1|> <|body_start_2|> if not self.vec: return False while self.col >= len(self.v...
Vector2D
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Vector2D: def __init__(self, vec2d): """Initialize your data structure here. :type vec2d: List[List[int]]""" <|body_0|> def next(self): """:rtype: int""" <|body_1|> def hasNext(self): """:rtype: bool""" <|body_2|> <|end_skeleton|> <|bod...
stack_v2_sparse_classes_75kplus_train_006665
1,132
no_license
[ { "docstring": "Initialize your data structure here. :type vec2d: List[List[int]]", "name": "__init__", "signature": "def __init__(self, vec2d)" }, { "docstring": ":rtype: int", "name": "next", "signature": "def next(self)" }, { "docstring": ":rtype: bool", "name": "hasNext",...
3
null
Implement the Python class `Vector2D` described below. Class description: Implement the Vector2D class. Method signatures and docstrings: - def __init__(self, vec2d): Initialize your data structure here. :type vec2d: List[List[int]] - def next(self): :rtype: int - def hasNext(self): :rtype: bool
Implement the Python class `Vector2D` described below. Class description: Implement the Vector2D class. Method signatures and docstrings: - def __init__(self, vec2d): Initialize your data structure here. :type vec2d: List[List[int]] - def next(self): :rtype: int - def hasNext(self): :rtype: bool <|skeleton|> class V...
2df1a58aa9474f2ecec2ee7c45ebf12466181391
<|skeleton|> class Vector2D: def __init__(self, vec2d): """Initialize your data structure here. :type vec2d: List[List[int]]""" <|body_0|> def next(self): """:rtype: int""" <|body_1|> def hasNext(self): """:rtype: bool""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Vector2D: def __init__(self, vec2d): """Initialize your data structure here. :type vec2d: List[List[int]]""" self.vec = vec2d self.row = 0 self.col = 0 def next(self): """:rtype: int""" tem = self.vec[self.row][self.col] self.col += 1 return...
the_stack_v2_python_sparse
Flatten2DVector.py
zjuzpz/Algorithms
train
2
abe7cfd8d0733d37bcc78cbca32ae742cf4e858f
[ "if UserProfile.objects.filter(username=username):\n raise serializers.ValidationError(username + ' 账号已存在')\nreturn username", "REGEX_MOBILE = '^1[358]\\\\d{9}$|^147\\\\d{8}$|^176\\\\d{8}$'\nif not re.match(REGEX_MOBILE, mobile):\n raise serializers.ValidationError('手机号码不合法')\nif UserProfile.objects.filter(...
<|body_start_0|> if UserProfile.objects.filter(username=username): raise serializers.ValidationError(username + ' 账号已存在') return username <|end_body_0|> <|body_start_1|> REGEX_MOBILE = '^1[358]\\d{9}$|^147\\d{8}$|^176\\d{8}$' if not re.match(REGEX_MOBILE, mobile): ...
创建用户序列化
UserCreateSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserCreateSerializer: """创建用户序列化""" def validate_username(self, username): """校验用户名是否存在 :param username: :return:""" <|body_0|> def validate_mobile(self, mobile): """校验手机号是否合法、是否已被注册 :param mobile: :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|...
stack_v2_sparse_classes_75kplus_train_006666
3,031
no_license
[ { "docstring": "校验用户名是否存在 :param username: :return:", "name": "validate_username", "signature": "def validate_username(self, username)" }, { "docstring": "校验手机号是否合法、是否已被注册 :param mobile: :return:", "name": "validate_mobile", "signature": "def validate_mobile(self, mobile)" } ]
2
stack_v2_sparse_classes_30k_train_041025
Implement the Python class `UserCreateSerializer` described below. Class description: 创建用户序列化 Method signatures and docstrings: - def validate_username(self, username): 校验用户名是否存在 :param username: :return: - def validate_mobile(self, mobile): 校验手机号是否合法、是否已被注册 :param mobile: :return:
Implement the Python class `UserCreateSerializer` described below. Class description: 创建用户序列化 Method signatures and docstrings: - def validate_username(self, username): 校验用户名是否存在 :param username: :return: - def validate_mobile(self, mobile): 校验手机号是否合法、是否已被注册 :param mobile: :return: <|skeleton|> class UserCreateSeria...
db1d7c4eb2d5d229ab54c6d5775f96fc1843716e
<|skeleton|> class UserCreateSerializer: """创建用户序列化""" def validate_username(self, username): """校验用户名是否存在 :param username: :return:""" <|body_0|> def validate_mobile(self, mobile): """校验手机号是否合法、是否已被注册 :param mobile: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UserCreateSerializer: """创建用户序列化""" def validate_username(self, username): """校验用户名是否存在 :param username: :return:""" if UserProfile.objects.filter(username=username): raise serializers.ValidationError(username + ' 账号已存在') return username def validate_mobile(self, ...
the_stack_v2_python_sparse
apps/rbac/serializers/user_serializer.py
fengjy96/rest_task
train
0
6e4200ea347b78c81ba5b83201529fafea418ac0
[ "self.config = config\nself.func_queue = func_queue\nself.glib_func = None", "self.glib_func = self.func_queue.get()\nwhile True:\n GLib.idle_add(self.glib_func, ['CONNECTING'])\n irc_sock = Irc(self.config)\n irc_sock.set_parser(IrcParser())\n try:\n irc_sock.connect('TWITCHCLIENT 1\\r\\n')\n ...
<|body_start_0|> self.config = config self.func_queue = func_queue self.glib_func = None <|end_body_0|> <|body_start_1|> self.glib_func = self.func_queue.get() while True: GLib.idle_add(self.glib_func, ['CONNECTING']) irc_sock = Irc(self.config) ...
IrcEventGenerator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IrcEventGenerator: def __init__(self, config, func_queue): """This class handles the Irc subclass to receive messages, and sends signals to the GUI after parsing those messages.""" <|body_0|> def run(self): """Connect to the IRC server and send events to the GUI. Thi...
stack_v2_sparse_classes_75kplus_train_006667
2,134
no_license
[ { "docstring": "This class handles the Irc subclass to receive messages, and sends signals to the GUI after parsing those messages.", "name": "__init__", "signature": "def __init__(self, config, func_queue)" }, { "docstring": "Connect to the IRC server and send events to the GUI. This funtion is...
2
stack_v2_sparse_classes_30k_train_053176
Implement the Python class `IrcEventGenerator` described below. Class description: Implement the IrcEventGenerator class. Method signatures and docstrings: - def __init__(self, config, func_queue): This class handles the Irc subclass to receive messages, and sends signals to the GUI after parsing those messages. - de...
Implement the Python class `IrcEventGenerator` described below. Class description: Implement the IrcEventGenerator class. Method signatures and docstrings: - def __init__(self, config, func_queue): This class handles the Irc subclass to receive messages, and sends signals to the GUI after parsing those messages. - de...
4e5115e34efd8ce11df2a5e9fe821921b791af1d
<|skeleton|> class IrcEventGenerator: def __init__(self, config, func_queue): """This class handles the Irc subclass to receive messages, and sends signals to the GUI after parsing those messages.""" <|body_0|> def run(self): """Connect to the IRC server and send events to the GUI. Thi...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class IrcEventGenerator: def __init__(self, config, func_queue): """This class handles the Irc subclass to receive messages, and sends signals to the GUI after parsing those messages.""" self.config = config self.func_queue = func_queue self.glib_func = None def run(self): ...
the_stack_v2_python_sparse
lib/irceventgenerator.py
funknapkin/pyBotTV
train
1
e289205113301f5ec8e762154fa23b908b845812
[ "if serializer_class is None:\n if 'context' in kwargs.keys():\n kwargs.pop('context')\n return self.get_serializer(queryset, *args, **kwargs)\nreturn serializer_class(queryset, *args, context=self.get_serializer_context(), **kwargs)", "if user_pk is None:\n queryset = self.get_queryset().filter(u...
<|body_start_0|> if serializer_class is None: if 'context' in kwargs.keys(): kwargs.pop('context') return self.get_serializer(queryset, *args, **kwargs) return serializer_class(queryset, *args, context=self.get_serializer_context(), **kwargs) <|end_body_0|> <|bod...
/users/<user_pk>/favs/ のようなネストされた要素に対してリストを返す時のmixin
UserNestedListMixin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserNestedListMixin: """/users/<user_pk>/favs/ のようなネストされた要素に対してリストを返す時のmixin""" def _serialize(self, serializer_class, queryset, *args, **kwargs): """Serializerの指定があればそれで返す.無ければself.get_serializerする. :param serializer_class: 使用するSerializerクラスを指定する :param args: Serializerをインスタンス化する際の位...
stack_v2_sparse_classes_75kplus_train_006668
5,541
no_license
[ { "docstring": "Serializerの指定があればそれで返す.無ければself.get_serializerする. :param serializer_class: 使用するSerializerクラスを指定する :param args: Serializerをインスタンス化する際の位置引数 :param kwargs: Serializerをインスタンス化する際のオプション引数 :return: インスタンス化されたSerializer", "name": "_serialize", "signature": "def _serialize(self, serializer_class...
2
stack_v2_sparse_classes_30k_train_011372
Implement the Python class `UserNestedListMixin` described below. Class description: /users/<user_pk>/favs/ のようなネストされた要素に対してリストを返す時のmixin Method signatures and docstrings: - def _serialize(self, serializer_class, queryset, *args, **kwargs): Serializerの指定があればそれで返す.無ければself.get_serializerする. :param serializer_class: 使用...
Implement the Python class `UserNestedListMixin` described below. Class description: /users/<user_pk>/favs/ のようなネストされた要素に対してリストを返す時のmixin Method signatures and docstrings: - def _serialize(self, serializer_class, queryset, *args, **kwargs): Serializerの指定があればそれで返す.無ければself.get_serializerする. :param serializer_class: 使用...
6f9487dcfc13c706d312be6586159c7d3a25c6aa
<|skeleton|> class UserNestedListMixin: """/users/<user_pk>/favs/ のようなネストされた要素に対してリストを返す時のmixin""" def _serialize(self, serializer_class, queryset, *args, **kwargs): """Serializerの指定があればそれで返す.無ければself.get_serializerする. :param serializer_class: 使用するSerializerクラスを指定する :param args: Serializerをインスタンス化する際の位...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UserNestedListMixin: """/users/<user_pk>/favs/ のようなネストされた要素に対してリストを返す時のmixin""" def _serialize(self, serializer_class, queryset, *args, **kwargs): """Serializerの指定があればそれで返す.無ければself.get_serializerする. :param serializer_class: 使用するSerializerクラスを指定する :param args: Serializerをインスタンス化する際の位置引数 :param kw...
the_stack_v2_python_sparse
src/plan/mixins.py
jphacks/KB_1809_2
train
3
db6532f9c032bb9a6762b2360d2ff32a014c0944
[ "labels = list()\nfor model_name, performance_metrics in models_performance.items():\n accuracy = performance_metrics[0][0]\n loss = performance_metrics[0][1]\n early_stopping = performance_metrics[0][2]\n plt.subplot(1, 2, 1)\n plt.ylabel('Accuracy')\n plt.xlabel('Epoch')\n plt.plot(accuracy, ...
<|body_start_0|> labels = list() for model_name, performance_metrics in models_performance.items(): accuracy = performance_metrics[0][0] loss = performance_metrics[0][1] early_stopping = performance_metrics[0][2] plt.subplot(1, 2, 1) plt.ylabel...
Visualizer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Visualizer: def visualize_models_performance(models_performance: dict): """:param models_performance: :return:""" <|body_0|> def visualize_training_results(accuracy, loss): """:param accuracy: :param loss: :return:""" <|body_1|> def model_visualisation(s...
stack_v2_sparse_classes_75kplus_train_006669
4,720
no_license
[ { "docstring": ":param models_performance: :return:", "name": "visualize_models_performance", "signature": "def visualize_models_performance(models_performance: dict)" }, { "docstring": ":param accuracy: :param loss: :return:", "name": "visualize_training_results", "signature": "def visu...
5
stack_v2_sparse_classes_30k_train_023215
Implement the Python class `Visualizer` described below. Class description: Implement the Visualizer class. Method signatures and docstrings: - def visualize_models_performance(models_performance: dict): :param models_performance: :return: - def visualize_training_results(accuracy, loss): :param accuracy: :param loss...
Implement the Python class `Visualizer` described below. Class description: Implement the Visualizer class. Method signatures and docstrings: - def visualize_models_performance(models_performance: dict): :param models_performance: :return: - def visualize_training_results(accuracy, loss): :param accuracy: :param loss...
0d8e8da2c19b9fd247089696fc808934aa6b6972
<|skeleton|> class Visualizer: def visualize_models_performance(models_performance: dict): """:param models_performance: :return:""" <|body_0|> def visualize_training_results(accuracy, loss): """:param accuracy: :param loss: :return:""" <|body_1|> def model_visualisation(s...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Visualizer: def visualize_models_performance(models_performance: dict): """:param models_performance: :return:""" labels = list() for model_name, performance_metrics in models_performance.items(): accuracy = performance_metrics[0][0] loss = performance_metrics[0...
the_stack_v2_python_sparse
utils.py
EvgeniiTitov/nn_trainer
train
0
ca1ad44426c43ffb9e3f3d8f55d2c569a9c9c5cb
[ "super(GRUValueDecoder, self).__init__()\nassert isinstance(embeddings, torch.nn.Embedding)\nself.embeddings = embeddings\nself.input_size = embeddings.embedding_dim\nself.output_size = embeddings.embedding_dim\nself.num_layers = num_layers\nself.hidden_size = hidden_size\nself.dropout = torch.nn.Dropout(dropout)\n...
<|body_start_0|> super(GRUValueDecoder, self).__init__() assert isinstance(embeddings, torch.nn.Embedding) self.embeddings = embeddings self.input_size = embeddings.embedding_dim self.output_size = embeddings.embedding_dim self.num_layers = num_layers self.hidden_...
The Value decoder
GRUValueDecoder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GRUValueDecoder: """The Value decoder""" def __init__(self, embeddings, num_layers=1, hidden_size=256, dropout=0.3): """Constructor""" <|body_0|> def forward(self, targets, memory, states, memory_lengths=None): """Do a teacher forcing :param targets: [bsz, seq_le...
stack_v2_sparse_classes_75kplus_train_006670
10,133
no_license
[ { "docstring": "Constructor", "name": "__init__", "signature": "def __init__(self, embeddings, num_layers=1, hidden_size=256, dropout=0.3)" }, { "docstring": "Do a teacher forcing :param targets: [bsz, seq_len] :param memory: [bsz, src_seq_len, memory_size] :param states: encoder states. [1, bsz...
2
stack_v2_sparse_classes_30k_train_017543
Implement the Python class `GRUValueDecoder` described below. Class description: The Value decoder Method signatures and docstrings: - def __init__(self, embeddings, num_layers=1, hidden_size=256, dropout=0.3): Constructor - def forward(self, targets, memory, states, memory_lengths=None): Do a teacher forcing :param ...
Implement the Python class `GRUValueDecoder` described below. Class description: The Value decoder Method signatures and docstrings: - def __init__(self, embeddings, num_layers=1, hidden_size=256, dropout=0.3): Constructor - def forward(self, targets, memory, states, memory_lengths=None): Do a teacher forcing :param ...
858559c7e39ad82a87ac2546162c7dbadf7d4de8
<|skeleton|> class GRUValueDecoder: """The Value decoder""" def __init__(self, embeddings, num_layers=1, hidden_size=256, dropout=0.3): """Constructor""" <|body_0|> def forward(self, targets, memory, states, memory_lengths=None): """Do a teacher forcing :param targets: [bsz, seq_le...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GRUValueDecoder: """The Value decoder""" def __init__(self, embeddings, num_layers=1, hidden_size=256, dropout=0.3): """Constructor""" super(GRUValueDecoder, self).__init__() assert isinstance(embeddings, torch.nn.Embedding) self.embeddings = embeddings self.input_...
the_stack_v2_python_sparse
ld_research/model/grus.py
JACKHAHA363/translation_game_drift
train
2
5d6de7dce4c356d2eea0434cc2dde063dcf1219a
[ "course_ids = []\nfor course in Course.objects.all():\n if definition.satisfies(course):\n course_ids.append(course.id)\nself.replace_course_ids(playlist, course_ids)", "playlist.courses.set(course_ids)\nplaylist.save()\nprint({'message': 'Playlist updated', 'name': playlist.name, 'semester': playlist.s...
<|body_start_0|> course_ids = [] for course in Course.objects.all(): if definition.satisfies(course): course_ids.append(course.id) self.replace_course_ids(playlist, course_ids) <|end_body_0|> <|body_start_1|> playlist.courses.set(course_ids) playlist....
Abstract Playlist Category Service.
AbstractPlaylistService
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AbstractPlaylistService: """Abstract Playlist Category Service.""" def _update(self, playlist, definition): """Take a single playlist and definition and update it.""" <|body_0|> def replace_course_ids(self, playlist, course_ids): """Replace a playlist's existing ...
stack_v2_sparse_classes_75kplus_train_006671
912
permissive
[ { "docstring": "Take a single playlist and definition and update it.", "name": "_update", "signature": "def _update(self, playlist, definition)" }, { "docstring": "Replace a playlist's existing courses.", "name": "replace_course_ids", "signature": "def replace_course_ids(self, playlist, ...
2
stack_v2_sparse_classes_30k_train_037670
Implement the Python class `AbstractPlaylistService` described below. Class description: Abstract Playlist Category Service. Method signatures and docstrings: - def _update(self, playlist, definition): Take a single playlist and definition and update it. - def replace_course_ids(self, playlist, course_ids): Replace a...
Implement the Python class `AbstractPlaylistService` described below. Class description: Abstract Playlist Category Service. Method signatures and docstrings: - def _update(self, playlist, definition): Take a single playlist and definition and update it. - def replace_course_ids(self, playlist, course_ids): Replace a...
34578dc14c8e5c2cfb28f8d6710e791cdd773d59
<|skeleton|> class AbstractPlaylistService: """Abstract Playlist Category Service.""" def _update(self, playlist, definition): """Take a single playlist and definition and update it.""" <|body_0|> def replace_course_ids(self, playlist, course_ids): """Replace a playlist's existing ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AbstractPlaylistService: """Abstract Playlist Category Service.""" def _update(self, playlist, definition): """Take a single playlist and definition and update it.""" course_ids = [] for course in Course.objects.all(): if definition.satisfies(course): c...
the_stack_v2_python_sparse
backend/playlist/service/abstract.py
AviFS/berkeleytime
train
0
fed8143e97905cbcc969f639dd818279870a36cb
[ "if isinstance(data, type(None)):\n raise TypeError('data must be a 2D numpy.ndarray')\nif not isinstance(data, np.ndarray) or len(data.shape) != 2:\n raise TypeError('data must be a 2D numpy.ndarray')\nif data.shape[1] < 2:\n raise ValueError('data must contain multiple data points')\ndata = data.T\nmean ...
<|body_start_0|> if isinstance(data, type(None)): raise TypeError('data must be a 2D numpy.ndarray') if not isinstance(data, np.ndarray) or len(data.shape) != 2: raise TypeError('data must be a 2D numpy.ndarray') if data.shape[1] < 2: raise ValueError('data mu...
Represents a Multivariate Normal distribution
MultiNormal
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiNormal: """Represents a Multivariate Normal distribution""" def __init__(self, data): """class constructor Args: - data: numpy.ndarray Array of shape (d, n) containing the dataset: - n int number of data points - d int number of dimensions in each data point If data is not a 2D ...
stack_v2_sparse_classes_75kplus_train_006672
3,111
no_license
[ { "docstring": "class constructor Args: - data: numpy.ndarray Array of shape (d, n) containing the dataset: - n int number of data points - d int number of dimensions in each data point If data is not a 2D numpy.ndarray, raise a TypeError with the msg: data must be a 2D numpy.ndarray If n is less than 2, raise ...
2
stack_v2_sparse_classes_30k_train_012643
Implement the Python class `MultiNormal` described below. Class description: Represents a Multivariate Normal distribution Method signatures and docstrings: - def __init__(self, data): class constructor Args: - data: numpy.ndarray Array of shape (d, n) containing the dataset: - n int number of data points - d int num...
Implement the Python class `MultiNormal` described below. Class description: Represents a Multivariate Normal distribution Method signatures and docstrings: - def __init__(self, data): class constructor Args: - data: numpy.ndarray Array of shape (d, n) containing the dataset: - n int number of data points - d int num...
eb47cd4d12e2f0627bb5e5af28cc0802ff13d0d9
<|skeleton|> class MultiNormal: """Represents a Multivariate Normal distribution""" def __init__(self, data): """class constructor Args: - data: numpy.ndarray Array of shape (d, n) containing the dataset: - n int number of data points - d int number of dimensions in each data point If data is not a 2D ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MultiNormal: """Represents a Multivariate Normal distribution""" def __init__(self, data): """class constructor Args: - data: numpy.ndarray Array of shape (d, n) containing the dataset: - n int number of data points - d int number of dimensions in each data point If data is not a 2D numpy.ndarray...
the_stack_v2_python_sparse
math/0x06-multivariate_prob/multinormal.py
rodrigocruz13/holbertonschool-machine_learning
train
4
797ff33b719b1a72a4fa852e6dc2d80006447f78
[ "zh_login(self=self, driver=self.driver)\nself.driver.press_keycode(4)\nmylogger.info('返回home page')", "test_name = '地图上发送默认地点'\nmylogger.debug('%s start' % test_name)\nself.driver.implicitly_wait(10)\nmainChat_element(self.driver)\nfirst_chat_element(self.driver)\nmylogger.info('进入与第一个联系人交互界面')\nself.driver.impl...
<|body_start_0|> zh_login(self=self, driver=self.driver) self.driver.press_keycode(4) mylogger.info('返回home page') <|end_body_0|> <|body_start_1|> test_name = '地图上发送默认地点' mylogger.debug('%s start' % test_name) self.driver.implicitly_wait(10) mainChat_element(self...
Message_share
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Message_share: def test1(self): """zh login""" <|body_0|> def test2_share_software(self): """message share software""" <|body_1|> def test3_send_file(self): """message share file""" <|body_2|> def test4_send_voice_1(self): ""...
stack_v2_sparse_classes_75kplus_train_006673
3,752
no_license
[ { "docstring": "zh login", "name": "test1", "signature": "def test1(self)" }, { "docstring": "message share software", "name": "test2_share_software", "signature": "def test2_share_software(self)" }, { "docstring": "message share file", "name": "test3_send_file", "signatu...
6
stack_v2_sparse_classes_30k_train_023063
Implement the Python class `Message_share` described below. Class description: Implement the Message_share class. Method signatures and docstrings: - def test1(self): zh login - def test2_share_software(self): message share software - def test3_send_file(self): message share file - def test4_send_voice_1(self): messa...
Implement the Python class `Message_share` described below. Class description: Implement the Message_share class. Method signatures and docstrings: - def test1(self): zh login - def test2_share_software(self): message share software - def test3_send_file(self): message share file - def test4_send_voice_1(self): messa...
5924b88c5bc2a41d62807cc665bb3a76dfe0f3d3
<|skeleton|> class Message_share: def test1(self): """zh login""" <|body_0|> def test2_share_software(self): """message share software""" <|body_1|> def test3_send_file(self): """message share file""" <|body_2|> def test4_send_voice_1(self): ""...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Message_share: def test1(self): """zh login""" zh_login(self=self, driver=self.driver) self.driver.press_keycode(4) mylogger.info('返回home page') def test2_share_software(self): """message share software""" test_name = '地图上发送默认地点' mylogger.debug('%s ...
the_stack_v2_python_sparse
testsuite/test4_chat_share.py
Lkamanda/LT
train
2
6c804f2256e200937e8471f6daca7ee3acbd9f12
[ "logger.debug(f'parsing a {len(buffer)} byte packet')\nopcode, = struct.unpack(str('!H'), buffer[:2])\nlogger.debug(f'opcode is {opcode}')\npacket = self.__create(opcode)\npacket.buffer = buffer\nreturn packet.decode()", "tftpassert(opcode in self._classes, f'Unsupported opcode: {opcode}')\npacket = self._classes...
<|body_start_0|> logger.debug(f'parsing a {len(buffer)} byte packet') opcode, = struct.unpack(str('!H'), buffer[:2]) logger.debug(f'opcode is {opcode}') packet = self.__create(opcode) packet.buffer = buffer return packet.decode() <|end_body_0|> <|body_start_1|> t...
This class generates TftpPacket objects. It is responsible for parsing raw buffers off of the wire and returning objects representing them, via the parse() method.
PacketFactory
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PacketFactory: """This class generates TftpPacket objects. It is responsible for parsing raw buffers off of the wire and returning objects representing them, via the parse() method.""" def parse(self, buffer: bytes) -> packet_type: """This method is used to parse an existing datagram...
stack_v2_sparse_classes_75kplus_train_006674
1,763
permissive
[ { "docstring": "This method is used to parse an existing datagram into its corresponding TftpPacket object. Args: buffer (bytes): Packet Data Returns: types: packet type base on the opcode", "name": "parse", "signature": "def parse(self, buffer: bytes) -> packet_type" }, { "docstring": "This met...
2
stack_v2_sparse_classes_30k_train_014178
Implement the Python class `PacketFactory` described below. Class description: This class generates TftpPacket objects. It is responsible for parsing raw buffers off of the wire and returning objects representing them, via the parse() method. Method signatures and docstrings: - def parse(self, buffer: bytes) -> packe...
Implement the Python class `PacketFactory` described below. Class description: This class generates TftpPacket objects. It is responsible for parsing raw buffers off of the wire and returning objects representing them, via the parse() method. Method signatures and docstrings: - def parse(self, buffer: bytes) -> packe...
9c171c7e969b80f2c00728df21d5534b3191620a
<|skeleton|> class PacketFactory: """This class generates TftpPacket objects. It is responsible for parsing raw buffers off of the wire and returning objects representing them, via the parse() method.""" def parse(self, buffer: bytes) -> packet_type: """This method is used to parse an existing datagram...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PacketFactory: """This class generates TftpPacket objects. It is responsible for parsing raw buffers off of the wire and returning objects representing them, via the parse() method.""" def parse(self, buffer: bytes) -> packet_type: """This method is used to parse an existing datagram into its cor...
the_stack_v2_python_sparse
tftpy/packet/factory/factory.py
jcarswell/tftpy
train
0
83943a93f3db0a5841bedc2ebc173cec97f3352f
[ "response = requests.get(url=self.query_rule_detail_url, headers=get_headers(HOST_189))\nself.assertEqual(200, response.status_code, '查询规则详情接口调用失败,失败原因%s' % response.text)\nself.assertEqual(self.sql_rule_id, response.json()['id'], '查询规则不一致')\nreturn response.json()['name']", "data = {'id': self.sql_rule_id, 'name...
<|body_start_0|> response = requests.get(url=self.query_rule_detail_url, headers=get_headers(HOST_189)) self.assertEqual(200, response.status_code, '查询规则详情接口调用失败,失败原因%s' % response.text) self.assertEqual(self.sql_rule_id, response.json()['id'], '查询规则不一致') return response.json()['name'] <...
QueryAndUpdateRuleDetail
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QueryAndUpdateRuleDetail: def test_rule_detail(self): """查询规则详细信息:最新一条sql规则""" <|body_0|> def test_rule_update(self): """更新规则-SQL类型的name""" <|body_1|> <|end_skeleton|> <|body_start_0|> response = requests.get(url=self.query_rule_detail_url, headers=...
stack_v2_sparse_classes_75kplus_train_006675
21,243
no_license
[ { "docstring": "查询规则详细信息:最新一条sql规则", "name": "test_rule_detail", "signature": "def test_rule_detail(self)" }, { "docstring": "更新规则-SQL类型的name", "name": "test_rule_update", "signature": "def test_rule_update(self)" } ]
2
null
Implement the Python class `QueryAndUpdateRuleDetail` described below. Class description: Implement the QueryAndUpdateRuleDetail class. Method signatures and docstrings: - def test_rule_detail(self): 查询规则详细信息:最新一条sql规则 - def test_rule_update(self): 更新规则-SQL类型的name
Implement the Python class `QueryAndUpdateRuleDetail` described below. Class description: Implement the QueryAndUpdateRuleDetail class. Method signatures and docstrings: - def test_rule_detail(self): 查询规则详细信息:最新一条sql规则 - def test_rule_update(self): 更新规则-SQL类型的name <|skeleton|> class QueryAndUpdateRuleDetail: de...
fc41513af3063169ff1b17d6f01f7074057ceb1f
<|skeleton|> class QueryAndUpdateRuleDetail: def test_rule_detail(self): """查询规则详细信息:最新一条sql规则""" <|body_0|> def test_rule_update(self): """更新规则-SQL类型的name""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class QueryAndUpdateRuleDetail: def test_rule_detail(self): """查询规则详细信息:最新一条sql规则""" response = requests.get(url=self.query_rule_detail_url, headers=get_headers(HOST_189)) self.assertEqual(200, response.status_code, '查询规则详情接口调用失败,失败原因%s' % response.text) self.assertEqual(self.sql_rul...
the_stack_v2_python_sparse
singl_api/api_test_cases/cases_for_analysis_model.py
bingjiegu/For_API
train
0
515d16b24900962ac4e292d3fe86f9e48481ba01
[ "self.filtering_policy = filtering_policy\nself.group_backup_params = group_backup_params\nself.onedrive_backup_params = onedrive_backup_params\nself.outlook_backup_params = outlook_backup_params\nself.public_folders_backup_params = public_folders_backup_params\nself.site_backup_params = site_backup_params\nself.te...
<|body_start_0|> self.filtering_policy = filtering_policy self.group_backup_params = group_backup_params self.onedrive_backup_params = onedrive_backup_params self.outlook_backup_params = outlook_backup_params self.public_folders_backup_params = public_folders_backup_params ...
Implementation of the 'O365BackupEnvParams' model. Message to capture any additional backup params for Office365 environment. This encapsulates both Outlook & OneDrive backup parameters. Attributes: filtering_policy (FilteringPolicyProto): This field has been deprecated. Use 'filtering_policy' specified within 'outlook...
O365BackupEnvParams
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class O365BackupEnvParams: """Implementation of the 'O365BackupEnvParams' model. Message to capture any additional backup params for Office365 environment. This encapsulates both Outlook & OneDrive backup parameters. Attributes: filtering_policy (FilteringPolicyProto): This field has been deprecated. U...
stack_v2_sparse_classes_75kplus_train_006676
5,762
permissive
[ { "docstring": "Constructor for the O365BackupEnvParams class", "name": "__init__", "signature": "def __init__(self, filtering_policy=None, group_backup_params=None, onedrive_backup_params=None, outlook_backup_params=None, public_folders_backup_params=None, site_backup_params=None, teams_backup_params=N...
2
stack_v2_sparse_classes_30k_train_007774
Implement the Python class `O365BackupEnvParams` described below. Class description: Implementation of the 'O365BackupEnvParams' model. Message to capture any additional backup params for Office365 environment. This encapsulates both Outlook & OneDrive backup parameters. Attributes: filtering_policy (FilteringPolicyPr...
Implement the Python class `O365BackupEnvParams` described below. Class description: Implementation of the 'O365BackupEnvParams' model. Message to capture any additional backup params for Office365 environment. This encapsulates both Outlook & OneDrive backup parameters. Attributes: filtering_policy (FilteringPolicyPr...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class O365BackupEnvParams: """Implementation of the 'O365BackupEnvParams' model. Message to capture any additional backup params for Office365 environment. This encapsulates both Outlook & OneDrive backup parameters. Attributes: filtering_policy (FilteringPolicyProto): This field has been deprecated. U...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class O365BackupEnvParams: """Implementation of the 'O365BackupEnvParams' model. Message to capture any additional backup params for Office365 environment. This encapsulates both Outlook & OneDrive backup parameters. Attributes: filtering_policy (FilteringPolicyProto): This field has been deprecated. Use 'filtering...
the_stack_v2_python_sparse
cohesity_management_sdk/models/o_365_backup_env_params.py
cohesity/management-sdk-python
train
24
89d62bb864bebe3b231123be90f670189b4baa12
[ "m_arit = ArithmeticUtil.arithmetic_mean(dat)\nn = ArithmeticUtil.number_of_elements(dat)\nreturn np.math.fsum((dat - m_arit) ** 2) / (n - 1)", "m_arit = ArithmeticUtil.arithmetic_mean(dat)\nn = ArithmeticUtil.number_of_elements(dat)\nreturn np.math.sqrt(np.math.fsum((dat - m_arit) ** 2) / (n - 1))", "m_arit = ...
<|body_start_0|> m_arit = ArithmeticUtil.arithmetic_mean(dat) n = ArithmeticUtil.number_of_elements(dat) return np.math.fsum((dat - m_arit) ** 2) / (n - 1) <|end_body_0|> <|body_start_1|> m_arit = ArithmeticUtil.arithmetic_mean(dat) n = ArithmeticUtil.number_of_elements(dat) ...
ModuleStatisticsManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ModuleStatisticsManager: def module_variance(self, dat): """TEST SMALL ERROR""" <|body_0|> def module_standard_deviation(self, dat): """TEST SMALL ERROR""" <|body_1|> def module_population_variance(self, dat): """TEST SMALL ERROR""" <|bod...
stack_v2_sparse_classes_75kplus_train_006677
1,949
no_license
[ { "docstring": "TEST SMALL ERROR", "name": "module_variance", "signature": "def module_variance(self, dat)" }, { "docstring": "TEST SMALL ERROR", "name": "module_standard_deviation", "signature": "def module_standard_deviation(self, dat)" }, { "docstring": "TEST SMALL ERROR", ...
6
stack_v2_sparse_classes_30k_train_028559
Implement the Python class `ModuleStatisticsManager` described below. Class description: Implement the ModuleStatisticsManager class. Method signatures and docstrings: - def module_variance(self, dat): TEST SMALL ERROR - def module_standard_deviation(self, dat): TEST SMALL ERROR - def module_population_variance(self,...
Implement the Python class `ModuleStatisticsManager` described below. Class description: Implement the ModuleStatisticsManager class. Method signatures and docstrings: - def module_variance(self, dat): TEST SMALL ERROR - def module_standard_deviation(self, dat): TEST SMALL ERROR - def module_population_variance(self,...
59c327a0ef80740e1c6967729d9472aac2afd1b5
<|skeleton|> class ModuleStatisticsManager: def module_variance(self, dat): """TEST SMALL ERROR""" <|body_0|> def module_standard_deviation(self, dat): """TEST SMALL ERROR""" <|body_1|> def module_population_variance(self, dat): """TEST SMALL ERROR""" <|bod...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ModuleStatisticsManager: def module_variance(self, dat): """TEST SMALL ERROR""" m_arit = ArithmeticUtil.arithmetic_mean(dat) n = ArithmeticUtil.number_of_elements(dat) return np.math.fsum((dat - m_arit) ** 2) / (n - 1) def module_standard_deviation(self, dat): """T...
the_stack_v2_python_sparse
VecStatsGraph/manager/ModuleStatisticsManager.py
IvanDragoJr/VecStatsGraph3d
train
0
a6be8bb62306965016430bdb096978abe08a4e76
[ "import csv\nelements = set()\nfor entry in entries:\n elements.update(entry.composition.elements)\nelements = sorted(list(elements), key=lambda a: a.X)\nwriter = csv.writer(open(filename, 'wb'), delimiter=unicode2str(','), quotechar=unicode2str('\"'), quoting=csv.QUOTE_MINIMAL)\nwriter.writerow(['Name'] + eleme...
<|body_start_0|> import csv elements = set() for entry in entries: elements.update(entry.composition.elements) elements = sorted(list(elements), key=lambda a: a.X) writer = csv.writer(open(filename, 'wb'), delimiter=unicode2str(','), quotechar=unicode2str('"'), quotin...
Utility class to export and import PDEntry to and from csv files, as well as to and from json.
PDEntryIO
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PDEntryIO: """Utility class to export and import PDEntry to and from csv files, as well as to and from json.""" def to_csv(filename, entries, latexify_names=False): """Exports PDEntries to a csv Args: filename: Filename to write to. entries: PDEntries to export. latexify_names: Forma...
stack_v2_sparse_classes_75kplus_train_006678
9,475
permissive
[ { "docstring": "Exports PDEntries to a csv Args: filename: Filename to write to. entries: PDEntries to export. latexify_names: Format entry names to be LaTex compatible, e.g., Li_{2}O", "name": "to_csv", "signature": "def to_csv(filename, entries, latexify_names=False)" }, { "docstring": "Import...
2
stack_v2_sparse_classes_30k_train_020110
Implement the Python class `PDEntryIO` described below. Class description: Utility class to export and import PDEntry to and from csv files, as well as to and from json. Method signatures and docstrings: - def to_csv(filename, entries, latexify_names=False): Exports PDEntries to a csv Args: filename: Filename to writ...
Implement the Python class `PDEntryIO` described below. Class description: Utility class to export and import PDEntry to and from csv files, as well as to and from json. Method signatures and docstrings: - def to_csv(filename, entries, latexify_names=False): Exports PDEntries to a csv Args: filename: Filename to writ...
0cfa800a56c850edfa6084ac9656db532de3639a
<|skeleton|> class PDEntryIO: """Utility class to export and import PDEntry to and from csv files, as well as to and from json.""" def to_csv(filename, entries, latexify_names=False): """Exports PDEntries to a csv Args: filename: Filename to write to. entries: PDEntries to export. latexify_names: Forma...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PDEntryIO: """Utility class to export and import PDEntry to and from csv files, as well as to and from json.""" def to_csv(filename, entries, latexify_names=False): """Exports PDEntries to a csv Args: filename: Filename to write to. entries: PDEntries to export. latexify_names: Format entry names...
the_stack_v2_python_sparse
pymatgen/phasediagram/entries.py
hautierg/pymatgen
train
2
8ccfb420dba0b5dc26683daba4ecfd299ee4fce0
[ "self.pi = pi\nself.n_states = n_states\nself.n_actions = n_actions\nself.gamma = gamma\nself.alpha = 0.3\nself.p = p\nself.r = r\nself.n_iterations = 100", "q = np.random.rand(self.n_states, self.n_actions)\nfor _ in range(100):\n v = np.zeros(self.n_states)\n for state in range(self.n_states):\n fo...
<|body_start_0|> self.pi = pi self.n_states = n_states self.n_actions = n_actions self.gamma = gamma self.alpha = 0.3 self.p = p self.r = r self.n_iterations = 100 <|end_body_0|> <|body_start_1|> q = np.random.rand(self.n_states, self.n_actions) ...
SPI
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SPI: def __init__(self, pi, n_states, n_actions, gamma, p, r): """pi = S*A p = A*S*S r = A*S""" <|body_0|> def update(self): """Soft Policy iteration""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.pi = pi self.n_states = n_states ...
stack_v2_sparse_classes_75kplus_train_006679
1,406
permissive
[ { "docstring": "pi = S*A p = A*S*S r = A*S", "name": "__init__", "signature": "def __init__(self, pi, n_states, n_actions, gamma, p, r)" }, { "docstring": "Soft Policy iteration", "name": "update", "signature": "def update(self)" } ]
2
stack_v2_sparse_classes_30k_train_033831
Implement the Python class `SPI` described below. Class description: Implement the SPI class. Method signatures and docstrings: - def __init__(self, pi, n_states, n_actions, gamma, p, r): pi = S*A p = A*S*S r = A*S - def update(self): Soft Policy iteration
Implement the Python class `SPI` described below. Class description: Implement the SPI class. Method signatures and docstrings: - def __init__(self, pi, n_states, n_actions, gamma, p, r): pi = S*A p = A*S*S r = A*S - def update(self): Soft Policy iteration <|skeleton|> class SPI: def __init__(self, pi, n_states...
e862324816c57dd5d07691ee8583259a6a62116c
<|skeleton|> class SPI: def __init__(self, pi, n_states, n_actions, gamma, p, r): """pi = S*A p = A*S*S r = A*S""" <|body_0|> def update(self): """Soft Policy iteration""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SPI: def __init__(self, pi, n_states, n_actions, gamma, p, r): """pi = S*A p = A*S*S r = A*S""" self.pi = pi self.n_states = n_states self.n_actions = n_actions self.gamma = gamma self.alpha = 0.3 self.p = p self.r = r self.n_iterations =...
the_stack_v2_python_sparse
gridworld/algorithms/SPI.py
Silviatulli/LOGEL
train
0
65bb7bb3b8f9fde6af95cf6460f1471bf1d609e1
[ "self.slot = slot\nself.comm = GPIO\nself.host = host\nself.tp00 = Tp00(self.slot, self.comm, self.host)\nself.tp00.start()", "if tpUtils.to_num(data) == 0:\n val = 1\nelse:\n val = 0\nsend_data = []\ntmp_data = {}\ntmp_data['line'] = 'A'\ntmp_data['v'] = val\nsend_data.append(tmp_data)\nself.tp00.send(json...
<|body_start_0|> self.slot = slot self.comm = GPIO self.host = host self.tp00 = Tp00(self.slot, self.comm, self.host) self.tp00.start() <|end_body_0|> <|body_start_1|> if tpUtils.to_num(data) == 0: val = 1 else: val = 0 send_data =...
#39 LED
Tp39_out
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Tp39_out: """#39 LED""" def __init__(self, slot, host=None): """コンストラクタ""" <|body_0|> def send(self, data): """値を送信します。""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.slot = slot self.comm = GPIO self.host = host se...
stack_v2_sparse_classes_75kplus_train_006680
1,494
permissive
[ { "docstring": "コンストラクタ", "name": "__init__", "signature": "def __init__(self, slot, host=None)" }, { "docstring": "値を送信します。", "name": "send", "signature": "def send(self, data)" } ]
2
stack_v2_sparse_classes_30k_train_006552
Implement the Python class `Tp39_out` described below. Class description: #39 LED Method signatures and docstrings: - def __init__(self, slot, host=None): コンストラクタ - def send(self, data): 値を送信します。
Implement the Python class `Tp39_out` described below. Class description: #39 LED Method signatures and docstrings: - def __init__(self, slot, host=None): コンストラクタ - def send(self, data): 値を送信します。 <|skeleton|> class Tp39_out: """#39 LED""" def __init__(self, slot, host=None): """コンストラクタ""" <|...
701430da89c45397a63fd522a4f5cf80516f57d0
<|skeleton|> class Tp39_out: """#39 LED""" def __init__(self, slot, host=None): """コンストラクタ""" <|body_0|> def send(self, data): """値を送信します。""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Tp39_out: """#39 LED""" def __init__(self, slot, host=None): """コンストラクタ""" self.slot = slot self.comm = GPIO self.host = host self.tp00 = Tp00(self.slot, self.comm, self.host) self.tp00.start() def send(self, data): """値を送信します。""" if tp...
the_stack_v2_python_sparse
py/tp39_out.py
cw-tpdev/node-red-contrib-tibbo-pi-p4
train
2
5f3ac8ae02121a9838082093aa03749c6a354596
[ "lineValue = in_value.split(',')\nif lineValue[0] == 'A':\n for j in range(int(lineValue[5])):\n out_key = (int(lineValue[1]) - 1, j)\n out_value = (lineValue[0], lineValue[2], float(lineValue[3]))\n yield (out_key, out_value)\nif lineValue[0] == 'B':\n for i in range(int(lineValue[4])):\...
<|body_start_0|> lineValue = in_value.split(',') if lineValue[0] == 'A': for j in range(int(lineValue[5])): out_key = (int(lineValue[1]) - 1, j) out_value = (lineValue[0], lineValue[2], float(lineValue[3])) yield (out_key, out_value) if...
Given a matrix A and a matrix B, compute the product A*B = C (matrix multiplication)
MatMul
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MatMul: """Given a matrix A and a matrix B, compute the product A*B = C (matrix multiplication)""" def mapper(self, in_key, in_value): """mapper function, which process a key-value pair in the data and generate intermediate key-value pair(s) Input: in_key: the key of a data record (i...
stack_v2_sparse_classes_75kplus_train_006681
5,451
no_license
[ { "docstring": "mapper function, which process a key-value pair in the data and generate intermediate key-value pair(s) Input: in_key: the key of a data record (in this example, can be ignored) in_value: the value of a data record, (in this example, it is a line of text string in the data file, check 'matrix.cs...
2
stack_v2_sparse_classes_30k_train_000115
Implement the Python class `MatMul` described below. Class description: Given a matrix A and a matrix B, compute the product A*B = C (matrix multiplication) Method signatures and docstrings: - def mapper(self, in_key, in_value): mapper function, which process a key-value pair in the data and generate intermediate key...
Implement the Python class `MatMul` described below. Class description: Given a matrix A and a matrix B, compute the product A*B = C (matrix multiplication) Method signatures and docstrings: - def mapper(self, in_key, in_value): mapper function, which process a key-value pair in the data and generate intermediate key...
4c18cc432ced229bb421a7b21978b8e8a88108b5
<|skeleton|> class MatMul: """Given a matrix A and a matrix B, compute the product A*B = C (matrix multiplication)""" def mapper(self, in_key, in_value): """mapper function, which process a key-value pair in the data and generate intermediate key-value pair(s) Input: in_key: the key of a data record (i...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MatMul: """Given a matrix A and a matrix B, compute the product A*B = C (matrix multiplication)""" def mapper(self, in_key, in_value): """mapper function, which process a key-value pair in the data and generate intermediate key-value pair(s) Input: in_key: the key of a data record (in this exampl...
the_stack_v2_python_sparse
Graduate/DS501/vanand_HW3/problem2.py
vanand23/WPI_Projects
train
1
c0272eb32147910dc43c3da8cffbfffc5bb629d9
[ "super(CoordinateInfo, self).__init__()\nself.name = name\nself.generic_level = False\nself.axis = ''\n'Axis'\nself.value = ''\n'Coordinate value'\nself.standard_name = ''\n'Standard name'\nself.long_name = ''\n'Long name'\nself.out_name = ''\n'\\n Out name\\n\\n This is the name of the variable in th...
<|body_start_0|> super(CoordinateInfo, self).__init__() self.name = name self.generic_level = False self.axis = '' 'Axis' self.value = '' 'Coordinate value' self.standard_name = '' 'Standard name' self.long_name = '' 'Long name' ...
Class to read and store coordinate information.
CoordinateInfo
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CoordinateInfo: """Class to read and store coordinate information.""" def __init__(self, name): """Class to read and store coordinate information. Parameters ---------- name: str coordinate's name""" <|body_0|> def read_json(self, json_data): """Read coordinate i...
stack_v2_sparse_classes_75kplus_train_006682
25,477
permissive
[ { "docstring": "Class to read and store coordinate information. Parameters ---------- name: str coordinate's name", "name": "__init__", "signature": "def __init__(self, name)" }, { "docstring": "Read coordinate information from json. Non-present options will be set to empty Parameters ----------...
2
null
Implement the Python class `CoordinateInfo` described below. Class description: Class to read and store coordinate information. Method signatures and docstrings: - def __init__(self, name): Class to read and store coordinate information. Parameters ---------- name: str coordinate's name - def read_json(self, json_dat...
Implement the Python class `CoordinateInfo` described below. Class description: Class to read and store coordinate information. Method signatures and docstrings: - def __init__(self, name): Class to read and store coordinate information. Parameters ---------- name: str coordinate's name - def read_json(self, json_dat...
d5bf3f459ff3a43e780d75d57b63b88b6cc8c4f2
<|skeleton|> class CoordinateInfo: """Class to read and store coordinate information.""" def __init__(self, name): """Class to read and store coordinate information. Parameters ---------- name: str coordinate's name""" <|body_0|> def read_json(self, json_data): """Read coordinate i...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CoordinateInfo: """Class to read and store coordinate information.""" def __init__(self, name): """Class to read and store coordinate information. Parameters ---------- name: str coordinate's name""" super(CoordinateInfo, self).__init__() self.name = name self.generic_leve...
the_stack_v2_python_sparse
esmvalcore/cmor/table.py
aperezpredictia/ESMValCore
train
1
767bc73f75682a9b257ae675be66f58e21ac1fdc
[ "rows_updated = queryset.update(is_active=False)\nif rows_updated == 1:\n message_bit = '1 user was'\nelse:\n message_bit = '{} users were'.format(rows_updated)\nself.message_user(request, '{} successfully deactivated.'.format(message_bit))", "rows_updated = queryset.update(is_active=True)\nif rows_updated ...
<|body_start_0|> rows_updated = queryset.update(is_active=False) if rows_updated == 1: message_bit = '1 user was' else: message_bit = '{} users were'.format(rows_updated) self.message_user(request, '{} successfully deactivated.'.format(message_bit)) <|end_body_0|>...
Define admin model for custom User model.
AccountsAdmin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AccountsAdmin: """Define admin model for custom User model.""" def deactivate_user(self, request, queryset): """Deactivate selected user accounts.""" <|body_0|> def activate_user(self, request, queryset): """Activate selected user accounts.""" <|body_1|> ...
stack_v2_sparse_classes_75kplus_train_006683
2,782
no_license
[ { "docstring": "Deactivate selected user accounts.", "name": "deactivate_user", "signature": "def deactivate_user(self, request, queryset)" }, { "docstring": "Activate selected user accounts.", "name": "activate_user", "signature": "def activate_user(self, request, queryset)" } ]
2
stack_v2_sparse_classes_30k_train_000839
Implement the Python class `AccountsAdmin` described below. Class description: Define admin model for custom User model. Method signatures and docstrings: - def deactivate_user(self, request, queryset): Deactivate selected user accounts. - def activate_user(self, request, queryset): Activate selected user accounts.
Implement the Python class `AccountsAdmin` described below. Class description: Define admin model for custom User model. Method signatures and docstrings: - def deactivate_user(self, request, queryset): Deactivate selected user accounts. - def activate_user(self, request, queryset): Activate selected user accounts. ...
321f0150be09f78c6d98516d246aedd168b85be8
<|skeleton|> class AccountsAdmin: """Define admin model for custom User model.""" def deactivate_user(self, request, queryset): """Deactivate selected user accounts.""" <|body_0|> def activate_user(self, request, queryset): """Activate selected user accounts.""" <|body_1|> ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AccountsAdmin: """Define admin model for custom User model.""" def deactivate_user(self, request, queryset): """Deactivate selected user accounts.""" rows_updated = queryset.update(is_active=False) if rows_updated == 1: message_bit = '1 user was' else: ...
the_stack_v2_python_sparse
accounts/admin.py
BuildForSDGCohort2/team-101-backend
train
6
8a9a7d07d4c8382bc910b34bbfd119acde0f2c45
[ "super(NETWORK, self).__init__()\nself.layer1 = torch.nn.Sequential(torch.nn.Linear(input_dim, hidden_dim), torch.nn.ReLU())\nself.layer2 = torch.nn.Sequential(torch.nn.Linear(hidden_dim, hidden_dim), torch.nn.ReLU())\nself.final = torch.nn.Linear(hidden_dim, output_dim)", "x = self.layer1(x)\nx = self.layer2(x)\...
<|body_start_0|> super(NETWORK, self).__init__() self.layer1 = torch.nn.Sequential(torch.nn.Linear(input_dim, hidden_dim), torch.nn.ReLU()) self.layer2 = torch.nn.Sequential(torch.nn.Linear(hidden_dim, hidden_dim), torch.nn.ReLU()) self.final = torch.nn.Linear(hidden_dim, output_dim) <|e...
NETWORK
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NETWORK: def __init__(self, input_dim: int, output_dim: int, hidden_dim: int) -> None: """DQN Network example Args: input_dim (int): `state` dimension. `state` is 2-D tensor of shape (n, input_dim) output_dim (int): Number of actions. Q_value is 2-D tensor of shape (n, output_dim) hidden...
stack_v2_sparse_classes_75kplus_train_006684
11,264
no_license
[ { "docstring": "DQN Network example Args: input_dim (int): `state` dimension. `state` is 2-D tensor of shape (n, input_dim) output_dim (int): Number of actions. Q_value is 2-D tensor of shape (n, output_dim) hidden_dim (int): Hidden dimension in fc layer", "name": "__init__", "signature": "def __init__(...
2
stack_v2_sparse_classes_30k_test_002257
Implement the Python class `NETWORK` described below. Class description: Implement the NETWORK class. Method signatures and docstrings: - def __init__(self, input_dim: int, output_dim: int, hidden_dim: int) -> None: DQN Network example Args: input_dim (int): `state` dimension. `state` is 2-D tensor of shape (n, input...
Implement the Python class `NETWORK` described below. Class description: Implement the NETWORK class. Method signatures and docstrings: - def __init__(self, input_dim: int, output_dim: int, hidden_dim: int) -> None: DQN Network example Args: input_dim (int): `state` dimension. `state` is 2-D tensor of shape (n, input...
6c3d1a7ba9246181b89e67b1f4857df99c85fa01
<|skeleton|> class NETWORK: def __init__(self, input_dim: int, output_dim: int, hidden_dim: int) -> None: """DQN Network example Args: input_dim (int): `state` dimension. `state` is 2-D tensor of shape (n, input_dim) output_dim (int): Number of actions. Q_value is 2-D tensor of shape (n, output_dim) hidden...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NETWORK: def __init__(self, input_dim: int, output_dim: int, hidden_dim: int) -> None: """DQN Network example Args: input_dim (int): `state` dimension. `state` is 2-D tensor of shape (n, input_dim) output_dim (int): Number of actions. Q_value is 2-D tensor of shape (n, output_dim) hidden_dim (int): Hi...
the_stack_v2_python_sparse
JumpKing.py
senweim/JumpKingAtHome
train
14
8deeffc1dec4fac2701da3f1bb323449e58e8474
[ "if value >= 2 ** bit_count:\n raise ValueError(f'Value {value} of new bit field value is too large for given bit count ({bit_count}).')\npacked = b''\nif fmt != self._fmt:\n if self._fmt:\n packed = self.finish_field()\n self._fmt = fmt\nmax_bit_count = 8 * struct.calcsize(fmt)\nself._field += form...
<|body_start_0|> if value >= 2 ** bit_count: raise ValueError(f'Value {value} of new bit field value is too large for given bit count ({bit_count}).') packed = b'' if fmt != self._fmt: if self._fmt: packed = self.finish_field() self._fmt = fmt ...
BitFieldWriter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BitFieldWriter: def write(self, value, bit_count, fmt: str) -> bytes: """Appends `value` to bit field and returns packed data whenever a field is completed. Note that a field is completed if the given `fmt` is different to the type of the current bit field.""" <|body_0|> def...
stack_v2_sparse_classes_75kplus_train_006685
4,457
no_license
[ { "docstring": "Appends `value` to bit field and returns packed data whenever a field is completed. Note that a field is completed if the given `fmt` is different to the type of the current bit field.", "name": "write", "signature": "def write(self, value, bit_count, fmt: str) -> bytes" }, { "do...
2
null
Implement the Python class `BitFieldWriter` described below. Class description: Implement the BitFieldWriter class. Method signatures and docstrings: - def write(self, value, bit_count, fmt: str) -> bytes: Appends `value` to bit field and returns packed data whenever a field is completed. Note that a field is complet...
Implement the Python class `BitFieldWriter` described below. Class description: Implement the BitFieldWriter class. Method signatures and docstrings: - def write(self, value, bit_count, fmt: str) -> bytes: Appends `value` to bit field and returns packed data whenever a field is completed. Note that a field is complet...
88693c0015056ee8e3d1dbcb795c05fca4349e38
<|skeleton|> class BitFieldWriter: def write(self, value, bit_count, fmt: str) -> bytes: """Appends `value` to bit field and returns packed data whenever a field is completed. Note that a field is completed if the given `fmt` is different to the type of the current bit field.""" <|body_0|> def...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BitFieldWriter: def write(self, value, bit_count, fmt: str) -> bytes: """Appends `value` to bit field and returns packed data whenever a field is completed. Note that a field is completed if the given `fmt` is different to the type of the current bit field.""" if value >= 2 ** bit_count: ...
the_stack_v2_python_sparse
soulstruct/base/params/utils.py
Nahnahchi/soulstruct
train
0
9e24943be8af28db2bbb5f7466475a61ca292dce
[ "try:\n playbook_file = open(resource, 'r')\nexcept (IOError, OSError) as e:\n logger.error('Could not load workflow from {0}. Reason: {1}'.format(resource, format_exception_message(e)))\n return None\nelse:\n with playbook_file:\n workflow_loaded = playbook_file.read()\n try:\n ...
<|body_start_0|> try: playbook_file = open(resource, 'r') except (IOError, OSError) as e: logger.error('Could not load workflow from {0}. Reason: {1}'.format(resource, format_exception_message(e))) return None else: with playbook_file: ...
JsonPlaybookLoader
[ "CC0-1.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JsonPlaybookLoader: def load_workflow(resource, workflow_name): """Loads a workflow from a file. Args: resource (str): Path to the workflow. workflow_name (str): Name of the workflow to load. Returns: True on success, False otherwise.""" <|body_0|> def load_playbook(resource...
stack_v2_sparse_classes_75kplus_train_006686
4,183
permissive
[ { "docstring": "Loads a workflow from a file. Args: resource (str): Path to the workflow. workflow_name (str): Name of the workflow to load. Returns: True on success, False otherwise.", "name": "load_workflow", "signature": "def load_workflow(resource, workflow_name)" }, { "docstring": "Loads a ...
3
stack_v2_sparse_classes_30k_train_017470
Implement the Python class `JsonPlaybookLoader` described below. Class description: Implement the JsonPlaybookLoader class. Method signatures and docstrings: - def load_workflow(resource, workflow_name): Loads a workflow from a file. Args: resource (str): Path to the workflow. workflow_name (str): Name of the workflo...
Implement the Python class `JsonPlaybookLoader` described below. Class description: Implement the JsonPlaybookLoader class. Method signatures and docstrings: - def load_workflow(resource, workflow_name): Loads a workflow from a file. Args: resource (str): Path to the workflow. workflow_name (str): Name of the workflo...
18cd8b6d10241955bea5422947af9cf67f73aead
<|skeleton|> class JsonPlaybookLoader: def load_workflow(resource, workflow_name): """Loads a workflow from a file. Args: resource (str): Path to the workflow. workflow_name (str): Name of the workflow to load. Returns: True on success, False otherwise.""" <|body_0|> def load_playbook(resource...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class JsonPlaybookLoader: def load_workflow(resource, workflow_name): """Loads a workflow from a file. Args: resource (str): Path to the workflow. workflow_name (str): Name of the workflow to load. Returns: True on success, False otherwise.""" try: playbook_file = open(resource, 'r') ...
the_stack_v2_python_sparse
core/jsonplaybookloader.py
JustinTervala/WALKOFF
train
0
9647ff58d5acf3cd67f825fb9b0e6931e6b7cfac
[ "def add(a, b):\n if not a or not b:\n return a or b\n return add(a ^ b, (a & b) << 1)\nif a * b < 0:\n if a > 0:\n return self.getSum(b, a)\n if add(~a, 1) == b:\n return 0\n if add(~a, 1) < b:\n return add(~add(add(~a, 1), add(~b, 1)), 1)\nreturn add(a, b)", "MAX = 214...
<|body_start_0|> def add(a, b): if not a or not b: return a or b return add(a ^ b, (a & b) << 1) if a * b < 0: if a > 0: return self.getSum(b, a) if add(~a, 1) == b: return 0 if add(~a, 1) < b: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def getSum(self, a: int, b: int) -> int: """a*b>=0 , or a < 0 and abs(a) > b > 0 (the negative number has a larger absolute value) b < 0 and abs(b) > a > 0 :param a: :param b: :return:""" <|body_0|> def getSum2(self, a, b): """:type a: int :type b: int :rty...
stack_v2_sparse_classes_75kplus_train_006687
1,319
no_license
[ { "docstring": "a*b>=0 , or a < 0 and abs(a) > b > 0 (the negative number has a larger absolute value) b < 0 and abs(b) > a > 0 :param a: :param b: :return:", "name": "getSum", "signature": "def getSum(self, a: int, b: int) -> int" }, { "docstring": ":type a: int :type b: int :rtype: int", "...
2
stack_v2_sparse_classes_30k_train_031548
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getSum(self, a: int, b: int) -> int: a*b>=0 , or a < 0 and abs(a) > b > 0 (the negative number has a larger absolute value) b < 0 and abs(b) > a > 0 :param a: :param b: :retu...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getSum(self, a: int, b: int) -> int: a*b>=0 , or a < 0 and abs(a) > b > 0 (the negative number has a larger absolute value) b < 0 and abs(b) > a > 0 :param a: :param b: :retu...
5d3574ccd282d0146c83c286ae28d8baaabd4910
<|skeleton|> class Solution: def getSum(self, a: int, b: int) -> int: """a*b>=0 , or a < 0 and abs(a) > b > 0 (the negative number has a larger absolute value) b < 0 and abs(b) > a > 0 :param a: :param b: :return:""" <|body_0|> def getSum2(self, a, b): """:type a: int :type b: int :rty...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def getSum(self, a: int, b: int) -> int: """a*b>=0 , or a < 0 and abs(a) > b > 0 (the negative number has a larger absolute value) b < 0 and abs(b) > a > 0 :param a: :param b: :return:""" def add(a, b): if not a or not b: return a or b return a...
the_stack_v2_python_sparse
371_两整数之和.py
lovehhf/LeetCode
train
0
b0885b3053ff65667b86eb1a0d192b8ef818f1f8
[ "import re\nfor int_pat in self.patterns:\n match = re.search(int_pat, text, flags=re.IGNORECASE)\n if match:\n return match[1]\nreturn False", "if self.recept(text, *args, **kwargs):\n return True\nelse:\n return False" ]
<|body_start_0|> import re for int_pat in self.patterns: match = re.search(int_pat, text, flags=re.IGNORECASE) if match: return match[1] return False <|end_body_0|> <|body_start_1|> if self.recept(text, *args, **kwargs): return True ...
Slot which validates answer by patterns in regexp
PatternedTextSlot
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PatternedTextSlot: """Slot which validates answer by patterns in regexp""" def recept(self, text, *args, **kwargs): """Method that actually recepts message and extracts Slot's Value from it Args: text: text to be analyzed (str) *args: **kwargs: Returns:""" <|body_0|> def...
stack_v2_sparse_classes_75kplus_train_006688
26,321
no_license
[ { "docstring": "Method that actually recepts message and extracts Slot's Value from it Args: text: text to be analyzed (str) *args: **kwargs: Returns:", "name": "recept", "signature": "def recept(self, text, *args, **kwargs)" }, { "docstring": "Method that checks if UserMessage can be recepted b...
2
stack_v2_sparse_classes_30k_train_030293
Implement the Python class `PatternedTextSlot` described below. Class description: Slot which validates answer by patterns in regexp Method signatures and docstrings: - def recept(self, text, *args, **kwargs): Method that actually recepts message and extracts Slot's Value from it Args: text: text to be analyzed (str)...
Implement the Python class `PatternedTextSlot` described below. Class description: Slot which validates answer by patterns in regexp Method signatures and docstrings: - def recept(self, text, *args, **kwargs): Method that actually recepts message and extracts Slot's Value from it Args: text: text to be analyzed (str)...
7a0bc78ca03ee8ca1202e8ad2a6860444f0ce75d
<|skeleton|> class PatternedTextSlot: """Slot which validates answer by patterns in regexp""" def recept(self, text, *args, **kwargs): """Method that actually recepts message and extracts Slot's Value from it Args: text: text to be analyzed (str) *args: **kwargs: Returns:""" <|body_0|> def...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PatternedTextSlot: """Slot which validates answer by patterns in regexp""" def recept(self, text, *args, **kwargs): """Method that actually recepts message and extracts Slot's Value from it Args: text: text to be analyzed (str) *args: **kwargs: Returns:""" import re for int_pat in...
the_stack_v2_python_sparse
ruler_bot/components/slots/slots.py
acriptis/dj_bot
train
3
2532dd7cbbaa8ffc5cf68c4dfdf0e6314d782e36
[ "if not pRoot:\n return 0\nreturn max(self.TreeDepth(pRoot.left), self.TreeDepth(pRoot.right)) + 1", "if not pRoot:\n return 0\nqueue, res = ([pRoot], 0)\nwhile queue:\n tmp = []\n for node in queue:\n if node.left:\n tmp.append(node.left)\n if node.right:\n tmp.app...
<|body_start_0|> if not pRoot: return 0 return max(self.TreeDepth(pRoot.left), self.TreeDepth(pRoot.right)) + 1 <|end_body_0|> <|body_start_1|> if not pRoot: return 0 queue, res = ([pRoot], 0) while queue: tmp = [] for node in queu...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def TreeDepth2(self, pRoot: TreeNode) -> int: """dfs遍历(后序遍历-左右根)""" <|body_0|> def TreeDepth(self, pRoot: TreeNode) -> int: """bfs遍历""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not pRoot: return 0 return max(self...
stack_v2_sparse_classes_75kplus_train_006689
1,394
no_license
[ { "docstring": "dfs遍历(后序遍历-左右根)", "name": "TreeDepth2", "signature": "def TreeDepth2(self, pRoot: TreeNode) -> int" }, { "docstring": "bfs遍历", "name": "TreeDepth", "signature": "def TreeDepth(self, pRoot: TreeNode) -> int" } ]
2
stack_v2_sparse_classes_30k_train_046153
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def TreeDepth2(self, pRoot: TreeNode) -> int: dfs遍历(后序遍历-左右根) - def TreeDepth(self, pRoot: TreeNode) -> int: bfs遍历
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def TreeDepth2(self, pRoot: TreeNode) -> int: dfs遍历(后序遍历-左右根) - def TreeDepth(self, pRoot: TreeNode) -> int: bfs遍历 <|skeleton|> class Solution: def TreeDepth2(self, pRoot: ...
965ce22e7bda7b6590247f1a6c6e4a68b4dd2c8f
<|skeleton|> class Solution: def TreeDepth2(self, pRoot: TreeNode) -> int: """dfs遍历(后序遍历-左右根)""" <|body_0|> def TreeDepth(self, pRoot: TreeNode) -> int: """bfs遍历""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def TreeDepth2(self, pRoot: TreeNode) -> int: """dfs遍历(后序遍历-左右根)""" if not pRoot: return 0 return max(self.TreeDepth(pRoot.left), self.TreeDepth(pRoot.right)) + 1 def TreeDepth(self, pRoot: TreeNode) -> int: """bfs遍历""" if not pRoot: ...
the_stack_v2_python_sparse
bishi/binary_tree.py
jeellee/tools
train
0
4465bedab331f4fc1378cddb2d4933ed199d76f4
[ "super(DNET_COLORED, self).__init__()\nself.nc = 3\nself.ef_dim = nef\nself.df_dim = ndf\nself.define_module()", "nef = self.ef_dim\nndf = self.df_dim\nself.netD_1 = nn.Sequential(conv4x4(self.nc, ndf), nn.BatchNorm2d(num_features=ndf), nn.LeakyReLU(negative_slope=0.2, inplace=True), conv4x4(ndf, ndf * 2), nn.Bat...
<|body_start_0|> super(DNET_COLORED, self).__init__() self.nc = 3 self.ef_dim = nef self.df_dim = ndf self.define_module() <|end_body_0|> <|body_start_1|> nef = self.ef_dim ndf = self.df_dim self.netD_1 = nn.Sequential(conv4x4(self.nc, ndf), nn.BatchNorm2...
Discriminator class for the ENCOLOR stage. Args: - ndf (int, optional): Number of discriminator filters in the first convolutional layer. (Default: 64) - nef (int, optional): Projected embeddings dimensions. (Default: 128)
DNET_COLORED
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DNET_COLORED: """Discriminator class for the ENCOLOR stage. Args: - ndf (int, optional): Number of discriminator filters in the first convolutional layer. (Default: 64) - nef (int, optional): Projected embeddings dimensions. (Default: 128)""" def __init__(self, ndf=64, nef=128): """I...
stack_v2_sparse_classes_75kplus_train_006690
22,492
no_license
[ { "docstring": "Initialize the ENCOLOR stage discriminator. Other attributes: - nc (int): Number of channels.", "name": "__init__", "signature": "def __init__(self, ndf=64, nef=128)" }, { "docstring": "Define stage 2 discriminator's model.", "name": "define_module", "signature": "def def...
3
stack_v2_sparse_classes_30k_val_001195
Implement the Python class `DNET_COLORED` described below. Class description: Discriminator class for the ENCOLOR stage. Args: - ndf (int, optional): Number of discriminator filters in the first convolutional layer. (Default: 64) - nef (int, optional): Projected embeddings dimensions. (Default: 128) Method signatures...
Implement the Python class `DNET_COLORED` described below. Class description: Discriminator class for the ENCOLOR stage. Args: - ndf (int, optional): Number of discriminator filters in the first convolutional layer. (Default: 64) - nef (int, optional): Projected embeddings dimensions. (Default: 128) Method signatures...
70d344d80425e7bbcc7984737dbe50a6638293c9
<|skeleton|> class DNET_COLORED: """Discriminator class for the ENCOLOR stage. Args: - ndf (int, optional): Number of discriminator filters in the first convolutional layer. (Default: 64) - nef (int, optional): Projected embeddings dimensions. (Default: 128)""" def __init__(self, ndf=64, nef=128): """I...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DNET_COLORED: """Discriminator class for the ENCOLOR stage. Args: - ndf (int, optional): Number of discriminator filters in the first convolutional layer. (Default: 64) - nef (int, optional): Projected embeddings dimensions. (Default: 128)""" def __init__(self, ndf=64, nef=128): """Initialize the...
the_stack_v2_python_sparse
TeleGAN/model.py
ails-lab/teleGAN
train
1
b498e8d3b1e133d7edd12740ead585f835fab64d
[ "self.result = 0\ncache = {0: 1}\n\ndef dfs(root, target, currPathSum):\n if root is None:\n return\n currPathSum += root.val\n oldPathSum = currPathSum - target\n self.result += cache.get(oldPathSum, 0)\n cache[currPathSum] = cache.get(currPathSum, 0) + 1\n dfs(root.left, target, currPathS...
<|body_start_0|> self.result = 0 cache = {0: 1} def dfs(root, target, currPathSum): if root is None: return currPathSum += root.val oldPathSum = currPathSum - target self.result += cache.get(oldPathSum, 0) cache[currPat...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def pathSum(self, root, sum): """:type root: TreeNode :type sum: int :rtype: int""" <|body_0|> def rewrite(self, root, sum): """:type root: TreeNode :type sum: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.result = 0...
stack_v2_sparse_classes_75kplus_train_006691
3,541
no_license
[ { "docstring": ":type root: TreeNode :type sum: int :rtype: int", "name": "pathSum", "signature": "def pathSum(self, root, sum)" }, { "docstring": ":type root: TreeNode :type sum: int :rtype: int", "name": "rewrite", "signature": "def rewrite(self, root, sum)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def pathSum(self, root, sum): :type root: TreeNode :type sum: int :rtype: int - def rewrite(self, root, sum): :type root: TreeNode :type sum: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def pathSum(self, root, sum): :type root: TreeNode :type sum: int :rtype: int - def rewrite(self, root, sum): :type root: TreeNode :type sum: int :rtype: int <|skeleton|> class ...
6350568d16b0f8c49a020f055bb6d72e2705ea56
<|skeleton|> class Solution: def pathSum(self, root, sum): """:type root: TreeNode :type sum: int :rtype: int""" <|body_0|> def rewrite(self, root, sum): """:type root: TreeNode :type sum: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def pathSum(self, root, sum): """:type root: TreeNode :type sum: int :rtype: int""" self.result = 0 cache = {0: 1} def dfs(root, target, currPathSum): if root is None: return currPathSum += root.val oldPathSum = cur...
the_stack_v2_python_sparse
tree/437_Path_Sum_III.py
vsdrun/lc_public
train
6
bf5c964ecd6760ddc39e1fd64fbf352911625e3a
[ "config_form = TicketConfigurationForm(self.request.form, obj=self.barcamp, config=self.config)\nadd_form = TicketClassForm(self.request.form, config=self.config)\nadd_form.events.choices = [(e._id, e.name) for e in self.barcamp.eventlist]\nreturn self.render(view=self.barcamp_view, barcamp=self.barcamp, config_for...
<|body_start_0|> config_form = TicketConfigurationForm(self.request.form, obj=self.barcamp, config=self.config) add_form = TicketClassForm(self.request.form, config=self.config) add_form.events.choices = [(e._id, e.name) for e in self.barcamp.eventlist] return self.render(view=self.barca...
shows the ticket editor and configuration screen
TicketEditor
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TicketEditor: """shows the ticket editor and configuration screen""" def get(self, slug=None): """render the view""" <|body_0|> def post(self, slug=None): """add a new ticket class""" <|body_1|> def delete(self, slug=None): """delete a sponso...
stack_v2_sparse_classes_75kplus_train_006692
7,063
permissive
[ { "docstring": "render the view", "name": "get", "signature": "def get(self, slug=None)" }, { "docstring": "add a new ticket class", "name": "post", "signature": "def post(self, slug=None)" }, { "docstring": "delete a sponsor again and give the index via idx param", "name": "...
3
null
Implement the Python class `TicketEditor` described below. Class description: shows the ticket editor and configuration screen Method signatures and docstrings: - def get(self, slug=None): render the view - def post(self, slug=None): add a new ticket class - def delete(self, slug=None): delete a sponsor again and giv...
Implement the Python class `TicketEditor` described below. Class description: shows the ticket editor and configuration screen Method signatures and docstrings: - def get(self, slug=None): render the view - def post(self, slug=None): add a new ticket class - def delete(self, slug=None): delete a sponsor again and giv...
9b45664e46c451b2cbe00bb55583b043e769083d
<|skeleton|> class TicketEditor: """shows the ticket editor and configuration screen""" def get(self, slug=None): """render the view""" <|body_0|> def post(self, slug=None): """add a new ticket class""" <|body_1|> def delete(self, slug=None): """delete a sponso...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TicketEditor: """shows the ticket editor and configuration screen""" def get(self, slug=None): """render the view""" config_form = TicketConfigurationForm(self.request.form, obj=self.barcamp, config=self.config) add_form = TicketClassForm(self.request.form, config=self.config) ...
the_stack_v2_python_sparse
camper/barcamps/ticketeditor.py
comlounge/camper
train
14
f6457593cc9db9d9db149102a50275f26f1dc34f
[ "parsed = urlparse(url)\nif not parsed.path:\n return None\nfilename = os.path.basename(parsed.path)\n_, extension = os.path.splitext(filename)\nif not extension:\n return None\nelse:\n return filename", "header = response.info().get('Content-Disposition', '')\nif not header:\n return None\n_, params ...
<|body_start_0|> parsed = urlparse(url) if not parsed.path: return None filename = os.path.basename(parsed.path) _, extension = os.path.splitext(filename) if not extension: return None else: return filename <|end_body_0|> <|body_start_...
UrlDownload
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UrlDownload: def _url_filename(self, url): """Based on the url return the filename it contains or None if no filename is specified. URL with a filename: http://example.com/file.txt URL without a filename: http://example.com :param url: The URL as a string :return: The filename or None if...
stack_v2_sparse_classes_75kplus_train_006693
2,292
permissive
[ { "docstring": "Based on the url return the filename it contains or None if no filename is specified. URL with a filename: http://example.com/file.txt URL without a filename: http://example.com :param url: The URL as a string :return: The filename or None if no filename is in the URL.", "name": "_url_filena...
3
null
Implement the Python class `UrlDownload` described below. Class description: Implement the UrlDownload class. Method signatures and docstrings: - def _url_filename(self, url): Based on the url return the filename it contains or None if no filename is specified. URL with a filename: http://example.com/file.txt URL wit...
Implement the Python class `UrlDownload` described below. Class description: Implement the UrlDownload class. Method signatures and docstrings: - def _url_filename(self, url): Based on the url return the filename it contains or None if no filename is specified. URL with a filename: http://example.com/file.txt URL wit...
ba94d46ce58ac7e936fc45acaca1168ae0d7780b
<|skeleton|> class UrlDownload: def _url_filename(self, url): """Based on the url return the filename it contains or None if no filename is specified. URL with a filename: http://example.com/file.txt URL without a filename: http://example.com :param url: The URL as a string :return: The filename or None if...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UrlDownload: def _url_filename(self, url): """Based on the url return the filename it contains or None if no filename is specified. URL with a filename: http://example.com/file.txt URL without a filename: http://example.com :param url: The URL as a string :return: The filename or None if no filename i...
the_stack_v2_python_sparse
src/wurf/url_download.py
steinwurf/waf
train
15
5b11ec1e6e105f7d6d4b320533de8cf1fdb342f4
[ "self.object = self.get_object()\noauth_token = request.GET.get('oauth_token', '')\noauth_verifier = request.GET.get('oauth_verifier', '')\nif oauth_token and oauth_verifier:\n '\\n Ok, this is an oauth_callback from twitter, we have both vars in the GET env\\n extract them and compare to ...
<|body_start_0|> self.object = self.get_object() oauth_token = request.GET.get('oauth_token', '') oauth_verifier = request.GET.get('oauth_verifier', '') if oauth_token and oauth_verifier: '\n Ok, this is an oauth_callback from twitter, we have both vars in the GET ...
view for three-legged oauth key retrieval to allow ewe_ebooks to post on user's behalf
BotAuthorizeView
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BotAuthorizeView: """view for three-legged oauth key retrieval to allow ewe_ebooks to post on user's behalf""" def get(self, request, *args, **kwargs): """Overwrite the default get method for this view so we can use the same view for both parts of the authorization process""" ...
stack_v2_sparse_classes_75kplus_train_006694
10,146
permissive
[ { "docstring": "Overwrite the default get method for this view so we can use the same view for both parts of the authorization process", "name": "get", "signature": "def get(self, request, *args, **kwargs)" }, { "docstring": "Function for generating initial request token for three-legged oauth T...
4
stack_v2_sparse_classes_30k_train_008061
Implement the Python class `BotAuthorizeView` described below. Class description: view for three-legged oauth key retrieval to allow ewe_ebooks to post on user's behalf Method signatures and docstrings: - def get(self, request, *args, **kwargs): Overwrite the default get method for this view so we can use the same vi...
Implement the Python class `BotAuthorizeView` described below. Class description: view for three-legged oauth key retrieval to allow ewe_ebooks to post on user's behalf Method signatures and docstrings: - def get(self, request, *args, **kwargs): Overwrite the default get method for this view so we can use the same vi...
06ffa6c881d205ab00a55c195ee79bccd2da77ec
<|skeleton|> class BotAuthorizeView: """view for three-legged oauth key retrieval to allow ewe_ebooks to post on user's behalf""" def get(self, request, *args, **kwargs): """Overwrite the default get method for this view so we can use the same view for both parts of the authorization process""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BotAuthorizeView: """view for three-legged oauth key retrieval to allow ewe_ebooks to post on user's behalf""" def get(self, request, *args, **kwargs): """Overwrite the default get method for this view so we can use the same view for both parts of the authorization process""" self.object ...
the_stack_v2_python_sparse
bots/views.py
jaymcgrath/ewe_ebooks
train
4
0a107924bf5ad651bba0fead48d0853bb5e914b2
[ "if not (head and head.next):\n return head\nnext = head.next\nhead.next = self.swapPairs(next.next)\nnext.next = head\nreturn next", "prev = dummy = ListNode(None)\nprev.next = head\nwhile prev.next and prev.next.next:\n a1 = prev.next\n a2 = a1.next\n a1.next = a2.next\n a2.next = a1\n prev.ne...
<|body_start_0|> if not (head and head.next): return head next = head.next head.next = self.swapPairs(next.next) next.next = head return next <|end_body_0|> <|body_start_1|> prev = dummy = ListNode(None) prev.next = head while prev.next and pr...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def swapPairs_1(self, head: ListNode) -> ListNode: """1. 递归解法""" <|body_0|> def swapPairs(self, head: ListNode) -> ListNode: """2. 递推解法:多个节点 prev、a1、a2、next 的交替操作; 难点:要返回处理后链表的 首节点 --> 设置一个 dummy 节点!!""" <|body_1|> <|end_skeleton|> <|body_start_0|...
stack_v2_sparse_classes_75kplus_train_006695
2,016
no_license
[ { "docstring": "1. 递归解法", "name": "swapPairs_1", "signature": "def swapPairs_1(self, head: ListNode) -> ListNode" }, { "docstring": "2. 递推解法:多个节点 prev、a1、a2、next 的交替操作; 难点:要返回处理后链表的 首节点 --> 设置一个 dummy 节点!!", "name": "swapPairs", "signature": "def swapPairs(self, head: ListNode) -> ListNo...
2
stack_v2_sparse_classes_30k_train_042668
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def swapPairs_1(self, head: ListNode) -> ListNode: 1. 递归解法 - def swapPairs(self, head: ListNode) -> ListNode: 2. 递推解法:多个节点 prev、a1、a2、next 的交替操作; 难点:要返回处理后链表的 首节点 --> 设置一个 dummy ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def swapPairs_1(self, head: ListNode) -> ListNode: 1. 递归解法 - def swapPairs(self, head: ListNode) -> ListNode: 2. 递推解法:多个节点 prev、a1、a2、next 的交替操作; 难点:要返回处理后链表的 首节点 --> 设置一个 dummy ...
4732fb80710a08a715c3e7080c394f5298b8326d
<|skeleton|> class Solution: def swapPairs_1(self, head: ListNode) -> ListNode: """1. 递归解法""" <|body_0|> def swapPairs(self, head: ListNode) -> ListNode: """2. 递推解法:多个节点 prev、a1、a2、next 的交替操作; 难点:要返回处理后链表的 首节点 --> 设置一个 dummy 节点!!""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def swapPairs_1(self, head: ListNode) -> ListNode: """1. 递归解法""" if not (head and head.next): return head next = head.next head.next = self.swapPairs(next.next) next.next = head return next def swapPairs(self, head: ListNode) -> ListNo...
the_stack_v2_python_sparse
02-linkedlist/24.两两交换链表中的节点.py
xiaoruijiang/algorithm
train
0
c658c2bb4604adf45191337b4a2fb2ea872a6d34
[ "company = self.cleaned_data['company']\nif company.duns_number:\n raise ValidationError(self.COMPANY_ALREADY_DNB_LINKED)\nreturn company", "duns_number = self.cleaned_data['duns_number']\nif Company.objects.filter(duns_number=duns_number).exists():\n raise ValidationError(self.DUNS_NUMBER_ALREADY_LINKED)\n...
<|body_start_0|> company = self.cleaned_data['company'] if company.duns_number: raise ValidationError(self.COMPANY_ALREADY_DNB_LINKED) return company <|end_body_0|> <|body_start_1|> duns_number = self.cleaned_data['duns_number'] if Company.objects.filter(duns_number=...
Form used for selecting Data Hub company id and D&B duns number for linking.
SelectIdsToLinkForm
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SelectIdsToLinkForm: """Form used for selecting Data Hub company id and D&B duns number for linking.""" def clean_company(self): """Check that the company does not already have a duns number.""" <|body_0|> def clean_duns_number(self): """Check that the duns_numbe...
stack_v2_sparse_classes_75kplus_train_006696
1,589
permissive
[ { "docstring": "Check that the company does not already have a duns number.", "name": "clean_company", "signature": "def clean_company(self)" }, { "docstring": "Check that the duns_number chosen has not already been linked to a Data Hub company.", "name": "clean_duns_number", "signature"...
2
stack_v2_sparse_classes_30k_train_026580
Implement the Python class `SelectIdsToLinkForm` described below. Class description: Form used for selecting Data Hub company id and D&B duns number for linking. Method signatures and docstrings: - def clean_company(self): Check that the company does not already have a duns number. - def clean_duns_number(self): Chec...
Implement the Python class `SelectIdsToLinkForm` described below. Class description: Form used for selecting Data Hub company id and D&B duns number for linking. Method signatures and docstrings: - def clean_company(self): Check that the company does not already have a duns number. - def clean_duns_number(self): Chec...
a92faabf73fb93b5bfd94fd465eafc3e29aa6d8e
<|skeleton|> class SelectIdsToLinkForm: """Form used for selecting Data Hub company id and D&B duns number for linking.""" def clean_company(self): """Check that the company does not already have a duns number.""" <|body_0|> def clean_duns_number(self): """Check that the duns_numbe...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SelectIdsToLinkForm: """Form used for selecting Data Hub company id and D&B duns number for linking.""" def clean_company(self): """Check that the company does not already have a duns number.""" company = self.cleaned_data['company'] if company.duns_number: raise Valid...
the_stack_v2_python_sparse
datahub/company/admin/dnb_link/forms.py
cgsunkel/data-hub-api
train
0
7a463cb3e435fae4040d8942676e6ee5a05afba8
[ "super(LOOSuper, self).__init__(**kwargs)\nself.loo_axis = loo_axis\nself.split_groups = None\nif split_groups_file is not None:\n self.split_groups = file_utils.pickle_load(split_groups_file)\nself.index_splitter = IndexSplitter(**kwargs)\nself.loo_pool = not no_loo_pool\nself.use_folds = use_folds\nself.num_fo...
<|body_start_0|> super(LOOSuper, self).__init__(**kwargs) self.loo_axis = loo_axis self.split_groups = None if split_groups_file is not None: self.split_groups = file_utils.pickle_load(split_groups_file) self.index_splitter = IndexSplitter(**kwargs) self.loo_p...
Return several splits of a leave one out scheme
LOOSuper
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LOOSuper: """Return several splits of a leave one out scheme""" def __init__(self, loo_axis: str='SUBSTRATES', split_groups_file: str=None, no_loo_pool: bool=False, num_folds: int=3, use_folds: bool=False, num_kfold_trials: int=1, **kwargs): """__init__. Args: val_size (float): Fract...
stack_v2_sparse_classes_75kplus_train_006697
23,923
no_license
[ { "docstring": "__init__. Args: val_size (float): Fraction of the training set to siphon off into val loo_axis (str) : Name of the axis to do the leave one out over split_groups_file (str) : Name of the split groups file no_loo_pool (bool): If true, pool all items together. Treat them as separate metrics. num_f...
2
stack_v2_sparse_classes_30k_train_050044
Implement the Python class `LOOSuper` described below. Class description: Return several splits of a leave one out scheme Method signatures and docstrings: - def __init__(self, loo_axis: str='SUBSTRATES', split_groups_file: str=None, no_loo_pool: bool=False, num_folds: int=3, use_folds: bool=False, num_kfold_trials: ...
Implement the Python class `LOOSuper` described below. Class description: Return several splits of a leave one out scheme Method signatures and docstrings: - def __init__(self, loo_axis: str='SUBSTRATES', split_groups_file: str=None, no_loo_pool: bool=False, num_folds: int=3, use_folds: bool=False, num_kfold_trials: ...
84c9026c78bec9a2267960a87080b71beba5c305
<|skeleton|> class LOOSuper: """Return several splits of a leave one out scheme""" def __init__(self, loo_axis: str='SUBSTRATES', split_groups_file: str=None, no_loo_pool: bool=False, num_folds: int=3, use_folds: bool=False, num_kfold_trials: int=1, **kwargs): """__init__. Args: val_size (float): Fract...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LOOSuper: """Return several splits of a leave one out scheme""" def __init__(self, loo_axis: str='SUBSTRATES', split_groups_file: str=None, no_loo_pool: bool=False, num_folds: int=3, use_folds: bool=False, num_kfold_trials: int=1, **kwargs): """__init__. Args: val_size (float): Fraction of the tr...
the_stack_v2_python_sparse
enzpred/dataset/splitter.py
liudongliangHI/enz-pred
train
0
9eb69f1a81048ca25d742c762784297a5b94ad17
[ "listview = reverse(self.listview_name)\nresponse = self.client.get(listview)\nself.assertEqual(response.status_code, status.HTTP_200_OK)\nself.assertIn('results', response.data)", "detailview = reverse(self.detailview_name, args=(self.object.pk,))\nresponse = self.client.get(detailview)\nself.assertEqual(respons...
<|body_start_0|> listview = reverse(self.listview_name) response = self.client.get(listview) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertIn('results', response.data) <|end_body_0|> <|body_start_1|> detailview = reverse(self.detailview_name, args=(self.o...
OpenBudgetsAPITestCase
[ "BSD-2-Clause", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OpenBudgetsAPITestCase: def listview(self): """Simple test to verify the API list view returns what we'd minimally expect""" <|body_0|> def detailview(self): """Simple test to verify the API detail view returns what we'd minimally expect""" <|body_1|> <|end_...
stack_v2_sparse_classes_75kplus_train_006698
1,732
permissive
[ { "docstring": "Simple test to verify the API list view returns what we'd minimally expect", "name": "listview", "signature": "def listview(self)" }, { "docstring": "Simple test to verify the API detail view returns what we'd minimally expect", "name": "detailview", "signature": "def det...
2
stack_v2_sparse_classes_30k_train_035698
Implement the Python class `OpenBudgetsAPITestCase` described below. Class description: Implement the OpenBudgetsAPITestCase class. Method signatures and docstrings: - def listview(self): Simple test to verify the API list view returns what we'd minimally expect - def detailview(self): Simple test to verify the API d...
Implement the Python class `OpenBudgetsAPITestCase` described below. Class description: Implement the OpenBudgetsAPITestCase class. Method signatures and docstrings: - def listview(self): Simple test to verify the API list view returns what we'd minimally expect - def detailview(self): Simple test to verify the API d...
f4364156e83e0328285731d266b97f016d539df9
<|skeleton|> class OpenBudgetsAPITestCase: def listview(self): """Simple test to verify the API list view returns what we'd minimally expect""" <|body_0|> def detailview(self): """Simple test to verify the API detail view returns what we'd minimally expect""" <|body_1|> <|end_...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class OpenBudgetsAPITestCase: def listview(self): """Simple test to verify the API list view returns what we'd minimally expect""" listview = reverse(self.listview_name) response = self.client.get(listview) self.assertEqual(response.status_code, status.HTTP_200_OK) self.asser...
the_stack_v2_python_sparse
openbudgets/commons/tests.py
hasadna/openmuni-budgets
train
3
00d3d1516ffdba006272dd4deacb065b45c11c41
[ "value = self.raw_value.strip()\nif value in {'-', '--', '---'}:\n self.set_empty = True\n value = None\nelif value:\n try:\n value = int(self.raw_value)\n if not 0 < value < 31:\n raise ValueError\n except ValueError:\n self.add_error(errors.WRONG_VALUE_ERROR, column_nam...
<|body_start_0|> value = self.raw_value.strip() if value in {'-', '--', '---'}: self.set_empty = True value = None elif value: try: value = int(self.raw_value) if not 0 < value < 31: raise ValueError ...
Handler for workflow 'repeat every' column.
RepeatEveryColumnHandler
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RepeatEveryColumnHandler: """Handler for workflow 'repeat every' column.""" def parse_item(self): """Parse 'repeat every' value""" <|body_0|> def get_value(self): """Get 'Repeat Every' user readable value for Workflow.""" <|body_1|> <|end_skeleton|> <|b...
stack_v2_sparse_classes_75kplus_train_006699
8,702
permissive
[ { "docstring": "Parse 'repeat every' value", "name": "parse_item", "signature": "def parse_item(self)" }, { "docstring": "Get 'Repeat Every' user readable value for Workflow.", "name": "get_value", "signature": "def get_value(self)" } ]
2
stack_v2_sparse_classes_30k_train_025020
Implement the Python class `RepeatEveryColumnHandler` described below. Class description: Handler for workflow 'repeat every' column. Method signatures and docstrings: - def parse_item(self): Parse 'repeat every' value - def get_value(self): Get 'Repeat Every' user readable value for Workflow.
Implement the Python class `RepeatEveryColumnHandler` described below. Class description: Handler for workflow 'repeat every' column. Method signatures and docstrings: - def parse_item(self): Parse 'repeat every' value - def get_value(self): Get 'Repeat Every' user readable value for Workflow. <|skeleton|> class Rep...
9bdc0fc6ca9e252f4919db682d80e360d5581eb4
<|skeleton|> class RepeatEveryColumnHandler: """Handler for workflow 'repeat every' column.""" def parse_item(self): """Parse 'repeat every' value""" <|body_0|> def get_value(self): """Get 'Repeat Every' user readable value for Workflow.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RepeatEveryColumnHandler: """Handler for workflow 'repeat every' column.""" def parse_item(self): """Parse 'repeat every' value""" value = self.raw_value.strip() if value in {'-', '--', '---'}: self.set_empty = True value = None elif value: ...
the_stack_v2_python_sparse
src/ggrc_workflows/converters/handlers.py
HLD/ggrc-core
train
0