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
4523682dcf460318a9c7000cf83a526cfb0b40e8
[ "states = [{' ': 0, 'sign': 1, 'digit': 2, '.': 4}, {'digit': 2, '.': 4}, {'digit': 2, '.': 3, 'e': 5, ' ': 8}, {'digit': 3, 'e': 5, ' ': 8}, {'digit': 3}, {'sign': 6, 'digit': 7}, {'digit': 7}, {'digit': 7, ' ': 8}, {' ': 8}]\nstate = 0\nfor c in s:\n if '0' <= c <= '9':\n target = 'digit'\n elif c in...
<|body_start_0|> states = [{' ': 0, 'sign': 1, 'digit': 2, '.': 4}, {'digit': 2, '.': 4}, {'digit': 2, '.': 3, 'e': 5, ' ': 8}, {'digit': 3, 'e': 5, ' ': 8}, {'digit': 3}, {'sign': 6, 'digit': 7}, {'digit': 7}, {'digit': 7, ' ': 8}, {' ': 8}] state = 0 for c in s: if '0' <= c <= '9':...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isNumber(self, s: str) -> bool: """:type s: str :rtype: bool""" <|body_0|> def isNumber_cheat(self, s): """:type s: str :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> states = [{' ': 0, 'sign': 1, 'digit': 2, '.': 4}, {'d...
stack_v2_sparse_classes_75kplus_train_068400
1,950
no_license
[ { "docstring": ":type s: str :rtype: bool", "name": "isNumber", "signature": "def isNumber(self, s: str) -> bool" }, { "docstring": ":type s: str :rtype: bool", "name": "isNumber_cheat", "signature": "def isNumber_cheat(self, s)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isNumber(self, s: str) -> bool: :type s: str :rtype: bool - def isNumber_cheat(self, s): :type s: str :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isNumber(self, s: str) -> bool: :type s: str :rtype: bool - def isNumber_cheat(self, s): :type s: str :rtype: bool <|skeleton|> class Solution: def isNumber(self, s: st...
8343f4258d20661f70f0462c358ef8b118a03de4
<|skeleton|> class Solution: def isNumber(self, s: str) -> bool: """:type s: str :rtype: bool""" <|body_0|> def isNumber_cheat(self, s): """:type s: str :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def isNumber(self, s: str) -> bool: """:type s: str :rtype: bool""" states = [{' ': 0, 'sign': 1, 'digit': 2, '.': 4}, {'digit': 2, '.': 4}, {'digit': 2, '.': 3, 'e': 5, ' ': 8}, {'digit': 3, 'e': 5, ' ': 8}, {'digit': 3}, {'sign': 6, 'digit': 7}, {'digit': 7}, {'digit': 7, ' ': 8}, ...
the_stack_v2_python_sparse
python/offer_20_isNumber.py
Aiooon/MyLeetcode
train
0
afe1f6fc453aafec31c5918572f6cbb9c6a7cc63
[ "self.id = bag_files[0].split('_')[4].split('.')[0]\nself.bags = [bag.Bag(folder, bf, launch_file) for bf in bag_files]\nself.length = len(self.bags)\nself.area_poly = area_poly\nself.area_max = area_poly.area\nself.tmin = 0.0\nself.tmax = 0.0\nself.found = 0.0\nself.rescued = 0.0\nself.fov = 0.0", "for i, b in e...
<|body_start_0|> self.id = bag_files[0].split('_')[4].split('.')[0] self.bags = [bag.Bag(folder, bf, launch_file) for bf in bag_files] self.length = len(self.bags) self.area_poly = area_poly self.area_max = area_poly.area self.tmin = 0.0 self.tmax = 0.0 se...
a class for storing the bag file contents of one (simulation) run with multiple UAVs
Run
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Run: """a class for storing the bag file contents of one (simulation) run with multiple UAVs""" def __init__(self, folder, bag_files, launch_file, area_poly): """initialize class :param string folder: absolute path of the bag file directory :param string bag_files: name of the bag fi...
stack_v2_sparse_classes_75kplus_train_068401
5,444
permissive
[ { "docstring": "initialize class :param string folder: absolute path of the bag file directory :param string bag_files: name of the bag files for this run :param string launch_file: launch file that was launched to generate the bag files :param polygon area_poly: maximum coverable area", "name": "__init__",...
5
stack_v2_sparse_classes_30k_train_004851
Implement the Python class `Run` described below. Class description: a class for storing the bag file contents of one (simulation) run with multiple UAVs Method signatures and docstrings: - def __init__(self, folder, bag_files, launch_file, area_poly): initialize class :param string folder: absolute path of the bag f...
Implement the Python class `Run` described below. Class description: a class for storing the bag file contents of one (simulation) run with multiple UAVs Method signatures and docstrings: - def __init__(self, folder, bag_files, launch_file, area_poly): initialize class :param string folder: absolute path of the bag f...
1b5fdbf42f027964b96a06e060f3a1757b91d9fd
<|skeleton|> class Run: """a class for storing the bag file contents of one (simulation) run with multiple UAVs""" def __init__(self, folder, bag_files, launch_file, area_poly): """initialize class :param string folder: absolute path of the bag file directory :param string bag_files: name of the bag fi...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Run: """a class for storing the bag file contents of one (simulation) run with multiple UAVs""" def __init__(self, folder, bag_files, launch_file, area_poly): """initialize class :param string folder: absolute path of the bag file directory :param string bag_files: name of the bag files for this ...
the_stack_v2_python_sparse
cpswarm_sar/scripts/modules/run.py
cpswarm/complex_behaviors
train
4
81f70950637831e8dca13cac4198a0aa535444b8
[ "self.file_name = file_name\nself.file_type = file_type\nself.data = {}\nself.config_dir = 'config/'\nself.parse_config_file()", "log.info('Parsing configuration file: %s.%s' % (self.file_name, self.file_type))\nif 'xml' == self.file_type:\n path = self.config_dir + self.file_name + '.' + self.file_type\n s...
<|body_start_0|> self.file_name = file_name self.file_type = file_type self.data = {} self.config_dir = 'config/' self.parse_config_file() <|end_body_0|> <|body_start_1|> log.info('Parsing configuration file: %s.%s' % (self.file_name, self.file_type)) if 'xml' ==...
Config base class. Stores basic configuration information for a given subsytem. A given configuration will read its configuration input file and created a dictionary of the data stored. Example usage could be storing pin numbers of motors, ip addresses of hosts, etc.
Config
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Config: """Config base class. Stores basic configuration information for a given subsytem. A given configuration will read its configuration input file and created a dictionary of the data stored. Example usage could be storing pin numbers of motors, ip addresses of hosts, etc.""" def __init...
stack_v2_sparse_classes_75kplus_train_068402
6,119
no_license
[ { "docstring": "Initialize a configuration object.", "name": "__init__", "signature": "def __init__(self, file_name, file_type='xml')" }, { "docstring": "Parse configuration file and store data in data dictionary.", "name": "parse_config_file", "signature": "def parse_config_file(self)" ...
2
stack_v2_sparse_classes_30k_train_038112
Implement the Python class `Config` described below. Class description: Config base class. Stores basic configuration information for a given subsytem. A given configuration will read its configuration input file and created a dictionary of the data stored. Example usage could be storing pin numbers of motors, ip addr...
Implement the Python class `Config` described below. Class description: Config base class. Stores basic configuration information for a given subsytem. A given configuration will read its configuration input file and created a dictionary of the data stored. Example usage could be storing pin numbers of motors, ip addr...
6b2a26a9738c56228082030a75769eeb53cc2168
<|skeleton|> class Config: """Config base class. Stores basic configuration information for a given subsytem. A given configuration will read its configuration input file and created a dictionary of the data stored. Example usage could be storing pin numbers of motors, ip addresses of hosts, etc.""" def __init...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Config: """Config base class. Stores basic configuration information for a given subsytem. A given configuration will read its configuration input file and created a dictionary of the data stored. Example usage could be storing pin numbers of motors, ip addresses of hosts, etc.""" def __init__(self, file...
the_stack_v2_python_sparse
init.py
joshrands/smartspa-develop
train
1
9cd2a7ebe7f3daf4783cfdd6ab2b091a822e36d7
[ "filtered_paths = OrderedDict()\nfor path in paths:\n if not STATIC_POSTPROCESS_IGNORE_REGEX.match(path):\n filtered_paths[path] = paths[path]\nyield from super().post_process(filtered_paths, dry_run=dry_run, **options)", "url = super().url(name, force=force)\ncdn_domain = getattr(settings, 'CDN_DOMAIN'...
<|body_start_0|> filtered_paths = OrderedDict() for path in paths: if not STATIC_POSTPROCESS_IGNORE_REGEX.match(path): filtered_paths[path] = paths[path] yield from super().post_process(filtered_paths, dry_run=dry_run, **options) <|end_body_0|> <|body_start_1|> ...
Manifest static files storage backend that can be placed behing a CDN and ignores files that are already versioned by webpack.
CDNManifestStaticFilesStorage
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "AGPL-3.0-only" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CDNManifestStaticFilesStorage: """Manifest static files storage backend that can be placed behing a CDN and ignores files that are already versioned by webpack.""" def post_process(self, paths, dry_run=False, **options): """Remove paths from file to post process. Some js static files...
stack_v2_sparse_classes_75kplus_train_068403
2,168
permissive
[ { "docstring": "Remove paths from file to post process. Some js static files generated by webpack already have a unique name per build and may be referenced from within the js applications. We therefore don't want to hash their name and include them in the manifest file. We use a regex configurable via settings...
2
null
Implement the Python class `CDNManifestStaticFilesStorage` described below. Class description: Manifest static files storage backend that can be placed behing a CDN and ignores files that are already versioned by webpack. Method signatures and docstrings: - def post_process(self, paths, dry_run=False, **options): Rem...
Implement the Python class `CDNManifestStaticFilesStorage` described below. Class description: Manifest static files storage backend that can be placed behing a CDN and ignores files that are already versioned by webpack. Method signatures and docstrings: - def post_process(self, paths, dry_run=False, **options): Rem...
f2d46fc46b271eb3b4d565039a29c15ba15f027c
<|skeleton|> class CDNManifestStaticFilesStorage: """Manifest static files storage backend that can be placed behing a CDN and ignores files that are already versioned by webpack.""" def post_process(self, paths, dry_run=False, **options): """Remove paths from file to post process. Some js static files...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CDNManifestStaticFilesStorage: """Manifest static files storage backend that can be placed behing a CDN and ignores files that are already versioned by webpack.""" def post_process(self, paths, dry_run=False, **options): """Remove paths from file to post process. Some js static files generated by...
the_stack_v2_python_sparse
cookiecutter/{{cookiecutter.organization}}-richie-site-factory/template/{{cookiecutter.site}}/src/backend/base/storage.py
openfun/richie
train
238
f5f41b8b1c8b4dac5e3bcf693a8b5570a8e21a35
[ "if 'lat' in udims and 'lon' in udims and self._dim_in(['lat', 'lon'], source_coordinates, eval_coordinates) and source_coordinates['lat'].is_uniform and source_coordinates['lon'].is_uniform and eval_coordinates['lat'].is_uniform and eval_coordinates['lon'].is_uniform:\n return udims\nreturn tuple()", "if len(...
<|body_start_0|> if 'lat' in udims and 'lon' in udims and self._dim_in(['lat', 'lon'], source_coordinates, eval_coordinates) and source_coordinates['lat'].is_uniform and source_coordinates['lon'].is_uniform and eval_coordinates['lat'].is_uniform and eval_coordinates['lon'].is_uniform: return udims ...
Rasterio Interpolation Attributes ---------- {interpolator_attributes} rasterio_interpolators : list of str Interpolator methods available via rasterio
RasterioInterpolator
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RasterioInterpolator: """Rasterio Interpolation Attributes ---------- {interpolator_attributes} rasterio_interpolators : list of str Interpolator methods available via rasterio""" def can_interpolate(self, udims, source_coordinates, eval_coordinates): """{interpolator_can_interpolate...
stack_v2_sparse_classes_75kplus_train_068404
4,214
permissive
[ { "docstring": "{interpolator_can_interpolate}", "name": "can_interpolate", "signature": "def can_interpolate(self, udims, source_coordinates, eval_coordinates)" }, { "docstring": "{interpolator_interpolate}", "name": "interpolate", "signature": "def interpolate(self, udims, source_coord...
2
stack_v2_sparse_classes_30k_train_054484
Implement the Python class `RasterioInterpolator` described below. Class description: Rasterio Interpolation Attributes ---------- {interpolator_attributes} rasterio_interpolators : list of str Interpolator methods available via rasterio Method signatures and docstrings: - def can_interpolate(self, udims, source_coor...
Implement the Python class `RasterioInterpolator` described below. Class description: Rasterio Interpolation Attributes ---------- {interpolator_attributes} rasterio_interpolators : list of str Interpolator methods available via rasterio Method signatures and docstrings: - def can_interpolate(self, udims, source_coor...
66d8ec7a9086e39347e32922e15a3f59cb055415
<|skeleton|> class RasterioInterpolator: """Rasterio Interpolation Attributes ---------- {interpolator_attributes} rasterio_interpolators : list of str Interpolator methods available via rasterio""" def can_interpolate(self, udims, source_coordinates, eval_coordinates): """{interpolator_can_interpolate...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RasterioInterpolator: """Rasterio Interpolation Attributes ---------- {interpolator_attributes} rasterio_interpolators : list of str Interpolator methods available via rasterio""" def can_interpolate(self, udims, source_coordinates, eval_coordinates): """{interpolator_can_interpolate}""" ...
the_stack_v2_python_sparse
podpac/core/interpolation/rasterio_interpolator.py
creare-com/podpac
train
48
85807e817813c4f6ed9e0f089ec36f1c8f2ee60e
[ "self.x = np.array(x)\nself.y = np.array(y)\nself.feature_names = x_feature_names\nself.label_names = y_label_names\nself.cv_parts = cv_parts", "if x_test is None:\n x_test = self.x\nclf.fit(self.x, self.y)\ny_pred = clf.predict(x_test)\nreturn (clf, y_pred)", "if one_vs_rest:\n clf = OneVsRestClassifier(...
<|body_start_0|> self.x = np.array(x) self.y = np.array(y) self.feature_names = x_feature_names self.label_names = y_label_names self.cv_parts = cv_parts <|end_body_0|> <|body_start_1|> if x_test is None: x_test = self.x clf.fit(self.x, self.y) ...
Base classifier for all implemented classifiers - parent class. All implemented classifiers needs to have implementation of its methods.
BaseClassifier
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseClassifier: """Base classifier for all implemented classifiers - parent class. All implemented classifiers needs to have implementation of its methods.""" def __init__(self, x, y, x_feature_names, y_label_names, cv_parts=5): """:param x: list of x values/features in shape (number...
stack_v2_sparse_classes_75kplus_train_068405
4,977
no_license
[ { "docstring": ":param x: list of x values/features in shape (number of instances x number of features); x_train :param y: list of labels, 1D vector of numbers from 0 to N-1, where N is number of labels; y_train :param x_feature_names: list of feature names = x data column headers :param y_label_names: list of ...
6
null
Implement the Python class `BaseClassifier` described below. Class description: Base classifier for all implemented classifiers - parent class. All implemented classifiers needs to have implementation of its methods. Method signatures and docstrings: - def __init__(self, x, y, x_feature_names, y_label_names, cv_parts...
Implement the Python class `BaseClassifier` described below. Class description: Base classifier for all implemented classifiers - parent class. All implemented classifiers needs to have implementation of its methods. Method signatures and docstrings: - def __init__(self, x, y, x_feature_names, y_label_names, cv_parts...
5630a5be624305b5db5f9daae8c66c32bfdfce42
<|skeleton|> class BaseClassifier: """Base classifier for all implemented classifiers - parent class. All implemented classifiers needs to have implementation of its methods.""" def __init__(self, x, y, x_feature_names, y_label_names, cv_parts=5): """:param x: list of x values/features in shape (number...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BaseClassifier: """Base classifier for all implemented classifiers - parent class. All implemented classifiers needs to have implementation of its methods.""" def __init__(self, x, y, x_feature_names, y_label_names, cv_parts=5): """:param x: list of x values/features in shape (number of instances...
the_stack_v2_python_sparse
classifiers/base_classifier.py
lukaszsus/memotion-images-analysis
train
0
6a576e5319ac2dd4d542a18e16966eb85664ea0e
[ "if lang == 'en':\n self.__trans = None\nelse:\n self.__trans = gettext.translation(LOCALEDOMAIN, LOCALEDIR, [lang], fallback=True)", "if self.__trans:\n return self.__trans.gettext(message)\nelse:\n return unicode(gettext.gettext(message))" ]
<|body_start_0|> if lang == 'en': self.__trans = None else: self.__trans = gettext.translation(LOCALEDOMAIN, LOCALEDIR, [lang], fallback=True) <|end_body_0|> <|body_start_1|> if self.__trans: return self.__trans.gettext(message) else: retu...
This class provides translated strings for the configured language.
Translator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Translator: """This class provides translated strings for the configured language.""" def __init__(self, lang='en'): """:param lang: The language to translate to. The language can be: * The name of any installed .mo file * "en" to use the message strings in the code * "default" to us...
stack_v2_sparse_classes_75kplus_train_068406
17,715
no_license
[ { "docstring": ":param lang: The language to translate to. The language can be: * The name of any installed .mo file * \"en\" to use the message strings in the code * \"default\" to use the default translation being used by gettext. :type lang: string :return: nothing", "name": "__init__", "signature": ...
2
stack_v2_sparse_classes_30k_train_013456
Implement the Python class `Translator` described below. Class description: This class provides translated strings for the configured language. Method signatures and docstrings: - def __init__(self, lang='en'): :param lang: The language to translate to. The language can be: * The name of any installed .mo file * "en"...
Implement the Python class `Translator` described below. Class description: This class provides translated strings for the configured language. Method signatures and docstrings: - def __init__(self, lang='en'): :param lang: The language to translate to. The language can be: * The name of any installed .mo file * "en"...
222ebf6c9d4357af9e324a88d3aaa9641873853c
<|skeleton|> class Translator: """This class provides translated strings for the configured language.""" def __init__(self, lang='en'): """:param lang: The language to translate to. The language can be: * The name of any installed .mo file * "en" to use the message strings in the code * "default" to us...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Translator: """This class provides translated strings for the configured language.""" def __init__(self, lang='en'): """:param lang: The language to translate to. The language can be: * The name of any installed .mo file * "en" to use the message strings in the code * "default" to use the default...
the_stack_v2_python_sparse
AncestorFill/AncestorFill.py
jralls/addons-source
train
0
68ad5214491d94b3cadddcb31441c3ba95632f6d
[ "self.sensor = gateway.api.sensors[sensor_id]\nself.gateway = gateway\nself.description = description\nself.async_add_entities = async_add_entities\nself.unsubscribe = self.sensor.subscribe(self.async_update_callback)", "if self.description.update_key in self.sensor.changed_keys:\n self.unsubscribe()\n self...
<|body_start_0|> self.sensor = gateway.api.sensors[sensor_id] self.gateway = gateway self.description = description self.async_add_entities = async_add_entities self.unsubscribe = self.sensor.subscribe(self.async_update_callback) <|end_body_0|> <|body_start_1|> if self.d...
Track sensors without a battery state and add entity when battery state exist.
DeconzBatteryTracker
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DeconzBatteryTracker: """Track sensors without a battery state and add entity when battery state exist.""" def __init__(self, sensor_id: str, gateway: DeconzGateway, description: DeconzSensorDescription, async_add_entities: AddEntitiesCallback) -> None: """Set up tracker.""" ...
stack_v2_sparse_classes_75kplus_train_068407
16,422
permissive
[ { "docstring": "Set up tracker.", "name": "__init__", "signature": "def __init__(self, sensor_id: str, gateway: DeconzGateway, description: DeconzSensorDescription, async_add_entities: AddEntitiesCallback) -> None" }, { "docstring": "Update the device's state.", "name": "async_update_callbac...
2
stack_v2_sparse_classes_30k_train_001032
Implement the Python class `DeconzBatteryTracker` described below. Class description: Track sensors without a battery state and add entity when battery state exist. Method signatures and docstrings: - def __init__(self, sensor_id: str, gateway: DeconzGateway, description: DeconzSensorDescription, async_add_entities: ...
Implement the Python class `DeconzBatteryTracker` described below. Class description: Track sensors without a battery state and add entity when battery state exist. Method signatures and docstrings: - def __init__(self, sensor_id: str, gateway: DeconzGateway, description: DeconzSensorDescription, async_add_entities: ...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class DeconzBatteryTracker: """Track sensors without a battery state and add entity when battery state exist.""" def __init__(self, sensor_id: str, gateway: DeconzGateway, description: DeconzSensorDescription, async_add_entities: AddEntitiesCallback) -> None: """Set up tracker.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DeconzBatteryTracker: """Track sensors without a battery state and add entity when battery state exist.""" def __init__(self, sensor_id: str, gateway: DeconzGateway, description: DeconzSensorDescription, async_add_entities: AddEntitiesCallback) -> None: """Set up tracker.""" self.sensor =...
the_stack_v2_python_sparse
homeassistant/components/deconz/sensor.py
home-assistant/core
train
35,501
5caa4aa84954312f4e003054e7fc477ad9b7511a
[ "self._num_classes = num_classes\nself._per_class_metric = per_class_metric\nself._dice_op_overall = segmentation_losses.SegmentationLossDiceScore(metric_type=metric_type)\nself._dice_scores_overall = tf.Variable(0.0)\nself._count = tf.Variable(0.0)\nif self._per_class_metric:\n self._dice_op_per_class = segment...
<|body_start_0|> self._num_classes = num_classes self._per_class_metric = per_class_metric self._dice_op_overall = segmentation_losses.SegmentationLossDiceScore(metric_type=metric_type) self._dice_scores_overall = tf.Variable(0.0) self._count = tf.Variable(0.0) if self._p...
Dice score metric for semantic segmentation. This class follows the same function interface as tf.keras.metrics.Metric but does not derive from tf.keras.metrics.Metric or utilize its functions. The reason is a tf.keras.metrics.Metric object does not run well on CPU while created on GPU, when running with MirroredStrate...
DiceScore
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DiceScore: """Dice score metric for semantic segmentation. This class follows the same function interface as tf.keras.metrics.Metric but does not derive from tf.keras.metrics.Metric or utilize its functions. The reason is a tf.keras.metrics.Metric object does not run well on CPU while created on ...
stack_v2_sparse_classes_75kplus_train_068408
5,352
permissive
[ { "docstring": "Constructs segmentation evaluator class. Args: num_classes: The number of classes. metric_type: An optional `str` of type of dice scores. per_class_metric: Whether to report per-class metric. name: A `str`, name of the metric instance.. dtype: The data type of the metric result.", "name": "_...
4
stack_v2_sparse_classes_30k_train_043758
Implement the Python class `DiceScore` described below. Class description: Dice score metric for semantic segmentation. This class follows the same function interface as tf.keras.metrics.Metric but does not derive from tf.keras.metrics.Metric or utilize its functions. The reason is a tf.keras.metrics.Metric object doe...
Implement the Python class `DiceScore` described below. Class description: Dice score metric for semantic segmentation. This class follows the same function interface as tf.keras.metrics.Metric but does not derive from tf.keras.metrics.Metric or utilize its functions. The reason is a tf.keras.metrics.Metric object doe...
d3507b550a3ade40cade60a79eb5b8978b56c7ae
<|skeleton|> class DiceScore: """Dice score metric for semantic segmentation. This class follows the same function interface as tf.keras.metrics.Metric but does not derive from tf.keras.metrics.Metric or utilize its functions. The reason is a tf.keras.metrics.Metric object does not run well on CPU while created on ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DiceScore: """Dice score metric for semantic segmentation. This class follows the same function interface as tf.keras.metrics.Metric but does not derive from tf.keras.metrics.Metric or utilize its functions. The reason is a tf.keras.metrics.Metric object does not run well on CPU while created on GPU, when run...
the_stack_v2_python_sparse
official/projects/volumetric_models/evaluation/segmentation_metrics.py
jianzhnie/models
train
2
8ce7a4a2eda571f61fb19354435555f67422cd01
[ "if len(self.pool.samples) == 0:\n raise LookupError('no samples for executing samtools')\nif self.chromosome not in self.pool.vcf:\n self.pool.vcf[self.chromosome] = VcfFile.VcfFile(self.pool, chrom=self.chromosome, bcf=True)\n inputFileString = ''\n for sample in self.pool.samples:\n inputFileS...
<|body_start_0|> if len(self.pool.samples) == 0: raise LookupError('no samples for executing samtools') if self.chromosome not in self.pool.vcf: self.pool.vcf[self.chromosome] = VcfFile.VcfFile(self.pool, chrom=self.chromosome, bcf=True) inputFileString = '' ...
SamtoolsMpileup
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SamtoolsMpileup: def callSnvs(self): """The method samtoolsMpileup calls the single nucleotide variations of a pool with samtools mpileup. :param pool: the pool to call all SNVs from :type pool: an instance of a :py:class:`Pool.Pool` object :raises: LookupError if the pool has no samples...
stack_v2_sparse_classes_75kplus_train_068409
3,327
no_license
[ { "docstring": "The method samtoolsMpileup calls the single nucleotide variations of a pool with samtools mpileup. :param pool: the pool to call all SNVs from :type pool: an instance of a :py:class:`Pool.Pool` object :raises: LookupError if the pool has no samples to execute samtools on", "name": "callSnvs"...
2
stack_v2_sparse_classes_30k_train_006674
Implement the Python class `SamtoolsMpileup` described below. Class description: Implement the SamtoolsMpileup class. Method signatures and docstrings: - def callSnvs(self): The method samtoolsMpileup calls the single nucleotide variations of a pool with samtools mpileup. :param pool: the pool to call all SNVs from :...
Implement the Python class `SamtoolsMpileup` described below. Class description: Implement the SamtoolsMpileup class. Method signatures and docstrings: - def callSnvs(self): The method samtoolsMpileup calls the single nucleotide variations of a pool with samtools mpileup. :param pool: the pool to call all SNVs from :...
53315eca821785aa02218e903b60921ecf18246b
<|skeleton|> class SamtoolsMpileup: def callSnvs(self): """The method samtoolsMpileup calls the single nucleotide variations of a pool with samtools mpileup. :param pool: the pool to call all SNVs from :type pool: an instance of a :py:class:`Pool.Pool` object :raises: LookupError if the pool has no samples...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SamtoolsMpileup: def callSnvs(self): """The method samtoolsMpileup calls the single nucleotide variations of a pool with samtools mpileup. :param pool: the pool to call all SNVs from :type pool: an instance of a :py:class:`Pool.Pool` object :raises: LookupError if the pool has no samples to execute sa...
the_stack_v2_python_sparse
pythonCodebase/src/programs/snvCallers/SamtoolsMpileup.py
JJacobi13/VLPB
train
0
790d98e00bb0145128e134623287e9008f58d3a6
[ "if len(nums) <= 1:\n return 0\nfor i in range(len(nums)):\n if i == 0:\n if nums[i] > nums[i + 1]:\n return i\n elif i == len(nums) - 1:\n if nums[i] > nums[i - 1]:\n return i\n elif nums[i] > nums[i - 1] and nums[i] > nums[i + 1]:\n return i\nreturn -1", "i...
<|body_start_0|> if len(nums) <= 1: return 0 for i in range(len(nums)): if i == 0: if nums[i] > nums[i + 1]: return i elif i == len(nums) - 1: if nums[i] > nums[i - 1]: return i elif n...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findPeakElement(self, nums: List[int]) -> int: """常规解法,O(n)时间复杂度""" <|body_0|> def findPeakElement_2(self, nums: List[int]) -> int: """时间复杂度为O(logn)的解法""" <|body_1|> <|end_skeleton|> <|body_start_0|> if len(nums) <= 1: retu...
stack_v2_sparse_classes_75kplus_train_068410
2,327
no_license
[ { "docstring": "常规解法,O(n)时间复杂度", "name": "findPeakElement", "signature": "def findPeakElement(self, nums: List[int]) -> int" }, { "docstring": "时间复杂度为O(logn)的解法", "name": "findPeakElement_2", "signature": "def findPeakElement_2(self, nums: List[int]) -> int" } ]
2
stack_v2_sparse_classes_30k_train_051345
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findPeakElement(self, nums: List[int]) -> int: 常规解法,O(n)时间复杂度 - def findPeakElement_2(self, nums: List[int]) -> int: 时间复杂度为O(logn)的解法
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findPeakElement(self, nums: List[int]) -> int: 常规解法,O(n)时间复杂度 - def findPeakElement_2(self, nums: List[int]) -> int: 时间复杂度为O(logn)的解法 <|skeleton|> class Solution: def f...
13e7ec9fe7a92ab13b247bd4edeb1ada5de81a08
<|skeleton|> class Solution: def findPeakElement(self, nums: List[int]) -> int: """常规解法,O(n)时间复杂度""" <|body_0|> def findPeakElement_2(self, nums: List[int]) -> int: """时间复杂度为O(logn)的解法""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def findPeakElement(self, nums: List[int]) -> int: """常规解法,O(n)时间复杂度""" if len(nums) <= 1: return 0 for i in range(len(nums)): if i == 0: if nums[i] > nums[i + 1]: return i elif i == len(nums) - 1: ...
the_stack_v2_python_sparse
Algorithms/162_Find_Peak_Element/Find_Peak_Element.py
lirui-ML/my_leetcode
train
1
bebd68cb51dcce31b359ff68edacb5bedfd905b0
[ "text = 'Alignment tensors.\\n\\n'\ntext = text + '%-8s%-20s\\n' % ('Index', 'Name')\nfor i in range(len(self)):\n text = text + '%-8i%-20s\\n' % (i, self[i].name)\ntext = text + \"\\nThese can be accessed by typing 'pipe.align_tensor[index]'.\\n\"\nreturn text", "obj = AlignTensorData(name)\nself.append(obj)\...
<|body_start_0|> text = 'Alignment tensors.\n\n' text = text + '%-8s%-20s\n' % ('Index', 'Name') for i in range(len(self)): text = text + '%-8i%-20s\n' % (i, self[i].name) text = text + "\nThese can be accessed by typing 'pipe.align_tensor[index]'.\n" return text <|en...
List type data container for holding all the alignment tensors. The elements of the list should be AlignTensorData instances.
AlignTensorList
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AlignTensorList: """List type data container for holding all the alignment tensors. The elements of the list should be AlignTensorData instances.""" def __repr__(self): """Replacement function for displaying an instance of this class.""" <|body_0|> def add_item(self, nam...
stack_v2_sparse_classes_75kplus_train_068411
47,193
no_license
[ { "docstring": "Replacement function for displaying an instance of this class.", "name": "__repr__", "signature": "def __repr__(self)" }, { "docstring": "Append a new AlignTensorData instance to the list. @param name: The tensor ID string. @type name: str @return: The tensor object. @rtype: Alig...
5
stack_v2_sparse_classes_30k_train_038644
Implement the Python class `AlignTensorList` described below. Class description: List type data container for holding all the alignment tensors. The elements of the list should be AlignTensorData instances. Method signatures and docstrings: - def __repr__(self): Replacement function for displaying an instance of this...
Implement the Python class `AlignTensorList` described below. Class description: List type data container for holding all the alignment tensors. The elements of the list should be AlignTensorData instances. Method signatures and docstrings: - def __repr__(self): Replacement function for displaying an instance of this...
c317326ddeacd1a1c608128769676899daeae531
<|skeleton|> class AlignTensorList: """List type data container for holding all the alignment tensors. The elements of the list should be AlignTensorData instances.""" def __repr__(self): """Replacement function for displaying an instance of this class.""" <|body_0|> def add_item(self, nam...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AlignTensorList: """List type data container for holding all the alignment tensors. The elements of the list should be AlignTensorData instances.""" def __repr__(self): """Replacement function for displaying an instance of this class.""" text = 'Alignment tensors.\n\n' text = text...
the_stack_v2_python_sparse
data_store/align_tensor.py
jlec/relax
train
4
99a6742b6e158c89d0d84b799f8187795b2123c4
[ "klassen = CompetitieIndivKlasse.objects.select_related('competitie').filter(competitie=comp).prefetch_related('regiocompetitiesporterboog_set').order_by('volgorde')\nfor obj in klassen:\n if obj.min_ag > AG_NUL:\n ag_str = '%5.3f' % obj.min_ag\n obj.min_ag_str = ag_str.replace('.', ',')\n if to...
<|body_start_0|> klassen = CompetitieIndivKlasse.objects.select_related('competitie').filter(competitie=comp).prefetch_related('regiocompetitiesporterboog_set').order_by('volgorde') for obj in klassen: if obj.min_ag > AG_NUL: ag_str = '%5.3f' % obj.min_ag obj....
deze view laat de vastgestelde aanvangsgemiddelden voor de volgende competitie zien
KlassengrenzenTonenView
[ "BSD-3-Clause-Clear" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KlassengrenzenTonenView: """deze view laat de vastgestelde aanvangsgemiddelden voor de volgende competitie zien""" def _get_indiv_klassen(comp, toon_aantal): """geef een lijst van individuele competitie wedstrijdklassen terug met het AG geformatteerd voor presentatie.""" <|bo...
stack_v2_sparse_classes_75kplus_train_068412
4,879
permissive
[ { "docstring": "geef een lijst van individuele competitie wedstrijdklassen terug met het AG geformatteerd voor presentatie.", "name": "_get_indiv_klassen", "signature": "def _get_indiv_klassen(comp, toon_aantal)" }, { "docstring": "geef een lijst van team competitie wedstrijdklassen terug met he...
3
stack_v2_sparse_classes_30k_train_026389
Implement the Python class `KlassengrenzenTonenView` described below. Class description: deze view laat de vastgestelde aanvangsgemiddelden voor de volgende competitie zien Method signatures and docstrings: - def _get_indiv_klassen(comp, toon_aantal): geef een lijst van individuele competitie wedstrijdklassen terug m...
Implement the Python class `KlassengrenzenTonenView` described below. Class description: deze view laat de vastgestelde aanvangsgemiddelden voor de volgende competitie zien Method signatures and docstrings: - def _get_indiv_klassen(comp, toon_aantal): geef een lijst van individuele competitie wedstrijdklassen terug m...
5ed38165a231f0caa56f67e8faf2dd074916e500
<|skeleton|> class KlassengrenzenTonenView: """deze view laat de vastgestelde aanvangsgemiddelden voor de volgende competitie zien""" def _get_indiv_klassen(comp, toon_aantal): """geef een lijst van individuele competitie wedstrijdklassen terug met het AG geformatteerd voor presentatie.""" <|bo...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class KlassengrenzenTonenView: """deze view laat de vastgestelde aanvangsgemiddelden voor de volgende competitie zien""" def _get_indiv_klassen(comp, toon_aantal): """geef een lijst van individuele competitie wedstrijdklassen terug met het AG geformatteerd voor presentatie.""" klassen = Competi...
the_stack_v2_python_sparse
Competitie/views_klassengrenzen.py
RamonvdW/nhb-apps
train
2
570f3cae1483e576b7f35e887ddcf378398fb5d5
[ "super(TemporalConvNet, self).__init__()\nself.C = C\nself.X = X\nself.R = R\nself.mask_nonlinear = mask_nonlinear\nlayer_norm = ChannelwiseLayerNorm(N)\nbottleneck_conv1x1 = nn.Conv1d(N, B, 1, bias=False)\nrepeats = []\nfor r in range(R):\n blocks = []\n for x in range(X):\n dilation = 2 ** x\n ...
<|body_start_0|> super(TemporalConvNet, self).__init__() self.C = C self.X = X self.R = R self.mask_nonlinear = mask_nonlinear layer_norm = ChannelwiseLayerNorm(N) bottleneck_conv1x1 = nn.Conv1d(N, B, 1, bias=False) repeats = [] for r in range(R): ...
TemporalConvNet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TemporalConvNet: def __init__(self, N, B, H, P, X, R, C, norm_type='gLN', causal=False, mask_nonlinear='relu', locs=None, feat_loc='residual'): """Args: N: Number of filters in autoencoder B: Number of channels in bottleneck 1 × 1-conv block H: Number of channels in convolutional blocks ...
stack_v2_sparse_classes_75kplus_train_068413
14,028
no_license
[ { "docstring": "Args: N: Number of filters in autoencoder B: Number of channels in bottleneck 1 × 1-conv block H: Number of channels in convolutional blocks P: Kernel size in convolutional blocks X: Number of convolutional blocks in each repeat R: Number of repeats C: Number of speakers norm_type: BN, gLN, cLN ...
3
stack_v2_sparse_classes_30k_train_031801
Implement the Python class `TemporalConvNet` described below. Class description: Implement the TemporalConvNet class. Method signatures and docstrings: - def __init__(self, N, B, H, P, X, R, C, norm_type='gLN', causal=False, mask_nonlinear='relu', locs=None, feat_loc='residual'): Args: N: Number of filters in autoenc...
Implement the Python class `TemporalConvNet` described below. Class description: Implement the TemporalConvNet class. Method signatures and docstrings: - def __init__(self, N, B, H, P, X, R, C, norm_type='gLN', causal=False, mask_nonlinear='relu', locs=None, feat_loc='residual'): Args: N: Number of filters in autoenc...
01314d4f1f5bd35d5a4938969948dd4f0bf13ab2
<|skeleton|> class TemporalConvNet: def __init__(self, N, B, H, P, X, R, C, norm_type='gLN', causal=False, mask_nonlinear='relu', locs=None, feat_loc='residual'): """Args: N: Number of filters in autoencoder B: Number of channels in bottleneck 1 × 1-conv block H: Number of channels in convolutional blocks ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TemporalConvNet: def __init__(self, N, B, H, P, X, R, C, norm_type='gLN', causal=False, mask_nonlinear='relu', locs=None, feat_loc='residual'): """Args: N: Number of filters in autoencoder B: Number of channels in bottleneck 1 × 1-conv block H: Number of channels in convolutional blocks P: Kernel size...
the_stack_v2_python_sparse
src/da_conv_tasnet.py
henryhenrychen/speech_separation_domain_adaptation
train
0
33e548776cc0853b16741e70ac517fd549d35b84
[ "super(StackedGCN, self).__init__()\nself.args = args\nself.input_channels = input_channels\nself.output_channels = output_channels\nself.setup_layers()", "self.layers = []\nself.args.layers = [self.input_channels] + self.args.layers + [self.output_channels]\nfor i, _ in enumerate(self.args.layers[:-1]):\n sel...
<|body_start_0|> super(StackedGCN, self).__init__() self.args = args self.input_channels = input_channels self.output_channels = output_channels self.setup_layers() <|end_body_0|> <|body_start_1|> self.layers = [] self.args.layers = [self.input_channels] + self.a...
Multi-layer GCN model.
StackedGCN
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StackedGCN: """Multi-layer GCN model.""" def __init__(self, args, input_channels, output_channels): """:param args: Arguments object. :input_channels: Number of features. :output_channels: Number of target features.""" <|body_0|> def setup_layers(self): """Creati...
stack_v2_sparse_classes_75kplus_train_068414
3,788
no_license
[ { "docstring": ":param args: Arguments object. :input_channels: Number of features. :output_channels: Number of target features.", "name": "__init__", "signature": "def __init__(self, args, input_channels, output_channels)" }, { "docstring": "Creating the layes based on the args.", "name": "...
3
stack_v2_sparse_classes_30k_test_001112
Implement the Python class `StackedGCN` described below. Class description: Multi-layer GCN model. Method signatures and docstrings: - def __init__(self, args, input_channels, output_channels): :param args: Arguments object. :input_channels: Number of features. :output_channels: Number of target features. - def setup...
Implement the Python class `StackedGCN` described below. Class description: Multi-layer GCN model. Method signatures and docstrings: - def __init__(self, args, input_channels, output_channels): :param args: Arguments object. :input_channels: Number of features. :output_channels: Number of target features. - def setup...
7e55a422588c1d1e00f35a3d3a3ff896cce59e18
<|skeleton|> class StackedGCN: """Multi-layer GCN model.""" def __init__(self, args, input_channels, output_channels): """:param args: Arguments object. :input_channels: Number of features. :output_channels: Number of target features.""" <|body_0|> def setup_layers(self): """Creati...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class StackedGCN: """Multi-layer GCN model.""" def __init__(self, args, input_channels, output_channels): """:param args: Arguments object. :input_channels: Number of features. :output_channels: Number of target features.""" super(StackedGCN, self).__init__() self.args = args se...
the_stack_v2_python_sparse
generated/test_benedekrozemberczki_ClusterGCN.py
jansel/pytorch-jit-paritybench
train
35
16f9664f34326755cc256a0606a3f32728fae5f3
[ "input1 = tf.random.stateless_normal([4, 4, 4], [234, 231])\nlayer1 = preproc_layers.Transpose(perm=perm, conjugate=conjugate)\noutput1 = layer1(input1)\nself.assertAllEqual(output1, tf.transpose(input1, perm=perm, conjugate=conjugate))", "config = dict(perm=[1, 0], conjugate=True, name='transpose', dtype='float3...
<|body_start_0|> input1 = tf.random.stateless_normal([4, 4, 4], [234, 231]) layer1 = preproc_layers.Transpose(perm=perm, conjugate=conjugate) output1 = layer1(input1) self.assertAllEqual(output1, tf.transpose(input1, perm=perm, conjugate=conjugate)) <|end_body_0|> <|body_start_1|> ...
Tests for layer `Transpose`.
TransposeTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TransposeTest: """Tests for layer `Transpose`.""" def test_result(self, perm, conjugate): """Test result shapes.""" <|body_0|> def test_serialize_deserialize(self): """Test de/serialization.""" <|body_1|> <|end_skeleton|> <|body_start_0|> input1...
stack_v2_sparse_classes_75kplus_train_068415
6,474
permissive
[ { "docstring": "Test result shapes.", "name": "test_result", "signature": "def test_result(self, perm, conjugate)" }, { "docstring": "Test de/serialization.", "name": "test_serialize_deserialize", "signature": "def test_serialize_deserialize(self)" } ]
2
stack_v2_sparse_classes_30k_train_002572
Implement the Python class `TransposeTest` described below. Class description: Tests for layer `Transpose`. Method signatures and docstrings: - def test_result(self, perm, conjugate): Test result shapes. - def test_serialize_deserialize(self): Test de/serialization.
Implement the Python class `TransposeTest` described below. Class description: Tests for layer `Transpose`. Method signatures and docstrings: - def test_result(self, perm, conjugate): Test result shapes. - def test_serialize_deserialize(self): Test de/serialization. <|skeleton|> class TransposeTest: """Tests for...
cfd8930ee5281e7f6dceb17c4a5acaf625fd3243
<|skeleton|> class TransposeTest: """Tests for layer `Transpose`.""" def test_result(self, perm, conjugate): """Test result shapes.""" <|body_0|> def test_serialize_deserialize(self): """Test de/serialization.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TransposeTest: """Tests for layer `Transpose`.""" def test_result(self, perm, conjugate): """Test result shapes.""" input1 = tf.random.stateless_normal([4, 4, 4], [234, 231]) layer1 = preproc_layers.Transpose(perm=perm, conjugate=conjugate) output1 = layer1(input1) ...
the_stack_v2_python_sparse
tensorflow_mri/python/layers/preproc_layers_test.py
mrphys/tensorflow-mri
train
29
a8059bf4412b8d3615ec1e4fa1e8e88d5a6906dc
[ "def dfs(arr, index):\n if sum(arr) == target:\n res.append(arr)\n return\n for i, num in enumerate(candidates):\n if i >= index and sum(arr) + num <= target:\n dfs(arr + [num], i)\nres = []\ndfs([], 0)\nreturn res", "candidates.sort()\nn = len(candidates)\nres = []\n\ndef ba...
<|body_start_0|> def dfs(arr, index): if sum(arr) == target: res.append(arr) return for i, num in enumerate(candidates): if i >= index and sum(arr) + num <= target: dfs(arr + [num], i) res = [] dfs([], 0)...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: """思路:1. :param candidates: :param target: :return:""" <|body_0|> def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: """执行用时 :52 ms, 在所有 Python3 ...
stack_v2_sparse_classes_75kplus_train_068416
2,275
no_license
[ { "docstring": "思路:1. :param candidates: :param target: :return:", "name": "combinationSum", "signature": "def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]" }, { "docstring": "执行用时 :52 ms, 在所有 Python3 提交中击败了89.99%的用户 内存消耗 :13.8 MB, 在所有 Python3 提交中击败了5.00%的用户 :param...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: 思路:1. :param candidates: :param target: :return: - def combinationSum2(self, candidates: List[int...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: 思路:1. :param candidates: :param target: :return: - def combinationSum2(self, candidates: List[int...
e43ee86c5a8cdb808da09b4b6138e10275abadb5
<|skeleton|> class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: """思路:1. :param candidates: :param target: :return:""" <|body_0|> def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: """执行用时 :52 ms, 在所有 Python3 ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: """思路:1. :param candidates: :param target: :return:""" def dfs(arr, index): if sum(arr) == target: res.append(arr) return for i, num in enumerate(c...
the_stack_v2_python_sparse
LeetCode/回溯法/39. Combination Sum.py
yiming1012/MyLeetCode
train
2
53b2d13537d0c70e9e253dcf50b2dfb1088e9a3a
[ "mit.Mit.__init__(self)\nself.regist_moc(OraSyncPriority.OraSyncPriority, OraSyncPriority.OraSyncPriorityRule)\nself.open_oracle(**db_cfg_info.get_configure(db_cfg_info.ORACLE_SYNC_CON_NAME))\nself.init_mit_lock()", "data = self.rdm_find('OraSyncPriority', ne_id=ne_id, priority=priority)\nif len(data) > 0:\n r...
<|body_start_0|> mit.Mit.__init__(self) self.regist_moc(OraSyncPriority.OraSyncPriority, OraSyncPriority.OraSyncPriorityRule) self.open_oracle(**db_cfg_info.get_configure(db_cfg_info.ORACLE_SYNC_CON_NAME)) self.init_mit_lock() <|end_body_0|> <|body_start_1|> data = self.rdm_find...
Class: DBSyncPriorityMit Description: ͬȼܵmit Base: mit.Mit Others:
DBSyncPriorityMit
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DBSyncPriorityMit: """Class: DBSyncPriorityMit Description: ͬȼܵmit Base: mit.Mit Others:""" def __init__(self): """Method: __init__ Description: 캯 Parameter: Return: Others:""" <|body_0|> def get_priority_info(self, ne_id, priority): """Method: get_priority_info ...
stack_v2_sparse_classes_75kplus_train_068417
2,686
no_license
[ { "docstring": "Method: __init__ Description: 캯 Parameter: Return: Others:", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Method: get_priority_info Description: ȼȡͬ¼ Paramters: ne_id: ԪID priority: ȼ Return: ͬ¼ҲNone", "name": "get_priority_info", "signature": ...
4
null
Implement the Python class `DBSyncPriorityMit` described below. Class description: Class: DBSyncPriorityMit Description: ͬȼܵmit Base: mit.Mit Others: Method signatures and docstrings: - def __init__(self): Method: __init__ Description: 캯 Parameter: Return: Others: - def get_priority_info(self, ne_id, priority): Metho...
Implement the Python class `DBSyncPriorityMit` described below. Class description: Class: DBSyncPriorityMit Description: ͬȼܵmit Base: mit.Mit Others: Method signatures and docstrings: - def __init__(self): Method: __init__ Description: 캯 Parameter: Return: Others: - def get_priority_info(self, ne_id, priority): Metho...
e78df71fbc5d73dd93ba9452d4b54183fe1e7e1f
<|skeleton|> class DBSyncPriorityMit: """Class: DBSyncPriorityMit Description: ͬȼܵmit Base: mit.Mit Others:""" def __init__(self): """Method: __init__ Description: 캯 Parameter: Return: Others:""" <|body_0|> def get_priority_info(self, ne_id, priority): """Method: get_priority_info ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DBSyncPriorityMit: """Class: DBSyncPriorityMit Description: ͬȼܵmit Base: mit.Mit Others:""" def __init__(self): """Method: __init__ Description: 캯 Parameter: Return: Others:""" mit.Mit.__init__(self) self.regist_moc(OraSyncPriority.OraSyncPriority, OraSyncPriority.OraSyncPriorityR...
the_stack_v2_python_sparse
weixin/code/rfid_plt/db_sync/db_sync_update_app/db_sync_priority_mit.py
allenforrest/wxbiz
train
0
204837e6365227f2b5c9259cee61720831530093
[ "m = MultiFileInput()\nself.assertTrue(m.needs_multipart_form)\nself.assertFalse(m.is_hidden)", "m = MultiFileInput({'count': 0})\nr = m.render(name='blah', value='bla', attrs={'id': 'test'})\nself.assert_('<input type=\"file\" name=\"blah[]\" id=\"test0\" />' in r)", "m = MultiFileInput()\nr = m.render(name='b...
<|body_start_0|> m = MultiFileInput() self.assertTrue(m.needs_multipart_form) self.assertFalse(m.is_hidden) <|end_body_0|> <|body_start_1|> m = MultiFileInput({'count': 0}) r = m.render(name='blah', value='bla', attrs={'id': 'test'}) self.assert_('<input type="file" name...
Tests for the widget itself.
MultiFileInputTest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiFileInputTest: """Tests for the widget itself.""" def testBasics(self): """Make sure the basics are correct (needs_multipart_form & is_hidden).""" <|body_0|> def testNoRender(self): """Makes sure we show a minimum of 1 input box.""" <|body_1|> d...
stack_v2_sparse_classes_75kplus_train_068418
3,598
no_license
[ { "docstring": "Make sure the basics are correct (needs_multipart_form & is_hidden).", "name": "testBasics", "signature": "def testBasics(self)" }, { "docstring": "Makes sure we show a minimum of 1 input box.", "name": "testNoRender", "signature": "def testNoRender(self)" }, { "d...
4
stack_v2_sparse_classes_30k_test_000555
Implement the Python class `MultiFileInputTest` described below. Class description: Tests for the widget itself. Method signatures and docstrings: - def testBasics(self): Make sure the basics are correct (needs_multipart_form & is_hidden). - def testNoRender(self): Makes sure we show a minimum of 1 input box. - def t...
Implement the Python class `MultiFileInputTest` described below. Class description: Tests for the widget itself. Method signatures and docstrings: - def testBasics(self): Make sure the basics are correct (needs_multipart_form & is_hidden). - def testNoRender(self): Makes sure we show a minimum of 1 input box. - def t...
2791145f62a7e296be859a400499812b394249e9
<|skeleton|> class MultiFileInputTest: """Tests for the widget itself.""" def testBasics(self): """Make sure the basics are correct (needs_multipart_form & is_hidden).""" <|body_0|> def testNoRender(self): """Makes sure we show a minimum of 1 input box.""" <|body_1|> d...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MultiFileInputTest: """Tests for the widget itself.""" def testBasics(self): """Make sure the basics are correct (needs_multipart_form & is_hidden).""" m = MultiFileInput() self.assertTrue(m.needs_multipart_form) self.assertFalse(m.is_hidden) def testNoRender(self): ...
the_stack_v2_python_sparse
combaragi/ccboard/tests.py
yonseics/yonseics
train
1
30d30150ac10063ee1a4e816b3ba2661930c94c1
[ "checksum = crc(path, content)\ntry:\n fobj = File.objects.get(path=path)\nexcept File.DoesNotExist:\n return True\nelse:\n return str(fobj.checksum) != checksum", "checksum = crc(path, content)\ntry:\n fobj = File.objects.get(path=path)\nexcept File.DoesNotExist:\n fobj = File(path=path)\nfobj.che...
<|body_start_0|> checksum = crc(path, content) try: fobj = File.objects.get(path=path) except File.DoesNotExist: return True else: return str(fobj.checksum) != checksum <|end_body_0|> <|body_start_1|> checksum = crc(path, content) try:...
FileManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FileManager: def is_changed(self, path, content=None): """Compare checksum of the file stored in DB and the actual file on the disk. `is_changed` is always true if no info about the file is stored in DB.""" <|body_0|> def save_file(self, path, content=None): """Save ...
stack_v2_sparse_classes_75kplus_train_068419
1,644
no_license
[ { "docstring": "Compare checksum of the file stored in DB and the actual file on the disk. `is_changed` is always true if no info about the file is stored in DB.", "name": "is_changed", "signature": "def is_changed(self, path, content=None)" }, { "docstring": "Save checksum of the file.", "n...
2
stack_v2_sparse_classes_30k_train_019978
Implement the Python class `FileManager` described below. Class description: Implement the FileManager class. Method signatures and docstrings: - def is_changed(self, path, content=None): Compare checksum of the file stored in DB and the actual file on the disk. `is_changed` is always true if no info about the file i...
Implement the Python class `FileManager` described below. Class description: Implement the FileManager class. Method signatures and docstrings: - def is_changed(self, path, content=None): Compare checksum of the file stored in DB and the actual file on the disk. `is_changed` is always true if no info about the file i...
40313d4b413a219ff2f7dfc9775258f23608b2cc
<|skeleton|> class FileManager: def is_changed(self, path, content=None): """Compare checksum of the file stored in DB and the actual file on the disk. `is_changed` is always true if no info about the file is stored in DB.""" <|body_0|> def save_file(self, path, content=None): """Save ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FileManager: def is_changed(self, path, content=None): """Compare checksum of the file stored in DB and the actual file on the disk. `is_changed` is always true if no info about the file is stored in DB.""" checksum = crc(path, content) try: fobj = File.objects.get(path=pat...
the_stack_v2_python_sparse
parser/models.py
govtrack/govtrack.us-web
train
310
343d7d2e05a4a3f2296b2e3bb30e15285a7f66fb
[ "self.target = target\nif self.target is not None and self.target not in self.SUPPORTED_LINE_NOTATIONS:\n raise ValueError(f'{target} is not a supported line representation. Choose from {self.SUPPORTED_LINE_NOTATIONS}')\nif self.target == 'smiles' or (self.target is None or self.target == 'none'):\n self.conv...
<|body_start_0|> self.target = target if self.target is not None and self.target not in self.SUPPORTED_LINE_NOTATIONS: raise ValueError(f'{target} is not a supported line representation. Choose from {self.SUPPORTED_LINE_NOTATIONS}') if self.target == 'smiles' or (self.target is None ...
Molecule line notation conversion from smiles to selfies or inchi
SmilesConverter
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SmilesConverter: """Molecule line notation conversion from smiles to selfies or inchi""" def __init__(self, target: str=None): """Convert input smiles to a target line notation Args: target: target representation.""" <|body_0|> def decode(self, inp: str): """Deco...
stack_v2_sparse_classes_75kplus_train_068420
1,998
permissive
[ { "docstring": "Convert input smiles to a target line notation Args: target: target representation.", "name": "__init__", "signature": "def __init__(self, target: str=None)" }, { "docstring": "Decode inputs into smiles Args: inp: input representation to decode", "name": "decode", "signat...
3
stack_v2_sparse_classes_30k_train_021771
Implement the Python class `SmilesConverter` described below. Class description: Molecule line notation conversion from smiles to selfies or inchi Method signatures and docstrings: - def __init__(self, target: str=None): Convert input smiles to a target line notation Args: target: target representation. - def decode(...
Implement the Python class `SmilesConverter` described below. Class description: Molecule line notation conversion from smiles to selfies or inchi Method signatures and docstrings: - def __init__(self, target: str=None): Convert input smiles to a target line notation Args: target: target representation. - def decode(...
4390f9fce25fa2da94338227f7c8f33a23e25b2a
<|skeleton|> class SmilesConverter: """Molecule line notation conversion from smiles to selfies or inchi""" def __init__(self, target: str=None): """Convert input smiles to a target line notation Args: target: target representation.""" <|body_0|> def decode(self, inp: str): """Deco...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SmilesConverter: """Molecule line notation conversion from smiles to selfies or inchi""" def __init__(self, target: str=None): """Convert input smiles to a target line notation Args: target: target representation.""" self.target = target if self.target is not None and self.target ...
the_stack_v2_python_sparse
molfeat/utils/converters.py
datamol-io/molfeat
train
111
5f5f1bcec45a0c98deb62d8df1cb3a9b2adc02b2
[ "self.dynamodb = boto3.client('dynamodb', region_name=region)\nself.table = table_name\nself.max_items = max_items\nself.worker_num = worker_num\nself.num_workers = num_workers\nif worker_num >= num_workers:\n raise ValueError('worker_num must be less than num_workers')", "exclusive_start_key = None\ndone = Fa...
<|body_start_0|> self.dynamodb = boto3.client('dynamodb', region_name=region) self.table = table_name self.max_items = max_items self.worker_num = worker_num self.num_workers = num_workers if worker_num >= num_workers: raise ValueError('worker_num must be less...
Adds lookup key to legacy items in the S3 index table. The lookup key is collection&experiment&channel&resolution. A global secondary index (GSI) will use the lookup key to allow finding all cuboids that belong to a particular channel via a DynamoDB query. An instance of this class may be used as one worker in a parall...
LookupKeyWriter
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LookupKeyWriter: """Adds lookup key to legacy items in the S3 index table. The lookup key is collection&experiment&channel&resolution. A global secondary index (GSI) will use the lookup key to allow finding all cuboids that belong to a particular channel via a DynamoDB query. An instance of this ...
stack_v2_sparse_classes_75kplus_train_068421
9,145
permissive
[ { "docstring": "Constructor. If parallelizing, supply worker_num and num_workers. See the AWS documentation for parallel scan here: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Scan.html#Scan.ParallelScan Args: table_name (str): Name of Dynamo S3 index table to operate on. region (str): AWS ...
4
stack_v2_sparse_classes_30k_train_015264
Implement the Python class `LookupKeyWriter` described below. Class description: Adds lookup key to legacy items in the S3 index table. The lookup key is collection&experiment&channel&resolution. A global secondary index (GSI) will use the lookup key to allow finding all cuboids that belong to a particular channel via...
Implement the Python class `LookupKeyWriter` described below. Class description: Adds lookup key to legacy items in the S3 index table. The lookup key is collection&experiment&channel&resolution. A global secondary index (GSI) will use the lookup key to allow finding all cuboids that belong to a particular channel via...
44d41e2b7a7b961e55746e1a5527d5419a74c2ce
<|skeleton|> class LookupKeyWriter: """Adds lookup key to legacy items in the S3 index table. The lookup key is collection&experiment&channel&resolution. A global secondary index (GSI) will use the lookup key to allow finding all cuboids that belong to a particular channel via a DynamoDB query. An instance of this ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LookupKeyWriter: """Adds lookup key to legacy items in the S3 index table. The lookup key is collection&experiment&channel&resolution. A global secondary index (GSI) will use the lookup key to allow finding all cuboids that belong to a particular channel via a DynamoDB query. An instance of this class may be ...
the_stack_v2_python_sparse
spdb/spatialdb/utils/add_lookup_keys_to_s3_index.py
jhuapl-boss/spdb
train
6
d14e4bb1ae99503d6df80c16ae31726bcee433d0
[ "self.path = os.getcwd()\nself.stdscr = stdscr\nself.scroll = 0\nself.cursor = 0\nself.allow_file = allow_file\nself.allow_folder = allow_folder", "self.stdscr.erase()\nself.stdscr.addstr(0, 0, self.path, curses.COLOR_WHITE + curses.A_UNDERLINE)\nfor i, v in enumerate(self.dirs + self.files):\n if i - self.scr...
<|body_start_0|> self.path = os.getcwd() self.stdscr = stdscr self.scroll = 0 self.cursor = 0 self.allow_file = allow_file self.allow_folder = allow_folder <|end_body_0|> <|body_start_1|> self.stdscr.erase() self.stdscr.addstr(0, 0, self.path, curses.COLO...
FileSelectMenu
[ "MIT", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FileSelectMenu: def __init__(self, stdscr, allow_file=True, allow_folder=False): """Initialize the file select menu. Args: stdscr (_type_): The screen handle allow_file (bool, optional): Whether to allow file selection. Defaults to True. allow_folder (bool, optional): Whether to allow fo...
stack_v2_sparse_classes_75kplus_train_068422
33,878
permissive
[ { "docstring": "Initialize the file select menu. Args: stdscr (_type_): The screen handle allow_file (bool, optional): Whether to allow file selection. Defaults to True. allow_folder (bool, optional): Whether to allow folder selection. Defaults to False.", "name": "__init__", "signature": "def __init__(...
5
stack_v2_sparse_classes_30k_train_002859
Implement the Python class `FileSelectMenu` described below. Class description: Implement the FileSelectMenu class. Method signatures and docstrings: - def __init__(self, stdscr, allow_file=True, allow_folder=False): Initialize the file select menu. Args: stdscr (_type_): The screen handle allow_file (bool, optional)...
Implement the Python class `FileSelectMenu` described below. Class description: Implement the FileSelectMenu class. Method signatures and docstrings: - def __init__(self, stdscr, allow_file=True, allow_folder=False): Initialize the file select menu. Args: stdscr (_type_): The screen handle allow_file (bool, optional)...
efa24e27f09b707865326fe4a30f4a65b7a031fe
<|skeleton|> class FileSelectMenu: def __init__(self, stdscr, allow_file=True, allow_folder=False): """Initialize the file select menu. Args: stdscr (_type_): The screen handle allow_file (bool, optional): Whether to allow file selection. Defaults to True. allow_folder (bool, optional): Whether to allow fo...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FileSelectMenu: def __init__(self, stdscr, allow_file=True, allow_folder=False): """Initialize the file select menu. Args: stdscr (_type_): The screen handle allow_file (bool, optional): Whether to allow file selection. Defaults to True. allow_folder (bool, optional): Whether to allow folder selection...
the_stack_v2_python_sparse
scripts/configure_build.py
graphcore/popart
train
73
9b20852090e7a9d15cc07a6ac5478a92a261a55e
[ "if algorithm == 1:\n reg = linear_model.ARDRegression()\nelif algorithm == 2:\n reg = linear_model.SGDRegressor()\nelif algorithm == 3:\n reg = linear_model.PassiveAggressiveRegressor()\nreturn reg", "if algorithm == 1:\n reg = linear_model.RANSACRegressor()\nelif algorithm == 2:\n reg = linear_mo...
<|body_start_0|> if algorithm == 1: reg = linear_model.ARDRegression() elif algorithm == 2: reg = linear_model.SGDRegressor() elif algorithm == 3: reg = linear_model.PassiveAggressiveRegressor() return reg <|end_body_0|> <|body_start_1|> if al...
expand edition of linear model from sklearn library.
ExpandLinearRegressor
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExpandLinearRegressor: """expand edition of linear model from sklearn library.""" def estimate(self, algorithm=None): """1. automatic relevance determination, Compared to the OLS (ordinary least squares) estimator, the coefficient weights are slightly shifted toward zeros, which stab...
stack_v2_sparse_classes_75kplus_train_068423
11,649
permissive
[ { "docstring": "1. automatic relevance determination, Compared to the OLS (ordinary least squares) estimator, the coefficient weights are slightly shifted toward zeros, which stabilises them. 2. stochastic gradient descent method NOTE: could used for different penalty 3. online passive-aggressive They are simil...
2
null
Implement the Python class `ExpandLinearRegressor` described below. Class description: expand edition of linear model from sklearn library. Method signatures and docstrings: - def estimate(self, algorithm=None): 1. automatic relevance determination, Compared to the OLS (ordinary least squares) estimator, the coeffici...
Implement the Python class `ExpandLinearRegressor` described below. Class description: expand edition of linear model from sklearn library. Method signatures and docstrings: - def estimate(self, algorithm=None): 1. automatic relevance determination, Compared to the OLS (ordinary least squares) estimator, the coeffici...
5bcfd68e30477f36736e040e1cdcd26086d325c1
<|skeleton|> class ExpandLinearRegressor: """expand edition of linear model from sklearn library.""" def estimate(self, algorithm=None): """1. automatic relevance determination, Compared to the OLS (ordinary least squares) estimator, the coefficient weights are slightly shifted toward zeros, which stab...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ExpandLinearRegressor: """expand edition of linear model from sklearn library.""" def estimate(self, algorithm=None): """1. automatic relevance determination, Compared to the OLS (ordinary least squares) estimator, the coefficient weights are slightly shifted toward zeros, which stabilises them. ...
the_stack_v2_python_sparse
MetReg/models/ml/linear.py
gaoyunqing/MetReg
train
0
337d7d236dcfabaef1c90e43810b21073d0be51b
[ "env_session = os.getenv('SESSION_DURATION')\nif env_session:\n try:\n self.session_duration = int(env_session)\n except Exception:\n pass", "if user_id:\n session = super().create_session(user_id)\n user_id = self.user_id_by_session_id.get(session)\n session_dictionary = {'user_id': ...
<|body_start_0|> env_session = os.getenv('SESSION_DURATION') if env_session: try: self.session_duration = int(env_session) except Exception: pass <|end_body_0|> <|body_start_1|> if user_id: session = super().create_session(user...
[simple auth] Args: Auth ([class]): [class auth]
SessionExpAuth
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SessionExpAuth: """[simple auth] Args: Auth ([class]): [class auth]""" def __init__(self): """[constructor]""" <|body_0|> def create_session(self, user_id=None): """[create session with time] Args: user_id ([type], optional): [id user]. Defaults to None. Returns:...
stack_v2_sparse_classes_75kplus_train_068424
1,992
no_license
[ { "docstring": "[constructor]", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "[create session with time] Args: user_id ([type], optional): [id user]. Defaults to None. Returns: [type]: [sesion id]", "name": "create_session", "signature": "def create_session(sel...
3
null
Implement the Python class `SessionExpAuth` described below. Class description: [simple auth] Args: Auth ([class]): [class auth] Method signatures and docstrings: - def __init__(self): [constructor] - def create_session(self, user_id=None): [create session with time] Args: user_id ([type], optional): [id user]. Defau...
Implement the Python class `SessionExpAuth` described below. Class description: [simple auth] Args: Auth ([class]): [class auth] Method signatures and docstrings: - def __init__(self): [constructor] - def create_session(self, user_id=None): [create session with time] Args: user_id ([type], optional): [id user]. Defau...
0c235315b6c67e4cf26977c80f51e995da762fb1
<|skeleton|> class SessionExpAuth: """[simple auth] Args: Auth ([class]): [class auth]""" def __init__(self): """[constructor]""" <|body_0|> def create_session(self, user_id=None): """[create session with time] Args: user_id ([type], optional): [id user]. Defaults to None. Returns:...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SessionExpAuth: """[simple auth] Args: Auth ([class]): [class auth]""" def __init__(self): """[constructor]""" env_session = os.getenv('SESSION_DURATION') if env_session: try: self.session_duration = int(env_session) except Exception: ...
the_stack_v2_python_sparse
0x07-Session_authentication/api/v1/auth/session_exp_auth.py
abu-bakarr/holbertonschool-web_back_end
train
0
c1a7bcfd8a21426397955b444e0c6edbc0b0dd8d
[ "if not isinstance(wrap_layers, (list, tuple)):\n wrap_layers = [wrap_layers]\nself._wrap_layers = wrap_layers", "del state\n\ndef _sprite_to_polygons(layer, sprite):\n squared_polygons = [(sprite.vertices + np.array([i, j]), sprite.color, sprite.opacity) for i in [-1.0, 0.0, 1.0] for j in [-1.0, 0.0, 1.0]]...
<|body_start_0|> if not isinstance(wrap_layers, (list, tuple)): wrap_layers = [wrap_layers] self._wrap_layers = wrap_layers <|end_body_0|> <|body_start_1|> del state def _sprite_to_polygons(layer, sprite): squared_polygons = [(sprite.vertices + np.array([i, j]),...
Duplicates polygons at a grid of positions. Specifically, duplicates polygons at a 3x3 grid of positions centered around [0, 0] + polygon_position. This is used in torus environments to make a sprite appear to smoothly and incrementally disappear off one edge of the arena and reappear on the opposite edge.
TorusGeometry
[ "Apache-2.0", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TorusGeometry: """Duplicates polygons at a grid of positions. Specifically, duplicates polygons at a 3x3 grid of positions centered around [0, 0] + polygon_position. This is used in torus environments to make a sprite appear to smoothly and incrementally disappear off one edge of the arena and re...
stack_v2_sparse_classes_75kplus_train_068425
3,127
permissive
[ { "docstring": "Constructor. Args: wrap_layers: String or iterable of strings. All sprites in these layers will be rendered as if the arena is a torus.", "name": "__init__", "signature": "def __init__(self, wrap_layers)" }, { "docstring": "Get polygon modifier rendering sprites as if the arena i...
2
stack_v2_sparse_classes_30k_train_019420
Implement the Python class `TorusGeometry` described below. Class description: Duplicates polygons at a grid of positions. Specifically, duplicates polygons at a 3x3 grid of positions centered around [0, 0] + polygon_position. This is used in torus environments to make a sprite appear to smoothly and incrementally dis...
Implement the Python class `TorusGeometry` described below. Class description: Duplicates polygons at a grid of positions. Specifically, duplicates polygons at a 3x3 grid of positions centered around [0, 0] + polygon_position. This is used in torus environments to make a sprite appear to smoothly and incrementally dis...
3e89e46a5918d59475851f9d4f1558956c110d38
<|skeleton|> class TorusGeometry: """Duplicates polygons at a grid of positions. Specifically, duplicates polygons at a 3x3 grid of positions centered around [0, 0] + polygon_position. This is used in torus environments to make a sprite appear to smoothly and incrementally disappear off one edge of the arena and re...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TorusGeometry: """Duplicates polygons at a grid of positions. Specifically, duplicates polygons at a 3x3 grid of positions centered around [0, 0] + polygon_position. This is used in torus environments to make a sprite appear to smoothly and incrementally disappear off one edge of the arena and reappear on the...
the_stack_v2_python_sparse
moog/observers/polygon_modifiers.py
hokysung/moog.github.io
train
0
86c16f701ec7eaaf8eb37a443bce169eecb1aae9
[ "try:\n self.data['dendrogram'] = script.unit_cell_dendrogram\nexcept AttributeError:\n pass\nself.data['experiments'] = script._experiments", "d = OrderedDict()\nuc_params = uc_params_from_experiments(self.data['experiments'])\nd.update(plots.plot_uc_histograms(uc_params))\nif 'dendrogram' in self.data:\n ...
<|body_start_0|> try: self.data['dendrogram'] = script.unit_cell_dendrogram except AttributeError: pass self.data['experiments'] = script._experiments <|end_body_0|> <|body_start_1|> d = OrderedDict() uc_params = uc_params_from_experiments(self.data['expe...
Observer to record unit cell clustering data and make plots.
UnitCellAnalysisObserver
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UnitCellAnalysisObserver: """Observer to record unit cell clustering data and make plots.""" def update(self, script): """Update the data in the observer.""" <|body_0|> def make_plots(self): """Generate plots of the unit cell clustering.""" <|body_1|> <|...
stack_v2_sparse_classes_75kplus_train_068426
1,522
permissive
[ { "docstring": "Update the data in the observer.", "name": "update", "signature": "def update(self, script)" }, { "docstring": "Generate plots of the unit cell clustering.", "name": "make_plots", "signature": "def make_plots(self)" } ]
2
stack_v2_sparse_classes_30k_test_002936
Implement the Python class `UnitCellAnalysisObserver` described below. Class description: Observer to record unit cell clustering data and make plots. Method signatures and docstrings: - def update(self, script): Update the data in the observer. - def make_plots(self): Generate plots of the unit cell clustering.
Implement the Python class `UnitCellAnalysisObserver` described below. Class description: Observer to record unit cell clustering data and make plots. Method signatures and docstrings: - def update(self, script): Update the data in the observer. - def make_plots(self): Generate plots of the unit cell clustering. <|s...
fb9672b91854f564cbbba6f1cceeefa18d135965
<|skeleton|> class UnitCellAnalysisObserver: """Observer to record unit cell clustering data and make plots.""" def update(self, script): """Update the data in the observer.""" <|body_0|> def make_plots(self): """Generate plots of the unit cell clustering.""" <|body_1|> <|...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UnitCellAnalysisObserver: """Observer to record unit cell clustering data and make plots.""" def update(self, script): """Update the data in the observer.""" try: self.data['dendrogram'] = script.unit_cell_dendrogram except AttributeError: pass self...
the_stack_v2_python_sparse
algorithms/clustering/observers.py
jbeilstenedmands/dials
train
0
f6c381f559878ca543d682b1628ef1b5ef23d07a
[ "if config:\n self.config = Config(config)\n raw_config = deepcopy(self.config)\nelse:\n self.config = LrScheduler.config\n raw_config = self.config.to_json()\nraw_config.type = self.config.type\nmap_dict = LrSchedulerMappingDict()\nself.map_config = ConfigBackendMapping(map_dict.type_mapping_dict, map_...
<|body_start_0|> if config: self.config = Config(config) raw_config = deepcopy(self.config) else: self.config = LrScheduler.config raw_config = self.config.to_json() raw_config.type = self.config.type map_dict = LrSchedulerMappingDict() ...
Register and call LrScheduler class.
LrScheduler
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LrScheduler: """Register and call LrScheduler class.""" def __init__(self, config=None): """Initialize.""" <|body_0|> def __call__(self, optimizer=None, epochs=None, steps=None): """Call lr scheduler class.""" <|body_1|> <|end_skeleton|> <|body_start_0|...
stack_v2_sparse_classes_75kplus_train_068427
2,364
permissive
[ { "docstring": "Initialize.", "name": "__init__", "signature": "def __init__(self, config=None)" }, { "docstring": "Call lr scheduler class.", "name": "__call__", "signature": "def __call__(self, optimizer=None, epochs=None, steps=None)" } ]
2
stack_v2_sparse_classes_30k_train_039441
Implement the Python class `LrScheduler` described below. Class description: Register and call LrScheduler class. Method signatures and docstrings: - def __init__(self, config=None): Initialize. - def __call__(self, optimizer=None, epochs=None, steps=None): Call lr scheduler class.
Implement the Python class `LrScheduler` described below. Class description: Register and call LrScheduler class. Method signatures and docstrings: - def __init__(self, config=None): Initialize. - def __call__(self, optimizer=None, epochs=None, steps=None): Call lr scheduler class. <|skeleton|> class LrScheduler: ...
e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04
<|skeleton|> class LrScheduler: """Register and call LrScheduler class.""" def __init__(self, config=None): """Initialize.""" <|body_0|> def __call__(self, optimizer=None, epochs=None, steps=None): """Call lr scheduler class.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LrScheduler: """Register and call LrScheduler class.""" def __init__(self, config=None): """Initialize.""" if config: self.config = Config(config) raw_config = deepcopy(self.config) else: self.config = LrScheduler.config raw_config =...
the_stack_v2_python_sparse
zeus/trainer/modules/lr_schedulers/lr_scheduler.py
huawei-noah/xingtian
train
308
29e57a4f565e9897faf5446f054de4afc94d1fca
[ "sum = 0\nq = queue.Queue()\nq.put(root)\nwhile not q.empty():\n n = q.get()\n v = n.val\n if v >= L and v <= R:\n sum += v\n if n.left != None:\n q.put(n.left)\n if n.right != None:\n q.put(n.right)\nreturn sum", "def dfs(nd):\n if not nd:\n return\n if nd.val <= ...
<|body_start_0|> sum = 0 q = queue.Queue() q.put(root) while not q.empty(): n = q.get() v = n.val if v >= L and v <= R: sum += v if n.left != None: q.put(n.left) if n.right != None: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def rangeSumBST1(self, root, L, R): """:type root: TreeNode :type L: int :type R: int :rtype: int""" <|body_0|> def rangeSumBST2(self, root, L, R): """:type root: TreeNode :type L: int :type R: int :rtype: int""" <|body_1|> def rangeSumBST3(sel...
stack_v2_sparse_classes_75kplus_train_068428
2,147
no_license
[ { "docstring": ":type root: TreeNode :type L: int :type R: int :rtype: int", "name": "rangeSumBST1", "signature": "def rangeSumBST1(self, root, L, R)" }, { "docstring": ":type root: TreeNode :type L: int :type R: int :rtype: int", "name": "rangeSumBST2", "signature": "def rangeSumBST2(se...
3
stack_v2_sparse_classes_30k_train_011284
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rangeSumBST1(self, root, L, R): :type root: TreeNode :type L: int :type R: int :rtype: int - def rangeSumBST2(self, root, L, R): :type root: TreeNode :type L: int :type R: in...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rangeSumBST1(self, root, L, R): :type root: TreeNode :type L: int :type R: int :rtype: int - def rangeSumBST2(self, root, L, R): :type root: TreeNode :type L: int :type R: in...
d3e8669f932fc2e22711e8b7590d3365d020e189
<|skeleton|> class Solution: def rangeSumBST1(self, root, L, R): """:type root: TreeNode :type L: int :type R: int :rtype: int""" <|body_0|> def rangeSumBST2(self, root, L, R): """:type root: TreeNode :type L: int :type R: int :rtype: int""" <|body_1|> def rangeSumBST3(sel...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def rangeSumBST1(self, root, L, R): """:type root: TreeNode :type L: int :type R: int :rtype: int""" sum = 0 q = queue.Queue() q.put(root) while not q.empty(): n = q.get() v = n.val if v >= L and v <= R: sum ...
the_stack_v2_python_sparse
leetcode/938.py
liuweilin17/algorithm
train
3
b4b382159df88cff885a9dc0dc23d1a6a7571eb4
[ "self.settings = game.settings\nself.reset_stats()\nself.game_active = False\nself.high_score = self.file_score", "self.ships_left = self.settings.ship_limit\nself.score = 0\nself.level = 1", "with open(HIGH_SCORE_TXT, 'wt+') as f:\n try:\n score = int(f.read())\n except ValueError:\n score ...
<|body_start_0|> self.settings = game.settings self.reset_stats() self.game_active = False self.high_score = self.file_score <|end_body_0|> <|body_start_1|> self.ships_left = self.settings.ship_limit self.score = 0 self.level = 1 <|end_body_1|> <|body_start_2|> ...
Track statistics for Alien Invaders game.
GameStats
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GameStats: """Track statistics for Alien Invaders game.""" def __init__(self, game): """Initialize statistics.""" <|body_0|> def reset_stats(self): """Set dynamic statistics for the game. Initialize statistics at the beginning of the game, or Reset the statistics...
stack_v2_sparse_classes_75kplus_train_068429
1,766
permissive
[ { "docstring": "Initialize statistics.", "name": "__init__", "signature": "def __init__(self, game)" }, { "docstring": "Set dynamic statistics for the game. Initialize statistics at the beginning of the game, or Reset the statistics as the game progresses.", "name": "reset_stats", "signa...
4
stack_v2_sparse_classes_30k_train_025023
Implement the Python class `GameStats` described below. Class description: Track statistics for Alien Invaders game. Method signatures and docstrings: - def __init__(self, game): Initialize statistics. - def reset_stats(self): Set dynamic statistics for the game. Initialize statistics at the beginning of the game, or...
Implement the Python class `GameStats` described below. Class description: Track statistics for Alien Invaders game. Method signatures and docstrings: - def __init__(self, game): Initialize statistics. - def reset_stats(self): Set dynamic statistics for the game. Initialize statistics at the beginning of the game, or...
152fbe43256a80905881055490167d6fe1e3e996
<|skeleton|> class GameStats: """Track statistics for Alien Invaders game.""" def __init__(self, game): """Initialize statistics.""" <|body_0|> def reset_stats(self): """Set dynamic statistics for the game. Initialize statistics at the beginning of the game, or Reset the statistics...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GameStats: """Track statistics for Alien Invaders game.""" def __init__(self, game): """Initialize statistics.""" self.settings = game.settings self.reset_stats() self.game_active = False self.high_score = self.file_score def reset_stats(self): """Set ...
the_stack_v2_python_sparse
alieninvaders/game_stats.py
yatesmac/Alien-Invaders
train
0
9abcf8f69c6e346c5af9f4dec995135ccd8567b6
[ "super().__init__(states)\nif unk_token not in states:\n raise MsticpyException('`unk_token` should be a key in `states`')\nself.states = dict(states)\nself.unk_token = unk_token\nfor key, val in self.states.items():\n if isinstance(val, dict):\n self.states[key] = StateMatrix(self.states[key], unk_tok...
<|body_start_0|> super().__init__(states) if unk_token not in states: raise MsticpyException('`unk_token` should be a key in `states`') self.states = dict(states) self.unk_token = unk_token for key, val in self.states.items(): if isinstance(val, dict): ...
Class for storing trained counts/probabilities.
StateMatrix
[ "LicenseRef-scancode-generic-cla", "LGPL-3.0-only", "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "ISC", "LGPL-2.0-or-later", "PSF-2.0", "Apache-2.0", "BSD-2-Clause", "LGPL-2.1-only", "Unlicense", "Python-2.0", "LicenseRef-scancode-python-cwi", "MIT", "LGPL-2.1-or-later", "GPL-2....
stack_v2_sparse_python_classes_v1
<|skeleton|> class StateMatrix: """Class for storing trained counts/probabilities.""" def __init__(self, states: Union[dict, defaultdict], unk_token: str): """Containr for dict of counts/probs or dict of dicts of cond counts/probs. If you try and retrieve the count/probability for an unseen command/par...
stack_v2_sparse_classes_75kplus_train_068430
3,819
permissive
[ { "docstring": "Containr for dict of counts/probs or dict of dicts of cond counts/probs. If you try and retrieve the count/probability for an unseen command/param/value from the resulting object, it will return the value associated with the `unk_token` key. Parameters ---------- states: Union[dict, defaultdict]...
2
stack_v2_sparse_classes_30k_val_002355
Implement the Python class `StateMatrix` described below. Class description: Class for storing trained counts/probabilities. Method signatures and docstrings: - def __init__(self, states: Union[dict, defaultdict], unk_token: str): Containr for dict of counts/probs or dict of dicts of cond counts/probs. If you try and...
Implement the Python class `StateMatrix` described below. Class description: Class for storing trained counts/probabilities. Method signatures and docstrings: - def __init__(self, states: Union[dict, defaultdict], unk_token: str): Containr for dict of counts/probs or dict of dicts of cond counts/probs. If you try and...
44b1a390510f9be2772ec62cb95d0fc67dfc234b
<|skeleton|> class StateMatrix: """Class for storing trained counts/probabilities.""" def __init__(self, states: Union[dict, defaultdict], unk_token: str): """Containr for dict of counts/probs or dict of dicts of cond counts/probs. If you try and retrieve the count/probability for an unseen command/par...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class StateMatrix: """Class for storing trained counts/probabilities.""" def __init__(self, states: Union[dict, defaultdict], unk_token: str): """Containr for dict of counts/probs or dict of dicts of cond counts/probs. If you try and retrieve the count/probability for an unseen command/param/value from...
the_stack_v2_python_sparse
msticpy/analysis/anomalous_sequence/utils/data_structures.py
RiskIQ/msticpy
train
1
8dff85610280916f2d850ea2af95297cfc4c2836
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.learningAssignment'.casefold():\n from ....
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') try: mapping_value = parse_node.get_child_node('@odata.type').get_str_value() except AttributeError: mapping_value = None if mapping_value and mapping_value.casefold() ==...
LearningCourseActivity
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LearningCourseActivity: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LearningCourseActivity: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create ...
stack_v2_sparse_classes_75kplus_train_068431
5,069
permissive
[ { "docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: LearningCourseActivity", "name": "create_from_discriminator_value", "signature": "def create_from_discrimina...
3
stack_v2_sparse_classes_30k_train_031690
Implement the Python class `LearningCourseActivity` described below. Class description: Implement the LearningCourseActivity class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LearningCourseActivity: Creates a new instance of the appropriate class b...
Implement the Python class `LearningCourseActivity` described below. Class description: Implement the LearningCourseActivity class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LearningCourseActivity: Creates a new instance of the appropriate class b...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class LearningCourseActivity: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LearningCourseActivity: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LearningCourseActivity: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LearningCourseActivity: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Ret...
the_stack_v2_python_sparse
msgraph/generated/models/learning_course_activity.py
microsoftgraph/msgraph-sdk-python
train
135
f62098d359414a8df4399854e16ef6cc896f2563
[ "_folder_id: int = request.query_params.get('folder_id')\nif _folder_id:\n _qs = self.get_queryset().filter(folder_id=_folder_id)\nelse:\n _save_id: str = request.query_params.get('save_id')\n _qs = self.get_queryset().filter(folder__project__save_id=_save_id, error__exact='')\n_page = self.paginate_querys...
<|body_start_0|> _folder_id: int = request.query_params.get('folder_id') if _folder_id: _qs = self.get_queryset().filter(folder_id=_folder_id) else: _save_id: str = request.query_params.get('save_id') _qs = self.get_queryset().filter(folder__project__save_id=_...
FileViewSet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FileViewSet: def list(self, request, *args, **kwargs): """Filter files with pagination""" <|body_0|> def perform_destroy(self, instance): """Call celery task to delete""" <|body_1|> <|end_skeleton|> <|body_start_0|> _folder_id: int = request.query_p...
stack_v2_sparse_classes_75kplus_train_068432
12,600
no_license
[ { "docstring": "Filter files with pagination", "name": "list", "signature": "def list(self, request, *args, **kwargs)" }, { "docstring": "Call celery task to delete", "name": "perform_destroy", "signature": "def perform_destroy(self, instance)" } ]
2
null
Implement the Python class `FileViewSet` described below. Class description: Implement the FileViewSet class. Method signatures and docstrings: - def list(self, request, *args, **kwargs): Filter files with pagination - def perform_destroy(self, instance): Call celery task to delete
Implement the Python class `FileViewSet` described below. Class description: Implement the FileViewSet class. Method signatures and docstrings: - def list(self, request, *args, **kwargs): Filter files with pagination - def perform_destroy(self, instance): Call celery task to delete <|skeleton|> class FileViewSet: ...
e56936a884f14f5451b2fd5b2ab16621b73bbe69
<|skeleton|> class FileViewSet: def list(self, request, *args, **kwargs): """Filter files with pagination""" <|body_0|> def perform_destroy(self, instance): """Call celery task to delete""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FileViewSet: def list(self, request, *args, **kwargs): """Filter files with pagination""" _folder_id: int = request.query_params.get('folder_id') if _folder_id: _qs = self.get_queryset().filter(folder_id=_folder_id) else: _save_id: str = request.query_pa...
the_stack_v2_python_sparse
back/core/views.py
meoook/Abyss-Translate
train
0
0913967e95e7e18b520463c450723508b42fccc2
[ "lgt = len(A)\nrtn = sum(A)\nA = A + A\nidx = 0\ntotal = 0\nfor i in range(len(A)):\n if i - idx + 1 > lgt:\n total -= A[idx]\n idx += 1\n while A[idx] < 0 and idx <= i:\n total -= A[idx]\n idx += 1\n if A[i] >= total + A[i] and i < lgt:\n total = A[i]\n ...
<|body_start_0|> lgt = len(A) rtn = sum(A) A = A + A idx = 0 total = 0 for i in range(len(A)): if i - idx + 1 > lgt: total -= A[idx] idx += 1 while A[idx] < 0 and idx <= i: total -= A[idx] ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxSubarraySumCircularOld(self, A): """:type A: List[int] :rtype: int""" <|body_0|> def maxSubarraySumCircular(self, A): """:type A: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> lgt = len(A) rtn = sum(A...
stack_v2_sparse_classes_75kplus_train_068433
2,421
no_license
[ { "docstring": ":type A: List[int] :rtype: int", "name": "maxSubarraySumCircularOld", "signature": "def maxSubarraySumCircularOld(self, A)" }, { "docstring": ":type A: List[int] :rtype: int", "name": "maxSubarraySumCircular", "signature": "def maxSubarraySumCircular(self, A)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxSubarraySumCircularOld(self, A): :type A: List[int] :rtype: int - def maxSubarraySumCircular(self, A): :type A: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxSubarraySumCircularOld(self, A): :type A: List[int] :rtype: int - def maxSubarraySumCircular(self, A): :type A: List[int] :rtype: int <|skeleton|> class Solution: de...
196e58cd38db846653fb074cfd0363997121a7cf
<|skeleton|> class Solution: def maxSubarraySumCircularOld(self, A): """:type A: List[int] :rtype: int""" <|body_0|> def maxSubarraySumCircular(self, A): """:type A: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def maxSubarraySumCircularOld(self, A): """:type A: List[int] :rtype: int""" lgt = len(A) rtn = sum(A) A = A + A idx = 0 total = 0 for i in range(len(A)): if i - idx + 1 > lgt: total -= A[idx] idx += ...
the_stack_v2_python_sparse
Maximum Sum Circular Subarray.py
nithinveer/leetcode-solutions
train
0
67817eb31ed57b64e7d19582c4323d63ab07cf8f
[ "if input_data.shape[-1] != neural_network.num_inputs:\n raise QiskitMachineLearningError(f'Invalid input dimension! Received {input_data.shape} and ' + f'expected input compatible to {neural_network.num_inputs}')\nctx.neural_network = neural_network\nctx.sparse = sparse\nctx.save_for_backward(input_data, weight...
<|body_start_0|> if input_data.shape[-1] != neural_network.num_inputs: raise QiskitMachineLearningError(f'Invalid input dimension! Received {input_data.shape} and ' + f'expected input compatible to {neural_network.num_inputs}') ctx.neural_network = neural_network ctx.sparse = sparse ...
_TorchNNFunction
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _TorchNNFunction: def forward(ctx: Any, input_data: Tensor, weights: Tensor, neural_network: NeuralNetwork, sparse: bool) -> Tensor: """Forward pass computation. Args: ctx: The context to be passed to the backward pass. input_data: The input data. weights: The weights. neural_network: Th...
stack_v2_sparse_classes_75kplus_train_068434
12,051
permissive
[ { "docstring": "Forward pass computation. Args: ctx: The context to be passed to the backward pass. input_data: The input data. weights: The weights. neural_network: The neural network to be connected. sparse: Indicates whether to use sparse output or not. Returns: The resulting value of the forward pass. Raise...
2
stack_v2_sparse_classes_30k_train_027424
Implement the Python class `_TorchNNFunction` described below. Class description: Implement the _TorchNNFunction class. Method signatures and docstrings: - def forward(ctx: Any, input_data: Tensor, weights: Tensor, neural_network: NeuralNetwork, sparse: bool) -> Tensor: Forward pass computation. Args: ctx: The contex...
Implement the Python class `_TorchNNFunction` described below. Class description: Implement the _TorchNNFunction class. Method signatures and docstrings: - def forward(ctx: Any, input_data: Tensor, weights: Tensor, neural_network: NeuralNetwork, sparse: bool) -> Tensor: Forward pass computation. Args: ctx: The contex...
8a6e73beca8175e782d17d562f8e7b8642f7697a
<|skeleton|> class _TorchNNFunction: def forward(ctx: Any, input_data: Tensor, weights: Tensor, neural_network: NeuralNetwork, sparse: bool) -> Tensor: """Forward pass computation. Args: ctx: The context to be passed to the backward pass. input_data: The input data. weights: The weights. neural_network: Th...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class _TorchNNFunction: def forward(ctx: Any, input_data: Tensor, weights: Tensor, neural_network: NeuralNetwork, sparse: bool) -> Tensor: """Forward pass computation. Args: ctx: The context to be passed to the backward pass. input_data: The input data. weights: The weights. neural_network: The neural netwo...
the_stack_v2_python_sparse
qiskit_machine_learning/connectors/torch_connector.py
jessica-angel7/qiskit-machine-learning
train
1
f65dd171a966438af0c99701e09a46e20f78cdd6
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn SectionGroup()", "from .notebook import Notebook\nfrom .onenote_entity_hierarchy_model import OnenoteEntityHierarchyModel\nfrom .onenote_section import OnenoteSection\nfrom .notebook import Notebook\nfrom .onenote_entity_hierarchy_mode...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return SectionGroup() <|end_body_0|> <|body_start_1|> from .notebook import Notebook from .onenote_entity_hierarchy_model import OnenoteEntityHierarchyModel from .onenote_section import...
SectionGroup
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SectionGroup: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SectionGroup: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ...
stack_v2_sparse_classes_75kplus_train_068435
4,125
permissive
[ { "docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: SectionGroup", "name": "create_from_discriminator_value", "signature": "def create_from_discriminator_value(...
3
stack_v2_sparse_classes_30k_train_003514
Implement the Python class `SectionGroup` described below. Class description: Implement the SectionGroup class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SectionGroup: Creates a new instance of the appropriate class based on discriminator value Ar...
Implement the Python class `SectionGroup` described below. Class description: Implement the SectionGroup class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SectionGroup: Creates a new instance of the appropriate class based on discriminator value Ar...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class SectionGroup: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SectionGroup: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SectionGroup: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SectionGroup: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: SectionGroup""...
the_stack_v2_python_sparse
msgraph/generated/models/section_group.py
microsoftgraph/msgraph-sdk-python
train
135
ad2fd511e1073b47f541f1a9c2ada5414f3f3ff9
[ "self._gv = gv\nself._dlg = ElevatioBandsDialog()\nself._dlg.setWindowFlags(self._dlg.windowFlags() & ~Qt.WindowContextHelpButtonHint)\nself._dlg.move(self._gv.elevationBandsPos)\nself._dlg.okButton.clicked.connect(self.setBands)\nself._dlg.cancelButton.clicked.connect(self._dlg.close)\nself._dlg.elevBandsThreshold...
<|body_start_0|> self._gv = gv self._dlg = ElevatioBandsDialog() self._dlg.setWindowFlags(self._dlg.windowFlags() & ~Qt.WindowContextHelpButtonHint) self._dlg.move(self._gv.elevationBandsPos) self._dlg.okButton.clicked.connect(self.setBands) self._dlg.cancelButton.clicked...
Form and functions for defining elevation bands.
ElevationBands
[ "MIT", "GPL-2.0-or-later" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ElevationBands: """Form and functions for defining elevation bands.""" def __init__(self, gv): """Initialise class variables.""" <|body_0|> def run(self): """Run the form.""" <|body_1|> def setBands(self): """Save bands definition.""" ...
stack_v2_sparse_classes_75kplus_train_068436
2,977
permissive
[ { "docstring": "Initialise class variables.", "name": "__init__", "signature": "def __init__(self, gv)" }, { "docstring": "Run the form.", "name": "run", "signature": "def run(self)" }, { "docstring": "Save bands definition.", "name": "setBands", "signature": "def setBand...
3
stack_v2_sparse_classes_30k_train_024670
Implement the Python class `ElevationBands` described below. Class description: Form and functions for defining elevation bands. Method signatures and docstrings: - def __init__(self, gv): Initialise class variables. - def run(self): Run the form. - def setBands(self): Save bands definition.
Implement the Python class `ElevationBands` described below. Class description: Form and functions for defining elevation bands. Method signatures and docstrings: - def __init__(self, gv): Initialise class variables. - def run(self): Run the form. - def setBands(self): Save bands definition. <|skeleton|> class Eleva...
ddb3de70708687ca3167ec4b72ac432426175f45
<|skeleton|> class ElevationBands: """Form and functions for defining elevation bands.""" def __init__(self, gv): """Initialise class variables.""" <|body_0|> def run(self): """Run the form.""" <|body_1|> def setBands(self): """Save bands definition.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ElevationBands: """Form and functions for defining elevation bands.""" def __init__(self, gv): """Initialise class variables.""" self._gv = gv self._dlg = ElevatioBandsDialog() self._dlg.setWindowFlags(self._dlg.windowFlags() & ~Qt.WindowContextHelpButtonHint) self...
the_stack_v2_python_sparse
qswatplus/elevationbands.py
celray/swatplus-automatic-workflow
train
11
771ec820281805b5e5a7a0d06a5d59f11ab63ac5
[ "usuarios = getAllApoyaFem()\nserializer = self.serializer_class(usuarios, many=True)\nreturn Response(serializer.data, status=status.HTTP_200_OK)", "try:\n serializer = self.serializer_class(data=request.data)\n if serializer.is_valid():\n createApoyaFem(request.data)\n return Response(serial...
<|body_start_0|> usuarios = getAllApoyaFem() serializer = self.serializer_class(usuarios, many=True) return Response(serializer.data, status=status.HTTP_200_OK) <|end_body_0|> <|body_start_1|> try: serializer = self.serializer_class(data=request.data) if serializ...
Maneja el List de usuario ApoyaFem Args: viewsets ([type]): [description]
usuarioApoyaFemViewList
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class usuarioApoyaFemViewList: """Maneja el List de usuario ApoyaFem Args: viewsets ([type]): [description]""" def get(self, request, format=None): """Metodo GET de usuario ApoyaFem Args: request ([type]): [description] format ([type], optional): [description]. Defaults to None. Returns: L...
stack_v2_sparse_classes_75kplus_train_068437
18,724
no_license
[ { "docstring": "Metodo GET de usuario ApoyaFem Args: request ([type]): [description] format ([type], optional): [description]. Defaults to None. Returns: Listado de todos los usuarios de ApoyaFem", "name": "get", "signature": "def get(self, request, format=None)" }, { "docstring": "Metodo POST d...
2
stack_v2_sparse_classes_30k_train_002082
Implement the Python class `usuarioApoyaFemViewList` described below. Class description: Maneja el List de usuario ApoyaFem Args: viewsets ([type]): [description] Method signatures and docstrings: - def get(self, request, format=None): Metodo GET de usuario ApoyaFem Args: request ([type]): [description] format ([type...
Implement the Python class `usuarioApoyaFemViewList` described below. Class description: Maneja el List de usuario ApoyaFem Args: viewsets ([type]): [description] Method signatures and docstrings: - def get(self, request, format=None): Metodo GET de usuario ApoyaFem Args: request ([type]): [description] format ([type...
5edfc0fb9316c899dbd5cd5607989300c75ab4e8
<|skeleton|> class usuarioApoyaFemViewList: """Maneja el List de usuario ApoyaFem Args: viewsets ([type]): [description]""" def get(self, request, format=None): """Metodo GET de usuario ApoyaFem Args: request ([type]): [description] format ([type], optional): [description]. Defaults to None. Returns: L...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class usuarioApoyaFemViewList: """Maneja el List de usuario ApoyaFem Args: viewsets ([type]): [description]""" def get(self, request, format=None): """Metodo GET de usuario ApoyaFem Args: request ([type]): [description] format ([type], optional): [description]. Defaults to None. Returns: Listado de tod...
the_stack_v2_python_sparse
usuarios_API/views.py
MartinGalvanCastro/ApoyaFem-API
train
0
72c10470840e55140f4d7fd1c6cda6aef61509e6
[ "if n == 1:\n return 0\nif n % 2 == 0:\n return self.integerReplacement(n / 2) + 1\nelse:\n add = self.integerReplacement(n + 1) + 1\n subtract = self.integerReplacement(n - 1) + 1\n return min(add, subtract)", "def min_operations(n: int):\n if n in dp:\n return dp[n]\n if n % 2 == 0:\...
<|body_start_0|> if n == 1: return 0 if n % 2 == 0: return self.integerReplacement(n / 2) + 1 else: add = self.integerReplacement(n + 1) + 1 subtract = self.integerReplacement(n - 1) + 1 return min(add, subtract) <|end_body_0|> <|body_...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def integerReplacement(self, n: int) -> int: """My Solution: Brute Force Solution IDEA: We explore all possibilities. Given the rules, integerReplacement(n) will converge to 1 for all integers. Thus, we can use recursion to see how many steps it will take. When odd, we explore ...
stack_v2_sparse_classes_75kplus_train_068438
1,715
no_license
[ { "docstring": "My Solution: Brute Force Solution IDEA: We explore all possibilities. Given the rules, integerReplacement(n) will converge to 1 for all integers. Thus, we can use recursion to see how many steps it will take. When odd, we explore BOTH possibilities of adding or subtracting, and take the route wi...
2
stack_v2_sparse_classes_30k_train_014668
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def integerReplacement(self, n: int) -> int: My Solution: Brute Force Solution IDEA: We explore all possibilities. Given the rules, integerReplacement(n) will converge to 1 for a...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def integerReplacement(self, n: int) -> int: My Solution: Brute Force Solution IDEA: We explore all possibilities. Given the rules, integerReplacement(n) will converge to 1 for a...
8b11ceb675089a12a4a44f9b044dac7c3e666819
<|skeleton|> class Solution: def integerReplacement(self, n: int) -> int: """My Solution: Brute Force Solution IDEA: We explore all possibilities. Given the rules, integerReplacement(n) will converge to 1 for all integers. Thus, we can use recursion to see how many steps it will take. When odd, we explore ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def integerReplacement(self, n: int) -> int: """My Solution: Brute Force Solution IDEA: We explore all possibilities. Given the rules, integerReplacement(n) will converge to 1 for all integers. Thus, we can use recursion to see how many steps it will take. When odd, we explore BOTH possibili...
the_stack_v2_python_sparse
Python_Solutions/397_Integer_Replacement.py
lw75251/leetcode
train
0
e9ad7b3c2636fb38e377a562443f6c87e2f8255b
[ "self.X_mn = self.load_base_connectome(base_filename)\nr_state = np.random.RandomState(signature_seed)\nself.sigs = self.generate_injury_signatures(self.X_mn, n_injuries, r_state)", "X, Y = self.sample_injury_strengths(n_samples, self.X_mn, self.sigs[0], self.sigs[1], noise_weight)\nassert X.shape[0] == n_samples...
<|body_start_0|> self.X_mn = self.load_base_connectome(base_filename) r_state = np.random.RandomState(signature_seed) self.sigs = self.generate_injury_signatures(self.X_mn, n_injuries, r_state) <|end_body_0|> <|body_start_1|> X, Y = self.sample_injury_strengths(n_samples, self.X_mn, sel...
ConnectomeInjury
[ "LicenseRef-scancode-cecill-b-en" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConnectomeInjury: def __init__(self, base_filename, n_injuries=2, signature_seed=333): """Use to create synthetic injury data.""" <|body_0|> def generate_injury(self, n_samples=100, noise_weight=0.125): """Return n_samples of synthetic injury data and corresponding i...
stack_v2_sparse_classes_75kplus_train_068439
8,625
permissive
[ { "docstring": "Use to create synthetic injury data.", "name": "__init__", "signature": "def __init__(self, base_filename, n_injuries=2, signature_seed=333)" }, { "docstring": "Return n_samples of synthetic injury data and corresponding injury strength.", "name": "generate_injury", "sign...
5
stack_v2_sparse_classes_30k_train_025008
Implement the Python class `ConnectomeInjury` described below. Class description: Implement the ConnectomeInjury class. Method signatures and docstrings: - def __init__(self, base_filename, n_injuries=2, signature_seed=333): Use to create synthetic injury data. - def generate_injury(self, n_samples=100, noise_weight=...
Implement the Python class `ConnectomeInjury` described below. Class description: Implement the ConnectomeInjury class. Method signatures and docstrings: - def __init__(self, base_filename, n_injuries=2, signature_seed=333): Use to create synthetic injury data. - def generate_injury(self, n_samples=100, noise_weight=...
7a807ed690929563ce36086eaf0998d0e8856aea
<|skeleton|> class ConnectomeInjury: def __init__(self, base_filename, n_injuries=2, signature_seed=333): """Use to create synthetic injury data.""" <|body_0|> def generate_injury(self, n_samples=100, noise_weight=0.125): """Return n_samples of synthetic injury data and corresponding i...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ConnectomeInjury: def __init__(self, base_filename, n_injuries=2, signature_seed=333): """Use to create synthetic injury data.""" self.X_mn = self.load_base_connectome(base_filename) r_state = np.random.RandomState(signature_seed) self.sigs = self.generate_injury_signatures(sel...
the_stack_v2_python_sparse
pynet/datasets/connectome.py
Duplums/pynet
train
0
354dd1371ffcea6c1b3b9aa25d5f189e21dac658
[ "\"\"\"如果在测试用例中使用了mock模拟这个接口的返回,那么就不会执行这个接口的代码\"\"\"\nprint('调用第三方支付接口*****')\nurl = 'http://third.payment.pay/'\ndata = {'card_num': card_num, 'amount': amount}\nresponse = requests.post(url, data=data)\nprint(response)\nreturn response.status_code", "try:\n resp = self.requestOutofSystem(card_num, amount)\n ...
<|body_start_0|> """如果在测试用例中使用了mock模拟这个接口的返回,那么就不会执行这个接口的代码""" print('调用第三方支付接口*****') url = 'http://third.payment.pay/' data = {'card_num': card_num, 'amount': amount} response = requests.post(url, data=data) print(response) return response.status_code <|end_body...
Payment
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Payment: def requestOutofSystem(self, card_num, amount): """请求第三方支付接口""" <|body_0|> def doPay(self, user_id, card_num, amount): """支付:user_id 用户ID card_num 卡号 amount 支付金额""" <|body_1|> <|end_skeleton|> <|body_start_0|> """如果在测试用例中使用了mock模拟这个接口的返回,那么...
stack_v2_sparse_classes_75kplus_train_068440
1,489
no_license
[ { "docstring": "请求第三方支付接口", "name": "requestOutofSystem", "signature": "def requestOutofSystem(self, card_num, amount)" }, { "docstring": "支付:user_id 用户ID card_num 卡号 amount 支付金额", "name": "doPay", "signature": "def doPay(self, user_id, card_num, amount)" } ]
2
stack_v2_sparse_classes_30k_train_001818
Implement the Python class `Payment` described below. Class description: Implement the Payment class. Method signatures and docstrings: - def requestOutofSystem(self, card_num, amount): 请求第三方支付接口 - def doPay(self, user_id, card_num, amount): 支付:user_id 用户ID card_num 卡号 amount 支付金额
Implement the Python class `Payment` described below. Class description: Implement the Payment class. Method signatures and docstrings: - def requestOutofSystem(self, card_num, amount): 请求第三方支付接口 - def doPay(self, user_id, card_num, amount): 支付:user_id 用户ID card_num 卡号 amount 支付金额 <|skeleton|> class Payment: de...
2f425a1263e78fba36bc1094175c1e967498cafc
<|skeleton|> class Payment: def requestOutofSystem(self, card_num, amount): """请求第三方支付接口""" <|body_0|> def doPay(self, user_id, card_num, amount): """支付:user_id 用户ID card_num 卡号 amount 支付金额""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Payment: def requestOutofSystem(self, card_num, amount): """请求第三方支付接口""" """如果在测试用例中使用了mock模拟这个接口的返回,那么就不会执行这个接口的代码""" print('调用第三方支付接口*****') url = 'http://third.payment.pay/' data = {'card_num': card_num, 'amount': amount} response = requests.post(url, data=da...
the_stack_v2_python_sparse
python_1/study_mock/payment.py
KRIS123456654321/pytest
train
2
2eb55fcddea90bb15adb59172156b3272eb15d69
[ "self.batch_request = self._parse_batch_request(batch_request, config)\nself.feature_ids = feature_ids\nsuper().__init__(AwsDownloadClient, data_folder=data_folder, config=config)", "if isinstance(batch_request, BatchStatisticalRequest):\n return batch_request\nif isinstance(batch_request, dict):\n return B...
<|body_start_0|> self.batch_request = self._parse_batch_request(batch_request, config) self.feature_ids = feature_ids super().__init__(AwsDownloadClient, data_folder=data_folder, config=config) <|end_body_0|> <|body_start_1|> if isinstance(batch_request, BatchStatisticalRequest): ...
A utility class for downloading results of Batch Statistical API from an S3 bucket.
AwsBatchStatisticalResults
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AwsBatchStatisticalResults: """A utility class for downloading results of Batch Statistical API from an S3 bucket.""" def __init__(self, batch_request: BatchStatisticalRequestType, *, feature_ids: Optional[Sequence[Union[str, int]]]=None, data_folder: Optional[str]=None, config: Optional[SHC...
stack_v2_sparse_classes_75kplus_train_068441
4,135
permissive
[ { "docstring": ":param batch_request: Info about a batch request - either an instance of `BatchStatisticalRequest` or a batch ID or a raw payload of the batch response. :param feature_ids: A list of feature IDs of saved results on the bucket. If provided it will download only these results. If not provided it w...
4
null
Implement the Python class `AwsBatchStatisticalResults` described below. Class description: A utility class for downloading results of Batch Statistical API from an S3 bucket. Method signatures and docstrings: - def __init__(self, batch_request: BatchStatisticalRequestType, *, feature_ids: Optional[Sequence[Union[str...
Implement the Python class `AwsBatchStatisticalResults` described below. Class description: A utility class for downloading results of Batch Statistical API from an S3 bucket. Method signatures and docstrings: - def __init__(self, batch_request: BatchStatisticalRequestType, *, feature_ids: Optional[Sequence[Union[str...
98d0327e3929999ec07645f77b16fceb7f9c88b9
<|skeleton|> class AwsBatchStatisticalResults: """A utility class for downloading results of Batch Statistical API from an S3 bucket.""" def __init__(self, batch_request: BatchStatisticalRequestType, *, feature_ids: Optional[Sequence[Union[str, int]]]=None, data_folder: Optional[str]=None, config: Optional[SHC...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AwsBatchStatisticalResults: """A utility class for downloading results of Batch Statistical API from an S3 bucket.""" def __init__(self, batch_request: BatchStatisticalRequestType, *, feature_ids: Optional[Sequence[Union[str, int]]]=None, data_folder: Optional[str]=None, config: Optional[SHConfig]=None):...
the_stack_v2_python_sparse
sentinelhub/aws/batch.py
sentinel-hub/sentinelhub-py
train
704
f9af40cd2e25dc709b9306c7845924535e279107
[ "super(Worker, self).__init__(parent)\nself._parent = parent\nself._func = func\nself._args = args\nself._kwargs = kwargs\nself._on_complete = on_complete", "try:\n result = self._func(*self._args, **self._kwargs)\nexcept Exception as e:\n result = e\nfinally:\n WorkerCompletedEvent.post_to(self.parent()...
<|body_start_0|> super(Worker, self).__init__(parent) self._parent = parent self._func = func self._args = args self._kwargs = kwargs self._on_complete = on_complete <|end_body_0|> <|body_start_1|> try: result = self._func(*self._args, **self._kwargs)...
A worker thread to offload long running tasks. Raises WorkerCompletedEvent on completion of task. Event is posted on Qt event loop.
Worker
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Worker: """A worker thread to offload long running tasks. Raises WorkerCompletedEvent on completion of task. Event is posted on Qt event loop.""" def __init__(self, parent, on_complete, func, *args, **kwargs): """Create an instance of the worker thread. Args: parent: owning widget/th...
stack_v2_sparse_classes_75kplus_train_068442
3,372
permissive
[ { "docstring": "Create an instance of the worker thread. Args: parent: owning widget/thread on_complete: callback on completion of task func: task method args: arguments for the task kwargs: keyword arguments for the task", "name": "__init__", "signature": "def __init__(self, parent, on_complete, func, ...
2
stack_v2_sparse_classes_30k_train_016395
Implement the Python class `Worker` described below. Class description: A worker thread to offload long running tasks. Raises WorkerCompletedEvent on completion of task. Event is posted on Qt event loop. Method signatures and docstrings: - def __init__(self, parent, on_complete, func, *args, **kwargs): Create an inst...
Implement the Python class `Worker` described below. Class description: A worker thread to offload long running tasks. Raises WorkerCompletedEvent on completion of task. Event is posted on Qt event loop. Method signatures and docstrings: - def __init__(self, parent, on_complete, func, *args, **kwargs): Create an inst...
aa936982737e5ffe8ff808197d0896ee6e5239a8
<|skeleton|> class Worker: """A worker thread to offload long running tasks. Raises WorkerCompletedEvent on completion of task. Event is posted on Qt event loop.""" def __init__(self, parent, on_complete, func, *args, **kwargs): """Create an instance of the worker thread. Args: parent: owning widget/th...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Worker: """A worker thread to offload long running tasks. Raises WorkerCompletedEvent on completion of task. Event is posted on Qt event loop.""" def __init__(self, parent, on_complete, func, *args, **kwargs): """Create an instance of the worker thread. Args: parent: owning widget/thread on_compl...
the_stack_v2_python_sparse
pomito/plugins/ui/qt/utils.py
codito/pomito
train
1
8d953a5f437869a57749a0f2bf291073d34b8b97
[ "_, i, O = (0, 1.0, 0.5)\npatch = np.array([[_, _, _, _, _, _, _, O, O, _, _, _, _, _, _, _], [_, _, _, _, _, _, O, i, i, O, _, _, _, _, _, _], [_, _, _, _, _, _, O, i, i, O, _, _, _, _, _, _], [_, _, _, _, _, O, i, i, i, i, O, _, _, _, _, _], [O, O, O, O, O, O, i, i, i, i, O, O, O, O, O, O], [O, i, i, i, i, i, i, ...
<|body_start_0|> _, i, O = (0, 1.0, 0.5) patch = np.array([[_, _, _, _, _, _, _, O, O, _, _, _, _, _, _, _], [_, _, _, _, _, _, O, i, i, O, _, _, _, _, _, _], [_, _, _, _, _, _, O, i, i, O, _, _, _, _, _, _], [_, _, _, _, _, O, i, i, i, i, O, _, _, _, _, _], [O, O, O, O, O, O, i, i, i, i, O, O, O, O, O,...
Rasters
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Rasters: def superstar(): """test data patch Ignore: >>> kwplot.autompl() >>> patch = Rasters.superstar() >>> data = np.clip(kwimage.imscale(patch, 2.2), 0, 1) >>> kwplot.imshow(data)""" <|body_0|> def eff(): """test data patch Ignore: >>> kwplot.autompl() >>> eff = ...
stack_v2_sparse_classes_75kplus_train_068443
20,195
permissive
[ { "docstring": "test data patch Ignore: >>> kwplot.autompl() >>> patch = Rasters.superstar() >>> data = np.clip(kwimage.imscale(patch, 2.2), 0, 1) >>> kwplot.imshow(data)", "name": "superstar", "signature": "def superstar()" }, { "docstring": "test data patch Ignore: >>> kwplot.autompl() >>> eff...
2
stack_v2_sparse_classes_30k_train_011486
Implement the Python class `Rasters` described below. Class description: Implement the Rasters class. Method signatures and docstrings: - def superstar(): test data patch Ignore: >>> kwplot.autompl() >>> patch = Rasters.superstar() >>> data = np.clip(kwimage.imscale(patch, 2.2), 0, 1) >>> kwplot.imshow(data) - def ef...
Implement the Python class `Rasters` described below. Class description: Implement the Rasters class. Method signatures and docstrings: - def superstar(): test data patch Ignore: >>> kwplot.autompl() >>> patch = Rasters.superstar() >>> data = np.clip(kwimage.imscale(patch, 2.2), 0, 1) >>> kwplot.imshow(data) - def ef...
77b7b557960cbf4dc6cbc69674e3e32a5efaad0a
<|skeleton|> class Rasters: def superstar(): """test data patch Ignore: >>> kwplot.autompl() >>> patch = Rasters.superstar() >>> data = np.clip(kwimage.imscale(patch, 2.2), 0, 1) >>> kwplot.imshow(data)""" <|body_0|> def eff(): """test data patch Ignore: >>> kwplot.autompl() >>> eff = ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Rasters: def superstar(): """test data patch Ignore: >>> kwplot.autompl() >>> patch = Rasters.superstar() >>> data = np.clip(kwimage.imscale(patch, 2.2), 0, 1) >>> kwplot.imshow(data)""" _, i, O = (0, 1.0, 0.5) patch = np.array([[_, _, _, _, _, _, _, O, O, _, _, _, _, _, _, _], [_, _, ...
the_stack_v2_python_sparse
kwcoco/demo/toypatterns.py
Kitware/kwcoco
train
20
a979e7a4e0aaf52d45ace3c4d44a4d8301af3e14
[ "def wrapper(*args, **kwargs):\n try:\n return int(self(*args, **kwargs))\n except ValueError as v_e:\n return f'{v_e} occured'\n except TypeError as t_e:\n return f'{t_e} occured'\nreturn wrapper", "def wrapper(*args, **kwargs):\n try:\n return str(self(*args, **kwargs))\n...
<|body_start_0|> def wrapper(*args, **kwargs): try: return int(self(*args, **kwargs)) except ValueError as v_e: return f'{v_e} occured' except TypeError as t_e: return f'{t_e} occured' return wrapper <|end_body_0|> <|bo...
Converts results of given functions to a specified type if possible. Otherwise raises ValueError
TypeDecorators
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TypeDecorators: """Converts results of given functions to a specified type if possible. Otherwise raises ValueError""" def to_int(self): """Convert the result of a function to int""" <|body_0|> def to_str(self): """Convert the result of a function to int""" ...
stack_v2_sparse_classes_75kplus_train_068444
2,408
no_license
[ { "docstring": "Convert the result of a function to int", "name": "to_int", "signature": "def to_int(self)" }, { "docstring": "Convert the result of a function to int", "name": "to_str", "signature": "def to_str(self)" }, { "docstring": "Convert the result of a function to int", ...
4
stack_v2_sparse_classes_30k_train_039669
Implement the Python class `TypeDecorators` described below. Class description: Converts results of given functions to a specified type if possible. Otherwise raises ValueError Method signatures and docstrings: - def to_int(self): Convert the result of a function to int - def to_str(self): Convert the result of a fun...
Implement the Python class `TypeDecorators` described below. Class description: Converts results of given functions to a specified type if possible. Otherwise raises ValueError Method signatures and docstrings: - def to_int(self): Convert the result of a function to int - def to_str(self): Convert the result of a fun...
91ebe6a942b7bf3dd8891793e7796e3f2cebf8b1
<|skeleton|> class TypeDecorators: """Converts results of given functions to a specified type if possible. Otherwise raises ValueError""" def to_int(self): """Convert the result of a function to int""" <|body_0|> def to_str(self): """Convert the result of a function to int""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TypeDecorators: """Converts results of given functions to a specified type if possible. Otherwise raises ValueError""" def to_int(self): """Convert the result of a function to int""" def wrapper(*args, **kwargs): try: return int(self(*args, **kwargs)) ...
the_stack_v2_python_sparse
lesson_16/task_3.py
PrtagonistOne/Beetroot_Academy
train
0
420e491b08374bb971f1828c385c84d36f78ebc5
[ "pygame.sprite.Sprite.__init__(self)\nself.image = pygame.image.load('assets/images/grounds/electrostatics.png')\nself.image = self.image.convert()\nself.image.set_colorkey((0, 0, 0))\nself.rect = self.image.get_rect()\nself.rect.left = 0\nself.rect.bottom = 512\nself.dx = 40", "self.rect.centerx += self.dx\nif s...
<|body_start_0|> pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load('assets/images/grounds/electrostatics.png') self.image = self.image.convert() self.image.set_colorkey((0, 0, 0)) self.rect = self.image.get_rect() self.rect.left = 0 self.rect.bott...
Electrostatics
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Electrostatics: def __init__(self): """Initialize the class""" <|body_0|> def update(self, screen): """Resets the shockwave's position whenever it exists the screen.""" <|body_1|> <|end_skeleton|> <|body_start_0|> pygame.sprite.Sprite.__init__(self)...
stack_v2_sparse_classes_75kplus_train_068445
976
no_license
[ { "docstring": "Initialize the class", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Resets the shockwave's position whenever it exists the screen.", "name": "update", "signature": "def update(self, screen)" } ]
2
null
Implement the Python class `Electrostatics` described below. Class description: Implement the Electrostatics class. Method signatures and docstrings: - def __init__(self): Initialize the class - def update(self, screen): Resets the shockwave's position whenever it exists the screen.
Implement the Python class `Electrostatics` described below. Class description: Implement the Electrostatics class. Method signatures and docstrings: - def __init__(self): Initialize the class - def update(self, screen): Resets the shockwave's position whenever it exists the screen. <|skeleton|> class Electrostatics...
d8ead79d4661489095b4738b5725bcc8a3b15f38
<|skeleton|> class Electrostatics: def __init__(self): """Initialize the class""" <|body_0|> def update(self, screen): """Resets the shockwave's position whenever it exists the screen.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Electrostatics: def __init__(self): """Initialize the class""" pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load('assets/images/grounds/electrostatics.png') self.image = self.image.convert() self.image.set_colorkey((0, 0, 0)) self.rect = self.im...
the_stack_v2_python_sparse
electrostatics.py
DDSGrandjean/Python_aroundTheWorld_fall2016
train
0
9e97e0220f093b63b4ebbbbfceef7434edd17751
[ "try:\n found_item = ItemModel.find_item_by_name(name)\nexcept:\n return ({'message': SERVER_ERROR}, 500)\nif found_item:\n return (found_item.json(), 200)\nreturn ({'message': NOT_FOUND_ERROR.format(name)}, 404)", "if ItemModel.find_item_by_name(name):\n return ({'message': ALREADY_EXISTS_ERROR.forma...
<|body_start_0|> try: found_item = ItemModel.find_item_by_name(name) except: return ({'message': SERVER_ERROR}, 500) if found_item: return (found_item.json(), 200) return ({'message': NOT_FOUND_ERROR.format(name)}, 404) <|end_body_0|> <|body_start_1|>...
Resource for one particular item.
Item
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Item: """Resource for one particular item.""" def get(cls, name: str): """endpoint for getting one item by name""" <|body_0|> def post(cls, name: str): """endpoint for creating an item, it does not accept full json, but parses it and uses only {price: <float>}"""...
stack_v2_sparse_classes_75kplus_train_068446
3,074
no_license
[ { "docstring": "endpoint for getting one item by name", "name": "get", "signature": "def get(cls, name: str)" }, { "docstring": "endpoint for creating an item, it does not accept full json, but parses it and uses only {price: <float>}", "name": "post", "signature": "def post(cls, name: s...
4
stack_v2_sparse_classes_30k_train_047281
Implement the Python class `Item` described below. Class description: Resource for one particular item. Method signatures and docstrings: - def get(cls, name: str): endpoint for getting one item by name - def post(cls, name: str): endpoint for creating an item, it does not accept full json, but parses it and uses onl...
Implement the Python class `Item` described below. Class description: Resource for one particular item. Method signatures and docstrings: - def get(cls, name: str): endpoint for getting one item by name - def post(cls, name: str): endpoint for creating an item, it does not accept full json, but parses it and uses onl...
6f8dfbff5f06bead56b2c56122a533d1bd148c2b
<|skeleton|> class Item: """Resource for one particular item.""" def get(cls, name: str): """endpoint for getting one item by name""" <|body_0|> def post(cls, name: str): """endpoint for creating an item, it does not accept full json, but parses it and uses only {price: <float>}"""...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Item: """Resource for one particular item.""" def get(cls, name: str): """endpoint for getting one item by name""" try: found_item = ItemModel.find_item_by_name(name) except: return ({'message': SERVER_ERROR}, 500) if found_item: return ...
the_stack_v2_python_sparse
section12/resources/item.py
ExperimentalHypothesis/flask-restful-web-api
train
0
5c973be837ff985ae4f8e7674ce5f281875f7067
[ "self.dimensions = dimensions\nself.r0 = r0\nself.ep = ep\nself.usf = usf\nself.r1bar = r1bar\nif r2bar is None:\n self.r2bar = NewPotential.r2bardef[dimensions]\nif rnnn is None:\n self.rnnn = NewPotential.rnnndef[dimensions]\nif alphabar is None:\n self.alphabar = NewPotential.alphabardef[dimensions]\nse...
<|body_start_0|> self.dimensions = dimensions self.r0 = r0 self.ep = ep self.usf = usf self.r1bar = r1bar if r2bar is None: self.r2bar = NewPotential.r2bardef[dimensions] if rnnn is None: self.rnnn = NewPotential.rnnndef[dimensions] ...
NewPotential
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NewPotential: def __init__(self, dimensions, r0, ep, usf=None, r1bar=1.05, r2bar=None, r3bar=None, rnnn=None, alphabar=None, offset=0.0, spline=None): """Creates/initializes instance of member of class, which represents a potential. Required arguments are the dimensionality, the equilibr...
stack_v2_sparse_classes_75kplus_train_068447
10,735
no_license
[ { "docstring": "Creates/initializes instance of member of class, which represents a potential. Required arguments are the dimensionality, the equilibrium separation (which can be set to 1 without loss of generality), and ep = phi(r2). Optional arguments (e.g. alphabar) are set using defaults if not specified.",...
6
stack_v2_sparse_classes_30k_train_039688
Implement the Python class `NewPotential` described below. Class description: Implement the NewPotential class. Method signatures and docstrings: - def __init__(self, dimensions, r0, ep, usf=None, r1bar=1.05, r2bar=None, r3bar=None, rnnn=None, alphabar=None, offset=0.0, spline=None): Creates/initializes instance of m...
Implement the Python class `NewPotential` described below. Class description: Implement the NewPotential class. Method signatures and docstrings: - def __init__(self, dimensions, r0, ep, usf=None, r1bar=1.05, r2bar=None, r3bar=None, rnnn=None, alphabar=None, offset=0.0, spline=None): Creates/initializes instance of m...
18eafe263026a2c00fc52fa537a70e595e68e9a7
<|skeleton|> class NewPotential: def __init__(self, dimensions, r0, ep, usf=None, r1bar=1.05, r2bar=None, r3bar=None, rnnn=None, alphabar=None, offset=0.0, spline=None): """Creates/initializes instance of member of class, which represents a potential. Required arguments are the dimensionality, the equilibr...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NewPotential: def __init__(self, dimensions, r0, ep, usf=None, r1bar=1.05, r2bar=None, r3bar=None, rnnn=None, alphabar=None, offset=0.0, spline=None): """Creates/initializes instance of member of class, which represents a potential. Required arguments are the dimensionality, the equilibrium separation...
the_stack_v2_python_sparse
newpotential_publish.py
varunprajan/PythonModules
train
2
86c2cbf485fcf963beb15bd05a49ab82019c577c
[ "self.memo = [[0 for i in range(len(matrix[0]))] for j in range(len(matrix))]\nfor i in range(len(matrix)):\n for j in range(len(matrix[0])):\n total = matrix[i][j]\n left_added = False\n up_added = False\n if j - 1 >= 0:\n total += self.memo[i][j - 1]\n left_add...
<|body_start_0|> self.memo = [[0 for i in range(len(matrix[0]))] for j in range(len(matrix))] for i in range(len(matrix)): for j in range(len(matrix[0])): total = matrix[i][j] left_added = False up_added = False if j - 1 >= 0: ...
NumMatrix
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NumMatrix: def __init__(self, matrix): """:type matrix: List[List[int]]""" <|body_0|> def sumRegion(self, row1, col1, row2, col2): """:type row1: int :type col1: int :type row2: int :type col2: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|>...
stack_v2_sparse_classes_75kplus_train_068448
1,711
permissive
[ { "docstring": ":type matrix: List[List[int]]", "name": "__init__", "signature": "def __init__(self, matrix)" }, { "docstring": ":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int", "name": "sumRegion", "signature": "def sumRegion(self, row1, col1, row2, col2)" ...
2
null
Implement the Python class `NumMatrix` described below. Class description: Implement the NumMatrix class. Method signatures and docstrings: - def __init__(self, matrix): :type matrix: List[List[int]] - def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:...
Implement the Python class `NumMatrix` described below. Class description: Implement the NumMatrix class. Method signatures and docstrings: - def __init__(self, matrix): :type matrix: List[List[int]] - def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:...
1c3461cfc05deb930d0866428eb00362b4338aab
<|skeleton|> class NumMatrix: def __init__(self, matrix): """:type matrix: List[List[int]]""" <|body_0|> def sumRegion(self, row1, col1, row2, col2): """:type row1: int :type col1: int :type row2: int :type col2: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NumMatrix: def __init__(self, matrix): """:type matrix: List[List[int]]""" self.memo = [[0 for i in range(len(matrix[0]))] for j in range(len(matrix))] for i in range(len(matrix)): for j in range(len(matrix[0])): total = matrix[i][j] left_add...
the_stack_v2_python_sparse
problems/304_range_sum_query_2d.py
apoorvkk/LeetCodeSolutions
train
1
cc11777e512aea4474ca2beb00a4b960d34830d0
[ "self.interval = interval\nthread = threading.Thread(target=self.run, args=())\nthread.daemon = True\nthread.start()", "while True:\n print('Doing something imporant in the background')\n time.sleep(self.interval)" ]
<|body_start_0|> self.interval = interval thread = threading.Thread(target=self.run, args=()) thread.daemon = True thread.start() <|end_body_0|> <|body_start_1|> while True: print('Doing something imporant in the background') time.sleep(self.interval) <|e...
Threading example class The run() method will be started and it will run in the background until the application exits.
ThreadingExample
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ThreadingExample: """Threading example class The run() method will be started and it will run in the background until the application exits.""" def __init__(self, interval=1): """Constructor :type interval: int :param interval: Check interval, in seconds""" <|body_0|> de...
stack_v2_sparse_classes_75kplus_train_068449
911
permissive
[ { "docstring": "Constructor :type interval: int :param interval: Check interval, in seconds", "name": "__init__", "signature": "def __init__(self, interval=1)" }, { "docstring": "Method that runs forever", "name": "run", "signature": "def run(self)" } ]
2
stack_v2_sparse_classes_30k_train_053096
Implement the Python class `ThreadingExample` described below. Class description: Threading example class The run() method will be started and it will run in the background until the application exits. Method signatures and docstrings: - def __init__(self, interval=1): Constructor :type interval: int :param interval:...
Implement the Python class `ThreadingExample` described below. Class description: Threading example class The run() method will be started and it will run in the background until the application exits. Method signatures and docstrings: - def __init__(self, interval=1): Constructor :type interval: int :param interval:...
665d39a2bd82543d5196555f0801ef8fd4a3ee48
<|skeleton|> class ThreadingExample: """Threading example class The run() method will be started and it will run in the background until the application exits.""" def __init__(self, interval=1): """Constructor :type interval: int :param interval: Check interval, in seconds""" <|body_0|> de...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ThreadingExample: """Threading example class The run() method will be started and it will run in the background until the application exits.""" def __init__(self, interval=1): """Constructor :type interval: int :param interval: Check interval, in seconds""" self.interval = interval ...
the_stack_v2_python_sparse
all-gists/832219525541e059aefa/snippet.py
gistable/gistable
train
76
1e174db90be2a847d657b207c5e3e078888b4b81
[ "i = 0\nm = 0\nwhile i < len(words):\n j = i + 1\n while j < len(words):\n f = True\n for c in words[i]:\n if c in words[j]:\n f = False\n break\n if f:\n m = max(m, len(words[i]) * len(words[j]))\n j += 1\n i += 1\nreturn m", ...
<|body_start_0|> i = 0 m = 0 while i < len(words): j = i + 1 while j < len(words): f = True for c in words[i]: if c in words[j]: f = False break if f: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxProduct1(self, words): """:type words: List[str] :rtype: int""" <|body_0|> def maxProduct(self, words): """:type words: List[str] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> i = 0 m = 0 while i < len(...
stack_v2_sparse_classes_75kplus_train_068450
1,149
no_license
[ { "docstring": ":type words: List[str] :rtype: int", "name": "maxProduct1", "signature": "def maxProduct1(self, words)" }, { "docstring": ":type words: List[str] :rtype: int", "name": "maxProduct", "signature": "def maxProduct(self, words)" } ]
2
stack_v2_sparse_classes_30k_test_002508
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProduct1(self, words): :type words: List[str] :rtype: int - def maxProduct(self, words): :type words: List[str] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProduct1(self, words): :type words: List[str] :rtype: int - def maxProduct(self, words): :type words: List[str] :rtype: int <|skeleton|> class Solution: def maxProdu...
e5b018493bbd12edcdcd0434f35d9c358106d391
<|skeleton|> class Solution: def maxProduct1(self, words): """:type words: List[str] :rtype: int""" <|body_0|> def maxProduct(self, words): """:type words: List[str] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def maxProduct1(self, words): """:type words: List[str] :rtype: int""" i = 0 m = 0 while i < len(words): j = i + 1 while j < len(words): f = True for c in words[i]: if c in words[j]: ...
the_stack_v2_python_sparse
py/leetcode/318.py
wfeng1991/learnpy
train
0
0d9bb132537ebfa52623d11993c9f439c404b163
[ "self.initial_value = initial_value\nself.target_value = target_value\nself.target_epoch = target_epoch\nself.decay_rate = target_value / initial_value", "if self.target_epoch == 0:\n return self.target_value\nvalue = self.initial_value * np.power(self.decay_rate, epoch / self.target_epoch)\nreturn max(value, ...
<|body_start_0|> self.initial_value = initial_value self.target_value = target_value self.target_epoch = target_epoch self.decay_rate = target_value / initial_value <|end_body_0|> <|body_start_1|> if self.target_epoch == 0: return self.target_value value = se...
This schedule applies an exponential decay function to an epoch index, considering a provided `initial_value` value. It is computed as: current_value = initial_value * decay_rate ^ (epoch / target_epoch), where `decay_rate` is equal to target_value / initial_value.
ExponentialDecaySchedule
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExponentialDecaySchedule: """This schedule applies an exponential decay function to an epoch index, considering a provided `initial_value` value. It is computed as: current_value = initial_value * decay_rate ^ (epoch / target_epoch), where `decay_rate` is equal to target_value / initial_value."""...
stack_v2_sparse_classes_75kplus_train_068451
10,292
permissive
[ { "docstring": "Initializes a schedule with an exponential decay function. :param initial_value: The initial value at which the schedule begins. :param target_value: The final value at which the schedule end. :param target_epoch: Zero-based index of the epoch from which the function value will be equal to the `...
2
null
Implement the Python class `ExponentialDecaySchedule` described below. Class description: This schedule applies an exponential decay function to an epoch index, considering a provided `initial_value` value. It is computed as: current_value = initial_value * decay_rate ^ (epoch / target_epoch), where `decay_rate` is eq...
Implement the Python class `ExponentialDecaySchedule` described below. Class description: This schedule applies an exponential decay function to an epoch index, considering a provided `initial_value` value. It is computed as: current_value = initial_value * decay_rate ^ (epoch / target_epoch), where `decay_rate` is eq...
c027c8b43c4865d46b8de01d8350dd338ec5a874
<|skeleton|> class ExponentialDecaySchedule: """This schedule applies an exponential decay function to an epoch index, considering a provided `initial_value` value. It is computed as: current_value = initial_value * decay_rate ^ (epoch / target_epoch), where `decay_rate` is equal to target_value / initial_value."""...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ExponentialDecaySchedule: """This schedule applies an exponential decay function to an epoch index, considering a provided `initial_value` value. It is computed as: current_value = initial_value * decay_rate ^ (epoch / target_epoch), where `decay_rate` is equal to target_value / initial_value.""" def __i...
the_stack_v2_python_sparse
nncf/common/schedulers.py
openvinotoolkit/nncf
train
558
cf30f048b85778437349548ef8b938323084d52e
[ "R_SPEED = 0.1\nT_SPEED = 0.05\nDIST_WHEEL_2_CENTER = 0.09\nWHEEL_RADIUS = 0.04\nA1, A2, A3 = (20, 160, 270)\n\ndef wheel_omega(wheel_angle):\n radians = math.pi * wheel_angle / 180\n return (math.sin(radians) * x * T_SPEED + math.cos(radians) * y * T_SPEED + DIST_WHEEL_2_CENTER * omega * R_SPEED) / WHEEL_RAD...
<|body_start_0|> R_SPEED = 0.1 T_SPEED = 0.05 DIST_WHEEL_2_CENTER = 0.09 WHEEL_RADIUS = 0.04 A1, A2, A3 = (20, 160, 270) def wheel_omega(wheel_angle): radians = math.pi * wheel_angle / 180 return (math.sin(radians) * x * T_SPEED + math.cos(radians...
DriveSystem
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DriveSystem: def set_desired_motion(self, x, y, omega): """Power the motors in such a way that theoretically we achieve the desired translational acceleration and rotational velocity (omega)""" <|body_0|> def drive_motors(self, a, b, c): """Drives the motors using PW...
stack_v2_sparse_classes_75kplus_train_068452
2,849
permissive
[ { "docstring": "Power the motors in such a way that theoretically we achieve the desired translational acceleration and rotational velocity (omega)", "name": "set_desired_motion", "signature": "def set_desired_motion(self, x, y, omega)" }, { "docstring": "Drives the motors using PWM and toggling...
2
null
Implement the Python class `DriveSystem` described below. Class description: Implement the DriveSystem class. Method signatures and docstrings: - def set_desired_motion(self, x, y, omega): Power the motors in such a way that theoretically we achieve the desired translational acceleration and rotational velocity (omeg...
Implement the Python class `DriveSystem` described below. Class description: Implement the DriveSystem class. Method signatures and docstrings: - def set_desired_motion(self, x, y, omega): Power the motors in such a way that theoretically we achieve the desired translational acceleration and rotational velocity (omeg...
6dde6b5d2f72fac3928c5042a27dc50e978c3425
<|skeleton|> class DriveSystem: def set_desired_motion(self, x, y, omega): """Power the motors in such a way that theoretically we achieve the desired translational acceleration and rotational velocity (omega)""" <|body_0|> def drive_motors(self, a, b, c): """Drives the motors using PW...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DriveSystem: def set_desired_motion(self, x, y, omega): """Power the motors in such a way that theoretically we achieve the desired translational acceleration and rotational velocity (omega)""" R_SPEED = 0.1 T_SPEED = 0.05 DIST_WHEEL_2_CENTER = 0.09 WHEEL_RADIUS = 0.04 ...
the_stack_v2_python_sparse
DriveSystem/DriveSystem.py
CallumJHays/g26-egb320-2019
train
0
8ce47345a5b3e9be28aff1618a2ef79edd482e34
[ "self.config_entry = entry\nself.lametric = LaMetricDevice(host=entry.data[CONF_HOST], api_key=entry.data[CONF_API_KEY], session=async_get_clientsession(hass))\nsuper().__init__(hass, LOGGER, name=DOMAIN, update_interval=SCAN_INTERVAL)", "try:\n return await self.lametric.device()\nexcept LaMetricAuthenticatio...
<|body_start_0|> self.config_entry = entry self.lametric = LaMetricDevice(host=entry.data[CONF_HOST], api_key=entry.data[CONF_API_KEY], session=async_get_clientsession(hass)) super().__init__(hass, LOGGER, name=DOMAIN, update_interval=SCAN_INTERVAL) <|end_body_0|> <|body_start_1|> try: ...
The LaMetric Data Update Coordinator.
LaMetricDataUpdateCoordinator
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LaMetricDataUpdateCoordinator: """The LaMetric Data Update Coordinator.""" def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None: """Initialize the LaMatric coordinator.""" <|body_0|> async def _async_update_data(self) -> Device: """Fetch device inf...
stack_v2_sparse_classes_75kplus_train_068453
1,627
permissive
[ { "docstring": "Initialize the LaMatric coordinator.", "name": "__init__", "signature": "def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None" }, { "docstring": "Fetch device information of the LaMetric device.", "name": "_async_update_data", "signature": "async def _async...
2
stack_v2_sparse_classes_30k_train_001743
Implement the Python class `LaMetricDataUpdateCoordinator` described below. Class description: The LaMetric Data Update Coordinator. Method signatures and docstrings: - def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None: Initialize the LaMatric coordinator. - async def _async_update_data(self) -> Dev...
Implement the Python class `LaMetricDataUpdateCoordinator` described below. Class description: The LaMetric Data Update Coordinator. Method signatures and docstrings: - def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None: Initialize the LaMatric coordinator. - async def _async_update_data(self) -> Dev...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class LaMetricDataUpdateCoordinator: """The LaMetric Data Update Coordinator.""" def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None: """Initialize the LaMatric coordinator.""" <|body_0|> async def _async_update_data(self) -> Device: """Fetch device inf...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LaMetricDataUpdateCoordinator: """The LaMetric Data Update Coordinator.""" def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None: """Initialize the LaMatric coordinator.""" self.config_entry = entry self.lametric = LaMetricDevice(host=entry.data[CONF_HOST], api_key=e...
the_stack_v2_python_sparse
homeassistant/components/lametric/coordinator.py
home-assistant/core
train
35,501
30d2b0b1cf973edc2df016f7856a4ad03f37f3f4
[ "parent = request.GET.get('parent', '')\nddlDmlType = request.GET.get('type', '')\nfilterInputValue = request.GET.get('filterInputValue', '')\nversion = request.GET.get('version', '')\ndic = {'parent': parent, 'ddlDmlType': ddlDmlType}\nobj = SqlCaseManage.objects.filter(**dic)\nif version:\n obj = obj.filter(ve...
<|body_start_0|> parent = request.GET.get('parent', '') ddlDmlType = request.GET.get('type', '') filterInputValue = request.GET.get('filterInputValue', '') version = request.GET.get('version', '') dic = {'parent': parent, 'ddlDmlType': ddlDmlType} obj = SqlCaseManage.obje...
SqlCaseManageList
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SqlCaseManageList: def get(self, request, *args, **kwargs): """SQL测试用例列表""" <|body_0|> def put(self, request, *args, **kwargs): """编辑SQL测试用例""" <|body_1|> def post(self, request, *args, **kwargs): """创建SQL测试用例 级联更新结构表ddl/dml的数量""" <|body_...
stack_v2_sparse_classes_75kplus_train_068454
14,029
no_license
[ { "docstring": "SQL测试用例列表", "name": "get", "signature": "def get(self, request, *args, **kwargs)" }, { "docstring": "编辑SQL测试用例", "name": "put", "signature": "def put(self, request, *args, **kwargs)" }, { "docstring": "创建SQL测试用例 级联更新结构表ddl/dml的数量", "name": "post", "signatu...
4
stack_v2_sparse_classes_30k_train_015293
Implement the Python class `SqlCaseManageList` described below. Class description: Implement the SqlCaseManageList class. Method signatures and docstrings: - def get(self, request, *args, **kwargs): SQL测试用例列表 - def put(self, request, *args, **kwargs): 编辑SQL测试用例 - def post(self, request, *args, **kwargs): 创建SQL测试用例 级联...
Implement the Python class `SqlCaseManageList` described below. Class description: Implement the SqlCaseManageList class. Method signatures and docstrings: - def get(self, request, *args, **kwargs): SQL测试用例列表 - def put(self, request, *args, **kwargs): 编辑SQL测试用例 - def post(self, request, *args, **kwargs): 创建SQL测试用例 级联...
f2523d6e51cde1b53ac6f453f8066b4b90c523b9
<|skeleton|> class SqlCaseManageList: def get(self, request, *args, **kwargs): """SQL测试用例列表""" <|body_0|> def put(self, request, *args, **kwargs): """编辑SQL测试用例""" <|body_1|> def post(self, request, *args, **kwargs): """创建SQL测试用例 级联更新结构表ddl/dml的数量""" <|body_...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SqlCaseManageList: def get(self, request, *args, **kwargs): """SQL测试用例列表""" parent = request.GET.get('parent', '') ddlDmlType = request.GET.get('type', '') filterInputValue = request.GET.get('filterInputValue', '') version = request.GET.get('version', '') dic = ...
the_stack_v2_python_sparse
api/db/rest/sqlCaseManage.py
zhuzhanhao1/backend
train
0
81f0d921f6bda0dcc0fd4617ba98e08ac85130a3
[ "super(BasicAligner, self).__init__()\nself._extensions = [palign().extension]\nself._outext = palign().extension\nself._name = 'basic'", "if isinstance(input_wav, float) is True:\n duration = input_wav\nelse:\n try:\n wav_speech = sppas.src.audiodata.aio.open(input_wav)\n duration = wav_speec...
<|body_start_0|> super(BasicAligner, self).__init__() self._extensions = [palign().extension] self._outext = palign().extension self._name = 'basic' <|end_body_0|> <|body_start_1|> if isinstance(input_wav, float) is True: duration = input_wav else: ...
Basic automatic alignment system. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi This segmentation assign the same duration to each phoneme. In case of phonetic variants, the fir...
BasicAligner
[ "GFDL-1.1-or-later", "GPL-3.0-only", "GPL-3.0-or-later", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BasicAligner: """Basic automatic alignment system. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi This segmentation assign the same duration to each phonem...
stack_v2_sparse_classes_75kplus_train_068455
6,949
permissive
[ { "docstring": "Create a BasicAligner instance. This class allows to align one unit assigning the same duration to each phoneme. It selects the shortest sequence in case of variants. :param model_dir: (str) Ignored.", "name": "__init__", "signature": "def __init__(self, model_dir=None)" }, { "do...
5
stack_v2_sparse_classes_30k_train_051764
Implement the Python class `BasicAligner` described below. Class description: Basic automatic alignment system. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi This segmentation ...
Implement the Python class `BasicAligner` described below. Class description: Basic automatic alignment system. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi This segmentation ...
3167b65f576abcc27a8767d24c274a04712bd948
<|skeleton|> class BasicAligner: """Basic automatic alignment system. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi This segmentation assign the same duration to each phonem...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BasicAligner: """Basic automatic alignment system. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi This segmentation assign the same duration to each phoneme. In case of...
the_stack_v2_python_sparse
sppas/sppas/src/annotations/Align/aligners/basicalign.py
mirfan899/MTTS
train
0
5b0c7f99a1d8bcf527c666e999693637d85072ce
[ "if item not in ('load', 'unload', 'reload'):\n raise ValueError('Invalid plugin type \"{queue_name}\"'.format(queue_name=item))\nif not self:\n Delay(0, self._loop_through_queues)\nvalue = self[item] = set()\nreturn value", "if 'unload' in self:\n self._unload_plugins()\n del self['unload']\nif 'load...
<|body_start_0|> if item not in ('load', 'unload', 'reload'): raise ValueError('Invalid plugin type "{queue_name}"'.format(queue_name=item)) if not self: Delay(0, self._loop_through_queues) value = self[item] = set() return value <|end_body_0|> <|body_start_1|> ...
Plugin queue class used to load/unload plugins.
_PluginQueue
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _PluginQueue: """Plugin queue class used to load/unload plugins.""" def __missing__(self, item): """Add the item to its queue and loop through queues after 1 tick.""" <|body_0|> def _loop_through_queues(self): """Loop through all queues to properly load/unload pl...
stack_v2_sparse_classes_75kplus_train_068456
5,183
no_license
[ { "docstring": "Add the item to its queue and loop through queues after 1 tick.", "name": "__missing__", "signature": "def __missing__(self, item)" }, { "docstring": "Loop through all queues to properly load/unload plugins.", "name": "_loop_through_queues", "signature": "def _loop_throug...
4
stack_v2_sparse_classes_30k_train_000766
Implement the Python class `_PluginQueue` described below. Class description: Plugin queue class used to load/unload plugins. Method signatures and docstrings: - def __missing__(self, item): Add the item to its queue and loop through queues after 1 tick. - def _loop_through_queues(self): Loop through all queues to pr...
Implement the Python class `_PluginQueue` described below. Class description: Plugin queue class used to load/unload plugins. Method signatures and docstrings: - def __missing__(self, item): Add the item to its queue and loop through queues after 1 tick. - def _loop_through_queues(self): Loop through all queues to pr...
cead3639bab2acce9da55a4e7f196c750160b27f
<|skeleton|> class _PluginQueue: """Plugin queue class used to load/unload plugins.""" def __missing__(self, item): """Add the item to its queue and loop through queues after 1 tick.""" <|body_0|> def _loop_through_queues(self): """Loop through all queues to properly load/unload pl...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class _PluginQueue: """Plugin queue class used to load/unload plugins.""" def __missing__(self, item): """Add the item to its queue and loop through queues after 1 tick.""" if item not in ('load', 'unload', 'reload'): raise ValueError('Invalid plugin type "{queue_name}"'.format(queu...
the_stack_v2_python_sparse
srcds/addons/source-python/plugins/admin/core/plugins/queue.py
Source-Python-Dev-Team/Source.Python.Admin
train
8
dc44f9fa36d9243accc60100661a258409ad21f2
[ "params = {'part': enf_parts(resource='channels', value=parts), 'hl': hl, 'maxResults': max_results, 'onBehalfOfContentOwner': on_behalf_of_content_owner, 'pageToken': page_token, **kwargs}\nif for_username is not None:\n params['forUsername'] = for_username\nelif channel_id is not None:\n params['id'] = enf_...
<|body_start_0|> params = {'part': enf_parts(resource='channels', value=parts), 'hl': hl, 'maxResults': max_results, 'onBehalfOfContentOwner': on_behalf_of_content_owner, 'pageToken': page_token, **kwargs} if for_username is not None: params['forUsername'] = for_username elif channel...
A channel resource contains information about a YouTube channel. References: https://developers.google.com/youtube/v3/docs/channels
ChannelsResource
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ChannelsResource: """A channel resource contains information about a YouTube channel. References: https://developers.google.com/youtube/v3/docs/channels""" def list(self, parts: Optional[Union[str, list, tuple, set]]=None, for_username: Optional[str]=None, channel_id: Optional[Union[str, lis...
stack_v2_sparse_classes_75kplus_train_068457
7,718
permissive
[ { "docstring": "Returns a collection of zero or more channel resources that match the request criteria. Args: parts: Comma-separated list of one or more channel resource properties. Accepted values: id,auditDetails,brandingSettings,contentDetails,contentOwnerDetails, localizations,snippet,statistics,status,topi...
2
null
Implement the Python class `ChannelsResource` described below. Class description: A channel resource contains information about a YouTube channel. References: https://developers.google.com/youtube/v3/docs/channels Method signatures and docstrings: - def list(self, parts: Optional[Union[str, list, tuple, set]]=None, f...
Implement the Python class `ChannelsResource` described below. Class description: A channel resource contains information about a YouTube channel. References: https://developers.google.com/youtube/v3/docs/channels Method signatures and docstrings: - def list(self, parts: Optional[Union[str, list, tuple, set]]=None, f...
1ed2f67a55b8df75c5fab9aacd7d9ff4d460812a
<|skeleton|> class ChannelsResource: """A channel resource contains information about a YouTube channel. References: https://developers.google.com/youtube/v3/docs/channels""" def list(self, parts: Optional[Union[str, list, tuple, set]]=None, for_username: Optional[str]=None, channel_id: Optional[Union[str, lis...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ChannelsResource: """A channel resource contains information about a YouTube channel. References: https://developers.google.com/youtube/v3/docs/channels""" def list(self, parts: Optional[Union[str, list, tuple, set]]=None, for_username: Optional[str]=None, channel_id: Optional[Union[str, list, tuple, set...
the_stack_v2_python_sparse
pyyoutube/resources/channels.py
sns-sdks/python-youtube
train
249
b18c34502918b94175ea56a6a68f003f5132f416
[ "nic_attributes = {}\nnic_plugin_attributes_query = db().query(cls.model.id, models.Plugin.name, models.Plugin.title, cls.model.attributes).join(models.ClusterPlugin, models.Plugin).filter(cls.model.interface_id == interface.id).filter(models.ClusterPlugin.enabled.is_(True)).all()\nfor nic_plugin_id, name, title, a...
<|body_start_0|> nic_attributes = {} nic_plugin_attributes_query = db().query(cls.model.id, models.Plugin.name, models.Plugin.title, cls.model.attributes).join(models.ClusterPlugin, models.Plugin).filter(cls.model.interface_id == interface.id).filter(models.ClusterPlugin.enabled.is_(True)).all() ...
NodeNICInterfaceClusterPlugin
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NodeNICInterfaceClusterPlugin: def get_all_enabled_attributes_by_interface(cls, interface): """Returns plugin enabled attributes for specific NIC. :param interface: Interface instance :type interface: models.node.NodeNICInterface :returns: dict -- Dict object with plugin NIC attributes""...
stack_v2_sparse_classes_75kplus_train_068458
24,356
permissive
[ { "docstring": "Returns plugin enabled attributes for specific NIC. :param interface: Interface instance :type interface: models.node.NodeNICInterface :returns: dict -- Dict object with plugin NIC attributes", "name": "get_all_enabled_attributes_by_interface", "signature": "def get_all_enabled_attribute...
3
stack_v2_sparse_classes_30k_val_002094
Implement the Python class `NodeNICInterfaceClusterPlugin` described below. Class description: Implement the NodeNICInterfaceClusterPlugin class. Method signatures and docstrings: - def get_all_enabled_attributes_by_interface(cls, interface): Returns plugin enabled attributes for specific NIC. :param interface: Inter...
Implement the Python class `NodeNICInterfaceClusterPlugin` described below. Class description: Implement the NodeNICInterfaceClusterPlugin class. Method signatures and docstrings: - def get_all_enabled_attributes_by_interface(cls, interface): Returns plugin enabled attributes for specific NIC. :param interface: Inter...
768ac74a420f822261c4eb8da72f1d8af3c6bbff
<|skeleton|> class NodeNICInterfaceClusterPlugin: def get_all_enabled_attributes_by_interface(cls, interface): """Returns plugin enabled attributes for specific NIC. :param interface: Interface instance :type interface: models.node.NodeNICInterface :returns: dict -- Dict object with plugin NIC attributes""...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NodeNICInterfaceClusterPlugin: def get_all_enabled_attributes_by_interface(cls, interface): """Returns plugin enabled attributes for specific NIC. :param interface: Interface instance :type interface: models.node.NodeNICInterface :returns: dict -- Dict object with plugin NIC attributes""" nic_...
the_stack_v2_python_sparse
nailgun/nailgun/objects/plugin.py
dis-xcom/fuel-web
train
0
e8ae744d3ac1d8c8dbeabbc7cacef45c85d8778d
[ "tail = []\nfor num in nums:\n if not tail or num > tail[-1]:\n tail.append(num)\n elif num in tail:\n continue\n else:\n left = 0\n right = len(tail) - 1\n while left < right:\n mid = (left + right) // 2\n if tail[mid] > num:\n right ...
<|body_start_0|> tail = [] for num in nums: if not tail or num > tail[-1]: tail.append(num) elif num in tail: continue else: left = 0 right = len(tail) - 1 while left < right: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def lengthOfLIS(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def lengthOfLIS2(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> tail = [] for num in nums: ...
stack_v2_sparse_classes_75kplus_train_068459
1,748
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "lengthOfLIS", "signature": "def lengthOfLIS(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "lengthOfLIS2", "signature": "def lengthOfLIS2(self, nums)" } ]
2
stack_v2_sparse_classes_30k_train_013936
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def lengthOfLIS(self, nums): :type nums: List[int] :rtype: int - def lengthOfLIS2(self, nums): :type nums: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def lengthOfLIS(self, nums): :type nums: List[int] :rtype: int - def lengthOfLIS2(self, nums): :type nums: List[int] :rtype: int <|skeleton|> class Solution: def lengthOfLI...
2866df7587ee867a958a2b4fc02345bc3ef56999
<|skeleton|> class Solution: def lengthOfLIS(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def lengthOfLIS2(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def lengthOfLIS(self, nums): """:type nums: List[int] :rtype: int""" tail = [] for num in nums: if not tail or num > tail[-1]: tail.append(num) elif num in tail: continue else: left = 0 ...
the_stack_v2_python_sparse
中级算法/lengthOfLIS.py
OrangeJessie/Fighting_Leetcode
train
1
8fb8a228c08dc5a74701271bd6db5937c47f0de2
[ "use_openssl_only = os.getenv('SF_USE_OPENSSL_ONLY', 'False') == 'True'\nCHUNK_SIZE = 64 * kilobyte\nif not use_openssl_only:\n m = SHA256.new()\nelse:\n backend = default_backend()\n chosen_hash = hashes.SHA256()\n hasher = hashes.Hash(chosen_hash, backend)\nwhile True:\n chunk = src.read(CHUNK_SIZE...
<|body_start_0|> use_openssl_only = os.getenv('SF_USE_OPENSSL_ONLY', 'False') == 'True' CHUNK_SIZE = 64 * kilobyte if not use_openssl_only: m = SHA256.new() else: backend = default_backend() chosen_hash = hashes.SHA256() hasher = hashes.Has...
SnowflakeFileUtil
[ "Apache-2.0", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SnowflakeFileUtil: def get_digest_and_size(src: IO[bytes]) -> tuple[str, int]: """Gets stream digest and size. Args: src: The input stream. Returns: Tuple of src's digest and src's size in bytes.""" <|body_0|> def compress_with_gzip_from_stream(src_stream: IO[bytes]) -> tupl...
stack_v2_sparse_classes_75kplus_train_068460
5,427
permissive
[ { "docstring": "Gets stream digest and size. Args: src: The input stream. Returns: Tuple of src's digest and src's size in bytes.", "name": "get_digest_and_size", "signature": "def get_digest_and_size(src: IO[bytes]) -> tuple[str, int]" }, { "docstring": "Compresses a stream of bytes with GZIP. ...
6
stack_v2_sparse_classes_30k_train_033989
Implement the Python class `SnowflakeFileUtil` described below. Class description: Implement the SnowflakeFileUtil class. Method signatures and docstrings: - def get_digest_and_size(src: IO[bytes]) -> tuple[str, int]: Gets stream digest and size. Args: src: The input stream. Returns: Tuple of src's digest and src's s...
Implement the Python class `SnowflakeFileUtil` described below. Class description: Implement the SnowflakeFileUtil class. Method signatures and docstrings: - def get_digest_and_size(src: IO[bytes]) -> tuple[str, int]: Gets stream digest and size. Args: src: The input stream. Returns: Tuple of src's digest and src's s...
da1ae4ed1e940e4210348c59c9c660ebaa78fc2e
<|skeleton|> class SnowflakeFileUtil: def get_digest_and_size(src: IO[bytes]) -> tuple[str, int]: """Gets stream digest and size. Args: src: The input stream. Returns: Tuple of src's digest and src's size in bytes.""" <|body_0|> def compress_with_gzip_from_stream(src_stream: IO[bytes]) -> tupl...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SnowflakeFileUtil: def get_digest_and_size(src: IO[bytes]) -> tuple[str, int]: """Gets stream digest and size. Args: src: The input stream. Returns: Tuple of src's digest and src's size in bytes.""" use_openssl_only = os.getenv('SF_USE_OPENSSL_ONLY', 'False') == 'True' CHUNK_SIZE = 64 ...
the_stack_v2_python_sparse
src/snowflake/connector/file_util.py
snowflakedb/snowflake-connector-python
train
492
c6992478c7dcc7b645135dcf7ed4c1e77f31f589
[ "if not head:\n return head\nlast = None\nwhile head.next:\n later = head.next\n head.next = last\n last = head\n head = later\nhead.next = last\nreturn head\nprev = None\nwhile head:\n cur = head\n head = head.next\n cur.next = prev\n prev = cur\nreturn prev", "if not head:\n return...
<|body_start_0|> if not head: return head last = None while head.next: later = head.next head.next = last last = head head = later head.next = last return head prev = None while head: cur = he...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def reverseList(self, head): """:type head: ListNode :rtype: ListNode""" <|body_0|> def reverseList2(self, head, last=None): """:type head: ListNode :rtype: ListNode""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not head: ...
stack_v2_sparse_classes_75kplus_train_068461
1,595
no_license
[ { "docstring": ":type head: ListNode :rtype: ListNode", "name": "reverseList", "signature": "def reverseList(self, head)" }, { "docstring": ":type head: ListNode :rtype: ListNode", "name": "reverseList2", "signature": "def reverseList2(self, head, last=None)" } ]
2
stack_v2_sparse_classes_30k_train_010252
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseList(self, head): :type head: ListNode :rtype: ListNode - def reverseList2(self, head, last=None): :type head: ListNode :rtype: ListNode
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseList(self, head): :type head: ListNode :rtype: ListNode - def reverseList2(self, head, last=None): :type head: ListNode :rtype: ListNode <|skeleton|> class Solution: ...
b4dccd3d1c59aa1e92f10ed5c4f7a3e1d08897d8
<|skeleton|> class Solution: def reverseList(self, head): """:type head: ListNode :rtype: ListNode""" <|body_0|> def reverseList2(self, head, last=None): """:type head: ListNode :rtype: ListNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def reverseList(self, head): """:type head: ListNode :rtype: ListNode""" if not head: return head last = None while head.next: later = head.next head.next = last last = head head = later head.next = l...
the_stack_v2_python_sparse
ReverseLinkedList.py
janewjy/Leetcode
train
1
6f39c3f052c4588ea6cc831c745044adddd662bd
[ "super(OpenStackBaseTest, cls).setUpClass(application_name, model_alias)\ncls.keystone_session = openstack_utils.get_overcloud_keystone_session(model_name=cls.model_name)\ncls.cacert = openstack_utils.get_cacert()\ncls.nova_client = openstack_utils.get_nova_session_client(cls.keystone_session)", "try:\n loggin...
<|body_start_0|> super(OpenStackBaseTest, cls).setUpClass(application_name, model_alias) cls.keystone_session = openstack_utils.get_overcloud_keystone_session(model_name=cls.model_name) cls.cacert = openstack_utils.get_cacert() cls.nova_client = openstack_utils.get_nova_session_client(cl...
Generic helpers for testing OpenStack API charms.
OpenStackBaseTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OpenStackBaseTest: """Generic helpers for testing OpenStack API charms.""" def setUpClass(cls, application_name=None, model_alias=None): """Run setup for test class to create common resources.""" <|body_0|> def resource_cleanup(self): """Remove test resources."""...
stack_v2_sparse_classes_75kplus_train_068462
22,129
permissive
[ { "docstring": "Run setup for test class to create common resources.", "name": "setUpClass", "signature": "def setUpClass(cls, application_name=None, model_alias=None)" }, { "docstring": "Remove test resources.", "name": "resource_cleanup", "signature": "def resource_cleanup(self)" }, ...
6
stack_v2_sparse_classes_30k_train_024259
Implement the Python class `OpenStackBaseTest` described below. Class description: Generic helpers for testing OpenStack API charms. Method signatures and docstrings: - def setUpClass(cls, application_name=None, model_alias=None): Run setup for test class to create common resources. - def resource_cleanup(self): Remo...
Implement the Python class `OpenStackBaseTest` described below. Class description: Generic helpers for testing OpenStack API charms. Method signatures and docstrings: - def setUpClass(cls, application_name=None, model_alias=None): Run setup for test class to create common resources. - def resource_cleanup(self): Remo...
b0f5a2430a19b4e2835c2ccb9482d0831ffe3483
<|skeleton|> class OpenStackBaseTest: """Generic helpers for testing OpenStack API charms.""" def setUpClass(cls, application_name=None, model_alias=None): """Run setup for test class to create common resources.""" <|body_0|> def resource_cleanup(self): """Remove test resources."""...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class OpenStackBaseTest: """Generic helpers for testing OpenStack API charms.""" def setUpClass(cls, application_name=None, model_alias=None): """Run setup for test class to create common resources.""" super(OpenStackBaseTest, cls).setUpClass(application_name, model_alias) cls.keystone_...
the_stack_v2_python_sparse
zaza/openstack/charm_tests/test_utils.py
camille-rodriguez/zaza-openstack-tests
train
1
a8fc39d4c595b3829992f6ee4fbab9648b01373c
[ "if os.path.isfile(Config.CR_CONFIG_FULL_PATH):\n log.log_debug('Configuration file: Found. Reading it.')\n self.read_config_file()\nelse:\n log.log_info('Configuration file: Not found. Creating it.')\n self.write_config_file()", "log.log_debug('Reading the config file...')\nConfig.config.read(Config....
<|body_start_0|> if os.path.isfile(Config.CR_CONFIG_FULL_PATH): log.log_debug('Configuration file: Found. Reading it.') self.read_config_file() else: log.log_info('Configuration file: Not found. Creating it.') self.write_config_file() <|end_body_0|> <|bod...
Manages CentralReport configuration.
Config
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Config: """Manages CentralReport configuration.""" def __init__(self): """Constructor""" <|body_0|> def read_config_file(self): """Reads the configuration file.""" <|body_1|> def write_config_file(self): """Writes the actual configuration int...
stack_v2_sparse_classes_75kplus_train_068463
6,426
permissive
[ { "docstring": "Constructor", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Reads the configuration file.", "name": "read_config_file", "signature": "def read_config_file(self)" }, { "docstring": "Writes the actual configuration into the config file.", ...
5
stack_v2_sparse_classes_30k_train_027665
Implement the Python class `Config` described below. Class description: Manages CentralReport configuration. Method signatures and docstrings: - def __init__(self): Constructor - def read_config_file(self): Reads the configuration file. - def write_config_file(self): Writes the actual configuration into the config fi...
Implement the Python class `Config` described below. Class description: Manages CentralReport configuration. Method signatures and docstrings: - def __init__(self): Constructor - def read_config_file(self): Reads the configuration file. - def write_config_file(self): Writes the actual configuration into the config fi...
421447f31d07321f65198c5b5746baa16c9d9725
<|skeleton|> class Config: """Manages CentralReport configuration.""" def __init__(self): """Constructor""" <|body_0|> def read_config_file(self): """Reads the configuration file.""" <|body_1|> def write_config_file(self): """Writes the actual configuration int...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Config: """Manages CentralReport configuration.""" def __init__(self): """Constructor""" if os.path.isfile(Config.CR_CONFIG_FULL_PATH): log.log_debug('Configuration file: Found. Reading it.') self.read_config_file() else: log.log_info('Configura...
the_stack_v2_python_sparse
centralreport/cr/tools.py
haiyangd/CentralReport
train
0
1390d0e7272e1e101fd32cfa60a3f7d69555b372
[ "cmd = 'fleetrun --gpu=0,1 dist_fleet_dygraph_api.py'\npro = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\npro.wait()\npro.returncode == 0", "cmd = 'fleetrun --gpu=0 dist_fleet_dygraph_api.py'\npro = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.P...
<|body_start_0|> cmd = 'fleetrun --gpu=0,1 dist_fleet_dygraph_api.py' pro = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) pro.wait() pro.returncode == 0 <|end_body_0|> <|body_start_1|> cmd = 'fleetrun --gpu=0 dist_fleet_dygraph_api.py' ...
Test dygraph
TestDygraph
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestDygraph: """Test dygraph""" def test_dist_fleet_dygraph_api_2gpus(self): """test_dist_fleet_dygraph_api_2gpus.""" <|body_0|> def test_dist_fleet_dygraph_api_1gpus(self): """test_dist_fleet_dygraph_api_1gpus""" <|body_1|> def test_dist_fleet_dygra...
stack_v2_sparse_classes_75kplus_train_068464
1,941
no_license
[ { "docstring": "test_dist_fleet_dygraph_api_2gpus.", "name": "test_dist_fleet_dygraph_api_2gpus", "signature": "def test_dist_fleet_dygraph_api_2gpus(self)" }, { "docstring": "test_dist_fleet_dygraph_api_1gpus", "name": "test_dist_fleet_dygraph_api_1gpus", "signature": "def test_dist_fle...
4
stack_v2_sparse_classes_30k_train_024535
Implement the Python class `TestDygraph` described below. Class description: Test dygraph Method signatures and docstrings: - def test_dist_fleet_dygraph_api_2gpus(self): test_dist_fleet_dygraph_api_2gpus. - def test_dist_fleet_dygraph_api_1gpus(self): test_dist_fleet_dygraph_api_1gpus - def test_dist_fleet_dygraph_l...
Implement the Python class `TestDygraph` described below. Class description: Test dygraph Method signatures and docstrings: - def test_dist_fleet_dygraph_api_2gpus(self): test_dist_fleet_dygraph_api_2gpus. - def test_dist_fleet_dygraph_api_1gpus(self): test_dist_fleet_dygraph_api_1gpus - def test_dist_fleet_dygraph_l...
e3562ab40b574f06bba68df6895a055fa31a085d
<|skeleton|> class TestDygraph: """Test dygraph""" def test_dist_fleet_dygraph_api_2gpus(self): """test_dist_fleet_dygraph_api_2gpus.""" <|body_0|> def test_dist_fleet_dygraph_api_1gpus(self): """test_dist_fleet_dygraph_api_1gpus""" <|body_1|> def test_dist_fleet_dygra...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestDygraph: """Test dygraph""" def test_dist_fleet_dygraph_api_2gpus(self): """test_dist_fleet_dygraph_api_2gpus.""" cmd = 'fleetrun --gpu=0,1 dist_fleet_dygraph_api.py' pro = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) pro.wait() ...
the_stack_v2_python_sparse
dist_cts/dist_fleet_pipeline/test_dist_fleet_dygraph_api.py
gentelyang/scripts
train
0
d3621d82aad1d0a68f2502c47792103df57ae7c5
[ "to_return = []\nfor module in modules.values():\n try:\n if module.meta.allow_today:\n today = module.today()\n if today:\n to_return.append({'name': module.meta.display_name, 'renderable': today, 'destroy_func': lambda: emit(f'{module.meta.name}.destroy')})\n exce...
<|body_start_0|> to_return = [] for module in modules.values(): try: if module.meta.allow_today: today = module.today() if today: to_return.append({'name': module.meta.display_name, 'renderable': today, 'destroy_...
TodayModule
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TodayModule: def _get_today() -> List[dict]: """Generator to get the Today items from each module""" <|body_0|> def card(cls): """Returns the today card""" <|body_1|> <|end_skeleton|> <|body_start_0|> to_return = [] for module in modules.val...
stack_v2_sparse_classes_75kplus_train_068465
1,941
permissive
[ { "docstring": "Generator to get the Today items from each module", "name": "_get_today", "signature": "def _get_today() -> List[dict]" }, { "docstring": "Returns the today card", "name": "card", "signature": "def card(cls)" } ]
2
stack_v2_sparse_classes_30k_train_044739
Implement the Python class `TodayModule` described below. Class description: Implement the TodayModule class. Method signatures and docstrings: - def _get_today() -> List[dict]: Generator to get the Today items from each module - def card(cls): Returns the today card
Implement the Python class `TodayModule` described below. Class description: Implement the TodayModule class. Method signatures and docstrings: - def _get_today() -> List[dict]: Generator to get the Today items from each module - def card(cls): Returns the today card <|skeleton|> class TodayModule: def _get_tod...
9962f09b543a3c52929501dba29aa48b495db578
<|skeleton|> class TodayModule: def _get_today() -> List[dict]: """Generator to get the Today items from each module""" <|body_0|> def card(cls): """Returns the today card""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TodayModule: def _get_today() -> List[dict]: """Generator to get the Today items from each module""" to_return = [] for module in modules.values(): try: if module.meta.allow_today: today = module.today() if today: ...
the_stack_v2_python_sparse
trash_dash/modules/today.py
manjunaath5583/respectful_racoons
train
2
bee60778f293ac7988cd143b9f45fa91645e7059
[ "if n == 1:\n return 1\nelif n == 2:\n return 2\nelse:\n return self.rec_climbStairs(n - 1) + self.rec_climbStairs(n - 2)", "if n == 1:\n return 1\na = 1\nb = 2\nfor i in range(n - 2):\n tmp = a + b\n a = b\n b = tmp\nreturn b" ]
<|body_start_0|> if n == 1: return 1 elif n == 2: return 2 else: return self.rec_climbStairs(n - 1) + self.rec_climbStairs(n - 2) <|end_body_0|> <|body_start_1|> if n == 1: return 1 a = 1 b = 2 for i in range(n - 2)...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def rec_climbStairs(self, n): """:type n: int :rtype: int""" <|body_0|> def dp_climbStairs(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> if n == 1: return 1 elif n == 2: ...
stack_v2_sparse_classes_75kplus_train_068466
820
permissive
[ { "docstring": ":type n: int :rtype: int", "name": "rec_climbStairs", "signature": "def rec_climbStairs(self, n)" }, { "docstring": ":type n: int :rtype: int", "name": "dp_climbStairs", "signature": "def dp_climbStairs(self, n)" } ]
2
stack_v2_sparse_classes_30k_train_034743
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rec_climbStairs(self, n): :type n: int :rtype: int - def dp_climbStairs(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 rec_climbStairs(self, n): :type n: int :rtype: int - def dp_climbStairs(self, n): :type n: int :rtype: int <|skeleton|> class Solution: def rec_climbStairs(self, n): ...
e93f93fd58d1945708d6aa300dcbcd17d0708274
<|skeleton|> class Solution: def rec_climbStairs(self, n): """:type n: int :rtype: int""" <|body_0|> def dp_climbStairs(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 rec_climbStairs(self, n): """:type n: int :rtype: int""" if n == 1: return 1 elif n == 2: return 2 else: return self.rec_climbStairs(n - 1) + self.rec_climbStairs(n - 2) def dp_climbStairs(self, n): """:type n: int ...
the_stack_v2_python_sparse
LeetCode/Python/DP/70. Climbing Stairs.py
Alfonsxh/LeetCode-Challenge-python
train
1
91093f8de2b68e57eb4a7a9666f6aa9c23dbc50d
[ "if sideAngle is None:\n if len(loop) > 0:\n sideAngle = 2.0 * math.pi / float(len(loop))\n else:\n sideAngle = 1.0\n print('Warning, loop has no sides in SideLoop in lineation.')\nif sideLength is None:\n if len(loop) > 0:\n sideLength = euclidean.getLoopLength(loop) / float(le...
<|body_start_0|> if sideAngle is None: if len(loop) > 0: sideAngle = 2.0 * math.pi / float(len(loop)) else: sideAngle = 1.0 print('Warning, loop has no sides in SideLoop in lineation.') if sideLength is None: if len(loop...
Class to handle loop, side angle and side length.
SideLoop
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SideLoop: """Class to handle loop, side angle and side length.""" def __init__(self, loop, sideAngle=None, sideLength=None): """Initialize.""" <|body_0|> def getManipulationPluginLoops(self, elementNode): """Get loop manipulated by the plugins in the manipulation...
stack_v2_sparse_classes_75kplus_train_068467
12,603
no_license
[ { "docstring": "Initialize.", "name": "__init__", "signature": "def __init__(self, loop, sideAngle=None, sideLength=None)" }, { "docstring": "Get loop manipulated by the plugins in the manipulation paths folder.", "name": "getManipulationPluginLoops", "signature": "def getManipulationPlu...
3
stack_v2_sparse_classes_30k_test_001169
Implement the Python class `SideLoop` described below. Class description: Class to handle loop, side angle and side length. Method signatures and docstrings: - def __init__(self, loop, sideAngle=None, sideLength=None): Initialize. - def getManipulationPluginLoops(self, elementNode): Get loop manipulated by the plugin...
Implement the Python class `SideLoop` described below. Class description: Class to handle loop, side angle and side length. Method signatures and docstrings: - def __init__(self, loop, sideAngle=None, sideLength=None): Initialize. - def getManipulationPluginLoops(self, elementNode): Get loop manipulated by the plugin...
ef1732ade7b1ae3c676e5321333c7ca88c9db514
<|skeleton|> class SideLoop: """Class to handle loop, side angle and side length.""" def __init__(self, loop, sideAngle=None, sideLength=None): """Initialize.""" <|body_0|> def getManipulationPluginLoops(self, elementNode): """Get loop manipulated by the plugins in the manipulation...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SideLoop: """Class to handle loop, side angle and side length.""" def __init__(self, loop, sideAngle=None, sideLength=None): """Initialize.""" if sideAngle is None: if len(loop) > 0: sideAngle = 2.0 * math.pi / float(len(loop)) else: ...
the_stack_v2_python_sparse
fabmetheus_utilities/geometry/creation/lineation.py
joewalnes/SFACT
train
1
3d51bbd22301245944d5baca5906efa0e09e1dbe
[ "super().__init__()\nif background_color is None:\n background_color = torch.full((3,), -1, dtype=torch.float32)\nself.register_buffer('bg_color', background_color)\nself.noise_std = noise_std", "p_distances = z_vals[..., 1:] - z_vals[..., :-1]\nlast_elem = torch.as_tensor([10000000000.0])[None, :].expand(p_di...
<|body_start_0|> super().__init__() if background_color is None: background_color = torch.full((3,), -1, dtype=torch.float32) self.register_buffer('bg_color', background_color) self.noise_std = noise_std <|end_body_0|> <|body_start_1|> p_distances = z_vals[..., 1:] -...
Color aggregation function. Takes the raw predictions obtained from a NIF model, the depth values and a ray direction to produce the final color of a pixel. Please refer to the original NeRF paper for more information. Usage: .. code-block:: python # Assume the models are given. nif_model = NeRFModel() renderer = Point...
NeRFAggregator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NeRFAggregator: """Color aggregation function. Takes the raw predictions obtained from a NIF model, the depth values and a ray direction to produce the final color of a pixel. Please refer to the original NeRF paper for more information. Usage: .. code-block:: python # Assume the models are given...
stack_v2_sparse_classes_75kplus_train_068468
4,738
permissive
[ { "docstring": "Args: background_color (torch.Tensor): The background color to be added for rendering. If set to None, no background will be added. Default is None. noise_std (float): The standard deviation of the noise to be added to alpha. Set 0 to disable the noise addition. Default is 0.", "name": "__in...
2
stack_v2_sparse_classes_30k_test_001831
Implement the Python class `NeRFAggregator` described below. Class description: Color aggregation function. Takes the raw predictions obtained from a NIF model, the depth values and a ray direction to produce the final color of a pixel. Please refer to the original NeRF paper for more information. Usage: .. code-block...
Implement the Python class `NeRFAggregator` described below. Class description: Color aggregation function. Takes the raw predictions obtained from a NIF model, the depth values and a ray direction to produce the final color of a pixel. Please refer to the original NeRF paper for more information. Usage: .. code-block...
da3680cce7e8fc4c194f13a1528cddbad9a18ab0
<|skeleton|> class NeRFAggregator: """Color aggregation function. Takes the raw predictions obtained from a NIF model, the depth values and a ray direction to produce the final color of a pixel. Please refer to the original NeRF paper for more information. Usage: .. code-block:: python # Assume the models are given...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NeRFAggregator: """Color aggregation function. Takes the raw predictions obtained from a NIF model, the depth values and a ray direction to produce the final color of a pixel. Please refer to the original NeRF paper for more information. Usage: .. code-block:: python # Assume the models are given. nif_model =...
the_stack_v2_python_sparse
pynif3d/aggregation/nerf_aggregator.py
pfnet/pynif3d
train
72
487d8725374bfb0bd04c29b639f883de29abbb7c
[ "row_length = len(matrix)\nif row_length == 0:\n return\ncol_length = len(matrix[0])\nupdate_place = []\nfor i in range(row_length):\n for j in range(col_length):\n if matrix[i][j] == 0:\n update_place.append((i, j))\nfor row, col in update_place:\n for i in range(row_length):\n ma...
<|body_start_0|> row_length = len(matrix) if row_length == 0: return col_length = len(matrix[0]) update_place = [] for i in range(row_length): for j in range(col_length): if matrix[i][j] == 0: update_place.append((i, j))...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def setZeroes(self, matrix: [[int]]) -> None: """Do not return anything, modify matrix in-place instead.""" <|body_0|> def setZeroes_2(self, matrix: [[int]]) -> None: """Do not return anything, modify matrix in-place instead.""" <|body_1|> <|end_sk...
stack_v2_sparse_classes_75kplus_train_068469
1,986
permissive
[ { "docstring": "Do not return anything, modify matrix in-place instead.", "name": "setZeroes", "signature": "def setZeroes(self, matrix: [[int]]) -> None" }, { "docstring": "Do not return anything, modify matrix in-place instead.", "name": "setZeroes_2", "signature": "def setZeroes_2(sel...
2
stack_v2_sparse_classes_30k_train_041149
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def setZeroes(self, matrix: [[int]]) -> None: Do not return anything, modify matrix in-place instead. - def setZeroes_2(self, matrix: [[int]]) -> None: Do not return anything, mo...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def setZeroes(self, matrix: [[int]]) -> None: Do not return anything, modify matrix in-place instead. - def setZeroes_2(self, matrix: [[int]]) -> None: Do not return anything, mo...
735e782742fab15bdb046eb6d5fc7b03502cc92d
<|skeleton|> class Solution: def setZeroes(self, matrix: [[int]]) -> None: """Do not return anything, modify matrix in-place instead.""" <|body_0|> def setZeroes_2(self, matrix: [[int]]) -> None: """Do not return anything, modify matrix in-place instead.""" <|body_1|> <|end_sk...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def setZeroes(self, matrix: [[int]]) -> None: """Do not return anything, modify matrix in-place instead.""" row_length = len(matrix) if row_length == 0: return col_length = len(matrix[0]) update_place = [] for i in range(row_length): ...
the_stack_v2_python_sparse
LeetCode/_0051_0100/_073_SetMatrixZeroes.py
BigEggStudy/LeetCode-Py
train
1
a233129b361ef71013245e3d5f4aedc5f66d6d03
[ "@tff_math.make_val_and_grad_fn\ndef himmelblau(coord):\n x, y = (coord[..., 0], coord[..., 1])\n return (x * x + y - 11) ** 2 + (x + y * y - 7) ** 2\nstart = tf.constant([[1, 1], [-2, 2], [-1, -1], [1, -2]], dtype='float64')\nresults = self.evaluate(tff_math.optimizer.bfgs_minimize(himmelblau, initial_positi...
<|body_start_0|> @tff_math.make_val_and_grad_fn def himmelblau(coord): x, y = (coord[..., 0], coord[..., 1]) return (x * x + y - 11) ** 2 + (x + y * y - 7) ** 2 start = tf.constant([[1, 1], [-2, 2], [-1, -1], [1, -2]], dtype='float64') results = self.evaluate(tff_...
Tests for optimization algorithms.
OptimizerTest
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OptimizerTest: """Tests for optimization algorithms.""" def test_bfgs_minimize(self): """Use BFGS algorithm to find all four minima of Himmelblau's function.""" <|body_0|> def test_lbfgs_minimize(self): """Use L-BFGS algorithm to optimize randomly generated quadr...
stack_v2_sparse_classes_75kplus_train_068470
3,979
permissive
[ { "docstring": "Use BFGS algorithm to find all four minima of Himmelblau's function.", "name": "test_bfgs_minimize", "signature": "def test_bfgs_minimize(self)" }, { "docstring": "Use L-BFGS algorithm to optimize randomly generated quadratic bowls.", "name": "test_lbfgs_minimize", "signa...
4
stack_v2_sparse_classes_30k_train_039013
Implement the Python class `OptimizerTest` described below. Class description: Tests for optimization algorithms. Method signatures and docstrings: - def test_bfgs_minimize(self): Use BFGS algorithm to find all four minima of Himmelblau's function. - def test_lbfgs_minimize(self): Use L-BFGS algorithm to optimize ran...
Implement the Python class `OptimizerTest` described below. Class description: Tests for optimization algorithms. Method signatures and docstrings: - def test_bfgs_minimize(self): Use BFGS algorithm to find all four minima of Himmelblau's function. - def test_lbfgs_minimize(self): Use L-BFGS algorithm to optimize ran...
0d3a2193c0f2d320b65e602cf01d7a617da484df
<|skeleton|> class OptimizerTest: """Tests for optimization algorithms.""" def test_bfgs_minimize(self): """Use BFGS algorithm to find all four minima of Himmelblau's function.""" <|body_0|> def test_lbfgs_minimize(self): """Use L-BFGS algorithm to optimize randomly generated quadr...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class OptimizerTest: """Tests for optimization algorithms.""" def test_bfgs_minimize(self): """Use BFGS algorithm to find all four minima of Himmelblau's function.""" @tff_math.make_val_and_grad_fn def himmelblau(coord): x, y = (coord[..., 0], coord[..., 1]) retu...
the_stack_v2_python_sparse
tf_quant_finance/math/optimizer/optimizer_test.py
google/tf-quant-finance
train
4,165
f6163f73acfc79fcc6e4a3f99366478820560295
[ "fewshot_re_kit.framework.FewShotREModel.__init__(self, sentence_encoder)\nself.hidden_size = hidden_size\nself.node_dim = hidden_size + N\nself.gnn_obj = gnn_iclr.GNN_nl(N, self.node_dim, nf=96, J=1)", "support = self.sentence_encoder(support)\nquery = self.sentence_encoder(query)\nsupport = support.view(-1, N, ...
<|body_start_0|> fewshot_re_kit.framework.FewShotREModel.__init__(self, sentence_encoder) self.hidden_size = hidden_size self.node_dim = hidden_size + N self.gnn_obj = gnn_iclr.GNN_nl(N, self.node_dim, nf=96, J=1) <|end_body_0|> <|body_start_1|> support = self.sentence_encoder(s...
GNN
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GNN: def __init__(self, sentence_encoder, N, hidden_size=230): """N: Num of classes""" <|body_0|> def forward(self, support, query, N, K, NQ): """support: Inputs of the support set. query: Inputs of the query set. N: Num of classes K: Num of instances for each class ...
stack_v2_sparse_classes_75kplus_train_068471
1,805
permissive
[ { "docstring": "N: Num of classes", "name": "__init__", "signature": "def __init__(self, sentence_encoder, N, hidden_size=230)" }, { "docstring": "support: Inputs of the support set. query: Inputs of the query set. N: Num of classes K: Num of instances for each class in the support set Q: Num of...
2
stack_v2_sparse_classes_30k_train_054558
Implement the Python class `GNN` described below. Class description: Implement the GNN class. Method signatures and docstrings: - def __init__(self, sentence_encoder, N, hidden_size=230): N: Num of classes - def forward(self, support, query, N, K, NQ): support: Inputs of the support set. query: Inputs of the query se...
Implement the Python class `GNN` described below. Class description: Implement the GNN class. Method signatures and docstrings: - def __init__(self, sentence_encoder, N, hidden_size=230): N: Num of classes - def forward(self, support, query, N, K, NQ): support: Inputs of the support set. query: Inputs of the query se...
278a2315d2138810a379cd8d5718914dc56e2582
<|skeleton|> class GNN: def __init__(self, sentence_encoder, N, hidden_size=230): """N: Num of classes""" <|body_0|> def forward(self, support, query, N, K, NQ): """support: Inputs of the support set. query: Inputs of the query set. N: Num of classes K: Num of instances for each class ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GNN: def __init__(self, sentence_encoder, N, hidden_size=230): """N: Num of classes""" fewshot_re_kit.framework.FewShotREModel.__init__(self, sentence_encoder) self.hidden_size = hidden_size self.node_dim = hidden_size + N self.gnn_obj = gnn_iclr.GNN_nl(N, self.node_dim...
the_stack_v2_python_sparse
models/gnn.py
thunlp/FewRel
train
752
31e0b0aa64493ae4785a99201a9d65df4806e9cb
[ "super().__init__()\nself._n_pts_per_ray = n_pts_per_ray\nself._min_depth = min_depth\nself._max_depth = max_depth\nself._n_rays_per_image = n_rays_per_image\nself._unit_directions = unit_directions\nself._stratified_sampling = stratified_sampling\nself._lin_disp = lin_disp\n_xy_grid = torch.stack(tuple(reversed(me...
<|body_start_0|> super().__init__() self._n_pts_per_ray = n_pts_per_ray self._min_depth = min_depth self._max_depth = max_depth self._n_rays_per_image = n_rays_per_image self._unit_directions = unit_directions self._stratified_sampling = stratified_sampling ...
Samples a fixed number of points along rays which are regularly distributed in a batch of rectangular image grids. Points along each ray have uniformly-spaced z-coordinates between a predefined minimum and maximum depth. The raysampler first generates a 3D coordinate grid of the following form: ``` / min_x, min_y, max_...
MultinomialRaysampler
[ "MIT", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultinomialRaysampler: """Samples a fixed number of points along rays which are regularly distributed in a batch of rectangular image grids. Points along each ray have uniformly-spaced z-coordinates between a predefined minimum and maximum depth. The raysampler first generates a 3D coordinate gri...
stack_v2_sparse_classes_75kplus_train_068472
35,564
permissive
[ { "docstring": "Args: min_x: The leftmost x-coordinate of each ray's source pixel's center. max_x: The rightmost x-coordinate of each ray's source pixel's center. min_y: The topmost y-coordinate of each ray's source pixel's center. max_y: The bottommost y-coordinate of each ray's source pixel's center. image_wi...
2
stack_v2_sparse_classes_30k_train_010917
Implement the Python class `MultinomialRaysampler` described below. Class description: Samples a fixed number of points along rays which are regularly distributed in a batch of rectangular image grids. Points along each ray have uniformly-spaced z-coordinates between a predefined minimum and maximum depth. The raysamp...
Implement the Python class `MultinomialRaysampler` described below. Class description: Samples a fixed number of points along rays which are regularly distributed in a batch of rectangular image grids. Points along each ray have uniformly-spaced z-coordinates between a predefined minimum and maximum depth. The raysamp...
af9f9be8786c69c68308013f68e527f3fddb88be
<|skeleton|> class MultinomialRaysampler: """Samples a fixed number of points along rays which are regularly distributed in a batch of rectangular image grids. Points along each ray have uniformly-spaced z-coordinates between a predefined minimum and maximum depth. The raysampler first generates a 3D coordinate gri...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MultinomialRaysampler: """Samples a fixed number of points along rays which are regularly distributed in a batch of rectangular image grids. Points along each ray have uniformly-spaced z-coordinates between a predefined minimum and maximum depth. The raysampler first generates a 3D coordinate grid of the foll...
the_stack_v2_python_sparse
pytorch3d/renderer/implicit/raysampling.py
angshine/pytorch3d
train
1
c8152e029f6c81d613270fe69b7cb3ad92907c4c
[ "if flag:\n GroupTree(self.driver).click_menu_by_name('Default', '创建同级')\n title_name = '创建同级'\nelse:\n GroupTree(self.driver).click_menu_by_name('Default', '创建下一级')\n title_name = '创建下一级'\nreturn title_name", "INPUT_TEXT = (By.XPATH, f'//span[contains(text(),\"{til_name}\")]/parent::div/following-sib...
<|body_start_0|> if flag: GroupTree(self.driver).click_menu_by_name('Default', '创建同级') title_name = '创建同级' else: GroupTree(self.driver).click_menu_by_name('Default', '创建下一级') title_name = '创建下一级' return title_name <|end_body_0|> <|body_start_1|> ...
UserPage
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserPage: def add_department_by_root_name(self, flag=True): """从根部门 - Default 下创建 同级 / 下一级 分组 :param flag: 判断是创建同级分组还是下一级分组 :return: 当前需要创建的分组类别""" <|body_0|> def create_department_group(self, group_name, til_name, confirm=True): """方法封装:用于创建 同级/下一级 分组 :param dep_nam...
stack_v2_sparse_classes_75kplus_train_068473
7,356
no_license
[ { "docstring": "从根部门 - Default 下创建 同级 / 下一级 分组 :param flag: 判断是创建同级分组还是下一级分组 :return: 当前需要创建的分组类别", "name": "add_department_by_root_name", "signature": "def add_department_by_root_name(self, flag=True)" }, { "docstring": "方法封装:用于创建 同级/下一级 分组 :param dep_name: 部分分组名称 :param til_name: dialog弹框中的标题 ...
2
stack_v2_sparse_classes_30k_train_005932
Implement the Python class `UserPage` described below. Class description: Implement the UserPage class. Method signatures and docstrings: - def add_department_by_root_name(self, flag=True): 从根部门 - Default 下创建 同级 / 下一级 分组 :param flag: 判断是创建同级分组还是下一级分组 :return: 当前需要创建的分组类别 - def create_department_group(self, group_name...
Implement the Python class `UserPage` described below. Class description: Implement the UserPage class. Method signatures and docstrings: - def add_department_by_root_name(self, flag=True): 从根部门 - Default 下创建 同级 / 下一级 分组 :param flag: 判断是创建同级分组还是下一级分组 :return: 当前需要创建的分组类别 - def create_department_group(self, group_name...
53ffcfc63447b4462c788d5620872fa54a9283a1
<|skeleton|> class UserPage: def add_department_by_root_name(self, flag=True): """从根部门 - Default 下创建 同级 / 下一级 分组 :param flag: 判断是创建同级分组还是下一级分组 :return: 当前需要创建的分组类别""" <|body_0|> def create_department_group(self, group_name, til_name, confirm=True): """方法封装:用于创建 同级/下一级 分组 :param dep_nam...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UserPage: def add_department_by_root_name(self, flag=True): """从根部门 - Default 下创建 同级 / 下一级 分组 :param flag: 判断是创建同级分组还是下一级分组 :return: 当前需要创建的分组类别""" if flag: GroupTree(self.driver).click_menu_by_name('Default', '创建同级') title_name = '创建同级' else: GroupT...
the_stack_v2_python_sparse
guard/pages/user_backup.py
qinwenzhu/selenium_pytest_actual
train
0
3e0cc80ab4346315fef500193508119b535343dd
[ "if not user_id:\n return\nsession_id = super().create_session(user_id)\nif not session_id:\n return\nuser_session = UserSession(user_id=user_id, session_id=session_id)\nuser_session.save()\nUserSession.save_to_file()\nreturn session_id", "if not session_id:\n return None\nUserSession.load_from_file()\nu...
<|body_start_0|> if not user_id: return session_id = super().create_session(user_id) if not session_id: return user_session = UserSession(user_id=user_id, session_id=session_id) user_session.save() UserSession.save_to_file() return session_...
SessionDBAuth Class
SessionDBAuth
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SessionDBAuth: """SessionDBAuth Class""" def create_session(self, user_id=None): """creates and stores new instance of UserSession and returns the Session ID""" <|body_0|> def user_id_for_session_id(self, session_id=None): """returns the User ID by requesting Use...
stack_v2_sparse_classes_75kplus_train_068474
1,904
no_license
[ { "docstring": "creates and stores new instance of UserSession and returns the Session ID", "name": "create_session", "signature": "def create_session(self, user_id=None)" }, { "docstring": "returns the User ID by requesting UserSession in the database based on session_id", "name": "user_id_...
3
null
Implement the Python class `SessionDBAuth` described below. Class description: SessionDBAuth Class Method signatures and docstrings: - def create_session(self, user_id=None): creates and stores new instance of UserSession and returns the Session ID - def user_id_for_session_id(self, session_id=None): returns the User...
Implement the Python class `SessionDBAuth` described below. Class description: SessionDBAuth Class Method signatures and docstrings: - def create_session(self, user_id=None): creates and stores new instance of UserSession and returns the Session ID - def user_id_for_session_id(self, session_id=None): returns the User...
a09732a4f270d3dbeaf6ff1eb46c7bc0b71eaf4a
<|skeleton|> class SessionDBAuth: """SessionDBAuth Class""" def create_session(self, user_id=None): """creates and stores new instance of UserSession and returns the Session ID""" <|body_0|> def user_id_for_session_id(self, session_id=None): """returns the User ID by requesting Use...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SessionDBAuth: """SessionDBAuth Class""" def create_session(self, user_id=None): """creates and stores new instance of UserSession and returns the Session ID""" if not user_id: return session_id = super().create_session(user_id) if not session_id: r...
the_stack_v2_python_sparse
0x07-Session_authentication/api/v1/auth/session_db_auth.py
I7RANK/holbertonschool-web_back_end
train
0
b38f7ab24d7864cec3427a547e05ed5d1a8e57bf
[ "super(Loss, self).__init__()\nself.model_name = model_name\nself.loss_name = loss_name\nself.loss_struct = []\nfor loss in self.loss_name.split('+'):\n weight, loss_type = loss.split('*')\n if loss_type == 'CrossEntropy':\n loss_function = nn.CrossEntropyLoss()\n elif loss_type == 'SmoothCrossEntro...
<|body_start_0|> super(Loss, self).__init__() self.model_name = model_name self.loss_name = loss_name self.loss_struct = [] for loss in self.loss_name.split('+'): weight, loss_type = loss.split('*') if loss_type == 'CrossEntropy': loss_func...
Loss
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Loss: def __init__(self, model_name, loss_name, num_classes): """:param model_name: 模型的名称;类型为str :param loss_name: 损失的名称;类型为str :param num_classes: 网络的参数""" <|body_0|> def forward(self, outputs, labels): """:param outputs: 网络的输出,具体维度和网络有关 :param labels: 数据的真实类标,具体维度和...
stack_v2_sparse_classes_75kplus_train_068475
5,001
permissive
[ { "docstring": ":param model_name: 模型的名称;类型为str :param loss_name: 损失的名称;类型为str :param num_classes: 网络的参数", "name": "__init__", "signature": "def __init__(self, model_name, loss_name, num_classes)" }, { "docstring": ":param outputs: 网络的输出,具体维度和网络有关 :param labels: 数据的真实类标,具体维度和网络有关 :return loss_su...
4
stack_v2_sparse_classes_30k_train_023882
Implement the Python class `Loss` described below. Class description: Implement the Loss class. Method signatures and docstrings: - def __init__(self, model_name, loss_name, num_classes): :param model_name: 模型的名称;类型为str :param loss_name: 损失的名称;类型为str :param num_classes: 网络的参数 - def forward(self, outputs, labels): :pa...
Implement the Python class `Loss` described below. Class description: Implement the Loss class. Method signatures and docstrings: - def __init__(self, model_name, loss_name, num_classes): :param model_name: 模型的名称;类型为str :param loss_name: 损失的名称;类型为str :param num_classes: 网络的参数 - def forward(self, outputs, labels): :pa...
d479b772f446033d32a124b80a1f9cd835988020
<|skeleton|> class Loss: def __init__(self, model_name, loss_name, num_classes): """:param model_name: 模型的名称;类型为str :param loss_name: 损失的名称;类型为str :param num_classes: 网络的参数""" <|body_0|> def forward(self, outputs, labels): """:param outputs: 网络的输出,具体维度和网络有关 :param labels: 数据的真实类标,具体维度和...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Loss: def __init__(self, model_name, loss_name, num_classes): """:param model_name: 模型的名称;类型为str :param loss_name: 损失的名称;类型为str :param num_classes: 网络的参数""" super(Loss, self).__init__() self.model_name = model_name self.loss_name = loss_name self.loss_struct = [] ...
the_stack_v2_python_sparse
losses/get_loss.py
XiangqianMa/AI-Competition-HuaWei
train
13
cc2ef5ad5295dd3d39293af95e4b38cf8afa8ebf
[ "ctrlpanel.ControlPanel.__init__(self, parent, overlayList, displayCtx, frame)\nif showHistory:\n self.__notebook = notebook.Notebook(self, style=wx.LEFT | wx.VERTICAL, border=0)\n subparent = self.__notebook\nelse:\n subparent = self\n self.__notebook = None\nself.__info = LocationInfoPanel(subparent, ...
<|body_start_0|> ctrlpanel.ControlPanel.__init__(self, parent, overlayList, displayCtx, frame) if showHistory: self.__notebook = notebook.Notebook(self, style=wx.LEFT | wx.VERTICAL, border=0) subparent = self.__notebook else: subparent = self self....
The ``LocationPanel`` is a panel which contains controls allowing the user to view and modify the :attr:`.DisplayContext.location` property. A ``LocationPanel`` is intended to be contained within a :class:`.CanvasPanel`, and looks something like this: .. image:: images/locationpanel.png :scale: 50% :align: center By de...
LocationPanel
[ "BSD-3-Clause", "CC-BY-3.0", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LocationPanel: """The ``LocationPanel`` is a panel which contains controls allowing the user to view and modify the :attr:`.DisplayContext.location` property. A ``LocationPanel`` is intended to be contained within a :class:`.CanvasPanel`, and looks something like this: .. image:: images/locationp...
stack_v2_sparse_classes_75kplus_train_068476
44,415
permissive
[ { "docstring": "Creat a ``LocationPanel``. :arg parent: The :mod:`wx` parent object, assumed to be a :class:`.CanvasPanel`. :arg overlayList: The :class:`.OverlayList` instance. :arg displayCtx: The :class:`.DisplayContext` instance. :arg frame: The :class:`.FSLeyesFrame` instance. :arg showHistory: Defaults to...
2
stack_v2_sparse_classes_30k_train_023534
Implement the Python class `LocationPanel` described below. Class description: The ``LocationPanel`` is a panel which contains controls allowing the user to view and modify the :attr:`.DisplayContext.location` property. A ``LocationPanel`` is intended to be contained within a :class:`.CanvasPanel`, and looks something...
Implement the Python class `LocationPanel` described below. Class description: The ``LocationPanel`` is a panel which contains controls allowing the user to view and modify the :attr:`.DisplayContext.location` property. A ``LocationPanel`` is intended to be contained within a :class:`.CanvasPanel`, and looks something...
46ccb4fe2b2346eb57576247f49714032b61307a
<|skeleton|> class LocationPanel: """The ``LocationPanel`` is a panel which contains controls allowing the user to view and modify the :attr:`.DisplayContext.location` property. A ``LocationPanel`` is intended to be contained within a :class:`.CanvasPanel`, and looks something like this: .. image:: images/locationp...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LocationPanel: """The ``LocationPanel`` is a panel which contains controls allowing the user to view and modify the :attr:`.DisplayContext.location` property. A ``LocationPanel`` is intended to be contained within a :class:`.CanvasPanel`, and looks something like this: .. image:: images/locationpanel.png :sca...
the_stack_v2_python_sparse
fsleyes/controls/locationpanel.py
sanjayankur31/fsleyes
train
1
a639412340c7c976da22e0ae2f1cb875ddf94df8
[ "r = Round.query.get(round_id)\nif r is not None:\n return r.json()\nabort(404, 'Unknown round_id')", "r = Round.query.get(round_id)\nif r is not None:\n if r.deletable():\n c = r.competition\n db.session.delete(r)\n db.session.commit()\n return c.json()\n abort(400, 'Cannot d...
<|body_start_0|> r = Round.query.get(round_id) if r is not None: return r.json() abort(404, 'Unknown round_id') <|end_body_0|> <|body_start_1|> r = Round.query.get(round_id) if r is not None: if r.deletable(): c = r.competition ...
RoundAPISpecific
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RoundAPISpecific: def get(self, round_id): """Fetch a specific Round""" <|body_0|> def delete(self, round_id): """Delete a specific Round""" <|body_1|> <|end_skeleton|> <|body_start_0|> r = Round.query.get(round_id) if r is not None: ...
stack_v2_sparse_classes_75kplus_train_068477
25,303
no_license
[ { "docstring": "Fetch a specific Round", "name": "get", "signature": "def get(self, round_id)" }, { "docstring": "Delete a specific Round", "name": "delete", "signature": "def delete(self, round_id)" } ]
2
stack_v2_sparse_classes_30k_test_002864
Implement the Python class `RoundAPISpecific` described below. Class description: Implement the RoundAPISpecific class. Method signatures and docstrings: - def get(self, round_id): Fetch a specific Round - def delete(self, round_id): Delete a specific Round
Implement the Python class `RoundAPISpecific` described below. Class description: Implement the RoundAPISpecific class. Method signatures and docstrings: - def get(self, round_id): Fetch a specific Round - def delete(self, round_id): Delete a specific Round <|skeleton|> class RoundAPISpecific: def get(self, rou...
079b109fd13683a31d1d632faa5ab72cf0e78ddf
<|skeleton|> class RoundAPISpecific: def get(self, round_id): """Fetch a specific Round""" <|body_0|> def delete(self, round_id): """Delete a specific Round""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RoundAPISpecific: def get(self, round_id): """Fetch a specific Round""" r = Round.query.get(round_id) if r is not None: return r.json() abort(404, 'Unknown round_id') def delete(self, round_id): """Delete a specific Round""" r = Round.query.get(...
the_stack_v2_python_sparse
backend/apis/round/apis.py
AlenAlic/DANCE
train
0
75a54f872b0ca5f5205d49de4190ba6a1fcc5623
[ "dummy = ListNode(-1)\ndummy.next = head\nnode = dummy\nfor __ in range(m - 1):\n node = node.next\nprev = node.next\ncurr = prev.next\nfor __ in range(n - m):\n next = curr.next\n curr.next = prev\n prev = curr\n curr = next\nnode.next.next = curr\nnode.next = prev\nreturn dummy.next", "if not hea...
<|body_start_0|> dummy = ListNode(-1) dummy.next = head node = dummy for __ in range(m - 1): node = node.next prev = node.next curr = prev.next for __ in range(n - m): next = curr.next curr.next = prev prev = curr ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def reverseBetween(self, head, m, n): """:type head: ListNode :type m: int :type n: int :rtype: ListNode""" <|body_0|> def reverseList(self, head): """:type head: ListNode :rtype: ListNode""" <|body_1|> <|end_skeleton|> <|body_start_0|> du...
stack_v2_sparse_classes_75kplus_train_068478
1,022
no_license
[ { "docstring": ":type head: ListNode :type m: int :type n: int :rtype: ListNode", "name": "reverseBetween", "signature": "def reverseBetween(self, head, m, n)" }, { "docstring": ":type head: ListNode :rtype: ListNode", "name": "reverseList", "signature": "def reverseList(self, head)" }...
2
stack_v2_sparse_classes_30k_train_014933
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseBetween(self, head, m, n): :type head: ListNode :type m: int :type n: int :rtype: ListNode - def reverseList(self, head): :type head: ListNode :rtype: ListNode
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseBetween(self, head, m, n): :type head: ListNode :type m: int :type n: int :rtype: ListNode - def reverseList(self, head): :type head: ListNode :rtype: ListNode <|skel...
acf2395f3b946054009d4543f2a13e83402323d3
<|skeleton|> class Solution: def reverseBetween(self, head, m, n): """:type head: ListNode :type m: int :type n: int :rtype: ListNode""" <|body_0|> def reverseList(self, head): """:type head: ListNode :rtype: ListNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def reverseBetween(self, head, m, n): """:type head: ListNode :type m: int :type n: int :rtype: ListNode""" dummy = ListNode(-1) dummy.next = head node = dummy for __ in range(m - 1): node = node.next prev = node.next curr = prev.ne...
the_stack_v2_python_sparse
Problem_92/learning_solution.py
chenshanghao/LeetCode_learning
train
0
3a3561f612bfba87a7ad1f869c49ab5ce8dee96a
[ "self.L = data.shape[0]\nself.method = method\nself.data = data\nself.data_list = [data[x, :].tolist() for x in range(data.shape[0])]\nnp.random.seed(random_state)\nself.levels = 11\nself.ccore = True\nself.density_threshold = 0.01\nself.amount_threshold = 3\nself.amount_intervals = 1\nreturn", "for p in keywords...
<|body_start_0|> self.L = data.shape[0] self.method = method self.data = data self.data_list = [data[x, :].tolist() for x in range(data.shape[0])] np.random.seed(random_state) self.levels = 11 self.ccore = True self.density_threshold = 0.01 self.am...
All grid based algorithms are implemened here.
GBased
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GBased: """All grid based algorithms are implemened here.""" def __init__(self, method, data, random_state=0): """Initialize all the parameters. method: Name of the algorithms (lower case joined by underscore) data: Data (2D Matrix) random_state: Random initial state""" <|bod...
stack_v2_sparse_classes_75kplus_train_068479
2,932
permissive
[ { "docstring": "Initialize all the parameters. method: Name of the algorithms (lower case joined by underscore) data: Data (2D Matrix) random_state: Random initial state", "name": "__init__", "signature": "def __init__(self, method, data, random_state=0)" }, { "docstring": "Setup the algorithms"...
4
stack_v2_sparse_classes_30k_train_002132
Implement the Python class `GBased` described below. Class description: All grid based algorithms are implemened here. Method signatures and docstrings: - def __init__(self, method, data, random_state=0): Initialize all the parameters. method: Name of the algorithms (lower case joined by underscore) data: Data (2D Ma...
Implement the Python class `GBased` described below. Class description: All grid based algorithms are implemened here. Method signatures and docstrings: - def __init__(self, method, data, random_state=0): Initialize all the parameters. method: Name of the algorithms (lower case joined by underscore) data: Data (2D Ma...
d7427ba609fb7f5e50c26f52364e5e9e118bbc31
<|skeleton|> class GBased: """All grid based algorithms are implemened here.""" def __init__(self, method, data, random_state=0): """Initialize all the parameters. method: Name of the algorithms (lower case joined by underscore) data: Data (2D Matrix) random_state: Random initial state""" <|bod...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GBased: """All grid based algorithms are implemened here.""" def __init__(self, method, data, random_state=0): """Initialize all the parameters. method: Name of the algorithms (lower case joined by underscore) data: Data (2D Matrix) random_state: Random initial state""" self.L = data.shap...
the_stack_v2_python_sparse
sd/algorithms/gridbased.py
shibaji7/SuperDARN-Clustering
train
1
43b1d55b4ef923dd4f1a788cb08bc2b9de3a2371
[ "if activity.creator == self.current_user:\n return True\nraise ApiException(403, '权限错误')", "activity = Activity.get_or_404(id=activity_id)\nserializer = ActivitySerializer(instance=activity)\nself.write(serializer.data)", "activity = Activity.get_or_404(id=activity_id)\nform = self.validated_arguments\nself...
<|body_start_0|> if activity.creator == self.current_user: return True raise ApiException(403, '权限错误') <|end_body_0|> <|body_start_1|> activity = Activity.get_or_404(id=activity_id) serializer = ActivitySerializer(instance=activity) self.write(serializer.data) <|end_...
活动 object handler
ActivityObjectHandler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ActivityObjectHandler: """活动 object handler""" def has_patch_permission(self, activity): """是否具有又该活动的权限 Args: activity: Returns: bool""" <|body_0|> def get(self, activity_id): """获取活动详情 Args: activity_id: 活动 ID""" <|body_1|> def patch(self, activity_...
stack_v2_sparse_classes_75kplus_train_068480
24,746
no_license
[ { "docstring": "是否具有又该活动的权限 Args: activity: Returns: bool", "name": "has_patch_permission", "signature": "def has_patch_permission(self, activity)" }, { "docstring": "获取活动详情 Args: activity_id: 活动 ID", "name": "get", "signature": "def get(self, activity_id)" }, { "docstring": "修改活...
3
null
Implement the Python class `ActivityObjectHandler` described below. Class description: 活动 object handler Method signatures and docstrings: - def has_patch_permission(self, activity): 是否具有又该活动的权限 Args: activity: Returns: bool - def get(self, activity_id): 获取活动详情 Args: activity_id: 活动 ID - def patch(self, activity_id):...
Implement the Python class `ActivityObjectHandler` described below. Class description: 活动 object handler Method signatures and docstrings: - def has_patch_permission(self, activity): 是否具有又该活动的权限 Args: activity: Returns: bool - def get(self, activity_id): 获取活动详情 Args: activity_id: 活动 ID - def patch(self, activity_id):...
49c31d9cce6ca451ff069697913b33fe55028a46
<|skeleton|> class ActivityObjectHandler: """活动 object handler""" def has_patch_permission(self, activity): """是否具有又该活动的权限 Args: activity: Returns: bool""" <|body_0|> def get(self, activity_id): """获取活动详情 Args: activity_id: 活动 ID""" <|body_1|> def patch(self, activity_...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ActivityObjectHandler: """活动 object handler""" def has_patch_permission(self, activity): """是否具有又该活动的权限 Args: activity: Returns: bool""" if activity.creator == self.current_user: return True raise ApiException(403, '权限错误') def get(self, activity_id): """获取...
the_stack_v2_python_sparse
PaiDuiGuanJia/yiyun/handlers/rest/activity.py
haoweiking/image_tesseract_private
train
0
1fff5836adaabc5434a045f4b7c8399d072072cc
[ "citations.sort()\ni = 0\nwhile i < len(citations) and citations[len(citations) - 1 - i] > i:\n i += 1\nreturn i", "n = len(citations)\npapers = [0] * (n + 1)\nfor c in citations:\n papers[min(n, c)] += 1\nk = n\ns = papers[n]\nwhile k > s:\n k -= 1\n s += papers[k]\nreturn k" ]
<|body_start_0|> citations.sort() i = 0 while i < len(citations) and citations[len(citations) - 1 - i] > i: i += 1 return i <|end_body_0|> <|body_start_1|> n = len(citations) papers = [0] * (n + 1) for c in citations: papers[min(n, c)] += ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def hIndex(self, citations): """offical solution: https://leetcode.com/problems/h-index/solution/ o(nlogn),o(1) :type citations: List[int] :rtype: int""" <|body_0|> def hIndex2(self, citations): """o(n) o(n) :param citations: :return:""" <|body_1|> ...
stack_v2_sparse_classes_75kplus_train_068481
1,600
no_license
[ { "docstring": "offical solution: https://leetcode.com/problems/h-index/solution/ o(nlogn),o(1) :type citations: List[int] :rtype: int", "name": "hIndex", "signature": "def hIndex(self, citations)" }, { "docstring": "o(n) o(n) :param citations: :return:", "name": "hIndex2", "signature": ...
2
stack_v2_sparse_classes_30k_train_010717
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def hIndex(self, citations): offical solution: https://leetcode.com/problems/h-index/solution/ o(nlogn),o(1) :type citations: List[int] :rtype: int - def hIndex2(self, citations)...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def hIndex(self, citations): offical solution: https://leetcode.com/problems/h-index/solution/ o(nlogn),o(1) :type citations: List[int] :rtype: int - def hIndex2(self, citations)...
2526f8c0dec7101123123740e146ee4081e979ee
<|skeleton|> class Solution: def hIndex(self, citations): """offical solution: https://leetcode.com/problems/h-index/solution/ o(nlogn),o(1) :type citations: List[int] :rtype: int""" <|body_0|> def hIndex2(self, citations): """o(n) o(n) :param citations: :return:""" <|body_1|> ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def hIndex(self, citations): """offical solution: https://leetcode.com/problems/h-index/solution/ o(nlogn),o(1) :type citations: List[int] :rtype: int""" citations.sort() i = 0 while i < len(citations) and citations[len(citations) - 1 - i] > i: i += 1 ...
the_stack_v2_python_sparse
274. H-Index.py
zhangpengGenedock/leetcode_python
train
1
0e2229b616d9f49e9080b271842340ed4c456852
[ "b = x.max(axis=1, keepdims=True)\ny = np.exp(x - b)\nout = y / y.sum(axis=1, keepdims=True)\nself.out = out\nreturn out", "x = self.out\nbatch, features = x.shape\nidxs = np.arange(features)\nshape = (batch, features, features)\ndiagonal = np.zeros(shape)\ndiagonal[:, idxs, idxs] = x\ndxdtx = diagonal - np.einsu...
<|body_start_0|> b = x.max(axis=1, keepdims=True) y = np.exp(x - b) out = y / y.sum(axis=1, keepdims=True) self.out = out return out <|end_body_0|> <|body_start_1|> x = self.out batch, features = x.shape idxs = np.arange(features) shape = (batch, ...
Softmax activation module.
SoftMaxModule
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SoftMaxModule: """Softmax activation module.""" def forward(self, x): """Forward pass. Args: x: input to the module Returns: out: output of the module""" <|body_0|> def backward(self, dout): """Backward pass. Args: dout: gradients of the previous modul Returns: d...
stack_v2_sparse_classes_75kplus_train_068482
5,181
no_license
[ { "docstring": "Forward pass. Args: x: input to the module Returns: out: output of the module", "name": "forward", "signature": "def forward(self, x)" }, { "docstring": "Backward pass. Args: dout: gradients of the previous modul Returns: dx: gradients with respect to the input of the module", ...
2
stack_v2_sparse_classes_30k_train_033405
Implement the Python class `SoftMaxModule` described below. Class description: Softmax activation module. Method signatures and docstrings: - def forward(self, x): Forward pass. Args: x: input to the module Returns: out: output of the module - def backward(self, dout): Backward pass. Args: dout: gradients of the prev...
Implement the Python class `SoftMaxModule` described below. Class description: Softmax activation module. Method signatures and docstrings: - def forward(self, x): Forward pass. Args: x: input to the module Returns: out: output of the module - def backward(self, dout): Backward pass. Args: dout: gradients of the prev...
b2cd0d67337b101f3e204e519625e1aaf3cea43b
<|skeleton|> class SoftMaxModule: """Softmax activation module.""" def forward(self, x): """Forward pass. Args: x: input to the module Returns: out: output of the module""" <|body_0|> def backward(self, dout): """Backward pass. Args: dout: gradients of the previous modul Returns: d...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SoftMaxModule: """Softmax activation module.""" def forward(self, x): """Forward pass. Args: x: input to the module Returns: out: output of the module""" b = x.max(axis=1, keepdims=True) y = np.exp(x - b) out = y / y.sum(axis=1, keepdims=True) self.out = out ...
the_stack_v2_python_sparse
assignment_1/code/modules.py
Ivan-Yovchev/uvadlc_practicals_2019
train
0
0e94a289e58b0a482b98a3e90e58a74ef970597d
[ "result = self.plugin.weighted_mean(self.cube, self.weights1d)\nexpected = np.full((2, 2), 1.5)\nself.assertIsInstance(result, iris.cube.Cube)\nself.assertArrayAlmostEqual(result.data, expected)", "result = self.plugin.weighted_mean(self.cube, self.weights3d)\nexpected = np.array([[2.7, 2.1], [2.4, 1.8]])\nself.a...
<|body_start_0|> result = self.plugin.weighted_mean(self.cube, self.weights1d) expected = np.full((2, 2), 1.5) self.assertIsInstance(result, iris.cube.Cube) self.assertArrayAlmostEqual(result.data, expected) <|end_body_0|> <|body_start_1|> result = self.plugin.weighted_mean(self...
Test the weighted_mean function.
Test_weighted_mean
[ "BSD-3-Clause", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Test_weighted_mean: """Test the weighted_mean function.""" def test_with_weights(self): """Test function when a data cube and a weights cube are provided.""" <|body_0|> def test_with_spatially_varying_weights(self): """Test function when a data cube and a multi d...
stack_v2_sparse_classes_75kplus_train_068483
23,864
permissive
[ { "docstring": "Test function when a data cube and a weights cube are provided.", "name": "test_with_weights", "signature": "def test_with_weights(self)" }, { "docstring": "Test function when a data cube and a multi dimensional weights cube are provided. This tests spatially varying weights, whe...
4
stack_v2_sparse_classes_30k_train_046590
Implement the Python class `Test_weighted_mean` described below. Class description: Test the weighted_mean function. Method signatures and docstrings: - def test_with_weights(self): Test function when a data cube and a weights cube are provided. - def test_with_spatially_varying_weights(self): Test function when a da...
Implement the Python class `Test_weighted_mean` described below. Class description: Test the weighted_mean function. Method signatures and docstrings: - def test_with_weights(self): Test function when a data cube and a weights cube are provided. - def test_with_spatially_varying_weights(self): Test function when a da...
cd2c9019944345df1e703bf8f625db537ad9f559
<|skeleton|> class Test_weighted_mean: """Test the weighted_mean function.""" def test_with_weights(self): """Test function when a data cube and a weights cube are provided.""" <|body_0|> def test_with_spatially_varying_weights(self): """Test function when a data cube and a multi d...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Test_weighted_mean: """Test the weighted_mean function.""" def test_with_weights(self): """Test function when a data cube and a weights cube are provided.""" result = self.plugin.weighted_mean(self.cube, self.weights1d) expected = np.full((2, 2), 1.5) self.assertIsInstance...
the_stack_v2_python_sparse
improver_tests/blending/weighted_blend/test_WeightedBlendAcrossWholeDimension.py
metoppv/improver
train
101
f7c0618e8b1af213f6594ad1a6496f5de699e589
[ "height_points = np.array([5.0, 10.0, 20.0])\ncube = _set_up_height_cube(height_points)\nself.plugin_positive = Integration('height', positive_integration=True)\nself.plugin_positive.input_cube = cube.copy()\nself.plugin_negative = Integration('height')\nself.plugin_negative.input_cube = cube.copy()", "result = s...
<|body_start_0|> height_points = np.array([5.0, 10.0, 20.0]) cube = _set_up_height_cube(height_points) self.plugin_positive = Integration('height', positive_integration=True) self.plugin_positive.input_cube = cube.copy() self.plugin_negative = Integration('height') self.p...
Test the prepare_for_integration method.
Test_prepare_for_integration
[ "BSD-3-Clause", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Test_prepare_for_integration: """Test the prepare_for_integration method.""" def setUp(self): """Set up the cube.""" <|body_0|> def test_basic(self): """Test that the type of the returned value is as expected and the expected number of items are returned.""" ...
stack_v2_sparse_classes_75kplus_train_068484
25,011
permissive
[ { "docstring": "Set up the cube.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Test that the type of the returned value is as expected and the expected number of items are returned.", "name": "test_basic", "signature": "def test_basic(self)" }, { "docstring...
4
stack_v2_sparse_classes_30k_train_033211
Implement the Python class `Test_prepare_for_integration` described below. Class description: Test the prepare_for_integration method. Method signatures and docstrings: - def setUp(self): Set up the cube. - def test_basic(self): Test that the type of the returned value is as expected and the expected number of items ...
Implement the Python class `Test_prepare_for_integration` described below. Class description: Test the prepare_for_integration method. Method signatures and docstrings: - def setUp(self): Set up the cube. - def test_basic(self): Test that the type of the returned value is as expected and the expected number of items ...
cd2c9019944345df1e703bf8f625db537ad9f559
<|skeleton|> class Test_prepare_for_integration: """Test the prepare_for_integration method.""" def setUp(self): """Set up the cube.""" <|body_0|> def test_basic(self): """Test that the type of the returned value is as expected and the expected number of items are returned.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Test_prepare_for_integration: """Test the prepare_for_integration method.""" def setUp(self): """Set up the cube.""" height_points = np.array([5.0, 10.0, 20.0]) cube = _set_up_height_cube(height_points) self.plugin_positive = Integration('height', positive_integration=True...
the_stack_v2_python_sparse
improver_tests/utilities/test_mathematical_operations.py
metoppv/improver
train
101
0bd24d04ee281b3ab80a925e0270c4aa7750a7ba
[ "if user_id:\n return f'{console_url}/api/3/users/{user_id}'\nelse:\n return f'{console_url}/api/3/users'", "if asset_group_id:\n return f'{console_url}/api/3/users/{user_id}/asset_groups/{asset_group_id}'\nelse:\n return f'{console_url}/api/3/users/{user_id}/asset_groups'", "if site_id:\n return...
<|body_start_0|> if user_id: return f'{console_url}/api/3/users/{user_id}' else: return f'{console_url}/api/3/users' <|end_body_0|> <|body_start_1|> if asset_group_id: return f'{console_url}/api/3/users/{user_id}/asset_groups/{asset_group_id}' else: ...
User
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class User: def users(console_url, user_id=None): """Interacts with users endpoint :param console_url: URL to the InsightVM console :param user_id: ID of the user with which to interact :return: pre-populated /api/3/users endpoint""" <|body_0|> def user_asset_groups(console_url, u...
stack_v2_sparse_classes_75kplus_train_068485
22,639
permissive
[ { "docstring": "Interacts with users endpoint :param console_url: URL to the InsightVM console :param user_id: ID of the user with which to interact :return: pre-populated /api/3/users endpoint", "name": "users", "signature": "def users(console_url, user_id=None)" }, { "docstring": "Interacts wi...
3
null
Implement the Python class `User` described below. Class description: Implement the User class. Method signatures and docstrings: - def users(console_url, user_id=None): Interacts with users endpoint :param console_url: URL to the InsightVM console :param user_id: ID of the user with which to interact :return: pre-po...
Implement the Python class `User` described below. Class description: Implement the User class. Method signatures and docstrings: - def users(console_url, user_id=None): Interacts with users endpoint :param console_url: URL to the InsightVM console :param user_id: ID of the user with which to interact :return: pre-po...
718d15ca36c57231bb89df0aebc53d0210db400c
<|skeleton|> class User: def users(console_url, user_id=None): """Interacts with users endpoint :param console_url: URL to the InsightVM console :param user_id: ID of the user with which to interact :return: pre-populated /api/3/users endpoint""" <|body_0|> def user_asset_groups(console_url, u...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class User: def users(console_url, user_id=None): """Interacts with users endpoint :param console_url: URL to the InsightVM console :param user_id: ID of the user with which to interact :return: pre-populated /api/3/users endpoint""" if user_id: return f'{console_url}/api/3/users/{user_i...
the_stack_v2_python_sparse
plugins/rapid7_insightvm/komand_rapid7_insightvm/util/endpoints.py
rapid7/insightconnect-plugins
train
61
28ebc1f0afe528a5f6321a0b2496465dda18e7ff
[ "if post.get('Body', False) and post.get('From', False):\n message_type = 'sms'\n if 'whatsapp' in post.get('From'):\n message_type = 'whatsapp'\n params_sms_id = {'body': post.get('Body'), 'number': helpers.sanitize_mobile(post.get('From')), 'message_type': message_type, 'message_id': post.get('Sms...
<|body_start_0|> if post.get('Body', False) and post.get('From', False): message_type = 'sms' if 'whatsapp' in post.get('From'): message_type = 'whatsapp' params_sms_id = {'body': post.get('Body'), 'number': helpers.sanitize_mobile(post.get('From')), 'message_...
TwilioWebhooks
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TwilioWebhooks: def twilio_input_message(self, **post): """Webhoock para receber mensagens do whatsapp sandbox https://www.twilio.com/console/sms/whatsapp/sandbox POST from Twilio: { 'SmsMessageSid': 'SMe8f1366da573cdc95485b7d1143ff1ef', 'NumMedia': '0', 'SmsSid': 'SMe8f1366da573cdc95485...
stack_v2_sparse_classes_75kplus_train_068486
3,535
no_license
[ { "docstring": "Webhoock para receber mensagens do whatsapp sandbox https://www.twilio.com/console/sms/whatsapp/sandbox POST from Twilio: { 'SmsMessageSid': 'SMe8f1366da573cdc95485b7d1143ff1ef', 'NumMedia': '0', 'SmsSid': 'SMe8f1366da573cdc95485b7d1143ff1ef', 'SmsStatus': 'received', 'Body': 'Corpo da mensagem'...
2
stack_v2_sparse_classes_30k_train_012384
Implement the Python class `TwilioWebhooks` described below. Class description: Implement the TwilioWebhooks class. Method signatures and docstrings: - def twilio_input_message(self, **post): Webhoock para receber mensagens do whatsapp sandbox https://www.twilio.com/console/sms/whatsapp/sandbox POST from Twilio: { 'S...
Implement the Python class `TwilioWebhooks` described below. Class description: Implement the TwilioWebhooks class. Method signatures and docstrings: - def twilio_input_message(self, **post): Webhoock para receber mensagens do whatsapp sandbox https://www.twilio.com/console/sms/whatsapp/sandbox POST from Twilio: { 'S...
68019d063765508e8de00466f2dd5909a9d0b304
<|skeleton|> class TwilioWebhooks: def twilio_input_message(self, **post): """Webhoock para receber mensagens do whatsapp sandbox https://www.twilio.com/console/sms/whatsapp/sandbox POST from Twilio: { 'SmsMessageSid': 'SMe8f1366da573cdc95485b7d1143ff1ef', 'NumMedia': '0', 'SmsSid': 'SMe8f1366da573cdc95485...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TwilioWebhooks: def twilio_input_message(self, **post): """Webhoock para receber mensagens do whatsapp sandbox https://www.twilio.com/console/sms/whatsapp/sandbox POST from Twilio: { 'SmsMessageSid': 'SMe8f1366da573cdc95485b7d1143ff1ef', 'NumMedia': '0', 'SmsSid': 'SMe8f1366da573cdc95485b7d1143ff1ef',...
the_stack_v2_python_sparse
sms_twilio/controllers/sms_api_input.py
marcelsavegnago/social
train
0
271522da66065e77ba710d952907f78a75fc3536
[ "if not nums:\n return 0\ncum_sum = [0]\nfor num in nums:\n cum_sum.append(cum_sum[-1] + num)\nres = 0\nfor i in range(len(cum_sum) - 1):\n for j in range(i + 1, len(cum_sum)):\n if cum_sum[j] - cum_sum[i] == k:\n res += 1\nreturn res", "if not nums:\n return 0\ncounts_map = {0: 1}\n...
<|body_start_0|> if not nums: return 0 cum_sum = [0] for num in nums: cum_sum.append(cum_sum[-1] + num) res = 0 for i in range(len(cum_sum) - 1): for j in range(i + 1, len(cum_sum)): if cum_sum[j] - cum_sum[i] == k: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def subarray_sum(self, nums: List[int], k: int) -> int: """Time complexity O(n**2). Although this is faster than O(n**3) solution (brutal force without cumulative array), it is still not fast enough to pass the test.""" <|body_0|> def subarray_sum_hash_map(self, nu...
stack_v2_sparse_classes_75kplus_train_068487
1,152
no_license
[ { "docstring": "Time complexity O(n**2). Although this is faster than O(n**3) solution (brutal force without cumulative array), it is still not fast enough to pass the test.", "name": "subarray_sum", "signature": "def subarray_sum(self, nums: List[int], k: int) -> int" }, { "docstring": "O(n) so...
2
stack_v2_sparse_classes_30k_train_054135
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def subarray_sum(self, nums: List[int], k: int) -> int: Time complexity O(n**2). Although this is faster than O(n**3) solution (brutal force without cumulative array), it is stil...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def subarray_sum(self, nums: List[int], k: int) -> int: Time complexity O(n**2). Although this is faster than O(n**3) solution (brutal force without cumulative array), it is stil...
5625e6396b746255f3343253c75447ead95879c7
<|skeleton|> class Solution: def subarray_sum(self, nums: List[int], k: int) -> int: """Time complexity O(n**2). Although this is faster than O(n**3) solution (brutal force without cumulative array), it is still not fast enough to pass the test.""" <|body_0|> def subarray_sum_hash_map(self, nu...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def subarray_sum(self, nums: List[int], k: int) -> int: """Time complexity O(n**2). Although this is faster than O(n**3) solution (brutal force without cumulative array), it is still not fast enough to pass the test.""" if not nums: return 0 cum_sum = [0] ...
the_stack_v2_python_sparse
560_subarray_sum_equals_k/solution.py
FluffyFu/Leetcode
train
0
292f5a957a9579b79672c2bc95ae1e6ddd34a533
[ "self.x = length\nself.y = width\nself.z = height\nself.GraphList = []", "graph = nx.grid_graph([self.x, self.y, self.z])\nfor edge in self.GraphList:\n graph.add_edge(edge[0], edge[1])\nif graph_layout == 'spring':\n graph_pos = nx.spring_layout(graph)\nelif graph_layout == 'spectral':\n graph_pos = nx....
<|body_start_0|> self.x = length self.y = width self.z = height self.GraphList = [] <|end_body_0|> <|body_start_1|> graph = nx.grid_graph([self.x, self.y, self.z]) for edge in self.GraphList: graph.add_edge(edge[0], edge[1]) if graph_layout == 'spring...
LatticeGraphics
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LatticeGraphics: def __init__(self, length, width, height): """Creates a CayleyTree object in order to create an image of the graph.""" <|body_0|> def drawLattice(self, labels=None, graph_layout='spring', node_size=1000, node_color='blue', node_alpha=0.3, node_text_size=12, ...
stack_v2_sparse_classes_75kplus_train_068488
3,101
permissive
[ { "docstring": "Creates a CayleyTree object in order to create an image of the graph.", "name": "__init__", "signature": "def __init__(self, length, width, height)" }, { "docstring": "Method that physically draws the lattice graph based on length, width, and height.", "name": "drawLattice", ...
2
stack_v2_sparse_classes_30k_val_000930
Implement the Python class `LatticeGraphics` described below. Class description: Implement the LatticeGraphics class. Method signatures and docstrings: - def __init__(self, length, width, height): Creates a CayleyTree object in order to create an image of the graph. - def drawLattice(self, labels=None, graph_layout='...
Implement the Python class `LatticeGraphics` described below. Class description: Implement the LatticeGraphics class. Method signatures and docstrings: - def __init__(self, length, width, height): Creates a CayleyTree object in order to create an image of the graph. - def drawLattice(self, labels=None, graph_layout='...
dbd60c6fa04f00aa995094acc76ef0d06a0346b1
<|skeleton|> class LatticeGraphics: def __init__(self, length, width, height): """Creates a CayleyTree object in order to create an image of the graph.""" <|body_0|> def drawLattice(self, labels=None, graph_layout='spring', node_size=1000, node_color='blue', node_alpha=0.3, node_text_size=12, ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LatticeGraphics: def __init__(self, length, width, height): """Creates a CayleyTree object in order to create an image of the graph.""" self.x = length self.y = width self.z = height self.GraphList = [] def drawLattice(self, labels=None, graph_layout='spring', node...
the_stack_v2_python_sparse
graphics/latticegraphics.py
noe98/Cayley
train
5
1fb39bc8c5b7e308817e17e1e760f2286a5a6b8f
[ "length = len(heights)\nstack = []\nrect_map = collections.OrderedDict()\nfor i, item in enumerate(heights):\n stack = [inum for inum in stack if inum[1] < item]\n rect_map[i, item] = {}\n if not stack:\n rect_map[i, item]['left'] = -1\n else:\n rect_map[i, item]['left'] = stack[-1][0]\n ...
<|body_start_0|> length = len(heights) stack = [] rect_map = collections.OrderedDict() for i, item in enumerate(heights): stack = [inum for inum in stack if inum[1] < item] rect_map[i, item] = {} if not stack: rect_map[i, item]['left'] ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def largestRectangleArea(self, heights): """*** TLE *** for each height, find the closest height that is less than it on both left and right side. A dictionary to map current height with the index of left closest smaller height and right closest smaller height. map[cur_height] ...
stack_v2_sparse_classes_75kplus_train_068489
2,818
no_license
[ { "docstring": "*** TLE *** for each height, find the closest height that is less than it on both left and right side. A dictionary to map current height with the index of left closest smaller height and right closest smaller height. map[cur_height] = {\"left\":i, \"right\":j} use a stack to update the store he...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def largestRectangleArea(self, heights): *** TLE *** for each height, find the closest height that is less than it on both left and right side. A dictionary to map current height...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def largestRectangleArea(self, heights): *** TLE *** for each height, find the closest height that is less than it on both left and right side. A dictionary to map current height...
49d0831387227e69ae4067c1f5b7e828976377b4
<|skeleton|> class Solution: def largestRectangleArea(self, heights): """*** TLE *** for each height, find the closest height that is less than it on both left and right side. A dictionary to map current height with the index of left closest smaller height and right closest smaller height. map[cur_height] ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def largestRectangleArea(self, heights): """*** TLE *** for each height, find the closest height that is less than it on both left and right side. A dictionary to map current height with the index of left closest smaller height and right closest smaller height. map[cur_height] = {"left":i, "...
the_stack_v2_python_sparse
DataStructure/84_largest_rectangle_in_histogram.py
libinjungle/LeetCode_Python
train
0
0bb88da0966acdc0d54d431f09621cc8ae9bfde6
[ "assert stage in ('normalizer', 'converter', 'keywords'), \"stage should be 'normalizer'/'converter'/'keywords'\"\nfrom Utilities.movoto.logger import MLogger\nself._failures_logger = MLogger().getLogger('log_null_values_{stage}_{mls_id}'.format(stage=stage, mls_id=mls_id), mls_id)\nreturn self._failures_logger", ...
<|body_start_0|> assert stage in ('normalizer', 'converter', 'keywords'), "stage should be 'normalizer'/'converter'/'keywords'" from Utilities.movoto.logger import MLogger self._failures_logger = MLogger().getLogger('log_null_values_{stage}_{mls_id}'.format(stage=stage, mls_id=mls_id), mls_id) ...
MLS mapping failure logs Accroding to DATA-1531 Usage: :: opt.setup_failure_logger(stage, mls_id) opt.record_failure_log(mls_sysid, mls_number, column_name, column_value, exc_info) # will record log to ``log_null_values_{stage}_{mls_id}.log``
ConvertFailureLog
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConvertFailureLog: """MLS mapping failure logs Accroding to DATA-1531 Usage: :: opt.setup_failure_logger(stage, mls_id) opt.record_failure_log(mls_sysid, mls_number, column_name, column_value, exc_info) # will record log to ``log_null_values_{stage}_{mls_id}.log``""" def setup_failure_logger...
stack_v2_sparse_classes_75kplus_train_068490
3,064
permissive
[ { "docstring": "Setup failures logger Args: stage (str): normalizer/converter/keywords mls_id (int): Returns: logger: the failure logger", "name": "setup_failure_logger", "signature": "def setup_failure_logger(self, stage, mls_id)" }, { "docstring": "Format arguments to log message Args: mls_sys...
3
stack_v2_sparse_classes_30k_train_014107
Implement the Python class `ConvertFailureLog` described below. Class description: MLS mapping failure logs Accroding to DATA-1531 Usage: :: opt.setup_failure_logger(stage, mls_id) opt.record_failure_log(mls_sysid, mls_number, column_name, column_value, exc_info) # will record log to ``log_null_values_{stage}_{mls_id}...
Implement the Python class `ConvertFailureLog` described below. Class description: MLS mapping failure logs Accroding to DATA-1531 Usage: :: opt.setup_failure_logger(stage, mls_id) opt.record_failure_log(mls_sysid, mls_number, column_name, column_value, exc_info) # will record log to ``log_null_values_{stage}_{mls_id}...
9d0ef176629f18a4fd52bc2ef25e019f7be4317c
<|skeleton|> class ConvertFailureLog: """MLS mapping failure logs Accroding to DATA-1531 Usage: :: opt.setup_failure_logger(stage, mls_id) opt.record_failure_log(mls_sysid, mls_number, column_name, column_value, exc_info) # will record log to ``log_null_values_{stage}_{mls_id}.log``""" def setup_failure_logger...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ConvertFailureLog: """MLS mapping failure logs Accroding to DATA-1531 Usage: :: opt.setup_failure_logger(stage, mls_id) opt.record_failure_log(mls_sysid, mls_number, column_name, column_value, exc_info) # will record log to ``log_null_values_{stage}_{mls_id}.log``""" def setup_failure_logger(self, stage,...
the_stack_v2_python_sparse
kipp/options/mlogger.py
gladuo/kipp
train
0
001912067a0907aa4f306a28c4582b3ceb3ad172
[ "self.type = type\nself.concat_properties = concat_properties\nself.is_concat = bool(concat_properties)\nself.is_static = is_static\nself.is_state = is_state\nself.is_identity = is_identity", "tests = [self.is_static, self.is_state, self.is_identity]\npositives = [t for t in tests if t]\nreturn len(positives) == ...
<|body_start_0|> self.type = type self.concat_properties = concat_properties self.is_concat = bool(concat_properties) self.is_static = is_static self.is_state = is_state self.is_identity = is_identity <|end_body_0|> <|body_start_1|> tests = [self.is_static, self....
Convenience class to keep track of properties in a model.
VersionedProperty
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VersionedProperty: """Convenience class to keep track of properties in a model.""" def __init__(self, type=str, concat_properties=None, is_static=False, is_state=False, is_identity=False): """Init the property. A property should be only one of is_static, is_state, or is_identity :par...
stack_v2_sparse_classes_75kplus_train_068491
18,798
permissive
[ { "docstring": "Init the property. A property should be only one of is_static, is_state, or is_identity :param type: Expected type of value for this property. :type type: Class :param concat_fields: List of fields that this property is composed of :type concast_fields: list :param is_static: Is this property a ...
2
null
Implement the Python class `VersionedProperty` described below. Class description: Convenience class to keep track of properties in a model. Method signatures and docstrings: - def __init__(self, type=str, concat_properties=None, is_static=False, is_state=False, is_identity=False): Init the property. A property shoul...
Implement the Python class `VersionedProperty` described below. Class description: Convenience class to keep track of properties in a model. Method signatures and docstrings: - def __init__(self, type=str, concat_properties=None, is_static=False, is_state=False, is_identity=False): Init the property. A property shoul...
aaab76706c8268d3ff3e87c275baee9dd4714314
<|skeleton|> class VersionedProperty: """Convenience class to keep track of properties in a model.""" def __init__(self, type=str, concat_properties=None, is_static=False, is_state=False, is_identity=False): """Init the property. A property should be only one of is_static, is_state, or is_identity :par...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class VersionedProperty: """Convenience class to keep track of properties in a model.""" def __init__(self, type=str, concat_properties=None, is_static=False, is_state=False, is_identity=False): """Init the property. A property should be only one of is_static, is_state, or is_identity :param type: Expe...
the_stack_v2_python_sparse
cloud_snitch/models/base.py
rcbops/FleetDeploymentReporting
train
1
abe8d3058ece639f5e75f8f22e0649d94d1399a5
[ "import numpy as np\nself.positions = np.array(positions)\nself.position_value = 1000 / self.positions\nself.num_trials = num_trials", "import numpy as np\np = 0.51\ncumu_ret = []\nfor i, position in enumerate(self.positions):\n position_return = 2 * self.position_value[i] * np.random.binomial(position, p)\n ...
<|body_start_0|> import numpy as np self.positions = np.array(positions) self.position_value = 1000 / self.positions self.num_trials = num_trials <|end_body_0|> <|body_start_1|> import numpy as np p = 0.51 cumu_ret = [] for i, position in enumerate(self.p...
Class represents a string of $1000 investments and their daily returns
investment
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class investment: """Class represents a string of $1000 investments and their daily returns""" def __init__(self, positions=[1], num_trials=1): """Constructor for interval class inputs: positions: A list of integers of number of shares to buy. Each entry must be a factor of 1000. num_trial...
stack_v2_sparse_classes_75kplus_train_068492
1,980
no_license
[ { "docstring": "Constructor for interval class inputs: positions: A list of integers of number of shares to buy. Each entry must be a factor of 1000. num_trials: An integer representing the number of days to simulate investment", "name": "__init__", "signature": "def __init__(self, positions=[1], num_tr...
3
stack_v2_sparse_classes_30k_train_005910
Implement the Python class `investment` described below. Class description: Class represents a string of $1000 investments and their daily returns Method signatures and docstrings: - def __init__(self, positions=[1], num_trials=1): Constructor for interval class inputs: positions: A list of integers of number of shar...
Implement the Python class `investment` described below. Class description: Class represents a string of $1000 investments and their daily returns Method signatures and docstrings: - def __init__(self, positions=[1], num_trials=1): Constructor for interval class inputs: positions: A list of integers of number of shar...
5b904060e8bced7f91547ad7f7819773a7450a1e
<|skeleton|> class investment: """Class represents a string of $1000 investments and their daily returns""" def __init__(self, positions=[1], num_trials=1): """Constructor for interval class inputs: positions: A list of integers of number of shares to buy. Each entry must be a factor of 1000. num_trial...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class investment: """Class represents a string of $1000 investments and their daily returns""" def __init__(self, positions=[1], num_trials=1): """Constructor for interval class inputs: positions: A list of integers of number of shares to buy. Each entry must be a factor of 1000. num_trials: An integer...
the_stack_v2_python_sparse
jt2276/investment_package/investment.py
ds-ga-1007/assignment8
train
1
128ef5d80c9748b0e88f2b4bdd1bfcbfefcefd1f
[ "self.db = SqliteDB()\nself.code_list = []\nself.data = self.get_data()\nself.data_for_table = {}", "with self.db as cur:\n cur.execute('SELECT * FROM salaries')\nreturn cur.fetchall()", "for string in self.data:\n if string[1] not in self.code_list:\n self.code_list.append(string[1])\nfor i in sel...
<|body_start_0|> self.db = SqliteDB() self.code_list = [] self.data = self.get_data() self.data_for_table = {} <|end_body_0|> <|body_start_1|> with self.db as cur: cur.execute('SELECT * FROM salaries') return cur.fetchall() <|end_body_1|> <|body_start_2|> ...
Класс, рассчитывающий общую численность персонала по категориям
PersonelSummary
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PersonelSummary: """Класс, рассчитывающий общую численность персонала по категориям""" def __init__(self) -> None: """Метод инициализации класса""" <|body_0|> def get_data(self) -> tuple: """Метод, получающий из БД данные о всех записях :return: self.cur.fetchall...
stack_v2_sparse_classes_75kplus_train_068493
3,002
no_license
[ { "docstring": "Метод инициализации класса", "name": "__init__", "signature": "def __init__(self) -> None" }, { "docstring": "Метод, получающий из БД данные о всех записях :return: self.cur.fetchall() - список с результами запроса", "name": "get_data", "signature": "def get_data(self) ->...
4
stack_v2_sparse_classes_30k_train_010031
Implement the Python class `PersonelSummary` described below. Class description: Класс, рассчитывающий общую численность персонала по категориям Method signatures and docstrings: - def __init__(self) -> None: Метод инициализации класса - def get_data(self) -> tuple: Метод, получающий из БД данные о всех записях :retu...
Implement the Python class `PersonelSummary` described below. Class description: Класс, рассчитывающий общую численность персонала по категориям Method signatures and docstrings: - def __init__(self) -> None: Метод инициализации класса - def get_data(self) -> tuple: Метод, получающий из БД данные о всех записях :retu...
f63d5db6780cc02cb064e70d2076eba94cb45785
<|skeleton|> class PersonelSummary: """Класс, рассчитывающий общую численность персонала по категориям""" def __init__(self) -> None: """Метод инициализации класса""" <|body_0|> def get_data(self) -> tuple: """Метод, получающий из БД данные о всех записях :return: self.cur.fetchall...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PersonelSummary: """Класс, рассчитывающий общую численность персонала по категориям""" def __init__(self) -> None: """Метод инициализации класса""" self.db = SqliteDB() self.code_list = [] self.data = self.get_data() self.data_for_table = {} def get_data(self)...
the_stack_v2_python_sparse
counting/personel_summary.py
Pheeneek/Salary
train
0
8dc18a314224c615306e6e0f8b3b93d9062d961f
[ "client = LdapClient({'ldap_server_vendor': 'OpenLDAP', 'host': 'server_ip', 'connection_type': 'SSL', 'ssl_version': ssl_version})\nssl_version_value = client._get_ssl_version()\nassert ssl_version_value == expected_ssl_version", "client = LdapClient({'ldap_server_vendor': 'OpenLDAP', 'host': 'server_ip', 'conne...
<|body_start_0|> client = LdapClient({'ldap_server_vendor': 'OpenLDAP', 'host': 'server_ip', 'connection_type': 'SSL', 'ssl_version': ssl_version}) ssl_version_value = client._get_ssl_version() assert ssl_version_value == expected_ssl_version <|end_body_0|> <|body_start_1|> client = Lda...
Contains unit tests for general functions that deal with both OpenLDAP and Active Directory servers.
TestLDAPAuthentication
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestLDAPAuthentication: """Contains unit tests for general functions that deal with both OpenLDAP and Active Directory servers.""" def test_get_ssl_version(self, ssl_version, expected_ssl_version): """Given: - An ssl protocol version: 1. TLS 2. TLSv1 3. TLSv1_1 4. TLSv1_2 5. TLS_CLIE...
stack_v2_sparse_classes_75kplus_train_068494
12,670
permissive
[ { "docstring": "Given: - An ssl protocol version: 1. TLS 2. TLSv1 3. TLSv1_1 4. TLSv1_2 5. TLS_CLIENT 6. None 7. 'None' When: - Running the '_get_ssl_version()' function. Then: - Verify that the returned ssl version value is as expected: 1. TLS - 2 2. TLSv1 - 3 3. TLSv1_1 - 4 4. TLSv1_2 - 5 5. TLS_CLIENT - 16 6...
3
stack_v2_sparse_classes_30k_train_006255
Implement the Python class `TestLDAPAuthentication` described below. Class description: Contains unit tests for general functions that deal with both OpenLDAP and Active Directory servers. Method signatures and docstrings: - def test_get_ssl_version(self, ssl_version, expected_ssl_version): Given: - An ssl protocol v...
Implement the Python class `TestLDAPAuthentication` described below. Class description: Contains unit tests for general functions that deal with both OpenLDAP and Active Directory servers. Method signatures and docstrings: - def test_get_ssl_version(self, ssl_version, expected_ssl_version): Given: - An ssl protocol v...
890def5a0e0ae8d6eaa538148249ddbc851dbb6b
<|skeleton|> class TestLDAPAuthentication: """Contains unit tests for general functions that deal with both OpenLDAP and Active Directory servers.""" def test_get_ssl_version(self, ssl_version, expected_ssl_version): """Given: - An ssl protocol version: 1. TLS 2. TLSv1 3. TLSv1_1 4. TLSv1_2 5. TLS_CLIE...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestLDAPAuthentication: """Contains unit tests for general functions that deal with both OpenLDAP and Active Directory servers.""" def test_get_ssl_version(self, ssl_version, expected_ssl_version): """Given: - An ssl protocol version: 1. TLS 2. TLSv1 3. TLSv1_1 4. TLSv1_2 5. TLS_CLIENT 6. None 7....
the_stack_v2_python_sparse
Packs/OpenLDAP/Integrations/OpenLDAP/OpenLDAP_test.py
demisto/content
train
1,023
bba167eab6302db1318c271f291acd6d4cb5e417
[ "res = []\nfor i in range(0, len(nums) - 1):\n for j in range(i + 1, len(nums)):\n if nums[i] + nums[j] == target:\n res.append(nums[i])\n res.append(nums[j])\nreturn res", "lookup = {}\nfor i, num in enumerate(nums):\n if target - num in lookup:\n return [lookup[target -...
<|body_start_0|> res = [] for i in range(0, len(nums) - 1): for j in range(i + 1, len(nums)): if nums[i] + nums[j] == target: res.append(nums[i]) res.append(nums[j]) return res <|end_body_0|> <|body_start_1|> lookup = {...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def twoSum_ugly(self, nums, target): """:param nums: list[int] :param target: int :return: list[int]""" <|body_0|> def twoSum(self, nums, target): """:param nums: :param target: :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> res ...
stack_v2_sparse_classes_75kplus_train_068495
755
no_license
[ { "docstring": ":param nums: list[int] :param target: int :return: list[int]", "name": "twoSum_ugly", "signature": "def twoSum_ugly(self, nums, target)" }, { "docstring": ":param nums: :param target: :return:", "name": "twoSum", "signature": "def twoSum(self, nums, target)" } ]
2
stack_v2_sparse_classes_30k_train_038729
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def twoSum_ugly(self, nums, target): :param nums: list[int] :param target: int :return: list[int] - def twoSum(self, nums, target): :param nums: :param target: :return:
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def twoSum_ugly(self, nums, target): :param nums: list[int] :param target: int :return: list[int] - def twoSum(self, nums, target): :param nums: :param target: :return: <|skelet...
84bd4a00160e6b2a723a57e149474c6bb38bcce2
<|skeleton|> class Solution: def twoSum_ugly(self, nums, target): """:param nums: list[int] :param target: int :return: list[int]""" <|body_0|> def twoSum(self, nums, target): """:param nums: :param target: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def twoSum_ugly(self, nums, target): """:param nums: list[int] :param target: int :return: list[int]""" res = [] for i in range(0, len(nums) - 1): for j in range(i + 1, len(nums)): if nums[i] + nums[j] == target: res.append(nums...
the_stack_v2_python_sparse
1_num2sum.py
yanghongkai/yhkleetcode
train
0
22ef2b0ef2fd54e04c079274f902d878a79fc345
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn UserExperienceAnalyticsDeviceStartupHistory()", "from .entity import Entity\nfrom .user_experience_analytics_operating_system_restart_category import UserExperienceAnalyticsOperatingSystemRestartCategory\nfrom .entity import Entity\nfr...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return UserExperienceAnalyticsDeviceStartupHistory() <|end_body_0|> <|body_start_1|> from .entity import Entity from .user_experience_analytics_operating_system_restart_category import UserExpe...
The user experience analytics device startup history entity contains device boot performance history details.
UserExperienceAnalyticsDeviceStartupHistory
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserExperienceAnalyticsDeviceStartupHistory: """The user experience analytics device startup history entity contains device boot performance history details.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsDeviceStartupHistory: "...
stack_v2_sparse_classes_75kplus_train_068496
8,363
permissive
[ { "docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: UserExperienceAnalyticsDeviceStartupHistory", "name": "create_from_discriminator_value", "signature": "def c...
3
stack_v2_sparse_classes_30k_val_001299
Implement the Python class `UserExperienceAnalyticsDeviceStartupHistory` described below. Class description: The user experience analytics device startup history entity contains device boot performance history details. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseN...
Implement the Python class `UserExperienceAnalyticsDeviceStartupHistory` described below. Class description: The user experience analytics device startup history entity contains device boot performance history details. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseN...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class UserExperienceAnalyticsDeviceStartupHistory: """The user experience analytics device startup history entity contains device boot performance history details.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsDeviceStartupHistory: "...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UserExperienceAnalyticsDeviceStartupHistory: """The user experience analytics device startup history entity contains device boot performance history details.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsDeviceStartupHistory: """Creates a n...
the_stack_v2_python_sparse
msgraph/generated/models/user_experience_analytics_device_startup_history.py
microsoftgraph/msgraph-sdk-python
train
135
b05c36d26a1c55056627cec0b1fc2295229f3a32
[ "if model_id:\n try:\n model = self._model.find(int(model_id))\n except ValueError:\n self.status.BAD_REQUEST('Bad id %s' % model_id)\n else:\n if model:\n self.render_json(model)\n else:\n self.status.NOT_FOUND('Not found by id %s' % model_id)\nelse:\n ...
<|body_start_0|> if model_id: try: model = self._model.find(int(model_id)) except ValueError: self.status.BAD_REQUEST('Bad id %s' % model_id) else: if model: self.render_json(model) else: ...
RESTfulNested
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RESTfulNested: def get(self, parent_id, model_id=None): """READ or LIST.""" <|body_0|> def post(self, parent_id): """CREATE.""" <|body_1|> def put(self, parent_id, model_id): """EDIT.""" <|body_2|> def delete(self, parent_id, model_i...
stack_v2_sparse_classes_75kplus_train_068497
7,053
no_license
[ { "docstring": "READ or LIST.", "name": "get", "signature": "def get(self, parent_id, model_id=None)" }, { "docstring": "CREATE.", "name": "post", "signature": "def post(self, parent_id)" }, { "docstring": "EDIT.", "name": "put", "signature": "def put(self, parent_id, mod...
4
null
Implement the Python class `RESTfulNested` described below. Class description: Implement the RESTfulNested class. Method signatures and docstrings: - def get(self, parent_id, model_id=None): READ or LIST. - def post(self, parent_id): CREATE. - def put(self, parent_id, model_id): EDIT. - def delete(self, parent_id, mo...
Implement the Python class `RESTfulNested` described below. Class description: Implement the RESTfulNested class. Method signatures and docstrings: - def get(self, parent_id, model_id=None): READ or LIST. - def post(self, parent_id): CREATE. - def put(self, parent_id, model_id): EDIT. - def delete(self, parent_id, mo...
04e7ee88bb9d085c78b2a05b0492d45b6176d166
<|skeleton|> class RESTfulNested: def get(self, parent_id, model_id=None): """READ or LIST.""" <|body_0|> def post(self, parent_id): """CREATE.""" <|body_1|> def put(self, parent_id, model_id): """EDIT.""" <|body_2|> def delete(self, parent_id, model_i...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RESTfulNested: def get(self, parent_id, model_id=None): """READ or LIST.""" if model_id: try: model = self._model.find(int(model_id)) except ValueError: self.status.BAD_REQUEST('Bad id %s' % model_id) else: if ...
the_stack_v2_python_sparse
backend/plaft/interfaces/newrest.py
gcca/plaft_carinae
train
0
d318fbed9392837edd71967e45d25aa827dc9bf5
[ "Sprite.__init__(self)\nself.pose = np.array([x, y, theta])\nself.pose_velocity = np.array([0, 0, 0])\nself.mask = mask\nself.color = color\nself.image = Surface([width, height])\nself.image.set_colorkey(simulation.SIMULATION_BG_COLOR)\nself.dims = [width, height]\nself.rect = self.image.get_rect()\nself.autoscale ...
<|body_start_0|> Sprite.__init__(self) self.pose = np.array([x, y, theta]) self.pose_velocity = np.array([0, 0, 0]) self.mask = mask self.color = color self.image = Surface([width, height]) self.image.set_colorkey(simulation.SIMULATION_BG_COLOR) self.dims ...
Abstraction of a simulated object with a pose and a sprite.
SimulationObject
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SimulationObject: """Abstraction of a simulated object with a pose and a sprite.""" def __init__(self, x, y, theta, width=0, height=0, color=(0, 0, 0), mask=MASK_RECT): """Parameters ---------- x: float horizontal position in units y: float vertical position in units theta: heading i...
stack_v2_sparse_classes_75kplus_train_068498
4,642
permissive
[ { "docstring": "Parameters ---------- x: float horizontal position in units y: float vertical position in units theta: heading in radians width: float width in units height: float height in units color: tuple (r, g, b) mask: int sprite mask (circle or rectangle)", "name": "__init__", "signature": "def _...
5
stack_v2_sparse_classes_30k_train_039375
Implement the Python class `SimulationObject` described below. Class description: Abstraction of a simulated object with a pose and a sprite. Method signatures and docstrings: - def __init__(self, x, y, theta, width=0, height=0, color=(0, 0, 0), mask=MASK_RECT): Parameters ---------- x: float horizontal position in u...
Implement the Python class `SimulationObject` described below. Class description: Abstraction of a simulated object with a pose and a sprite. Method signatures and docstrings: - def __init__(self, x, y, theta, width=0, height=0, color=(0, 0, 0), mask=MASK_RECT): Parameters ---------- x: float horizontal position in u...
4e91e86c86bfbdd8d4639b0994e96e890a2f741e
<|skeleton|> class SimulationObject: """Abstraction of a simulated object with a pose and a sprite.""" def __init__(self, x, y, theta, width=0, height=0, color=(0, 0, 0), mask=MASK_RECT): """Parameters ---------- x: float horizontal position in units y: float vertical position in units theta: heading i...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SimulationObject: """Abstraction of a simulated object with a pose and a sprite.""" def __init__(self, x, y, theta, width=0, height=0, color=(0, 0, 0), mask=MASK_RECT): """Parameters ---------- x: float horizontal position in units y: float vertical position in units theta: heading in radians wid...
the_stack_v2_python_sparse
tools/simulator/r5engine/object.py
ut-ras/r5-2019
train
5
079e6154245ad9024ab8b89e4c1e41e31ab644e1
[ "obj = ContactType(name='Test', slug='test')\nobj.save()\nself.assertEquals('Test', obj.name)\nself.assertNotEquals(obj.id, None)\nobj.delete()", "type = ContactType(name='Test', slug='test')\ntype.save()\nobj = Contact(name='Test', contact_type=type)\nobj.save()\nself.assertEquals('Test', obj.name)\nself.assertN...
<|body_start_0|> obj = ContactType(name='Test', slug='test') obj.save() self.assertEquals('Test', obj.name) self.assertNotEquals(obj.id, None) obj.delete() <|end_body_0|> <|body_start_1|> type = ContactType(name='Test', slug='test') type.save() obj = Cont...
Identities Model Tests
IdentitiesModelsTest
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IdentitiesModelsTest: """Identities Model Tests""" def test_model_contacttype(self): """Test ContactType model""" <|body_0|> def test_model_contact(self): """Test Contact model""" <|body_1|> def test_model_field(self): """Test Field model""" ...
stack_v2_sparse_classes_75kplus_train_068499
16,679
permissive
[ { "docstring": "Test ContactType model", "name": "test_model_contacttype", "signature": "def test_model_contacttype(self)" }, { "docstring": "Test Contact model", "name": "test_model_contact", "signature": "def test_model_contact(self)" }, { "docstring": "Test Field model", "...
3
stack_v2_sparse_classes_30k_train_016749
Implement the Python class `IdentitiesModelsTest` described below. Class description: Identities Model Tests Method signatures and docstrings: - def test_model_contacttype(self): Test ContactType model - def test_model_contact(self): Test Contact model - def test_model_field(self): Test Field model
Implement the Python class `IdentitiesModelsTest` described below. Class description: Identities Model Tests Method signatures and docstrings: - def test_model_contacttype(self): Test ContactType model - def test_model_contact(self): Test Contact model - def test_model_field(self): Test Field model <|skeleton|> clas...
001e85eaf489c93b565efe679eb159cfcfef4c67
<|skeleton|> class IdentitiesModelsTest: """Identities Model Tests""" def test_model_contacttype(self): """Test ContactType model""" <|body_0|> def test_model_contact(self): """Test Contact model""" <|body_1|> def test_model_field(self): """Test Field model""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class IdentitiesModelsTest: """Identities Model Tests""" def test_model_contacttype(self): """Test ContactType model""" obj = ContactType(name='Test', slug='test') obj.save() self.assertEquals('Test', obj.name) self.assertNotEquals(obj.id, None) obj.delete() ...
the_stack_v2_python_sparse
identities/tests.py
alejo8591/maker
train
0