blob_id
stringlengths
40
40
bodies
listlengths
2
6
bodies_text
stringlengths
196
6.73k
class_docstring
stringlengths
0
700
class_name
stringlengths
1
86
detected_licenses
listlengths
0
45
format_version
stringclasses
1 value
full_text
stringlengths
438
7.52k
id
stringlengths
40
40
length_bytes
int64
506
50k
license_type
stringclasses
2 values
methods
listlengths
2
6
n_methods
int64
2
6
original_id
stringlengths
38
40
prompt
stringlengths
153
4.25k
prompted_full_text
stringlengths
645
10.7k
revision_id
stringlengths
40
40
skeleton
stringlengths
162
4.34k
snapshot_name
stringclasses
1 value
snapshot_source_dir
stringclasses
1 value
solution
stringlengths
302
7.33k
source
stringclasses
1 value
source_path
stringlengths
4
177
source_repo
stringlengths
6
110
split
stringclasses
1 value
star_events_count
int64
0
209k
d6ca8dd435162d3a0bf9409e984136bf54671cd9
[ "currency_code = currency_for_request(request)\ncurrency = Currency.objects.all_accepted().get(iso_4217_code=currency_code)\nserializer = CurrencySerializer(currency)\nreturn Response(serializer.data)", "serializer = CurrencySessionSerializer(data=request.data)\nif serializer.is_valid():\n currency_code = seri...
<|body_start_0|> currency_code = currency_for_request(request) currency = Currency.objects.all_accepted().get(iso_4217_code=currency_code) serializer = CurrencySerializer(currency) return Response(serializer.data) <|end_body_0|> <|body_start_1|> serializer = CurrencySessionSeria...
CurrencySessionAPIView
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CurrencySessionAPIView: def get(self, request, *args, **kwargs): """Return the currency for the request.""" <|body_0|> def post(self, request, *args, **kwargs): """Set the currency in the session.""" <|body_1|> <|end_skeleton|> <|body_start_0|> curr...
stack_v2_sparse_classes_36k_train_022500
2,594
permissive
[ { "docstring": "Return the currency for the request.", "name": "get", "signature": "def get(self, request, *args, **kwargs)" }, { "docstring": "Set the currency in the session.", "name": "post", "signature": "def post(self, request, *args, **kwargs)" } ]
2
null
Implement the Python class `CurrencySessionAPIView` described below. Class description: Implement the CurrencySessionAPIView class. Method signatures and docstrings: - def get(self, request, *args, **kwargs): Return the currency for the request. - def post(self, request, *args, **kwargs): Set the currency in the sess...
Implement the Python class `CurrencySessionAPIView` described below. Class description: Implement the CurrencySessionAPIView class. Method signatures and docstrings: - def get(self, request, *args, **kwargs): Return the currency for the request. - def post(self, request, *args, **kwargs): Set the currency in the sess...
c2814749c547349ff63415bdc81f53eb1215c7c0
<|skeleton|> class CurrencySessionAPIView: def get(self, request, *args, **kwargs): """Return the currency for the request.""" <|body_0|> def post(self, request, *args, **kwargs): """Set the currency in the session.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CurrencySessionAPIView: def get(self, request, *args, **kwargs): """Return the currency for the request.""" currency_code = currency_for_request(request) currency = Currency.objects.all_accepted().get(iso_4217_code=currency_code) serializer = CurrencySerializer(currency) ...
the_stack_v2_python_sparse
satchmo/currency/api/views.py
ToeKnee/jelly-roll
train
0
330c511f0f6f06d060ecc82374f7ed169e72094e
[ "self.data = None\nself._hass = hass\nself._app_id = app_id\nself._device_id = device_id\nself._values = values\nself._url = TTN_DATA_STORAGE_URL.format(app_id=app_id, endpoint='api/v2/query', device_id=device_id)\nself._headers = {ACCEPT: CONTENT_TYPE_JSON, AUTHORIZATION: f'key {access_key}'}", "try:\n sessio...
<|body_start_0|> self.data = None self._hass = hass self._app_id = app_id self._device_id = device_id self._values = values self._url = TTN_DATA_STORAGE_URL.format(app_id=app_id, endpoint='api/v2/query', device_id=device_id) self._headers = {ACCEPT: CONTENT_TYPE_J...
Get the latest data from The Things Network Data Storage.
TtnDataStorage
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TtnDataStorage: """Get the latest data from The Things Network Data Storage.""" def __init__(self, hass, app_id, device_id, access_key, values): """Initialize the data object.""" <|body_0|> async def async_update(self): """Get the current state from The Things Ne...
stack_v2_sparse_classes_36k_train_022501
5,254
permissive
[ { "docstring": "Initialize the data object.", "name": "__init__", "signature": "def __init__(self, hass, app_id, device_id, access_key, values)" }, { "docstring": "Get the current state from The Things Network Data Storage.", "name": "async_update", "signature": "async def async_update(s...
2
stack_v2_sparse_classes_30k_train_012851
Implement the Python class `TtnDataStorage` described below. Class description: Get the latest data from The Things Network Data Storage. Method signatures and docstrings: - def __init__(self, hass, app_id, device_id, access_key, values): Initialize the data object. - async def async_update(self): Get the current sta...
Implement the Python class `TtnDataStorage` described below. Class description: Get the latest data from The Things Network Data Storage. Method signatures and docstrings: - def __init__(self, hass, app_id, device_id, access_key, values): Initialize the data object. - async def async_update(self): Get the current sta...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class TtnDataStorage: """Get the latest data from The Things Network Data Storage.""" def __init__(self, hass, app_id, device_id, access_key, values): """Initialize the data object.""" <|body_0|> async def async_update(self): """Get the current state from The Things Ne...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TtnDataStorage: """Get the latest data from The Things Network Data Storage.""" def __init__(self, hass, app_id, device_id, access_key, values): """Initialize the data object.""" self.data = None self._hass = hass self._app_id = app_id self._device_id = device_id ...
the_stack_v2_python_sparse
homeassistant/components/thethingsnetwork/sensor.py
home-assistant/core
train
35,501
90748831127ee2c6594153a8350142c2c7888bbe
[ "res = Instrument.objects.all()\nif scenario_id:\n rs = RoadSegment.objects.filter(scenario__id=scenario_id).all()\n rc = RoadCondition.objects.filter(road_segment_road_condition__in=rs).all()\n rca = RoadConditionAction.objects.filter(road_condition_road_condition_actions__in=rc).all()\n ia = Instrumen...
<|body_start_0|> res = Instrument.objects.all() if scenario_id: rs = RoadSegment.objects.filter(scenario__id=scenario_id).all() rc = RoadCondition.objects.filter(road_segment_road_condition__in=rs).all() rca = RoadConditionAction.objects.filter(road_condition_road_con...
Query
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Query: def resolve_instruments(self, info, instrument_id=None, name=None, instrument_type_id=None, instrument_system_id=None, desc=None, folder_id=None, scenario_id=None, label_name=None, **kwargs): """Queries instruments from the database :param label_name: :param info: :param instrumen...
stack_v2_sparse_classes_36k_train_022502
9,470
no_license
[ { "docstring": "Queries instruments from the database :param label_name: :param info: :param instrument_id: The instrument ID to filter on :param name: The (part of the) name to filter on :param instrument_type_id: The instrument_type ID to filter on :param instrument_system_id: The instrument_system ID to filt...
3
null
Implement the Python class `Query` described below. Class description: Implement the Query class. Method signatures and docstrings: - def resolve_instruments(self, info, instrument_id=None, name=None, instrument_type_id=None, instrument_system_id=None, desc=None, folder_id=None, scenario_id=None, label_name=None, **k...
Implement the Python class `Query` described below. Class description: Implement the Query class. Method signatures and docstrings: - def resolve_instruments(self, info, instrument_id=None, name=None, instrument_type_id=None, instrument_system_id=None, desc=None, folder_id=None, scenario_id=None, label_name=None, **k...
618440303dcbf819cd61aa5e593b4b50483f0070
<|skeleton|> class Query: def resolve_instruments(self, info, instrument_id=None, name=None, instrument_type_id=None, instrument_system_id=None, desc=None, folder_id=None, scenario_id=None, label_name=None, **kwargs): """Queries instruments from the database :param label_name: :param info: :param instrumen...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Query: def resolve_instruments(self, info, instrument_id=None, name=None, instrument_type_id=None, instrument_system_id=None, desc=None, folder_id=None, scenario_id=None, label_name=None, **kwargs): """Queries instruments from the database :param label_name: :param info: :param instrument_id: The inst...
the_stack_v2_python_sparse
backend/api/instruments/schema.py
Rohan-Deshamudre/Smart-traffic-management-system
train
0
7db6f15b378c878d272b9d49ed79750117d32712
[ "node_data = dict(id='node' + node['id'], type=node['labels'][0])\nif node.get('properties'):\n node_data.update(node['properties'])\nreturn {'data': node_data}", "edge_data = dict(id='edge' + edge['id'], type=edge['type'], source='node' + edge['startNode'], target='node' + edge['endNode'])\nif edge.get('prope...
<|body_start_0|> node_data = dict(id='node' + node['id'], type=node['labels'][0]) if node.get('properties'): node_data.update(node['properties']) return {'data': node_data} <|end_body_0|> <|body_start_1|> edge_data = dict(id='edge' + edge['id'], type=edge['type'], source='no...
Cytoscape formatter. This formatter will return the graph compatible with the open source graph Javascript library Cytoscape (http://js.cytoscape.org/).
CytoscapeOutputFormatter
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CytoscapeOutputFormatter: """Cytoscape formatter. This formatter will return the graph compatible with the open source graph Javascript library Cytoscape (http://js.cytoscape.org/).""" def format_node(self, node): """Format a Cytoscape graph node. Args: node: A dictionary with one no...
stack_v2_sparse_classes_36k_train_022503
8,202
permissive
[ { "docstring": "Format a Cytoscape graph node. Args: node: A dictionary with one node Returns: Dictionary with a Cytoscape formatted node", "name": "format_node", "signature": "def format_node(self, node)" }, { "docstring": "Format a Cytoscape graph egde. Args: edge: A dictionary with one edge R...
2
stack_v2_sparse_classes_30k_train_016063
Implement the Python class `CytoscapeOutputFormatter` described below. Class description: Cytoscape formatter. This formatter will return the graph compatible with the open source graph Javascript library Cytoscape (http://js.cytoscape.org/). Method signatures and docstrings: - def format_node(self, node): Format a C...
Implement the Python class `CytoscapeOutputFormatter` described below. Class description: Cytoscape formatter. This formatter will return the graph compatible with the open source graph Javascript library Cytoscape (http://js.cytoscape.org/). Method signatures and docstrings: - def format_node(self, node): Format a C...
e0c833151c28e940103c3034f4cb26b1eb81750e
<|skeleton|> class CytoscapeOutputFormatter: """Cytoscape formatter. This formatter will return the graph compatible with the open source graph Javascript library Cytoscape (http://js.cytoscape.org/).""" def format_node(self, node): """Format a Cytoscape graph node. Args: node: A dictionary with one no...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CytoscapeOutputFormatter: """Cytoscape formatter. This formatter will return the graph compatible with the open source graph Javascript library Cytoscape (http://js.cytoscape.org/).""" def format_node(self, node): """Format a Cytoscape graph node. Args: node: A dictionary with one node Returns: D...
the_stack_v2_python_sparse
timesketch/lib/datastores/neo4j.py
LDO-CERT/timesketch
train
1
32823a1bc17d31398adf4dd83dd0f50127a45e62
[ "del kwargs\nsleep(1)\nreturn read_pd_df(self._DATA_DEFS.get(ioc_type), ioc_type)", "if isinstance(results, pd.DataFrame):\n return results\nreturn pd.DataFrame()" ]
<|body_start_0|> del kwargs sleep(1) return read_pd_df(self._DATA_DEFS.get(ioc_type), ioc_type) <|end_body_0|> <|body_start_1|> if isinstance(results, pd.DataFrame): return results return pd.DataFrame() <|end_body_1|>
TILookup demo class.
TILookupDemo
[ "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 TILookupDemo: """TILookup demo class.""" def lookup_ioc(self, ioc_type, **kwargs): """Lookup single IoC.""" <|body_0|> def result_to_df(results): """Convert IoC results to DataFrame.""" <|body_1|> <|end_skeleton|> <|body_start_0|> del kwargs ...
stack_v2_sparse_classes_36k_train_022504
7,922
permissive
[ { "docstring": "Lookup single IoC.", "name": "lookup_ioc", "signature": "def lookup_ioc(self, ioc_type, **kwargs)" }, { "docstring": "Convert IoC results to DataFrame.", "name": "result_to_df", "signature": "def result_to_df(results)" } ]
2
null
Implement the Python class `TILookupDemo` described below. Class description: TILookup demo class. Method signatures and docstrings: - def lookup_ioc(self, ioc_type, **kwargs): Lookup single IoC. - def result_to_df(results): Convert IoC results to DataFrame.
Implement the Python class `TILookupDemo` described below. Class description: TILookup demo class. Method signatures and docstrings: - def lookup_ioc(self, ioc_type, **kwargs): Lookup single IoC. - def result_to_df(results): Convert IoC results to DataFrame. <|skeleton|> class TILookupDemo: """TILookup demo clas...
44b1a390510f9be2772ec62cb95d0fc67dfc234b
<|skeleton|> class TILookupDemo: """TILookup demo class.""" def lookup_ioc(self, ioc_type, **kwargs): """Lookup single IoC.""" <|body_0|> def result_to_df(results): """Convert IoC results to DataFrame.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TILookupDemo: """TILookup demo class.""" def lookup_ioc(self, ioc_type, **kwargs): """Lookup single IoC.""" del kwargs sleep(1) return read_pd_df(self._DATA_DEFS.get(ioc_type), ioc_type) def result_to_df(results): """Convert IoC results to DataFrame.""" ...
the_stack_v2_python_sparse
tools/mp_demo_data.py
RiskIQ/msticpy
train
1
dc312aa954ab604b6fa2b6584a6586ca2253a8b2
[ "OptimizerBase.__init__(self, disp)\nself.n_epoch = n_epoch\nself.iter_per_epoch = iter_per_epoch\nself.maxiter = int(self.n_epoch * self.iter_per_epoch)\nself.print_freq = int(self.print_freq * self.iter_per_epoch)\nself.step_rate = step_rate\nself.decay = decay\nself.momentum = momentum\nself.offset = offset", ...
<|body_start_0|> OptimizerBase.__init__(self, disp) self.n_epoch = n_epoch self.iter_per_epoch = iter_per_epoch self.maxiter = int(self.n_epoch * self.iter_per_epoch) self.print_freq = int(self.print_freq * self.iter_per_epoch) self.step_rate = step_rate self.deca...
A wrapper-class for AdaDelta method from climin library. Requires gradient estimation.
AdaDelta
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AdaDelta: """A wrapper-class for AdaDelta method from climin library. Requires gradient estimation.""" def __init__(self, disp=False, iter_per_epoch=1, n_epoch=1000, step_rate=1.0, decay=0.9, momentum=0.0, offset=0.0001): """:param iter_per_epoch: number of iteration per epoch :param...
stack_v2_sparse_classes_36k_train_022505
4,677
no_license
[ { "docstring": ":param iter_per_epoch: number of iteration per epoch :param n_epoch: maximum number of epochs (or iterations if no sample_size is provided) The names of the other parameters are the same as in the corresponding climin method :param step_rate: step size of the method :param decay: decay of the mo...
2
stack_v2_sparse_classes_30k_val_000199
Implement the Python class `AdaDelta` described below. Class description: A wrapper-class for AdaDelta method from climin library. Requires gradient estimation. Method signatures and docstrings: - def __init__(self, disp=False, iter_per_epoch=1, n_epoch=1000, step_rate=1.0, decay=0.9, momentum=0.0, offset=0.0001): :p...
Implement the Python class `AdaDelta` described below. Class description: A wrapper-class for AdaDelta method from climin library. Requires gradient estimation. Method signatures and docstrings: - def __init__(self, disp=False, iter_per_epoch=1, n_epoch=1000, step_rate=1.0, decay=0.9, momentum=0.0, offset=0.0001): :p...
fbc0be813096f21e02e9f8d306df1c21f7e006a7
<|skeleton|> class AdaDelta: """A wrapper-class for AdaDelta method from climin library. Requires gradient estimation.""" def __init__(self, disp=False, iter_per_epoch=1, n_epoch=1000, step_rate=1.0, decay=0.9, momentum=0.0, offset=0.0001): """:param iter_per_epoch: number of iteration per epoch :param...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AdaDelta: """A wrapper-class for AdaDelta method from climin library. Requires gradient estimation.""" def __init__(self, disp=False, iter_per_epoch=1, n_epoch=1000, step_rate=1.0, decay=0.9, momentum=0.0, offset=0.0001): """:param iter_per_epoch: number of iteration per epoch :param n_epoch: max...
the_stack_v2_python_sparse
gplib/optim/methods/wrappers.py
izmailovpavel/gplib
train
2
bfa0457e263c20e92bf7be278d54247cc18aa0db
[ "m, n = (len(nums1), len(nums2))\nif m > n:\n return self.findMediaSortedArrays(nums2, nums1)\nif m == 0:\n return 0.5 * (nums2[(n - 1) // 2] + nums[n // 2])\ncut = (m + n) // 2\nlo, hi = (0, m)\nMIN, MAX = (float('-inf'), float('inf'))\nwhile True:\n cut1 = lo + (hi - lo) // 2\n cut2 = cut - cut1\n ...
<|body_start_0|> m, n = (len(nums1), len(nums2)) if m > n: return self.findMediaSortedArrays(nums2, nums1) if m == 0: return 0.5 * (nums2[(n - 1) // 2] + nums[n // 2]) cut = (m + n) // 2 lo, hi = (0, m) MIN, MAX = (float('-inf'), float('inf')) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findMediaSortedArrays1(self, nums1: List[int], nums2: List[int]) -> float: """binary search: search cutting points cut1 & cut2 in nums1 and nums2 so that cut1 + cut2 == (len(nums1) + len(nums2)) // 2 and nums1[cut1-1] <= nums2[cut2] and nums1[cut1] >= nums2[cut2-1] time: O(...
stack_v2_sparse_classes_36k_train_022506
2,528
no_license
[ { "docstring": "binary search: search cutting points cut1 & cut2 in nums1 and nums2 so that cut1 + cut2 == (len(nums1) + len(nums2)) // 2 and nums1[cut1-1] <= nums2[cut2] and nums1[cut1] >= nums2[cut2-1] time: O(log(min(m, n))) space: O(1)", "name": "findMediaSortedArrays1", "signature": "def findMediaS...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findMediaSortedArrays1(self, nums1: List[int], nums2: List[int]) -> float: binary search: search cutting points cut1 & cut2 in nums1 and nums2 so that cut1 + cut2 == (len(num...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findMediaSortedArrays1(self, nums1: List[int], nums2: List[int]) -> float: binary search: search cutting points cut1 & cut2 in nums1 and nums2 so that cut1 + cut2 == (len(num...
6ff1941ff213a843013100ac7033e2d4f90fbd6a
<|skeleton|> class Solution: def findMediaSortedArrays1(self, nums1: List[int], nums2: List[int]) -> float: """binary search: search cutting points cut1 & cut2 in nums1 and nums2 so that cut1 + cut2 == (len(nums1) + len(nums2)) // 2 and nums1[cut1-1] <= nums2[cut2] and nums1[cut1] >= nums2[cut2-1] time: O(...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def findMediaSortedArrays1(self, nums1: List[int], nums2: List[int]) -> float: """binary search: search cutting points cut1 & cut2 in nums1 and nums2 so that cut1 + cut2 == (len(nums1) + len(nums2)) // 2 and nums1[cut1-1] <= nums2[cut2] and nums1[cut1] >= nums2[cut2-1] time: O(log(min(m, n))...
the_stack_v2_python_sparse
Leetcode 0004. Median of Two Sorted Arrays.py
Chaoran-sjsu/leetcode
train
0
06caf0cb733db96dfbba5c34355065cb61dd2747
[ "self.db_url = _mask_uri(db_url)\nself.client = MDBClient(db_url)\nself.db = self.client.get()\nself._query_collection = self.db[CatalogConstants.catalog_collections['query']]\nself._feature_collection = self.db[CatalogConstants.catalog_collections['feature']]\nself._model_collection = self.db[CatalogConstants.cata...
<|body_start_0|> self.db_url = _mask_uri(db_url) self.client = MDBClient(db_url) self.db = self.client.get() self._query_collection = self.db[CatalogConstants.catalog_collections['query']] self._feature_collection = self.db[CatalogConstants.catalog_collections['feature']] ...
Catalog
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Catalog: def __init__(self, db_url: str): """initiates catalog and collection for storing features and queries Args: db_url(str): mongodb url""" <|body_0|> def save(self, dev_id: str, data_type: str, data: dict): """Args: def_id(str): dev identifier data_type(str): f...
stack_v2_sparse_classes_36k_train_022507
2,944
no_license
[ { "docstring": "initiates catalog and collection for storing features and queries Args: db_url(str): mongodb url", "name": "__init__", "signature": "def __init__(self, db_url: str)" }, { "docstring": "Args: def_id(str): dev identifier data_type(str): feature, query or model object data(dict): ca...
3
stack_v2_sparse_classes_30k_train_007598
Implement the Python class `Catalog` described below. Class description: Implement the Catalog class. Method signatures and docstrings: - def __init__(self, db_url: str): initiates catalog and collection for storing features and queries Args: db_url(str): mongodb url - def save(self, dev_id: str, data_type: str, data...
Implement the Python class `Catalog` described below. Class description: Implement the Catalog class. Method signatures and docstrings: - def __init__(self, db_url: str): initiates catalog and collection for storing features and queries Args: db_url(str): mongodb url - def save(self, dev_id: str, data_type: str, data...
d9b72831510b8a9e7004d3ccfac073e3ef3c1f52
<|skeleton|> class Catalog: def __init__(self, db_url: str): """initiates catalog and collection for storing features and queries Args: db_url(str): mongodb url""" <|body_0|> def save(self, dev_id: str, data_type: str, data: dict): """Args: def_id(str): dev identifier data_type(str): f...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Catalog: def __init__(self, db_url: str): """initiates catalog and collection for storing features and queries Args: db_url(str): mongodb url""" self.db_url = _mask_uri(db_url) self.client = MDBClient(db_url) self.db = self.client.get() self._query_collection = self.db[...
the_stack_v2_python_sparse
feature_store/catalog.py
miararoy/feature_store
train
0
044a3470f76db302683901cc6dae4b460ee42c52
[ "if host_ids and self.context['user'] not in host_ids:\n raise serializers.ValidationError('Must include self as host')\nelse:\n return host_ids", "hosts = validated_data.pop('hosts')\ninstance = Queue.objects.create(**validated_data)\nif hosts:\n instance.hosts.set(hosts)\nelse:\n instance.hosts.set(...
<|body_start_0|> if host_ids and self.context['user'] not in host_ids: raise serializers.ValidationError('Must include self as host') else: return host_ids <|end_body_0|> <|body_start_1|> hosts = validated_data.pop('hosts') instance = Queue.objects.create(**valid...
Serializer used when viewing queue as a host.
QueueHostSerializer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QueueHostSerializer: """Serializer used when viewing queue as a host.""" def validate_host_ids(self, host_ids): """Require empty hosts_ids (default to current user) or require current user in host_ids""" <|body_0|> def create(self, validated_data): """Set current...
stack_v2_sparse_classes_36k_train_022508
10,335
permissive
[ { "docstring": "Require empty hosts_ids (default to current user) or require current user in host_ids", "name": "validate_host_ids", "signature": "def validate_host_ids(self, host_ids)" }, { "docstring": "Set current user as host if not provided many-to-many fields cannot be set until the model ...
2
stack_v2_sparse_classes_30k_train_009833
Implement the Python class `QueueHostSerializer` described below. Class description: Serializer used when viewing queue as a host. Method signatures and docstrings: - def validate_host_ids(self, host_ids): Require empty hosts_ids (default to current user) or require current user in host_ids - def create(self, validat...
Implement the Python class `QueueHostSerializer` described below. Class description: Serializer used when viewing queue as a host. Method signatures and docstrings: - def validate_host_ids(self, host_ids): Require empty hosts_ids (default to current user) or require current user in host_ids - def create(self, validat...
12e2185faf35307564bea910ff1baad7bef1ff76
<|skeleton|> class QueueHostSerializer: """Serializer used when viewing queue as a host.""" def validate_host_ids(self, host_ids): """Require empty hosts_ids (default to current user) or require current user in host_ids""" <|body_0|> def create(self, validated_data): """Set current...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class QueueHostSerializer: """Serializer used when viewing queue as a host.""" def validate_host_ids(self, host_ids): """Require empty hosts_ids (default to current user) or require current user in host_ids""" if host_ids and self.context['user'] not in host_ids: raise serializers.V...
the_stack_v2_python_sparse
src/officehours_api/serializers.py
tl-its-umich-edu/remote-office-hours-queue
train
12
441a13a3359174644eab0deca73e2743880ee24e
[ "self._caffe = kwargs.pop('caffe')\nself._creator = kwargs.pop('creator')\nkwargs.setdefault('label_suffix', '')\nsuper(CashReportForm, self).__init__(*args, **kwargs)\nself.fields['cash_before_shift'].label = 'Pieniądze na początku zmiany'\nself.fields['cash_after_shift'].label = 'Pieniądze na końcu zmiany'\nself....
<|body_start_0|> self._caffe = kwargs.pop('caffe') self._creator = kwargs.pop('creator') kwargs.setdefault('label_suffix', '') super(CashReportForm, self).__init__(*args, **kwargs) self.fields['cash_before_shift'].label = 'Pieniądze na początku zmiany' self.fields['cash_a...
Responsible for creating a cash report.
CashReportForm
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CashReportForm: """Responsible for creating a cash report.""" def __init__(self, *args, **kwargs): """Initialize all CashReport's fields.""" <|body_0|> def save(self, commit=True): """Override of save method, to add Caffe relation.""" <|body_1|> <|end_sk...
stack_v2_sparse_classes_36k_train_022509
4,623
permissive
[ { "docstring": "Initialize all CashReport's fields.", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "Override of save method, to add Caffe relation.", "name": "save", "signature": "def save(self, commit=True)" } ]
2
stack_v2_sparse_classes_30k_train_005900
Implement the Python class `CashReportForm` described below. Class description: Responsible for creating a cash report. Method signatures and docstrings: - def __init__(self, *args, **kwargs): Initialize all CashReport's fields. - def save(self, commit=True): Override of save method, to add Caffe relation.
Implement the Python class `CashReportForm` described below. Class description: Responsible for creating a cash report. Method signatures and docstrings: - def __init__(self, *args, **kwargs): Initialize all CashReport's fields. - def save(self, commit=True): Override of save method, to add Caffe relation. <|skeleto...
cdb7f5edb29255c7e874eaa6231621063210a8b0
<|skeleton|> class CashReportForm: """Responsible for creating a cash report.""" def __init__(self, *args, **kwargs): """Initialize all CashReport's fields.""" <|body_0|> def save(self, commit=True): """Override of save method, to add Caffe relation.""" <|body_1|> <|end_sk...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CashReportForm: """Responsible for creating a cash report.""" def __init__(self, *args, **kwargs): """Initialize all CashReport's fields.""" self._caffe = kwargs.pop('caffe') self._creator = kwargs.pop('creator') kwargs.setdefault('label_suffix', '') super(CashRepo...
the_stack_v2_python_sparse
caffe/cash/forms.py
VirrageS/io-kawiarnie
train
3
0f6108aeac83bd52ab6edbcbf2758b089d8d8a02
[ "name = self['name']\nif transactions_to_include and (not match_string_or_regular_expression(name, transactions_to_include)):\n return False\nreturn not match_string_or_regular_expression(name, transactions_to_ignore)", "name, response_time = (self['name'], self[response_time_to_evaluate])\nfor transaction_spe...
<|body_start_0|> name = self['name'] if transactions_to_include and (not match_string_or_regular_expression(name, transactions_to_include)): return False return not match_string_or_regular_expression(name, transactions_to_ignore) <|end_body_0|> <|body_start_1|> name, respons...
Entity representing a performance transaction.
TransactionEntity
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TransactionEntity: """Entity representing a performance transaction.""" def is_to_be_included(self, transactions_to_include: list[str], transactions_to_ignore: list[str]) -> bool: """Return whether the transaction should be included.""" <|body_0|> def is_slow(self, respo...
stack_v2_sparse_classes_36k_train_022510
16,901
permissive
[ { "docstring": "Return whether the transaction should be included.", "name": "is_to_be_included", "signature": "def is_to_be_included(self, transactions_to_include: list[str], transactions_to_ignore: list[str]) -> bool" }, { "docstring": "Return whether the transaction is slow.", "name": "is...
2
null
Implement the Python class `TransactionEntity` described below. Class description: Entity representing a performance transaction. Method signatures and docstrings: - def is_to_be_included(self, transactions_to_include: list[str], transactions_to_ignore: list[str]) -> bool: Return whether the transaction should be inc...
Implement the Python class `TransactionEntity` described below. Class description: Entity representing a performance transaction. Method signatures and docstrings: - def is_to_be_included(self, transactions_to_include: list[str], transactions_to_ignore: list[str]) -> bool: Return whether the transaction should be inc...
5d9952bf0bd47895824fa78428d3e4f4d6b5d9b3
<|skeleton|> class TransactionEntity: """Entity representing a performance transaction.""" def is_to_be_included(self, transactions_to_include: list[str], transactions_to_ignore: list[str]) -> bool: """Return whether the transaction should be included.""" <|body_0|> def is_slow(self, respo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TransactionEntity: """Entity representing a performance transaction.""" def is_to_be_included(self, transactions_to_include: list[str], transactions_to_ignore: list[str]) -> bool: """Return whether the transaction should be included.""" name = self['name'] if transactions_to_inclu...
the_stack_v2_python_sparse
components/collector/src/base_collectors/source_collector.py
ICTU/quality-time
train
43
4b9bd497ae353583a4947fec6237f4e0d1ed224d
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn UnifiedApprovalStage()", "from .subject_set import SubjectSet\nfrom .subject_set import SubjectSet\nfields: Dict[str, Callable[[Any], None]] = {'approvalStageTimeOutInDays': lambda n: setattr(self, 'approval_stage_time_out_in_days', n....
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return UnifiedApprovalStage() <|end_body_0|> <|body_start_1|> from .subject_set import SubjectSet from .subject_set import SubjectSet fields: Dict[str, Callable[[Any], None]] = {'approv...
UnifiedApprovalStage
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UnifiedApprovalStage: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedApprovalStage: """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 ...
stack_v2_sparse_classes_36k_train_022511
4,542
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: UnifiedApprovalStage", "name": "create_from_discriminator_value", "signature": "def create_from_discriminato...
3
null
Implement the Python class `UnifiedApprovalStage` described below. Class description: Implement the UnifiedApprovalStage class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedApprovalStage: Creates a new instance of the appropriate class based o...
Implement the Python class `UnifiedApprovalStage` described below. Class description: Implement the UnifiedApprovalStage class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedApprovalStage: Creates a new instance of the appropriate class based o...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class UnifiedApprovalStage: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedApprovalStage: """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 ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UnifiedApprovalStage: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedApprovalStage: """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...
the_stack_v2_python_sparse
msgraph/generated/models/unified_approval_stage.py
microsoftgraph/msgraph-sdk-python
train
135
303fe8e106534239cd648882cdecb891e0d386b2
[ "dict, rolling_hash, res = ({}, 0, [])\nfor i in range(len(s)):\n rolling_hash = rolling_hash << 3 & 1073741823 | ord(s[i]) & 7\n if rolling_hash not in dict:\n dict[rolling_hash] = True\n elif dict[rolling_hash]:\n res.append(s[i - 9:i + 1])\n dict[rolling_hash] = False\nreturn res", ...
<|body_start_0|> dict, rolling_hash, res = ({}, 0, []) for i in range(len(s)): rolling_hash = rolling_hash << 3 & 1073741823 | ord(s[i]) & 7 if rolling_hash not in dict: dict[rolling_hash] = True elif dict[rolling_hash]: res.append(s[i ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findRepeatedDnaSequences(self, s): """:type s: str :rtype: List[str]""" <|body_0|> def findRepeatedDnaSequences2(self, s): """:type s: str :rtype: List[str]""" <|body_1|> <|end_skeleton|> <|body_start_0|> dict, rolling_hash, res = ({},...
stack_v2_sparse_classes_36k_train_022512
1,855
no_license
[ { "docstring": ":type s: str :rtype: List[str]", "name": "findRepeatedDnaSequences", "signature": "def findRepeatedDnaSequences(self, s)" }, { "docstring": ":type s: str :rtype: List[str]", "name": "findRepeatedDnaSequences2", "signature": "def findRepeatedDnaSequences2(self, s)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findRepeatedDnaSequences(self, s): :type s: str :rtype: List[str] - def findRepeatedDnaSequences2(self, s): :type s: str :rtype: List[str]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findRepeatedDnaSequences(self, s): :type s: str :rtype: List[str] - def findRepeatedDnaSequences2(self, s): :type s: str :rtype: List[str] <|skeleton|> class Solution: ...
035ef08434fa1ca781a6fb2f9eed3538b7d20c02
<|skeleton|> class Solution: def findRepeatedDnaSequences(self, s): """:type s: str :rtype: List[str]""" <|body_0|> def findRepeatedDnaSequences2(self, s): """:type s: str :rtype: List[str]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def findRepeatedDnaSequences(self, s): """:type s: str :rtype: List[str]""" dict, rolling_hash, res = ({}, 0, []) for i in range(len(s)): rolling_hash = rolling_hash << 3 & 1073741823 | ord(s[i]) & 7 if rolling_hash not in dict: dict[ro...
the_stack_v2_python_sparse
leetcode_python/Hash_table/repeated-dna-sequences.py
yennanliu/CS_basics
train
64
1630d7cfbe932aa37fa28265d63ba3b1c224ea36
[ "values = {'a': bf.Tru(), 'b': bf.Fls(), 'c': bf.Fls()}\nformula = bf.And([bf.Or([bf.Var('b'), bf.Var('a'), bf.Var('c')]), bf.Or([bf.Not(bf.Var('a')), bf.Not(bf.Var('c'))]), bf.Not(bf.Var('b'))])\nresult = formula.evaluate(values)\nself.assertTrue(result, 'Invalid evaluation, expected True.')", "values = {'a': bf...
<|body_start_0|> values = {'a': bf.Tru(), 'b': bf.Fls(), 'c': bf.Fls()} formula = bf.And([bf.Or([bf.Var('b'), bf.Var('a'), bf.Var('c')]), bf.Or([bf.Not(bf.Var('a')), bf.Not(bf.Var('c'))]), bf.Not(bf.Var('b'))]) result = formula.evaluate(values) self.assertTrue(result, 'Invalid evaluation...
Unit test for the evaluation method of the algorithm utilities.
evaluation_unit_test
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class evaluation_unit_test: """Unit test for the evaluation method of the algorithm utilities.""" def test_simple_evaluation_to_true(self): """Tests the evaluation of a simple formula with the specified values. Must evaluate to True.""" <|body_0|> def test_simple_evaluation_to...
stack_v2_sparse_classes_36k_train_022513
2,078
no_license
[ { "docstring": "Tests the evaluation of a simple formula with the specified values. Must evaluate to True.", "name": "test_simple_evaluation_to_true", "signature": "def test_simple_evaluation_to_true(self)" }, { "docstring": "Tests the evaluation of a simple formula with the specified values. Mu...
4
stack_v2_sparse_classes_30k_train_011426
Implement the Python class `evaluation_unit_test` described below. Class description: Unit test for the evaluation method of the algorithm utilities. Method signatures and docstrings: - def test_simple_evaluation_to_true(self): Tests the evaluation of a simple formula with the specified values. Must evaluate to True....
Implement the Python class `evaluation_unit_test` described below. Class description: Unit test for the evaluation method of the algorithm utilities. Method signatures and docstrings: - def test_simple_evaluation_to_true(self): Tests the evaluation of a simple formula with the specified values. Must evaluate to True....
bb4e876919bb956b75c442d528f3892553f1ee6f
<|skeleton|> class evaluation_unit_test: """Unit test for the evaluation method of the algorithm utilities.""" def test_simple_evaluation_to_true(self): """Tests the evaluation of a simple formula with the specified values. Must evaluate to True.""" <|body_0|> def test_simple_evaluation_to...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class evaluation_unit_test: """Unit test for the evaluation method of the algorithm utilities.""" def test_simple_evaluation_to_true(self): """Tests the evaluation of a simple formula with the specified values. Must evaluate to True.""" values = {'a': bf.Tru(), 'b': bf.Fls(), 'c': bf.Fls()} ...
the_stack_v2_python_sparse
unit_tests/evaluation_unit_test.py
KePcA/LVR-sat
train
0
7c3c5e87f9ada0fb82af9dd988e90bf85eb56c95
[ "super(SaveToDiskWrapper, self).__init__(env=env)\nself._output_dir = output_dir\nself._episode = None", "self._episode = Episode(self._output_dir, next(tokens))\nobservation = self.env.reset(*args, **kwargs)\nself._episode.append(**observation)\nreturn observation", "observation, reward, done, info = self.env....
<|body_start_0|> super(SaveToDiskWrapper, self).__init__(env=env) self._output_dir = output_dir self._episode = None <|end_body_0|> <|body_start_1|> self._episode = Episode(self._output_dir, next(tokens)) observation = self.env.reset(*args, **kwargs) self._episode.append...
Stores observations to the disk.
SaveToDiskWrapper
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SaveToDiskWrapper: """Stores observations to the disk.""" def __init__(self, env: gym.Env, *, output_dir: str) -> None: """Constructs a gym wrapper to store observations to the disk.""" <|body_0|> def reset(self, *args: Any, **kwargs: Any) -> Observations: """Res...
stack_v2_sparse_classes_36k_train_022514
8,971
permissive
[ { "docstring": "Constructs a gym wrapper to store observations to the disk.", "name": "__init__", "signature": "def __init__(self, env: gym.Env, *, output_dir: str) -> None" }, { "docstring": "Resets the wrapped environment and initializes a new episode.", "name": "reset", "signature": "...
3
stack_v2_sparse_classes_30k_train_020896
Implement the Python class `SaveToDiskWrapper` described below. Class description: Stores observations to the disk. Method signatures and docstrings: - def __init__(self, env: gym.Env, *, output_dir: str) -> None: Constructs a gym wrapper to store observations to the disk. - def reset(self, *args: Any, **kwargs: Any)...
Implement the Python class `SaveToDiskWrapper` described below. Class description: Stores observations to the disk. Method signatures and docstrings: - def __init__(self, env: gym.Env, *, output_dir: str) -> None: Constructs a gym wrapper to store observations to the disk. - def reset(self, *args: Any, **kwargs: Any)...
1680aee77a53228412f9bab34068f0a9576c58e3
<|skeleton|> class SaveToDiskWrapper: """Stores observations to the disk.""" def __init__(self, env: gym.Env, *, output_dir: str) -> None: """Constructs a gym wrapper to store observations to the disk.""" <|body_0|> def reset(self, *args: Any, **kwargs: Any) -> Observations: """Res...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SaveToDiskWrapper: """Stores observations to the disk.""" def __init__(self, env: gym.Env, *, output_dir: str) -> None: """Constructs a gym wrapper to store observations to the disk.""" super(SaveToDiskWrapper, self).__init__(env=env) self._output_dir = output_dir self._ep...
the_stack_v2_python_sparse
oatomobile/core/rl.py
OATML/oatomobile
train
177
dfb5e078391c943fe470f208aa39d20d044e8527
[ "try:\n extensions_config = getattr(current_app.extensions['invenio-app-ils'], 'series_metadata_extensions')\nexcept AttributeError:\n return {}\nExtensionSchema = extensions_config.to_schema()\nreturn ExtensionSchema().dump(obj)", "try:\n extensions_config = getattr(current_app.extensions['invenio-app-i...
<|body_start_0|> try: extensions_config = getattr(current_app.extensions['invenio-app-ils'], 'series_metadata_extensions') except AttributeError: return {} ExtensionSchema = extensions_config.to_schema() return ExtensionSchema().dump(obj) <|end_body_0|> <|body_st...
Series schema.
SeriesSchemaV1
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SeriesSchemaV1: """Series schema.""" def dump_extensions(self, obj): """Dumps the extensions value. :params obj: content of the object's 'extensions' field""" <|body_0|> def load_extensions(self, value): """Loads the 'extensions' field. :params value: content of ...
stack_v2_sparse_classes_36k_train_022515
4,051
permissive
[ { "docstring": "Dumps the extensions value. :params obj: content of the object's 'extensions' field", "name": "dump_extensions", "signature": "def dump_extensions(self, obj)" }, { "docstring": "Loads the 'extensions' field. :params value: content of the input's 'extensions' field", "name": "...
3
null
Implement the Python class `SeriesSchemaV1` described below. Class description: Series schema. Method signatures and docstrings: - def dump_extensions(self, obj): Dumps the extensions value. :params obj: content of the object's 'extensions' field - def load_extensions(self, value): Loads the 'extensions' field. :para...
Implement the Python class `SeriesSchemaV1` described below. Class description: Series schema. Method signatures and docstrings: - def dump_extensions(self, obj): Dumps the extensions value. :params obj: content of the object's 'extensions' field - def load_extensions(self, value): Loads the 'extensions' field. :para...
1c36526e85510100c5f64059518d1b716d87ac10
<|skeleton|> class SeriesSchemaV1: """Series schema.""" def dump_extensions(self, obj): """Dumps the extensions value. :params obj: content of the object's 'extensions' field""" <|body_0|> def load_extensions(self, value): """Loads the 'extensions' field. :params value: content of ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SeriesSchemaV1: """Series schema.""" def dump_extensions(self, obj): """Dumps the extensions value. :params obj: content of the object's 'extensions' field""" try: extensions_config = getattr(current_app.extensions['invenio-app-ils'], 'series_metadata_extensions') exce...
the_stack_v2_python_sparse
invenio_app_ils/series/loaders/jsonschemas/series.py
inveniosoftware/invenio-app-ils
train
64
cd709243eb68e48b2a763e4a73f99e6c0026f17b
[ "conf['angel.worker.matrix.transfer.request.timeout.ms'] = 60000\njconf = conf.dict_to_jconf()\nsuper(LinearRegRunner, self).train(conf, conf._jvm.com.tencent.angel.ml.regression.linear.LinearRegModel(jconf, None), 'com.tencent.angel.ml.regression.linear.LinearRegTrainTask')", "conf['angel.worker.matrix.transfer....
<|body_start_0|> conf['angel.worker.matrix.transfer.request.timeout.ms'] = 60000 jconf = conf.dict_to_jconf() super(LinearRegRunner, self).train(conf, conf._jvm.com.tencent.angel.ml.regression.linear.LinearRegModel(jconf, None), 'com.tencent.angel.ml.regression.linear.LinearRegTrainTask') <|end_...
Run linear regression task on angel
LinearRegRunner
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "MIT", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LinearRegRunner: """Run linear regression task on angel""" def train(self, conf): """Run linear regression train task :param conf: configuration of a algorithm and resource :return:""" <|body_0|> def predict(self, conf): """Run linear regression predict task :par...
stack_v2_sparse_classes_36k_train_022516
2,910
permissive
[ { "docstring": "Run linear regression train task :param conf: configuration of a algorithm and resource :return:", "name": "train", "signature": "def train(self, conf)" }, { "docstring": "Run linear regression predict task :param conf: configuration of algorithm and resource :return:", "name...
3
stack_v2_sparse_classes_30k_train_019133
Implement the Python class `LinearRegRunner` described below. Class description: Run linear regression task on angel Method signatures and docstrings: - def train(self, conf): Run linear regression train task :param conf: configuration of a algorithm and resource :return: - def predict(self, conf): Run linear regress...
Implement the Python class `LinearRegRunner` described below. Class description: Run linear regression task on angel Method signatures and docstrings: - def train(self, conf): Run linear regression train task :param conf: configuration of a algorithm and resource :return: - def predict(self, conf): Run linear regress...
cb015db12356ffbfbdde096e4ec112a2cd324ac3
<|skeleton|> class LinearRegRunner: """Run linear regression task on angel""" def train(self, conf): """Run linear regression train task :param conf: configuration of a algorithm and resource :return:""" <|body_0|> def predict(self, conf): """Run linear regression predict task :par...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LinearRegRunner: """Run linear regression task on angel""" def train(self, conf): """Run linear regression train task :param conf: configuration of a algorithm and resource :return:""" conf['angel.worker.matrix.transfer.request.timeout.ms'] = 60000 jconf = conf.dict_to_jconf() ...
the_stack_v2_python_sparse
angel-ps/python/pyangel/ml/regression/runner.py
haitwang-cloud/angel
train
0
be32339233a4716666f09b2ab0e5801aba4e918d
[ "if TurboJPEGSingleton.__instance is None:\n TurboJPEGSingleton()\nreturn TurboJPEGSingleton.__instance", "try:\n from turbojpeg import TurboJPEG\n TurboJPEGSingleton.__instance = TurboJPEG()\nexcept Exception:\n _LOGGER.exception('Error loading libturbojpeg; Cameras may impact HomeKit performance')\n...
<|body_start_0|> if TurboJPEGSingleton.__instance is None: TurboJPEGSingleton() return TurboJPEGSingleton.__instance <|end_body_0|> <|body_start_1|> try: from turbojpeg import TurboJPEG TurboJPEGSingleton.__instance = TurboJPEG() except Exception: ...
Load TurboJPEG only once. Ensures we do not log load failures each snapshot since camera image fetches happen every few seconds.
TurboJPEGSingleton
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TurboJPEGSingleton: """Load TurboJPEG only once. Ensures we do not log load failures each snapshot since camera image fetches happen every few seconds.""" def instance() -> TurboJPEG | Literal[False] | None: """Singleton for TurboJPEG.""" <|body_0|> def __init__(self) ->...
stack_v2_sparse_classes_36k_train_022517
3,257
permissive
[ { "docstring": "Singleton for TurboJPEG.", "name": "instance", "signature": "def instance() -> TurboJPEG | Literal[False] | None" }, { "docstring": "Try to create TurboJPEG only once.", "name": "__init__", "signature": "def __init__(self) -> None" } ]
2
stack_v2_sparse_classes_30k_train_020677
Implement the Python class `TurboJPEGSingleton` described below. Class description: Load TurboJPEG only once. Ensures we do not log load failures each snapshot since camera image fetches happen every few seconds. Method signatures and docstrings: - def instance() -> TurboJPEG | Literal[False] | None: Singleton for Tu...
Implement the Python class `TurboJPEGSingleton` described below. Class description: Load TurboJPEG only once. Ensures we do not log load failures each snapshot since camera image fetches happen every few seconds. Method signatures and docstrings: - def instance() -> TurboJPEG | Literal[False] | None: Singleton for Tu...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class TurboJPEGSingleton: """Load TurboJPEG only once. Ensures we do not log load failures each snapshot since camera image fetches happen every few seconds.""" def instance() -> TurboJPEG | Literal[False] | None: """Singleton for TurboJPEG.""" <|body_0|> def __init__(self) ->...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TurboJPEGSingleton: """Load TurboJPEG only once. Ensures we do not log load failures each snapshot since camera image fetches happen every few seconds.""" def instance() -> TurboJPEG | Literal[False] | None: """Singleton for TurboJPEG.""" if TurboJPEGSingleton.__instance is None: ...
the_stack_v2_python_sparse
homeassistant/components/camera/img_util.py
home-assistant/core
train
35,501
aa6cea4db7feb61a837d7c248371e0283b3aa299
[ "self.__width = width\nself.__height = height\nself.__score = 0\nself.__f = 0\nself.__food = food\nself.__snake = deque([(0, 0)])\nself.__direction = {'U': (-1, 0), 'L': (0, -1), 'R': (0, 1), 'D': (1, 0)}\nself.__lookup = {(0, 0)}", "def valid(x, y):\n return 0 <= x < self.__height and 0 <= y < self.__width an...
<|body_start_0|> self.__width = width self.__height = height self.__score = 0 self.__f = 0 self.__food = food self.__snake = deque([(0, 0)]) self.__direction = {'U': (-1, 0), 'L': (0, -1), 'R': (0, 1), 'D': (1, 0)} self.__lookup = {(0, 0)} <|end_body_0|> ...
SnakeGame
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SnakeGame: def __init__(self, width, height, food): """Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :typ...
stack_v2_sparse_classes_36k_train_022518
1,950
permissive
[ { "docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :type width: int :type height: int :type food: List[List[int]]", ...
2
null
Implement the Python class `SnakeGame` described below. Class description: Implement the SnakeGame class. Method signatures and docstrings: - def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E...
Implement the Python class `SnakeGame` described below. Class description: Implement the SnakeGame class. Method signatures and docstrings: - def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E...
4dc4e6642dc92f1983c13564cc0fd99917cab358
<|skeleton|> class SnakeGame: def __init__(self, width, height, food): """Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :typ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SnakeGame: def __init__(self, width, height, food): """Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :type width: int :...
the_stack_v2_python_sparse
Python/design-snake-game.py
kamyu104/LeetCode-Solutions
train
4,549
0e07df5de969277dc69536d0fe57a72958bcfed2
[ "if not email:\n raise ValueError('User must have an email address')\nprint('-----------------Antes de guardar usuarios')\nemail = self.normalize_email(email)\nuser = self.model(email=email)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user", "user = self.create_user(email, password)\nuser.i...
<|body_start_0|> if not email: raise ValueError('User must have an email address') print('-----------------Antes de guardar usuarios') email = self.normalize_email(email) user = self.model(email=email) user.set_password(password) user.save(using=self._db) ...
Administrador para perfiles de Usuario
UserProfileManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserProfileManager: """Administrador para perfiles de Usuario""" def create_user(self, email: str, password: str) -> User: """Crea un nuevo usuario""" <|body_0|> def create_superuser(self, email: str, password: str) -> User: """Crea un nuevo superusuario""" ...
stack_v2_sparse_classes_36k_train_022519
2,388
no_license
[ { "docstring": "Crea un nuevo usuario", "name": "create_user", "signature": "def create_user(self, email: str, password: str) -> User" }, { "docstring": "Crea un nuevo superusuario", "name": "create_superuser", "signature": "def create_superuser(self, email: str, password: str) -> User" ...
2
stack_v2_sparse_classes_30k_train_020099
Implement the Python class `UserProfileManager` described below. Class description: Administrador para perfiles de Usuario Method signatures and docstrings: - def create_user(self, email: str, password: str) -> User: Crea un nuevo usuario - def create_superuser(self, email: str, password: str) -> User: Crea un nuevo ...
Implement the Python class `UserProfileManager` described below. Class description: Administrador para perfiles de Usuario Method signatures and docstrings: - def create_user(self, email: str, password: str) -> User: Crea un nuevo usuario - def create_superuser(self, email: str, password: str) -> User: Crea un nuevo ...
6f7ee866d21cd87de1b03a57adc3276204031a9e
<|skeleton|> class UserProfileManager: """Administrador para perfiles de Usuario""" def create_user(self, email: str, password: str) -> User: """Crea un nuevo usuario""" <|body_0|> def create_superuser(self, email: str, password: str) -> User: """Crea un nuevo superusuario""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserProfileManager: """Administrador para perfiles de Usuario""" def create_user(self, email: str, password: str) -> User: """Crea un nuevo usuario""" if not email: raise ValueError('User must have an email address') print('-----------------Antes de guardar usuarios') ...
the_stack_v2_python_sparse
profiles/models.py
JCamilo5/backProyecto1
train
0
7d7e589b11a4ef6a52dcfcb0423815e2f290ec39
[ "super().__init__(**kwargs)\ndim = len(voxel_size)\nassert len(spatial_size) == 2 * dim, f'{spatial_size}'\nself._voxel_size = voxel_size\nself._spatial_size = spatial_size\nself._voxel_spatial_size = voxel_utils.compute_voxel_spatial_size(spatial_size, self._voxel_size)", "point_voxel_xyz_float = ops.floor(point...
<|body_start_0|> super().__init__(**kwargs) dim = len(voxel_size) assert len(spatial_size) == 2 * dim, f'{spatial_size}' self._voxel_size = voxel_size self._spatial_size = spatial_size self._voxel_spatial_size = voxel_utils.compute_voxel_spatial_size(spatial_size, self._v...
Voxelization layer.
PointToVoxel
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PointToVoxel: """Voxelization layer.""" def __init__(self, voxel_size, spatial_size, **kwargs): """Voxelization layer constructor. Args: voxel_size: voxel size in each xyz dimension. spatial_size: max/min range in each dim in global coordinate frame. name: layer name **kwargs: additi...
stack_v2_sparse_classes_36k_train_022520
9,351
permissive
[ { "docstring": "Voxelization layer constructor. Args: voxel_size: voxel size in each xyz dimension. spatial_size: max/min range in each dim in global coordinate frame. name: layer name **kwargs: additional key value args (e.g. dtype) passed to the parent class.", "name": "__init__", "signature": "def __...
2
stack_v2_sparse_classes_30k_train_008620
Implement the Python class `PointToVoxel` described below. Class description: Voxelization layer. Method signatures and docstrings: - def __init__(self, voxel_size, spatial_size, **kwargs): Voxelization layer constructor. Args: voxel_size: voxel size in each xyz dimension. spatial_size: max/min range in each dim in g...
Implement the Python class `PointToVoxel` described below. Class description: Voxelization layer. Method signatures and docstrings: - def __init__(self, voxel_size, spatial_size, **kwargs): Voxelization layer constructor. Args: voxel_size: voxel size in each xyz dimension. spatial_size: max/min range in each dim in g...
e83f229f1b7b847cd712d5cd4810097d3e06d14e
<|skeleton|> class PointToVoxel: """Voxelization layer.""" def __init__(self, voxel_size, spatial_size, **kwargs): """Voxelization layer constructor. Args: voxel_size: voxel size in each xyz dimension. spatial_size: max/min range in each dim in global coordinate frame. name: layer name **kwargs: additi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PointToVoxel: """Voxelization layer.""" def __init__(self, voxel_size, spatial_size, **kwargs): """Voxelization layer constructor. Args: voxel_size: voxel size in each xyz dimension. spatial_size: max/min range in each dim in global coordinate frame. name: layer name **kwargs: additional key valu...
the_stack_v2_python_sparse
keras_cv/layers/object_detection_3d/voxelization.py
keras-team/keras-cv
train
818
6aa499b865a746a5429bf954af963efb1e6ad538
[ "if self.params.opt_mode == 'min':\n opt_idx = np.argmin(self.exe_path.y)\nelif self.params.opt_mode == 'max':\n opt_idx = np.argmax(self.exe_path.y)\nopt_pair = [self.exe_path.x[opt_idx], self.exe_path.y[opt_idx]]\nreturn opt_pair", "def dist_fn(a, b):\n a = np.array(a[0] + [a[1]])\n b = np.array(b[0...
<|body_start_0|> if self.params.opt_mode == 'min': opt_idx = np.argmin(self.exe_path.y) elif self.params.opt_mode == 'max': opt_idx = np.argmax(self.exe_path.y) opt_pair = [self.exe_path.x[opt_idx], self.exe_path.y[opt_idx]] return opt_pair <|end_body_0|> <|body_...
Algorithm that scans over a grid of points, and as output returns the minimum function input over the grid.
GlobalOptGrid
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GlobalOptGrid: """Algorithm that scans over a grid of points, and as output returns the minimum function input over the grid.""" def get_output(self): """Return output based on self.exe_path.""" <|body_0|> def get_output_dist_fn(self): """Return distance function...
stack_v2_sparse_classes_36k_train_022521
19,618
no_license
[ { "docstring": "Return output based on self.exe_path.", "name": "get_output", "signature": "def get_output(self)" }, { "docstring": "Return distance function for pairs of outputs.", "name": "get_output_dist_fn", "signature": "def get_output_dist_fn(self)" } ]
2
stack_v2_sparse_classes_30k_train_013702
Implement the Python class `GlobalOptGrid` described below. Class description: Algorithm that scans over a grid of points, and as output returns the minimum function input over the grid. Method signatures and docstrings: - def get_output(self): Return output based on self.exe_path. - def get_output_dist_fn(self): Ret...
Implement the Python class `GlobalOptGrid` described below. Class description: Algorithm that scans over a grid of points, and as output returns the minimum function input over the grid. Method signatures and docstrings: - def get_output(self): Return output based on self.exe_path. - def get_output_dist_fn(self): Ret...
d75d1a89bb566e62662e4d010d91893bfe1ee9f4
<|skeleton|> class GlobalOptGrid: """Algorithm that scans over a grid of points, and as output returns the minimum function input over the grid.""" def get_output(self): """Return output based on self.exe_path.""" <|body_0|> def get_output_dist_fn(self): """Return distance function...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GlobalOptGrid: """Algorithm that scans over a grid of points, and as output returns the minimum function input over the grid.""" def get_output(self): """Return output based on self.exe_path.""" if self.params.opt_mode == 'min': opt_idx = np.argmin(self.exe_path.y) eli...
the_stack_v2_python_sparse
bax/alg/algorithms.py
willieneis/bayesian-algorithm-execution
train
45
0a93421684c42fe385e9b477fa47cd680587e965
[ "assert isinstance(public_key, str), type(public_key)\nsuper(MultiChainPaymentProvider, self).__init__()\nself.multi_chain_community = multi_chain_community\nself.public_key = public_key", "assert isinstance(candidate, Candidate), type(candidate)\nassert isinstance(quantity, Quantity), type(quantity)\nif self.bal...
<|body_start_0|> assert isinstance(public_key, str), type(public_key) super(MultiChainPaymentProvider, self).__init__() self.multi_chain_community = multi_chain_community self.public_key = public_key <|end_body_0|> <|body_start_1|> assert isinstance(candidate, Candidate), type(c...
"Multi chain payment provider which enables checking the multi chain balance of this peer and transferring multi chain to other peers
MultiChainPaymentProvider
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiChainPaymentProvider: """"Multi chain payment provider which enables checking the multi chain balance of this peer and transferring multi chain to other peers""" def __init__(self, multi_chain_community, public_key): """:param multi_chain_community: The multi chain community whi...
stack_v2_sparse_classes_36k_train_022522
3,445
no_license
[ { "docstring": ":param multi_chain_community: The multi chain community which manages multi chain transfers :param public_key: The public key of this peer", "name": "__init__", "signature": "def __init__(self, multi_chain_community, public_key)" }, { "docstring": "Transfers the selected quantity...
3
stack_v2_sparse_classes_30k_train_001271
Implement the Python class `MultiChainPaymentProvider` described below. Class description: "Multi chain payment provider which enables checking the multi chain balance of this peer and transferring multi chain to other peers Method signatures and docstrings: - def __init__(self, multi_chain_community, public_key): :p...
Implement the Python class `MultiChainPaymentProvider` described below. Class description: "Multi chain payment provider which enables checking the multi chain balance of this peer and transferring multi chain to other peers Method signatures and docstrings: - def __init__(self, multi_chain_community, public_key): :p...
cc4d1c27166d68c39e5c38e77bb70093f34e19e5
<|skeleton|> class MultiChainPaymentProvider: """"Multi chain payment provider which enables checking the multi chain balance of this peer and transferring multi chain to other peers""" def __init__(self, multi_chain_community, public_key): """:param multi_chain_community: The multi chain community whi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MultiChainPaymentProvider: """"Multi chain payment provider which enables checking the multi chain balance of this peer and transferring multi chain to other peers""" def __init__(self, multi_chain_community, public_key): """:param multi_chain_community: The multi chain community which manages mu...
the_stack_v2_python_sparse
market/core/payment_provider.py
devos50/decentralized-market
train
0
f05ec5e7e676982c02605a2473749c19645750b1
[ "super(InstrumentDialog, self).__init__(parent, wx.ID_ANY, title='Edit instrument', minWidth=300)\nself.inst = inst\nself.spec = inst.getSpecification()\nsetpanel = wx.Panel(self)\nsetsizer = wx.FlexGridSizer(len(self.spec) + 1, 2, 3, 3)\nsetpanel.SetSizer(setsizer)\nname = self.inst.getName()\nself.tbs = []\nsetsi...
<|body_start_0|> super(InstrumentDialog, self).__init__(parent, wx.ID_ANY, title='Edit instrument', minWidth=300) self.inst = inst self.spec = inst.getSpecification() setpanel = wx.Panel(self) setsizer = wx.FlexGridSizer(len(self.spec) + 1, 2, 3, 3) setpanel.SetSizer(sets...
A simple dialog for creating new instruments.
InstrumentDialog
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InstrumentDialog: """A simple dialog for creating new instruments.""" def __init__(self, parent, inst): """Create a new instrument dialog.""" <|body_0|> def update(self): """Update the instrument to reflect changes.""" <|body_1|> <|end_skeleton|> <|body...
stack_v2_sparse_classes_36k_train_022523
31,205
no_license
[ { "docstring": "Create a new instrument dialog.", "name": "__init__", "signature": "def __init__(self, parent, inst)" }, { "docstring": "Update the instrument to reflect changes.", "name": "update", "signature": "def update(self)" } ]
2
stack_v2_sparse_classes_30k_train_005836
Implement the Python class `InstrumentDialog` described below. Class description: A simple dialog for creating new instruments. Method signatures and docstrings: - def __init__(self, parent, inst): Create a new instrument dialog. - def update(self): Update the instrument to reflect changes.
Implement the Python class `InstrumentDialog` described below. Class description: A simple dialog for creating new instruments. Method signatures and docstrings: - def __init__(self, parent, inst): Create a new instrument dialog. - def update(self): Update the instrument to reflect changes. <|skeleton|> class Instru...
6001bd91ab998a3271b1a160fed7de0d0b342cc6
<|skeleton|> class InstrumentDialog: """A simple dialog for creating new instruments.""" def __init__(self, parent, inst): """Create a new instrument dialog.""" <|body_0|> def update(self): """Update the instrument to reflect changes.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InstrumentDialog: """A simple dialog for creating new instruments.""" def __init__(self, parent, inst): """Create a new instrument dialog.""" super(InstrumentDialog, self).__init__(parent, wx.ID_ANY, title='Edit instrument', minWidth=300) self.inst = inst self.spec = inst....
the_stack_v2_python_sparse
src/gui/object_config.py
tcflanagan/transport
train
0
cd13334606d2ab202838a1e176a051c52af96cd4
[ "if data_loc == 'disk':\n root = server_setup.BACKUP_DATA_ROOT_DIR\nelse:\n root = server_setup.DATA_ROOT_DIR\nif server_setup.DEPLOYMENT_MODE == DeploymentMode.Server:\n return SSHDataAccess(root)\nreturn LocalDataAccess(root)", "mode = server_setup.DEPLOYMENT_MODE\nif mode == DeploymentMode.Server:\n ...
<|body_start_0|> if data_loc == 'disk': root = server_setup.BACKUP_DATA_ROOT_DIR else: root = server_setup.DATA_ROOT_DIR if server_setup.DEPLOYMENT_MODE == DeploymentMode.Server: return SSHDataAccess(root) return LocalDataAccess(root) <|end_body_0|> <...
Factory for data access instances
Context
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Context: """Factory for data access instances""" def get_data_access(data_loc=None): """Return a data access instance appropriate for the current environment. :param str data_loc: pass "disk" if using data from backup disk, otherwise leave the default. :return: (:class:`powersimdata....
stack_v2_sparse_classes_36k_train_022524
1,570
permissive
[ { "docstring": "Return a data access instance appropriate for the current environment. :param str data_loc: pass \"disk\" if using data from backup disk, otherwise leave the default. :return: (:class:`powersimdata.data_access.data_access.DataAccess`) -- a data access instance", "name": "get_data_access", ...
2
stack_v2_sparse_classes_30k_train_006833
Implement the Python class `Context` described below. Class description: Factory for data access instances Method signatures and docstrings: - def get_data_access(data_loc=None): Return a data access instance appropriate for the current environment. :param str data_loc: pass "disk" if using data from backup disk, oth...
Implement the Python class `Context` described below. Class description: Factory for data access instances Method signatures and docstrings: - def get_data_access(data_loc=None): Return a data access instance appropriate for the current environment. :param str data_loc: pass "disk" if using data from backup disk, oth...
2fa9fb907fd55a96ffd3d584614b47af79a0bda8
<|skeleton|> class Context: """Factory for data access instances""" def get_data_access(data_loc=None): """Return a data access instance appropriate for the current environment. :param str data_loc: pass "disk" if using data from backup disk, otherwise leave the default. :return: (:class:`powersimdata....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Context: """Factory for data access instances""" def get_data_access(data_loc=None): """Return a data access instance appropriate for the current environment. :param str data_loc: pass "disk" if using data from backup disk, otherwise leave the default. :return: (:class:`powersimdata.data_access.d...
the_stack_v2_python_sparse
powersimdata/data_access/context.py
abhinavgairola/PowerSimData
train
0
72a5e1c06e1a851491947d3c873d0ba117671d7b
[ "super().__init__('opendr_object_detection_2d_detr_node')\nif output_rgb_image_topic is not None:\n self.image_publisher = self.create_publisher(ROS_Image, output_rgb_image_topic, 1)\nelse:\n self.image_publisher = None\nif detections_topic is not None:\n self.detection_publisher = self.create_publisher(De...
<|body_start_0|> super().__init__('opendr_object_detection_2d_detr_node') if output_rgb_image_topic is not None: self.image_publisher = self.create_publisher(ROS_Image, output_rgb_image_topic, 1) else: self.image_publisher = None if detections_topic is not None: ...
ObjectDetectionDetrNode
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ObjectDetectionDetrNode: def __init__(self, input_rgb_image_topic='image_raw', output_rgb_image_topic='/opendr/image_objects_annotated', detections_topic='/opendr/objects', device='cuda'): """Creates a ROS2 Node for object detection with DETR. :param input_rgb_image_topic: Topic from whi...
stack_v2_sparse_classes_36k_train_022525
7,921
permissive
[ { "docstring": "Creates a ROS2 Node for object detection with DETR. :param input_rgb_image_topic: Topic from which we are reading the input image :type input_rgb_image_topic: str :param output_rgb_image_topic: Topic to which we are publishing the annotated image (if None, no annotated image is published) :type ...
2
null
Implement the Python class `ObjectDetectionDetrNode` described below. Class description: Implement the ObjectDetectionDetrNode class. Method signatures and docstrings: - def __init__(self, input_rgb_image_topic='image_raw', output_rgb_image_topic='/opendr/image_objects_annotated', detections_topic='/opendr/objects', ...
Implement the Python class `ObjectDetectionDetrNode` described below. Class description: Implement the ObjectDetectionDetrNode class. Method signatures and docstrings: - def __init__(self, input_rgb_image_topic='image_raw', output_rgb_image_topic='/opendr/image_objects_annotated', detections_topic='/opendr/objects', ...
b3d6ce670cdf63469fc5766630eb295d67b3d788
<|skeleton|> class ObjectDetectionDetrNode: def __init__(self, input_rgb_image_topic='image_raw', output_rgb_image_topic='/opendr/image_objects_annotated', detections_topic='/opendr/objects', device='cuda'): """Creates a ROS2 Node for object detection with DETR. :param input_rgb_image_topic: Topic from whi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ObjectDetectionDetrNode: def __init__(self, input_rgb_image_topic='image_raw', output_rgb_image_topic='/opendr/image_objects_annotated', detections_topic='/opendr/objects', device='cuda'): """Creates a ROS2 Node for object detection with DETR. :param input_rgb_image_topic: Topic from which we are read...
the_stack_v2_python_sparse
projects/opendr_ws_2/src/opendr_perception/opendr_perception/object_detection_2d_detr_node.py
opendr-eu/opendr
train
535
d3bea7e63cc6cb5ab792c258b8c1ca7382e47c76
[ "if not isinstance(uid, str) or not bool(uid.strip()):\n message: str = 'uid cannot be Null'\n raise InputError(status=error_codes.input_error_code, description=message)\nif not isinstance(organization_id, str) or not bool(organization_id.strip()):\n message: str = 'organization_id cannot be Null'\n rai...
<|body_start_0|> if not isinstance(uid, str) or not bool(uid.strip()): message: str = 'uid cannot be Null' raise InputError(status=error_codes.input_error_code, description=message) if not isinstance(organization_id, str) or not bool(organization_id.strip()): message:...
UserValidators
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserValidators: def is_user_valid(organization_id: str, uid: str) -> Optional[bool]: """**is_user_valid** returns true if user_instance is found and user_instance.is_active :param organization_id: :param uid: :return:""" <|body_0|> async def is_user_valid_async(organization_...
stack_v2_sparse_classes_36k_train_022526
14,108
permissive
[ { "docstring": "**is_user_valid** returns true if user_instance is found and user_instance.is_active :param organization_id: :param uid: :return:", "name": "is_user_valid", "signature": "def is_user_valid(organization_id: str, uid: str) -> Optional[bool]" }, { "docstring": "**is_user_valid_async...
4
null
Implement the Python class `UserValidators` described below. Class description: Implement the UserValidators class. Method signatures and docstrings: - def is_user_valid(organization_id: str, uid: str) -> Optional[bool]: **is_user_valid** returns true if user_instance is found and user_instance.is_active :param organ...
Implement the Python class `UserValidators` described below. Class description: Implement the UserValidators class. Method signatures and docstrings: - def is_user_valid(organization_id: str, uid: str) -> Optional[bool]: **is_user_valid** returns true if user_instance is found and user_instance.is_active :param organ...
e8cf1df3f061c9745977e207568ffed2abdc70fc
<|skeleton|> class UserValidators: def is_user_valid(organization_id: str, uid: str) -> Optional[bool]: """**is_user_valid** returns true if user_instance is found and user_instance.is_active :param organization_id: :param uid: :return:""" <|body_0|> async def is_user_valid_async(organization_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserValidators: def is_user_valid(organization_id: str, uid: str) -> Optional[bool]: """**is_user_valid** returns true if user_instance is found and user_instance.is_active :param organization_id: :param uid: :return:""" if not isinstance(uid, str) or not bool(uid.strip()): message...
the_stack_v2_python_sparse
database/users.py
saaiiravi/membership_and_affiliate_api
train
0
66700b042f02ed0edec9cae8a9dc13a8237e6ad1
[ "self.object_attributes_param = object_attributes_param\nself.object_param = object_param\nself.mtype = mtype", "if dictionary is None:\n return None\nobject_attributes_param = cohesity_management_sdk.models.ad_attribute_restore_param.ADAttributeRestoreParam.from_dictionary(dictionary.get('objectAttributesPara...
<|body_start_0|> self.object_attributes_param = object_attributes_param self.object_param = object_param self.mtype = mtype <|end_body_0|> <|body_start_1|> if dictionary is None: return None object_attributes_param = cohesity_management_sdk.models.ad_attribute_restor...
Implementation of the 'ADUpdateRestoreTaskOptions' model. TODO: type description here. Attributes: object_attributes_param (ADAttributeRestoreParam): Object attributes restore params with the list of attributes to be restored. This is set only when type is kObjectAttributes. object_param (ADObjectRestoreParam): Object ...
ADUpdateRestoreTaskOptions
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ADUpdateRestoreTaskOptions: """Implementation of the 'ADUpdateRestoreTaskOptions' model. TODO: type description here. Attributes: object_attributes_param (ADAttributeRestoreParam): Object attributes restore params with the list of attributes to be restored. This is set only when type is kObjectAt...
stack_v2_sparse_classes_36k_train_022527
2,578
permissive
[ { "docstring": "Constructor for the ADUpdateRestoreTaskOptions class", "name": "__init__", "signature": "def __init__(self, object_attributes_param=None, object_param=None, mtype=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictio...
2
stack_v2_sparse_classes_30k_test_000769
Implement the Python class `ADUpdateRestoreTaskOptions` described below. Class description: Implementation of the 'ADUpdateRestoreTaskOptions' model. TODO: type description here. Attributes: object_attributes_param (ADAttributeRestoreParam): Object attributes restore params with the list of attributes to be restored. ...
Implement the Python class `ADUpdateRestoreTaskOptions` described below. Class description: Implementation of the 'ADUpdateRestoreTaskOptions' model. TODO: type description here. Attributes: object_attributes_param (ADAttributeRestoreParam): Object attributes restore params with the list of attributes to be restored. ...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class ADUpdateRestoreTaskOptions: """Implementation of the 'ADUpdateRestoreTaskOptions' model. TODO: type description here. Attributes: object_attributes_param (ADAttributeRestoreParam): Object attributes restore params with the list of attributes to be restored. This is set only when type is kObjectAt...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ADUpdateRestoreTaskOptions: """Implementation of the 'ADUpdateRestoreTaskOptions' model. TODO: type description here. Attributes: object_attributes_param (ADAttributeRestoreParam): Object attributes restore params with the list of attributes to be restored. This is set only when type is kObjectAttributes. obj...
the_stack_v2_python_sparse
cohesity_management_sdk/models/ad_update_restore_task_options.py
cohesity/management-sdk-python
train
24
0e11ce0548ad8099182b985528d48df94a26aca8
[ "Node.__init__(self, name)\nself.acceptChild = [Node.LIMIT]\nself.nodeType = Node.THRESHOLD", "if self.getSubNode(name, Node.LIMIT):\n raise HanCannotCreateConf('The limit: ' + name + ' already exists for threshold: ' + self.name)\nlimit = HanLimit(name, warning, error)\nself.appendChild(limit)" ]
<|body_start_0|> Node.__init__(self, name) self.acceptChild = [Node.LIMIT] self.nodeType = Node.THRESHOLD <|end_body_0|> <|body_start_1|> if self.getSubNode(name, Node.LIMIT): raise HanCannotCreateConf('The limit: ' + name + ' already exists for threshold: ' + self.name) ...
The han representation of a DQThreshold
HanThreshold
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HanThreshold: """The han representation of a DQThreshold""" def __init__(self, name): """Creates a han threshold configuration element""" <|body_0|> def addLimit(self, name, warning, error): """Adds a limit to the threshold @param name: the limits name @param war...
stack_v2_sparse_classes_36k_train_022528
30,609
permissive
[ { "docstring": "Creates a han threshold configuration element", "name": "__init__", "signature": "def __init__(self, name)" }, { "docstring": "Adds a limit to the threshold @param name: the limits name @param warning: the limit value for the warning level @param error: the limit value for the er...
2
null
Implement the Python class `HanThreshold` described below. Class description: The han representation of a DQThreshold Method signatures and docstrings: - def __init__(self, name): Creates a han threshold configuration element - def addLimit(self, name, warning, error): Adds a limit to the threshold @param name: the l...
Implement the Python class `HanThreshold` described below. Class description: The han representation of a DQThreshold Method signatures and docstrings: - def __init__(self, name): Creates a han threshold configuration element - def addLimit(self, name, warning, error): Adds a limit to the threshold @param name: the l...
354f92551294f7be678aebcd7b9d67d2c4448176
<|skeleton|> class HanThreshold: """The han representation of a DQThreshold""" def __init__(self, name): """Creates a han threshold configuration element""" <|body_0|> def addLimit(self, name, warning, error): """Adds a limit to the threshold @param name: the limits name @param war...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HanThreshold: """The han representation of a DQThreshold""" def __init__(self, name): """Creates a han threshold configuration element""" Node.__init__(self, name) self.acceptChild = [Node.LIMIT] self.nodeType = Node.THRESHOLD def addLimit(self, name, warning, error):...
the_stack_v2_python_sparse
DataQuality/DataQualityUtils/python/hanwriter.py
strigazi/athena
train
0
7afb0fb6f0da4ba058bd2b265400e8977bd727ce
[ "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')" ]
<|body_start_0|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') <|end_body_0|> <|body_start_1|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not im...
Service for retrieving and updating individual error groups.
ErrorGroupServiceServicer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ErrorGroupServiceServicer: """Service for retrieving and updating individual error groups.""" def GetGroup(self, request, context): """Get the specified group.""" <|body_0|> def UpdateGroup(self, request, context): """Replace the data for the specified group. Fai...
stack_v2_sparse_classes_36k_train_022529
3,345
permissive
[ { "docstring": "Get the specified group.", "name": "GetGroup", "signature": "def GetGroup(self, request, context)" }, { "docstring": "Replace the data for the specified group. Fails if the group does not exist.", "name": "UpdateGroup", "signature": "def UpdateGroup(self, request, context...
2
null
Implement the Python class `ErrorGroupServiceServicer` described below. Class description: Service for retrieving and updating individual error groups. Method signatures and docstrings: - def GetGroup(self, request, context): Get the specified group. - def UpdateGroup(self, request, context): Replace the data for the...
Implement the Python class `ErrorGroupServiceServicer` described below. Class description: Service for retrieving and updating individual error groups. Method signatures and docstrings: - def GetGroup(self, request, context): Get the specified group. - def UpdateGroup(self, request, context): Replace the data for the...
d897d56bce03d1fda98b79afb08264e51d46c421
<|skeleton|> class ErrorGroupServiceServicer: """Service for retrieving and updating individual error groups.""" def GetGroup(self, request, context): """Get the specified group.""" <|body_0|> def UpdateGroup(self, request, context): """Replace the data for the specified group. Fai...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ErrorGroupServiceServicer: """Service for retrieving and updating individual error groups.""" def GetGroup(self, request, context): """Get the specified group.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplem...
the_stack_v2_python_sparse
error_reporting/google/cloud/errorreporting_v1beta1/proto/error_group_service_pb2_grpc.py
tswast/google-cloud-python
train
1
bb0b96011d907fd36814a4be9b4aeb737cdd1a12
[ "if code == None:\n return json.dumps([c.__dict__ for c in Category().selectAllCategories()])\nelse:\n return json.dumps(Category().selectCategory(code).__dict__)", "if strJson != None:\n category = Category()\n category.__dict__ = json.loads(strJson)\n if category.isNew():\n category.insert...
<|body_start_0|> if code == None: return json.dumps([c.__dict__ for c in Category().selectAllCategories()]) else: return json.dumps(Category().selectCategory(code).__dict__) <|end_body_0|> <|body_start_1|> if strJson != None: category = Category() ...
Classe que controla os acessos ao cadastro de categorias.
CategoryController
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CategoryController: """Classe que controla os acessos ao cadastro de categorias.""" def GET(self, code=None): """Lista as categorias cadastradas no sistema.""" <|body_0|> def PUT(self, strJson): """Inclui ou atualiza""" <|body_1|> def DELETE(self, co...
stack_v2_sparse_classes_36k_train_022530
1,689
permissive
[ { "docstring": "Lista as categorias cadastradas no sistema.", "name": "GET", "signature": "def GET(self, code=None)" }, { "docstring": "Inclui ou atualiza", "name": "PUT", "signature": "def PUT(self, strJson)" }, { "docstring": "Apaga uma categoria do sistema.", "name": "DELE...
3
stack_v2_sparse_classes_30k_train_000104
Implement the Python class `CategoryController` described below. Class description: Classe que controla os acessos ao cadastro de categorias. Method signatures and docstrings: - def GET(self, code=None): Lista as categorias cadastradas no sistema. - def PUT(self, strJson): Inclui ou atualiza - def DELETE(self, code=N...
Implement the Python class `CategoryController` described below. Class description: Classe que controla os acessos ao cadastro de categorias. Method signatures and docstrings: - def GET(self, code=None): Lista as categorias cadastradas no sistema. - def PUT(self, strJson): Inclui ou atualiza - def DELETE(self, code=N...
bee8c9ecf4ef44ba579e4a3b58acf0c2f1467147
<|skeleton|> class CategoryController: """Classe que controla os acessos ao cadastro de categorias.""" def GET(self, code=None): """Lista as categorias cadastradas no sistema.""" <|body_0|> def PUT(self, strJson): """Inclui ou atualiza""" <|body_1|> def DELETE(self, co...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CategoryController: """Classe que controla os acessos ao cadastro de categorias.""" def GET(self, code=None): """Lista as categorias cadastradas no sistema.""" if code == None: return json.dumps([c.__dict__ for c in Category().selectAllCategories()]) else: ...
the_stack_v2_python_sparse
Back End/Controller/CategoriaController.py
jhelioreis/petnew
train
0
a99b567277147063307a96e3e32d303f9139c279
[ "form = ArtistForm({'name': '', 'artist_statement': 'test', 'image': 'test'})\nself.assertFalse(form.is_valid())\nself.assertIn('name', form.errors.keys())\nself.assertEqual(form.errors['name'][0], 'This field is required.')", "form = ArtistForm({'name': 'test', 'artist_statement': '', 'image': 'test'})\nself.ass...
<|body_start_0|> form = ArtistForm({'name': '', 'artist_statement': 'test', 'image': 'test'}) self.assertFalse(form.is_valid()) self.assertIn('name', form.errors.keys()) self.assertEqual(form.errors['name'][0], 'This field is required.') <|end_body_0|> <|body_start_1|> form = Ar...
Test that the artist form works
TestArtistForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestArtistForm: """Test that the artist form works""" def test_name_is_required(self): """Test if form submits without name field""" <|body_0|> def test_artist_statement_is_required(self): """Test if form submits without artist_statement field""" <|body_1...
stack_v2_sparse_classes_36k_train_022531
1,801
no_license
[ { "docstring": "Test if form submits without name field", "name": "test_name_is_required", "signature": "def test_name_is_required(self)" }, { "docstring": "Test if form submits without artist_statement field", "name": "test_artist_statement_is_required", "signature": "def test_artist_st...
3
stack_v2_sparse_classes_30k_train_007018
Implement the Python class `TestArtistForm` described below. Class description: Test that the artist form works Method signatures and docstrings: - def test_name_is_required(self): Test if form submits without name field - def test_artist_statement_is_required(self): Test if form submits without artist_statement fiel...
Implement the Python class `TestArtistForm` described below. Class description: Test that the artist form works Method signatures and docstrings: - def test_name_is_required(self): Test if form submits without name field - def test_artist_statement_is_required(self): Test if form submits without artist_statement fiel...
b4ef7a46708711bda460667b1f602d0bd67c0bae
<|skeleton|> class TestArtistForm: """Test that the artist form works""" def test_name_is_required(self): """Test if form submits without name field""" <|body_0|> def test_artist_statement_is_required(self): """Test if form submits without artist_statement field""" <|body_1...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestArtistForm: """Test that the artist form works""" def test_name_is_required(self): """Test if form submits without name field""" form = ArtistForm({'name': '', 'artist_statement': 'test', 'image': 'test'}) self.assertFalse(form.is_valid()) self.assertIn('name', form.er...
the_stack_v2_python_sparse
artists/test_forms.py
AmyOShea/MS4-ARTstop
train
1
bc65436d9a2bc4edf2fc88d854bc39f53fa65ad2
[ "self.fs_type = fs_type\nself.gateway = gateway\nself.protection_domain = protection_domain\nself.read_only = read_only\nself.secret_ref = secret_ref\nself.ssl_enabled = ssl_enabled\nself.storage_mode = storage_mode\nself.storage_pool = storage_pool\nself.system = system\nself.volume_name = volume_name", "if dict...
<|body_start_0|> self.fs_type = fs_type self.gateway = gateway self.protection_domain = protection_domain self.read_only = read_only self.secret_ref = secret_ref self.ssl_enabled = ssl_enabled self.storage_mode = storage_mode self.storage_pool = storage_po...
Implementation of the 'PodInfo_PodSpec_VolumeInfo_ScaleIO' model. TODO: type description here. Attributes: fs_type (string): TODO: Type description here. gateway (string): TODO: Type description here. protection_domain (string): TODO: Type description here. read_only (bool): TODO: Type description here. secret_ref (Obj...
PodInfo_PodSpec_VolumeInfo_ScaleIO
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PodInfo_PodSpec_VolumeInfo_ScaleIO: """Implementation of the 'PodInfo_PodSpec_VolumeInfo_ScaleIO' model. TODO: type description here. Attributes: fs_type (string): TODO: Type description here. gateway (string): TODO: Type description here. protection_domain (string): TODO: Type description here. ...
stack_v2_sparse_classes_36k_train_022532
3,699
permissive
[ { "docstring": "Constructor for the PodInfo_PodSpec_VolumeInfo_ScaleIO class", "name": "__init__", "signature": "def __init__(self, fs_type=None, gateway=None, protection_domain=None, read_only=None, secret_ref=None, ssl_enabled=None, storage_mode=None, storage_pool=None, system=None, volume_name=None)"...
2
null
Implement the Python class `PodInfo_PodSpec_VolumeInfo_ScaleIO` described below. Class description: Implementation of the 'PodInfo_PodSpec_VolumeInfo_ScaleIO' model. TODO: type description here. Attributes: fs_type (string): TODO: Type description here. gateway (string): TODO: Type description here. protection_domain ...
Implement the Python class `PodInfo_PodSpec_VolumeInfo_ScaleIO` described below. Class description: Implementation of the 'PodInfo_PodSpec_VolumeInfo_ScaleIO' model. TODO: type description here. Attributes: fs_type (string): TODO: Type description here. gateway (string): TODO: Type description here. protection_domain ...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class PodInfo_PodSpec_VolumeInfo_ScaleIO: """Implementation of the 'PodInfo_PodSpec_VolumeInfo_ScaleIO' model. TODO: type description here. Attributes: fs_type (string): TODO: Type description here. gateway (string): TODO: Type description here. protection_domain (string): TODO: Type description here. ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PodInfo_PodSpec_VolumeInfo_ScaleIO: """Implementation of the 'PodInfo_PodSpec_VolumeInfo_ScaleIO' model. TODO: type description here. Attributes: fs_type (string): TODO: Type description here. gateway (string): TODO: Type description here. protection_domain (string): TODO: Type description here. read_only (bo...
the_stack_v2_python_sparse
cohesity_management_sdk/models/pod_info_pod_spec_volume_info_scale_io.py
cohesity/management-sdk-python
train
24
f79227895895befb9d6477caac884e53171e7c28
[ "super().__init__(parent, Qt.FramelessWindowHint | Qt.WindowSystemMenuHint)\nself.question = str(question)\nself.style = style\nself.initUi()", "self.questionLabel = QLabel(self.question)\nself.questionLabel.setWordWrap(True)\nstyleBtn = '\\n QPushButton {\\n font-family: Asap;\\n fon...
<|body_start_0|> super().__init__(parent, Qt.FramelessWindowHint | Qt.WindowSystemMenuHint) self.question = str(question) self.style = style self.initUi() <|end_body_0|> <|body_start_1|> self.questionLabel = QLabel(self.question) self.questionLabel.setWordWrap(True) ...
Dialog to ask a question.
QuestionDialog
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QuestionDialog: """Dialog to ask a question.""" def __init__(self, parent, question, style=None): """Init.""" <|body_0|> def initUi(self): """Ui Setup.""" <|body_1|> def paintEvent(self, event): """Set window background color.""" <|bo...
stack_v2_sparse_classes_36k_train_022533
27,111
no_license
[ { "docstring": "Init.", "name": "__init__", "signature": "def __init__(self, parent, question, style=None)" }, { "docstring": "Ui Setup.", "name": "initUi", "signature": "def initUi(self)" }, { "docstring": "Set window background color.", "name": "paintEvent", "signature"...
3
stack_v2_sparse_classes_30k_train_002906
Implement the Python class `QuestionDialog` described below. Class description: Dialog to ask a question. Method signatures and docstrings: - def __init__(self, parent, question, style=None): Init. - def initUi(self): Ui Setup. - def paintEvent(self, event): Set window background color.
Implement the Python class `QuestionDialog` described below. Class description: Dialog to ask a question. Method signatures and docstrings: - def __init__(self, parent, question, style=None): Init. - def initUi(self): Ui Setup. - def paintEvent(self, event): Set window background color. <|skeleton|> class QuestionDi...
a5d18593e689123cac34af552628ed2818ca5d59
<|skeleton|> class QuestionDialog: """Dialog to ask a question.""" def __init__(self, parent, question, style=None): """Init.""" <|body_0|> def initUi(self): """Ui Setup.""" <|body_1|> def paintEvent(self, event): """Set window background color.""" <|bo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class QuestionDialog: """Dialog to ask a question.""" def __init__(self, parent, question, style=None): """Init.""" super().__init__(parent, Qt.FramelessWindowHint | Qt.WindowSystemMenuHint) self.question = str(question) self.style = style self.initUi() def initUi(s...
the_stack_v2_python_sparse
Dialogs.py
edgary777/lonchepos
train
0
98510541d5a94800927ccd29eacdf2e8a9eda1dc
[ "self._name = name or 'cms_swap'\nif holiday_calendar is None:\n holiday_calendar = dates.create_holiday_calendar(weekend_mask=dates.WeekendMask.SATURDAY_SUNDAY)\nwith tf.name_scope(self._name):\n self._dtype = dtype\n self._start_date = dates.convert_to_date_tensor(start_date)\n self._maturity_date = d...
<|body_start_0|> self._name = name or 'cms_swap' if holiday_calendar is None: holiday_calendar = dates.create_holiday_calendar(weekend_mask=dates.WeekendMask.SATURDAY_SUNDAY) with tf.name_scope(self._name): self._dtype = dtype self._start_date = dates.convert_...
Represents a batch of CMS Swaps. A CMS swap is a swap contract where the floating leg payments are based on the constant maturity swap (CMS) rate. The CMS rate refers to a future fixing of swap rate of a fixed maturity, i.e. the breakeven swap rate on a standard fixed-to-float swap of the specified maturity [1]. Let S_...
CMSSwap
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CMSSwap: """Represents a batch of CMS Swaps. A CMS swap is a swap contract where the floating leg payments are based on the constant maturity swap (CMS) rate. The CMS rate refers to a future fixing of swap rate of a fixed maturity, i.e. the breakeven swap rate on a standard fixed-to-float swap of...
stack_v2_sparse_classes_36k_train_022534
26,955
permissive
[ { "docstring": "Initialize a batch of CMS swap contracts. Args: start_date: A rank 1 `DateTensor` specifying the dates for the inception (start of the accrual) of the swap cpntracts. The shape of the input correspond to the numbercof instruments being created. maturity_date: A rank 1 `DateTensor` specifying the...
3
null
Implement the Python class `CMSSwap` described below. Class description: Represents a batch of CMS Swaps. A CMS swap is a swap contract where the floating leg payments are based on the constant maturity swap (CMS) rate. The CMS rate refers to a future fixing of swap rate of a fixed maturity, i.e. the breakeven swap ra...
Implement the Python class `CMSSwap` described below. Class description: Represents a batch of CMS Swaps. A CMS swap is a swap contract where the floating leg payments are based on the constant maturity swap (CMS) rate. The CMS rate refers to a future fixing of swap rate of a fixed maturity, i.e. the breakeven swap ra...
0d3a2193c0f2d320b65e602cf01d7a617da484df
<|skeleton|> class CMSSwap: """Represents a batch of CMS Swaps. A CMS swap is a swap contract where the floating leg payments are based on the constant maturity swap (CMS) rate. The CMS rate refers to a future fixing of swap rate of a fixed maturity, i.e. the breakeven swap rate on a standard fixed-to-float swap of...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CMSSwap: """Represents a batch of CMS Swaps. A CMS swap is a swap contract where the floating leg payments are based on the constant maturity swap (CMS) rate. The CMS rate refers to a future fixing of swap rate of a fixed maturity, i.e. the breakeven swap rate on a standard fixed-to-float swap of the specifie...
the_stack_v2_python_sparse
tf_quant_finance/experimental/instruments/cms_swap.py
google/tf-quant-finance
train
4,165
9cdedc343a3509e9a3ac40b2a79d33704c980b12
[ "need = defaultdict(int)\nwindow = defaultdict(int)\nfor c in p:\n need[c] += 1\nleft, right = (0, 0)\nvalid = 0\nres = []\nwhile right < len(s):\n c = s[right]\n right += 1\n if c in need:\n window[c] += 1\n if window[c] == need[c]:\n valid += 1\n while right - left >= len(p...
<|body_start_0|> need = defaultdict(int) window = defaultdict(int) for c in p: need[c] += 1 left, right = (0, 0) valid = 0 res = [] while right < len(s): c = s[right] right += 1 if c in need: window[c...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findAnagramsFramework(self, s, p): """:type s: str :type p: str :rtype: List[int] use the sliding window framework""" <|body_0|> def findAnagrams(self, s, p): """:type s: str :type p: str :rtype: List[int]""" <|body_1|> <|end_skeleton|> <|body...
stack_v2_sparse_classes_36k_train_022535
3,914
no_license
[ { "docstring": ":type s: str :type p: str :rtype: List[int] use the sliding window framework", "name": "findAnagramsFramework", "signature": "def findAnagramsFramework(self, s, p)" }, { "docstring": ":type s: str :type p: str :rtype: List[int]", "name": "findAnagrams", "signature": "def ...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findAnagramsFramework(self, s, p): :type s: str :type p: str :rtype: List[int] use the sliding window framework - def findAnagrams(self, s, p): :type s: str :type p: str :rty...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findAnagramsFramework(self, s, p): :type s: str :type p: str :rtype: List[int] use the sliding window framework - def findAnagrams(self, s, p): :type s: str :type p: str :rty...
810575368ecffa97677bdb51744d1f716140bbb1
<|skeleton|> class Solution: def findAnagramsFramework(self, s, p): """:type s: str :type p: str :rtype: List[int] use the sliding window framework""" <|body_0|> def findAnagrams(self, s, p): """:type s: str :type p: str :rtype: List[int]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def findAnagramsFramework(self, s, p): """:type s: str :type p: str :rtype: List[int] use the sliding window framework""" need = defaultdict(int) window = defaultdict(int) for c in p: need[c] += 1 left, right = (0, 0) valid = 0 res ...
the_stack_v2_python_sparse
F/FindAllAnagramsInAString.py
bssrdf/pyleet
train
2
3e61c8ae57ecfedb1b5cfbd62c4b2d1894894c8c
[ "self.symbol_list = context.symbol_list\nself.context = context\nself.heartbeat = context.heartbeat\nself.data_handler_cls = data_handler\nself.execution_handler_cls = execution_handler\nself.portfolio_cls = portfolio\nself.strategy_cls = strategy\nself.risk_handler_cls = risk_handler\nself.broker_handler_cls = bro...
<|body_start_0|> self.symbol_list = context.symbol_list self.context = context self.heartbeat = context.heartbeat self.data_handler_cls = data_handler self.execution_handler_cls = execution_handler self.portfolio_cls = portfolio self.strategy_cls = strategy ...
Event-driven backtest.
LiveTrader
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LiveTrader: """Event-driven backtest.""" def __init__(self, data_handler, execution_handler, portfolio, strategy, risk_handler, broker_handler, context): """. Parameters:""" <|body_0|> def _set_up(self): """Generates the trading instance objects from their classe...
stack_v2_sparse_classes_36k_train_022536
3,842
no_license
[ { "docstring": ". Parameters:", "name": "__init__", "signature": "def __init__(self, data_handler, execution_handler, portfolio, strategy, risk_handler, broker_handler, context)" }, { "docstring": "Generates the trading instance objects from their classes and sets up the trading environment.", ...
4
null
Implement the Python class `LiveTrader` described below. Class description: Event-driven backtest. Method signatures and docstrings: - def __init__(self, data_handler, execution_handler, portfolio, strategy, risk_handler, broker_handler, context): . Parameters: - def _set_up(self): Generates the trading instance obje...
Implement the Python class `LiveTrader` described below. Class description: Event-driven backtest. Method signatures and docstrings: - def __init__(self, data_handler, execution_handler, portfolio, strategy, risk_handler, broker_handler, context): . Parameters: - def _set_up(self): Generates the trading instance obje...
1b88117961a3912aa9b2c0326aa5081a884d0a8d
<|skeleton|> class LiveTrader: """Event-driven backtest.""" def __init__(self, data_handler, execution_handler, portfolio, strategy, risk_handler, broker_handler, context): """. Parameters:""" <|body_0|> def _set_up(self): """Generates the trading instance objects from their classe...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LiveTrader: """Event-driven backtest.""" def __init__(self, data_handler, execution_handler, portfolio, strategy, risk_handler, broker_handler, context): """. Parameters:""" self.symbol_list = context.symbol_list self.context = context self.heartbeat = context.heartbeat ...
the_stack_v2_python_sparse
htr/core/engines/live_trader.py
mglcampos/trader
train
0
5e0bb01d74bbd6f718e89f791108781631760596
[ "yes_to_all = force_import_from_game\nfor data_type in self.DATA_TYPES:\n yes_to_all = self.import_data_type(data_type, force_import_from_game, yes_to_all, with_window=with_window)\n if data_type == 'maps' and first_time and (self.maps is not None):\n archives_msb = self.maps.DukesArchives\n rep...
<|body_start_0|> yes_to_all = force_import_from_game for data_type in self.DATA_TYPES: yes_to_all = self.import_data_type(data_type, force_import_from_game, yes_to_all, with_window=with_window) if data_type == 'maps' and first_time and (self.maps is not None): arc...
GameDirectoryProject
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GameDirectoryProject: def initialize_project(self, force_import_from_game=False, with_window: ProjectWindow=None, first_time=False): """Also offer to translate events/regions with entity IDs and export entities modules.""" <|body_0|> def offer_fix_broken_regions(self, with_w...
stack_v2_sparse_classes_36k_train_022537
6,562
no_license
[ { "docstring": "Also offer to translate events/regions with entity IDs and export entities modules.", "name": "initialize_project", "signature": "def initialize_project(self, force_import_from_game=False, with_window: ProjectWindow=None, first_time=False)" }, { "docstring": "Offer to fix broken ...
4
stack_v2_sparse_classes_30k_test_000167
Implement the Python class `GameDirectoryProject` described below. Class description: Implement the GameDirectoryProject class. Method signatures and docstrings: - def initialize_project(self, force_import_from_game=False, with_window: ProjectWindow=None, first_time=False): Also offer to translate events/regions with...
Implement the Python class `GameDirectoryProject` described below. Class description: Implement the GameDirectoryProject class. Method signatures and docstrings: - def initialize_project(self, force_import_from_game=False, with_window: ProjectWindow=None, first_time=False): Also offer to translate events/regions with...
88693c0015056ee8e3d1dbcb795c05fca4349e38
<|skeleton|> class GameDirectoryProject: def initialize_project(self, force_import_from_game=False, with_window: ProjectWindow=None, first_time=False): """Also offer to translate events/regions with entity IDs and export entities modules.""" <|body_0|> def offer_fix_broken_regions(self, with_w...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GameDirectoryProject: def initialize_project(self, force_import_from_game=False, with_window: ProjectWindow=None, first_time=False): """Also offer to translate events/regions with entity IDs and export entities modules.""" yes_to_all = force_import_from_game for data_type in self.DATA_...
the_stack_v2_python_sparse
soulstruct/darksouls1r/project/core.py
Nahnahchi/soulstruct
train
0
afc9fd6acedf961760e56df85b34507f4857611f
[ "if name not in Replacements._rep:\n return None\nreturn Replacements._rep[name]", "if otherclass is None:\n otherclass = classname\nif (classname, otherclass, optype) not in Replacements._oprep:\n return None\nreturn Replacements._oprep[classname, otherclass, optype]" ]
<|body_start_0|> if name not in Replacements._rep: return None return Replacements._rep[name] <|end_body_0|> <|body_start_1|> if otherclass is None: otherclass = classname if (classname, otherclass, optype) not in Replacements._oprep: return None ...
A management singleton for functions that replace existing function calls with either an SDFG or a node. Used in the Python frontend to replace functions such as `numpy.ndarray` and operators such as `Array.__add__`.
Replacements
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Replacements: """A management singleton for functions that replace existing function calls with either an SDFG or a node. Used in the Python frontend to replace functions such as `numpy.ndarray` and operators such as `Array.__add__`.""" def get(name): """Returns an implementation of ...
stack_v2_sparse_classes_36k_train_022538
2,356
permissive
[ { "docstring": "Returns an implementation of a function.", "name": "get", "signature": "def get(name)" }, { "docstring": "Returns an implementation of an operator.", "name": "getop", "signature": "def getop(classname: str, optype: str, otherclass: str=None)" } ]
2
null
Implement the Python class `Replacements` described below. Class description: A management singleton for functions that replace existing function calls with either an SDFG or a node. Used in the Python frontend to replace functions such as `numpy.ndarray` and operators such as `Array.__add__`. Method signatures and d...
Implement the Python class `Replacements` described below. Class description: A management singleton for functions that replace existing function calls with either an SDFG or a node. Used in the Python frontend to replace functions such as `numpy.ndarray` and operators such as `Array.__add__`. Method signatures and d...
4d65e0951c112160fe783766404a806b6043b521
<|skeleton|> class Replacements: """A management singleton for functions that replace existing function calls with either an SDFG or a node. Used in the Python frontend to replace functions such as `numpy.ndarray` and operators such as `Array.__add__`.""" def get(name): """Returns an implementation of ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Replacements: """A management singleton for functions that replace existing function calls with either an SDFG or a node. Used in the Python frontend to replace functions such as `numpy.ndarray` and operators such as `Array.__add__`.""" def get(name): """Returns an implementation of a function.""...
the_stack_v2_python_sparse
dace/frontend/common/op_repository.py
1C4nfaN/dace
train
1
138a97d2124d1e38e875f47a964e795cc7f712fb
[ "results = []\ndbUtil = MsqlTools()\npageNo = (page - 1) * limit\nif logName == '':\n sql = string.Template('select * from t_log order by operation_time $sortOrder limit $pageNo,$limit;')\n sql = sql.substitute(pageNo=pageNo, limit=limit, sortOrder=sortOrder)\n items = MsqlTools.get_all(dbUtil, sql)\n s...
<|body_start_0|> results = [] dbUtil = MsqlTools() pageNo = (page - 1) * limit if logName == '': sql = string.Template('select * from t_log order by operation_time $sortOrder limit $pageNo,$limit;') sql = sql.substitute(pageNo=pageNo, limit=limit, sortOrder=sortOr...
db_log_list
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class db_log_list: def show_log_list(self, page, limit, sortOrder, logName): """查询t_user表所有数据""" <|body_0|> def add_log(self, log_name, operation_type, operation_status, log_describes): """添加日志 :return:""" <|body_1|> def sector_user(self, login_name): ...
stack_v2_sparse_classes_36k_train_022539
3,370
no_license
[ { "docstring": "查询t_user表所有数据", "name": "show_log_list", "signature": "def show_log_list(self, page, limit, sortOrder, logName)" }, { "docstring": "添加日志 :return:", "name": "add_log", "signature": "def add_log(self, log_name, operation_type, operation_status, log_describes)" }, { ...
3
stack_v2_sparse_classes_30k_train_006131
Implement the Python class `db_log_list` described below. Class description: Implement the db_log_list class. Method signatures and docstrings: - def show_log_list(self, page, limit, sortOrder, logName): 查询t_user表所有数据 - def add_log(self, log_name, operation_type, operation_status, log_describes): 添加日志 :return: - def ...
Implement the Python class `db_log_list` described below. Class description: Implement the db_log_list class. Method signatures and docstrings: - def show_log_list(self, page, limit, sortOrder, logName): 查询t_user表所有数据 - def add_log(self, log_name, operation_type, operation_status, log_describes): 添加日志 :return: - def ...
64ced2b9bd1fe9503521024ea2ddc05efc21f969
<|skeleton|> class db_log_list: def show_log_list(self, page, limit, sortOrder, logName): """查询t_user表所有数据""" <|body_0|> def add_log(self, log_name, operation_type, operation_status, log_describes): """添加日志 :return:""" <|body_1|> def sector_user(self, login_name): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class db_log_list: def show_log_list(self, page, limit, sortOrder, logName): """查询t_user表所有数据""" results = [] dbUtil = MsqlTools() pageNo = (page - 1) * limit if logName == '': sql = string.Template('select * from t_log order by operation_time $sortOrder limit $pa...
the_stack_v2_python_sparse
app/db/db_log_list.py
fzj123/auto_test_platform-master
train
0
5ffb6c30f4adf86f2d0c3d37d0ec642935186672
[ "data = get_enum_row_by_id(pk)\nif not data:\n raise NotFound\nresult = marshal(data, fields_item_enum_cn, envelope=structure_key_item_cn)\nreturn jsonify(result)", "result = delete_enum(pk)\nif result:\n success_msg = SUCCESS_MSG.copy()\n return make_response(jsonify(success_msg), 204)\nelse:\n failu...
<|body_start_0|> data = get_enum_row_by_id(pk) if not data: raise NotFound result = marshal(data, fields_item_enum_cn, envelope=structure_key_item_cn) return jsonify(result) <|end_body_0|> <|body_start_1|> result = delete_enum(pk) if result: succe...
EnumResource
EnumResource
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EnumResource: """EnumResource""" def get(self, pk): """Example: curl http://0.0.0.0:5000/yonyou/enum/1 :param pk: :return:""" <|body_0|> def delete(self, pk): """Example: curl http://0.0.0.0:5000/yonyou/enum/1 -X DELETE :param pk: :return:""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_022540
3,553
permissive
[ { "docstring": "Example: curl http://0.0.0.0:5000/yonyou/enum/1 :param pk: :return:", "name": "get", "signature": "def get(self, pk)" }, { "docstring": "Example: curl http://0.0.0.0:5000/yonyou/enum/1 -X DELETE :param pk: :return:", "name": "delete", "signature": "def delete(self, pk)" ...
2
stack_v2_sparse_classes_30k_train_015876
Implement the Python class `EnumResource` described below. Class description: EnumResource Method signatures and docstrings: - def get(self, pk): Example: curl http://0.0.0.0:5000/yonyou/enum/1 :param pk: :return: - def delete(self, pk): Example: curl http://0.0.0.0:5000/yonyou/enum/1 -X DELETE :param pk: :return:
Implement the Python class `EnumResource` described below. Class description: EnumResource Method signatures and docstrings: - def get(self, pk): Example: curl http://0.0.0.0:5000/yonyou/enum/1 :param pk: :return: - def delete(self, pk): Example: curl http://0.0.0.0:5000/yonyou/enum/1 -X DELETE :param pk: :return: <...
6ef54f3f7efbbaff6169e963dcf45ab25e11e593
<|skeleton|> class EnumResource: """EnumResource""" def get(self, pk): """Example: curl http://0.0.0.0:5000/yonyou/enum/1 :param pk: :return:""" <|body_0|> def delete(self, pk): """Example: curl http://0.0.0.0:5000/yonyou/enum/1 -X DELETE :param pk: :return:""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EnumResource: """EnumResource""" def get(self, pk): """Example: curl http://0.0.0.0:5000/yonyou/enum/1 :param pk: :return:""" data = get_enum_row_by_id(pk) if not data: raise NotFound result = marshal(data, fields_item_enum_cn, envelope=structure_key_item_cn) ...
the_stack_v2_python_sparse
web_api/yonyou/resources/enum.py
zhanghe06/flask_restful
train
2
d9fbd616b087fbbc8ac4e7ebfa1e627b08f9d304
[ "if isinstance(data, Log):\n data = data.log\nmodel = LogModel(**data)\ndb.session.add(model)\ndb.session.commit()\nreturn model.id", "id = data.get('id')\nresult = LogModel.query.get(id)\nsoft_delete(result)", "report_id = data.get('id')\nlogid = data.get('logid')\ntry:\n offset = int(data.get('offset', ...
<|body_start_0|> if isinstance(data, Log): data = data.log model = LogModel(**data) db.session.add(model) db.session.commit() return model.id <|end_body_0|> <|body_start_1|> id = data.get('id') result = LogModel.query.get(id) soft_delete(resul...
LogService
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LogService: def create(self, data): """:param data: :return:""" <|body_0|> def delete(self, data): """:param data: :return:""" <|body_1|> def search(self, data): """:param data: :return:""" <|body_2|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_022541
1,434
permissive
[ { "docstring": ":param data: :return:", "name": "create", "signature": "def create(self, data)" }, { "docstring": ":param data: :return:", "name": "delete", "signature": "def delete(self, data)" }, { "docstring": ":param data: :return:", "name": "search", "signature": "de...
3
stack_v2_sparse_classes_30k_train_004962
Implement the Python class `LogService` described below. Class description: Implement the LogService class. Method signatures and docstrings: - def create(self, data): :param data: :return: - def delete(self, data): :param data: :return: - def search(self, data): :param data: :return:
Implement the Python class `LogService` described below. Class description: Implement the LogService class. Method signatures and docstrings: - def create(self, data): :param data: :return: - def delete(self, data): :param data: :return: - def search(self, data): :param data: :return: <|skeleton|> class LogService: ...
54dc4000263ab9e8873f0d429a7fe48b11fb727a
<|skeleton|> class LogService: def create(self, data): """:param data: :return:""" <|body_0|> def delete(self, data): """:param data: :return:""" <|body_1|> def search(self, data): """:param data: :return:""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LogService: def create(self, data): """:param data: :return:""" if isinstance(data, Log): data = data.log model = LogModel(**data) db.session.add(model) db.session.commit() return model.id def delete(self, data): """:param data: :return:...
the_stack_v2_python_sparse
clover/log/service.py
taoyanli0808/clover
train
18
9dd91f29b7ba52fd1bfd24c1d4b5b34cd28d60c7
[ "compiler = cls(filename)\ncompiler.visit(node)\nreturn compiler.stack.pop()", "self.filename = filename\nself.block = '<undefined>'\nself.stack = []", "self.block = node.name\nobj = {'enamldef': True, 'type': node.name, 'base': node.base, 'doc': node.doc, 'lineno': node.lineno, 'identifier': node.identifier, '...
<|body_start_0|> compiler = cls(filename) compiler.visit(node) return compiler.stack.pop() <|end_body_0|> <|body_start_1|> self.filename = filename self.block = '<undefined>' self.stack = [] <|end_body_1|> <|body_start_2|> self.block = node.name obj = {'...
A visitor which compiles a Declaration node into a code object.
DeclarationCompiler
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DeclarationCompiler: """A visitor which compiles a Declaration node into a code object.""" def compile(cls, node, filename): """The main entry point of the DeclarationCompiler. This compiler compiles the given Declaration node into a description dictionary which can be used to build ...
stack_v2_sparse_classes_36k_train_022542
24,020
permissive
[ { "docstring": "The main entry point of the DeclarationCompiler. This compiler compiles the given Declaration node into a description dictionary which can be used to build out the component tree at run time. Top assist with debugging, every production generated by the compiler has the filename, lineno, and bloc...
6
stack_v2_sparse_classes_30k_train_015404
Implement the Python class `DeclarationCompiler` described below. Class description: A visitor which compiles a Declaration node into a code object. Method signatures and docstrings: - def compile(cls, node, filename): The main entry point of the DeclarationCompiler. This compiler compiles the given Declaration node ...
Implement the Python class `DeclarationCompiler` described below. Class description: A visitor which compiles a Declaration node into a code object. Method signatures and docstrings: - def compile(cls, node, filename): The main entry point of the DeclarationCompiler. This compiler compiles the given Declaration node ...
424bba29219de58fe9e47196de6763de8b2009f2
<|skeleton|> class DeclarationCompiler: """A visitor which compiles a Declaration node into a code object.""" def compile(cls, node, filename): """The main entry point of the DeclarationCompiler. This compiler compiles the given Declaration node into a description dictionary which can be used to build ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DeclarationCompiler: """A visitor which compiles a Declaration node into a code object.""" def compile(cls, node, filename): """The main entry point of the DeclarationCompiler. This compiler compiles the given Declaration node into a description dictionary which can be used to build out the compo...
the_stack_v2_python_sparse
enaml/core/enaml_compiler.py
enthought/enaml
train
17
df14c2c069f5f8b9cde8c3ffdc05492e8294cb72
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn Schema()", "from ..entity import Entity\nfrom .property_ import Property_\nfrom ..entity import Entity\nfrom .property_ import Property_\nfields: Dict[str, Callable[[Any], None]] = {'baseType': lambda n: setattr(self, 'base_type', n.ge...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return Schema() <|end_body_0|> <|body_start_1|> from ..entity import Entity from .property_ import Property_ from ..entity import Entity from .property_ import Property_ ...
Schema
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Schema: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Schema: """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: Schema""" ...
stack_v2_sparse_classes_36k_train_022543
2,452
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: Schema", "name": "create_from_discriminator_value", "signature": "def create_from_discriminator_value(parse_...
3
stack_v2_sparse_classes_30k_train_008692
Implement the Python class `Schema` described below. Class description: Implement the Schema class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Schema: Creates a new instance of the appropriate class based on discriminator value Args: parse_node: Th...
Implement the Python class `Schema` described below. Class description: Implement the Schema class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Schema: Creates a new instance of the appropriate class based on discriminator value Args: parse_node: Th...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class Schema: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Schema: """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: Schema""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Schema: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Schema: """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: Schema""" if not p...
the_stack_v2_python_sparse
msgraph/generated/models/external_connectors/schema.py
microsoftgraph/msgraph-sdk-python
train
135
affaba8fe4d4818a8879fc88b03017d526f7a3e8
[ "if flask.current_app:\n return flask.g\nelse:\n logger.warning('No current_app, falling back to non-threadsafe database connection')\n return cls", "holder = cls._holder()\nif not getattr(holder, '_db', None):\n holder._db = db_connection()\nreturn holder._db", "holder = cls._holder()\nif hasattr(h...
<|body_start_0|> if flask.current_app: return flask.g else: logger.warning('No current_app, falling back to non-threadsafe database connection') return cls <|end_body_0|> <|body_start_1|> holder = cls._holder() if not getattr(holder, '_db', None): ...
GlobalDB
[ "CC0-1.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GlobalDB: def _holder(cls): """We generally want to work in the `g` context (i.e. per request), but there are paths through the app which won't have access. In those situations, fall back to the non-threadsafe static member approach""" <|body_0|> def db(cls): """Buil...
stack_v2_sparse_classes_36k_train_022544
2,596
permissive
[ { "docstring": "We generally want to work in the `g` context (i.e. per request), but there are paths through the app which won't have access. In those situations, fall back to the non-threadsafe static member approach", "name": "_holder", "signature": "def _holder(cls)" }, { "docstring": "Build ...
3
null
Implement the Python class `GlobalDB` described below. Class description: Implement the GlobalDB class. Method signatures and docstrings: - def _holder(cls): We generally want to work in the `g` context (i.e. per request), but there are paths through the app which won't have access. In those situations, fall back to ...
Implement the Python class `GlobalDB` described below. Class description: Implement the GlobalDB class. Method signatures and docstrings: - def _holder(cls): We generally want to work in the `g` context (i.e. per request), but there are paths through the app which won't have access. In those situations, fall back to ...
b12c73976fd7eb5728eda90e56e053759c733c35
<|skeleton|> class GlobalDB: def _holder(cls): """We generally want to work in the `g` context (i.e. per request), but there are paths through the app which won't have access. In those situations, fall back to the non-threadsafe static member approach""" <|body_0|> def db(cls): """Buil...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GlobalDB: def _holder(cls): """We generally want to work in the `g` context (i.e. per request), but there are paths through the app which won't have access. In those situations, fall back to the non-threadsafe static member approach""" if flask.current_app: return flask.g e...
the_stack_v2_python_sparse
dataactcore/interfaces/db.py
fedspendingtransparency/data-act-broker-backend
train
55
cefbd0464db5762ad670394baf0502c961302603
[ "self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100')\nself.filtry = Caffe.objects.create(name='filtry', city='Warszawa', street='Filry', house_number='14', postal_code='44-100')\nfirst_cat = Category.objects.create(name='first', caffe=self.caff...
<|body_start_0|> self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100') self.filtry = Caffe.objects.create(name='filtry', city='Warszawa', street='Filry', house_number='14', postal_code='44-100') first_cat = Category.objects.cr...
FullProduct tests.
FullProductModelTest
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FullProductModelTest: """FullProduct tests.""" def setUp(self): """Test data setup.""" <|body_0|> def test_full_product(self): """Test creating FullProducts.""" <|body_1|> def test_fullproduct_validation(self): """Check if FullProduct has pro...
stack_v2_sparse_classes_36k_train_022545
14,711
permissive
[ { "docstring": "Test data setup.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Test creating FullProducts.", "name": "test_full_product", "signature": "def test_full_product(self)" }, { "docstring": "Check if FullProduct has proper validation.", "name":...
3
stack_v2_sparse_classes_30k_val_000375
Implement the Python class `FullProductModelTest` described below. Class description: FullProduct tests. Method signatures and docstrings: - def setUp(self): Test data setup. - def test_full_product(self): Test creating FullProducts. - def test_fullproduct_validation(self): Check if FullProduct has proper validation.
Implement the Python class `FullProductModelTest` described below. Class description: FullProduct tests. Method signatures and docstrings: - def setUp(self): Test data setup. - def test_full_product(self): Test creating FullProducts. - def test_fullproduct_validation(self): Check if FullProduct has proper validation....
cdb7f5edb29255c7e874eaa6231621063210a8b0
<|skeleton|> class FullProductModelTest: """FullProduct tests.""" def setUp(self): """Test data setup.""" <|body_0|> def test_full_product(self): """Test creating FullProducts.""" <|body_1|> def test_fullproduct_validation(self): """Check if FullProduct has pro...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FullProductModelTest: """FullProduct tests.""" def setUp(self): """Test data setup.""" self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100') self.filtry = Caffe.objects.create(name='filtry', city='Warszawa', str...
the_stack_v2_python_sparse
caffe/reports/test_models.py
VirrageS/io-kawiarnie
train
3
337dc67ed4620a488f66b001d77dd9753dde6486
[ "try:\n exception = request.json\n (services.log_service().upsert_exception(exception), 201)\nexcept Exception as e:\n nsp.abort(500, 'An internal error has occurred: {}'.format(e))", "try:\n exception = request.json\n (services.log_service().upsert_exception(exception), 204)\nexcept Exception as e...
<|body_start_0|> try: exception = request.json (services.log_service().upsert_exception(exception), 201) except Exception as e: nsp.abort(500, 'An internal error has occurred: {}'.format(e)) <|end_body_0|> <|body_start_1|> try: exception = request...
Exception
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Exception: def post(self): """Insert a new exception log""" <|body_0|> def put(self): """Update an exception object by it's id.""" <|body_1|> <|end_skeleton|> <|body_start_0|> try: exception = request.json (services.log_servi...
stack_v2_sparse_classes_36k_train_022546
4,427
no_license
[ { "docstring": "Insert a new exception log", "name": "post", "signature": "def post(self)" }, { "docstring": "Update an exception object by it's id.", "name": "put", "signature": "def put(self)" } ]
2
stack_v2_sparse_classes_30k_train_007215
Implement the Python class `Exception` described below. Class description: Implement the Exception class. Method signatures and docstrings: - def post(self): Insert a new exception log - def put(self): Update an exception object by it's id.
Implement the Python class `Exception` described below. Class description: Implement the Exception class. Method signatures and docstrings: - def post(self): Insert a new exception log - def put(self): Update an exception object by it's id. <|skeleton|> class Exception: def post(self): """Insert a new e...
df826cf7098aee59e0a1ced6f465c2e8bb3df9a5
<|skeleton|> class Exception: def post(self): """Insert a new exception log""" <|body_0|> def put(self): """Update an exception object by it's id.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Exception: def post(self): """Insert a new exception log""" try: exception = request.json (services.log_service().upsert_exception(exception), 201) except Exception as e: nsp.abort(500, 'An internal error has occurred: {}'.format(e)) def put(sel...
the_stack_v2_python_sparse
patient_portal/patient_portal/api/logs.py
bkh148/patient-cloud
train
0
39d06fdee411c634ee53e07a1ceda24cefca13b4
[ "super().__init__()\nself.downsampler = nn.AvgPool1d(4, stride=2, padding=1, count_include_pad=False)\nself.discriminators = nn.ModuleDict()\nfor idx in range(discriminator_number):\n self.discriminators[f'disc_{idx}'] = DiscriminatorBlock(downsampling_factor=downsampling_factor)", "output = []\nfor name, desc...
<|body_start_0|> super().__init__() self.downsampler = nn.AvgPool1d(4, stride=2, padding=1, count_include_pad=False) self.discriminators = nn.ModuleDict() for idx in range(discriminator_number): self.discriminators[f'disc_{idx}'] = DiscriminatorBlock(downsampling_factor=downs...
Discriminator model for MelGAN
Discriminator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Discriminator: """Discriminator model for MelGAN""" def __init__(self, discriminator_number: int=3, downsampling_factor: int=4): """Discriminator model for MelGAN Consists of several discriminators with various downsampling factors. Base discriminator consists only of convolutional l...
stack_v2_sparse_classes_36k_train_022547
4,148
no_license
[ { "docstring": "Discriminator model for MelGAN Consists of several discriminators with various downsampling factors. Base discriminator consists only of convolutional layers. Args: discriminator_number: number of discriminator blocks downsampling_factor: downsampling factor for every discriminator block.", ...
2
stack_v2_sparse_classes_30k_train_012327
Implement the Python class `Discriminator` described below. Class description: Discriminator model for MelGAN Method signatures and docstrings: - def __init__(self, discriminator_number: int=3, downsampling_factor: int=4): Discriminator model for MelGAN Consists of several discriminators with various downsampling fac...
Implement the Python class `Discriminator` described below. Class description: Discriminator model for MelGAN Method signatures and docstrings: - def __init__(self, discriminator_number: int=3, downsampling_factor: int=4): Discriminator model for MelGAN Consists of several discriminators with various downsampling fac...
d5eac1cfb7d382c26d9e1961e443941410e1c1ba
<|skeleton|> class Discriminator: """Discriminator model for MelGAN""" def __init__(self, discriminator_number: int=3, downsampling_factor: int=4): """Discriminator model for MelGAN Consists of several discriminators with various downsampling factors. Base discriminator consists only of convolutional l...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Discriminator: """Discriminator model for MelGAN""" def __init__(self, discriminator_number: int=3, downsampling_factor: int=4): """Discriminator model for MelGAN Consists of several discriminators with various downsampling factors. Base discriminator consists only of convolutional layers. Args: ...
the_stack_v2_python_sparse
src/models/discriminator.py
elephantmipt/MelGAN
train
6
27e37ed6be765abaa07ff4a912dfa1972a82dc2e
[ "self.end_time_usecs = end_time_usecs\nself.environment = environment\nself.job_uids = job_uids\nself.protection_source_id = protection_source_id\nself.start_time_usecs = start_time_usecs", "if dictionary is None:\n return None\nend_time_usecs = dictionary.get('endTimeUsecs')\nenvironment = dictionary.get('env...
<|body_start_0|> self.end_time_usecs = end_time_usecs self.environment = environment self.job_uids = job_uids self.protection_source_id = protection_source_id self.start_time_usecs = start_time_usecs <|end_body_0|> <|body_start_1|> if dictionary is None: retu...
Implementation of the 'RestorePointsForTimeRangeParam' model. Specifies the request parameters to restore points for time range API. Attributes: end_time_usecs (long|int): Specifies the end time specified as a Unix epoch Timestamp (in microseconds). environment (EnvironmentRestorePointsForTimeRangeParamEnum): Specifies...
RestorePointsForTimeRangeParam
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RestorePointsForTimeRangeParam: """Implementation of the 'RestorePointsForTimeRangeParam' model. Specifies the request parameters to restore points for time range API. Attributes: end_time_usecs (long|int): Specifies the end time specified as a Unix epoch Timestamp (in microseconds). environment ...
stack_v2_sparse_classes_36k_train_022548
6,957
permissive
[ { "docstring": "Constructor for the RestorePointsForTimeRangeParam class", "name": "__init__", "signature": "def __init__(self, end_time_usecs=None, environment=None, job_uids=None, protection_source_id=None, start_time_usecs=None)" }, { "docstring": "Creates an instance of this model from a dic...
2
null
Implement the Python class `RestorePointsForTimeRangeParam` described below. Class description: Implementation of the 'RestorePointsForTimeRangeParam' model. Specifies the request parameters to restore points for time range API. Attributes: end_time_usecs (long|int): Specifies the end time specified as a Unix epoch Ti...
Implement the Python class `RestorePointsForTimeRangeParam` described below. Class description: Implementation of the 'RestorePointsForTimeRangeParam' model. Specifies the request parameters to restore points for time range API. Attributes: end_time_usecs (long|int): Specifies the end time specified as a Unix epoch Ti...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class RestorePointsForTimeRangeParam: """Implementation of the 'RestorePointsForTimeRangeParam' model. Specifies the request parameters to restore points for time range API. Attributes: end_time_usecs (long|int): Specifies the end time specified as a Unix epoch Timestamp (in microseconds). environment ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RestorePointsForTimeRangeParam: """Implementation of the 'RestorePointsForTimeRangeParam' model. Specifies the request parameters to restore points for time range API. Attributes: end_time_usecs (long|int): Specifies the end time specified as a Unix epoch Timestamp (in microseconds). environment (EnvironmentR...
the_stack_v2_python_sparse
cohesity_management_sdk/models/restore_points_for_time_range_param.py
cohesity/management-sdk-python
train
24
a9597c3c329e90b11761a1dc46619a08794f40fe
[ "self.FLAGS = FLAGS\nself.input = input_\nself.labels = labels\nself.loss = None\nself.predict = None\nself.train_step = None\nself.evaluation = None", "with tf.name_scope('architecture'):\n self.predict = self.architecture()\nwith tf.name_scope('loss'):\n self.loss = self.calc_loss()\nwith tf.name_scope('t...
<|body_start_0|> self.FLAGS = FLAGS self.input = input_ self.labels = labels self.loss = None self.predict = None self.train_step = None self.evaluation = None <|end_body_0|> <|body_start_1|> with tf.name_scope('architecture'): self.predict = ...
This class represents convolutional network for mnist
DeepMnist
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DeepMnist: """This class represents convolutional network for mnist""" def __init__(self, input_, labels, FLAGS): """Constructor""" <|body_0|> def build(self): """build model""" <|body_1|> def architecture(self): """From tensorflow website de...
stack_v2_sparse_classes_36k_train_022549
5,072
no_license
[ { "docstring": "Constructor", "name": "__init__", "signature": "def __init__(self, input_, labels, FLAGS)" }, { "docstring": "build model", "name": "build", "signature": "def build(self)" }, { "docstring": "From tensorflow website deepnn builds the graph for a deep net for classi...
6
stack_v2_sparse_classes_30k_train_004485
Implement the Python class `DeepMnist` described below. Class description: This class represents convolutional network for mnist Method signatures and docstrings: - def __init__(self, input_, labels, FLAGS): Constructor - def build(self): build model - def architecture(self): From tensorflow website deepnn builds the...
Implement the Python class `DeepMnist` described below. Class description: This class represents convolutional network for mnist Method signatures and docstrings: - def __init__(self, input_, labels, FLAGS): Constructor - def build(self): build model - def architecture(self): From tensorflow website deepnn builds the...
284774a13bb155770ac0576e3624ff528e73cb18
<|skeleton|> class DeepMnist: """This class represents convolutional network for mnist""" def __init__(self, input_, labels, FLAGS): """Constructor""" <|body_0|> def build(self): """build model""" <|body_1|> def architecture(self): """From tensorflow website de...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DeepMnist: """This class represents convolutional network for mnist""" def __init__(self, input_, labels, FLAGS): """Constructor""" self.FLAGS = FLAGS self.input = input_ self.labels = labels self.loss = None self.predict = None self.train_step = No...
the_stack_v2_python_sparse
tutorial/mnist_conv.py
shohad25/thesis
train
0
6c064f3a5b767547fc49ee2eef89b62a6f47a332
[ "params = base.get_params(None, locals())\nrequest = http.Request('GET', self.get_url(), params)\nreturn (request, parsers.parse_json)", "params = base.get_params(None, locals())\nrequest = http.Request('DELETE', self.get_url(), params)\nreturn (request, parsers.parse_json)" ]
<|body_start_0|> params = base.get_params(None, locals()) request = http.Request('GET', self.get_url(), params) return (request, parsers.parse_json) <|end_body_0|> <|body_start_1|> params = base.get_params(None, locals()) request = http.Request('DELETE', self.get_url(), params) ...
Filters
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Filters: def get(self, type=None): """Returns all filters. Upstream documentation: https://developers.pipedrive.com/v1#methods-Filters""" <|body_0|> def delete(self, ids): """Marks multiple filters as deleted. Upstream documentation: https://developers.pipedrive.com/...
stack_v2_sparse_classes_36k_train_022550
1,086
permissive
[ { "docstring": "Returns all filters. Upstream documentation: https://developers.pipedrive.com/v1#methods-Filters", "name": "get", "signature": "def get(self, type=None)" }, { "docstring": "Marks multiple filters as deleted. Upstream documentation: https://developers.pipedrive.com/v1#methods-Filt...
2
null
Implement the Python class `Filters` described below. Class description: Implement the Filters class. Method signatures and docstrings: - def get(self, type=None): Returns all filters. Upstream documentation: https://developers.pipedrive.com/v1#methods-Filters - def delete(self, ids): Marks multiple filters as delete...
Implement the Python class `Filters` described below. Class description: Implement the Filters class. Method signatures and docstrings: - def get(self, type=None): Returns all filters. Upstream documentation: https://developers.pipedrive.com/v1#methods-Filters - def delete(self, ids): Marks multiple filters as delete...
25caa745a104c8dc209584fa359294c65dbf88bb
<|skeleton|> class Filters: def get(self, type=None): """Returns all filters. Upstream documentation: https://developers.pipedrive.com/v1#methods-Filters""" <|body_0|> def delete(self, ids): """Marks multiple filters as deleted. Upstream documentation: https://developers.pipedrive.com/...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Filters: def get(self, type=None): """Returns all filters. Upstream documentation: https://developers.pipedrive.com/v1#methods-Filters""" params = base.get_params(None, locals()) request = http.Request('GET', self.get_url(), params) return (request, parsers.parse_json) def...
the_stack_v2_python_sparse
libsaas/services/pipedrive/filters.py
piplcom/libsaas
train
1
5ba168808aada276dad4aad1a07b340dfb890745
[ "self.deque = collections.deque([])\nself.dic = {}\nself.capacity = capacity", "if key not in self.dic:\n return -1\nself.deque.remove(key)\nself.deque.append(key)\nreturn self.dic[key]", "if key in self.dic:\n self.deque.remove(key)\nelif len(self.dic) == self.capacity:\n v = self.deque.popleft()\n ...
<|body_start_0|> self.deque = collections.deque([]) self.dic = {} self.capacity = capacity <|end_body_0|> <|body_start_1|> if key not in self.dic: return -1 self.deque.remove(key) self.deque.append(key) return self.dic[key] <|end_body_1|> <|body_star...
LRUCache
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:rtype: int""" <|body_1|> def set(self, key, value): """:type key: int :type value: int :rtype: nothing""" <|body_2|> <|end_skeleton|> <...
stack_v2_sparse_classes_36k_train_022551
2,684
no_license
[ { "docstring": ":type capacity: int", "name": "__init__", "signature": "def __init__(self, capacity)" }, { "docstring": ":rtype: int", "name": "get", "signature": "def get(self, key)" }, { "docstring": ":type key: int :type value: int :rtype: nothing", "name": "set", "sig...
3
stack_v2_sparse_classes_30k_train_000261
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :rtype: int - def set(self, key, value): :type key: int :type value: int :rtype: nothing
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :rtype: int - def set(self, key, value): :type key: int :type value: int :rtype: nothing <|skeleton|> cla...
9b82e3bd1b404e3cff31469986577ceec3924f73
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:rtype: int""" <|body_1|> def set(self, key, value): """:type key: int :type value: int :rtype: nothing""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LRUCache: def __init__(self, capacity): """:type capacity: int""" self.deque = collections.deque([]) self.dic = {} self.capacity = capacity def get(self, key): """:rtype: int""" if key not in self.dic: return -1 self.deque.remove(key) ...
the_stack_v2_python_sparse
Python/146. LRU Cache.py
Qiumy/leetcode
train
0
0f3241d2f903e0e00fa0abcd291bec7d9d73ae7c
[ "super(EncoderLayer, self).__init__()\nwith self.init_scope():\n self.self_attn = MultiHeadAttention(n_units, h, dropout=dropout, initialW=initialW, initial_bias=initial_bias)\n self.feed_forward = PositionwiseFeedForward(n_units, d_units=d_units, dropout=dropout, initialW=initialW, initial_bias=initial_bias)...
<|body_start_0|> super(EncoderLayer, self).__init__() with self.init_scope(): self.self_attn = MultiHeadAttention(n_units, h, dropout=dropout, initialW=initialW, initial_bias=initial_bias) self.feed_forward = PositionwiseFeedForward(n_units, d_units=d_units, dropout=dropout, init...
Single encoder layer module. Args: n_units (int): Number of input/output dimension of a FeedForward layer. d_units (int): Number of units of hidden layer in a FeedForward layer. h (int): Number of attention heads. dropout (float): Dropout rate
EncoderLayer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EncoderLayer: """Single encoder layer module. Args: n_units (int): Number of input/output dimension of a FeedForward layer. d_units (int): Number of units of hidden layer in a FeedForward layer. h (int): Number of attention heads. dropout (float): Dropout rate""" def __init__(self, n_units, ...
stack_v2_sparse_classes_36k_train_022552
1,903
permissive
[ { "docstring": "Initialize EncoderLayer.", "name": "__init__", "signature": "def __init__(self, n_units, d_units=0, h=8, dropout=0.1, initialW=None, initial_bias=None)" }, { "docstring": "Forward Positional Encoding.", "name": "forward", "signature": "def forward(self, e, xx_mask, batch)...
2
null
Implement the Python class `EncoderLayer` described below. Class description: Single encoder layer module. Args: n_units (int): Number of input/output dimension of a FeedForward layer. d_units (int): Number of units of hidden layer in a FeedForward layer. h (int): Number of attention heads. dropout (float): Dropout ra...
Implement the Python class `EncoderLayer` described below. Class description: Single encoder layer module. Args: n_units (int): Number of input/output dimension of a FeedForward layer. d_units (int): Number of units of hidden layer in a FeedForward layer. h (int): Number of attention heads. dropout (float): Dropout ra...
bcd20948db7846ee523443ef9fd78c7a1248c95e
<|skeleton|> class EncoderLayer: """Single encoder layer module. Args: n_units (int): Number of input/output dimension of a FeedForward layer. d_units (int): Number of units of hidden layer in a FeedForward layer. h (int): Number of attention heads. dropout (float): Dropout rate""" def __init__(self, n_units, ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EncoderLayer: """Single encoder layer module. Args: n_units (int): Number of input/output dimension of a FeedForward layer. d_units (int): Number of units of hidden layer in a FeedForward layer. h (int): Number of attention heads. dropout (float): Dropout rate""" def __init__(self, n_units, d_units=0, h=...
the_stack_v2_python_sparse
espnet/nets/chainer_backend/transformer/encoder_layer.py
espnet/espnet
train
7,242
737e211d3b7624f7cadd1f7699e16d496a82375f
[ "user = users.get_current_user()\nif not user:\n self.response.out.write(json.dumps(error_obj('User not logged in.')))\n return\nfriend = self.request.get('email')\nif not friend:\n self.response.out.write(json.dumps(error_obj('Must provide email of friend to add.')))\n return\naccount = user_info.get_u...
<|body_start_0|> user = users.get_current_user() if not user: self.response.out.write(json.dumps(error_obj('User not logged in.'))) return friend = self.request.get('email') if not friend: self.response.out.write(json.dumps(error_obj('Must provide emai...
Friend
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Friend: def get(self): """Get a global friend's availability and blurb.""" <|body_0|> def post(self): """Add a friend""" <|body_1|> def delete(self): """Remove a friend.""" <|body_2|> <|end_skeleton|> <|body_start_0|> user = use...
stack_v2_sparse_classes_36k_train_022553
3,414
no_license
[ { "docstring": "Get a global friend's availability and blurb.", "name": "get", "signature": "def get(self)" }, { "docstring": "Add a friend", "name": "post", "signature": "def post(self)" }, { "docstring": "Remove a friend.", "name": "delete", "signature": "def delete(sel...
3
stack_v2_sparse_classes_30k_train_020791
Implement the Python class `Friend` described below. Class description: Implement the Friend class. Method signatures and docstrings: - def get(self): Get a global friend's availability and blurb. - def post(self): Add a friend - def delete(self): Remove a friend.
Implement the Python class `Friend` described below. Class description: Implement the Friend class. Method signatures and docstrings: - def get(self): Get a global friend's availability and blurb. - def post(self): Add a friend - def delete(self): Remove a friend. <|skeleton|> class Friend: def get(self): ...
0f121a58617131c01ff76ccca0e46a41aae76db6
<|skeleton|> class Friend: def get(self): """Get a global friend's availability and blurb.""" <|body_0|> def post(self): """Add a friend""" <|body_1|> def delete(self): """Remove a friend.""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Friend: def get(self): """Get a global friend's availability and blurb.""" user = users.get_current_user() if not user: self.response.out.write(json.dumps(error_obj('User not logged in.'))) return friend = self.request.get('email') if not friend:...
the_stack_v2_python_sparse
controllers/friend.py
ShelleyGoldberg/golight
train
0
664d0cd8a14df0c733193adf7cf4a6c6e7748a5c
[ "filtered = [x for x in self if ue_id in x.ue_measurements]\ncells = sorted(filtered, key=lambda x: x.ue_measurements[ue_id]['rsrp'], reverse=True)\nreturn CellPool(cells)", "filtered = [x for x in self if ue_id in x.ue_measurements]\ncells = sorted(filtered, key=lambda x: x.ue_measurements[ue_id]['rsrq'], revers...
<|body_start_0|> filtered = [x for x in self if ue_id in x.ue_measurements] cells = sorted(filtered, key=lambda x: x.ue_measurements[ue_id]['rsrp'], reverse=True) return CellPool(cells) <|end_body_0|> <|body_start_1|> filtered = [x for x in self if ue_id in x.ue_measurements] ce...
EmPOWER cell pool. This extends the list in order to add a few filtering and sorting methods
CellPool
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CellPool: """EmPOWER cell pool. This extends the list in order to add a few filtering and sorting methods""" def sort_by_rsrp(self, ue_id): """Return list sorted by rsrp for the specified address.""" <|body_0|> def sort_by_rsrq(self, ue_id): """Return list sorted...
stack_v2_sparse_classes_36k_train_022554
5,209
permissive
[ { "docstring": "Return list sorted by rsrp for the specified address.", "name": "sort_by_rsrp", "signature": "def sort_by_rsrp(self, ue_id)" }, { "docstring": "Return list sorted by rsrq for the specified address.", "name": "sort_by_rsrq", "signature": "def sort_by_rsrq(self, ue_id)" }...
4
stack_v2_sparse_classes_30k_train_001167
Implement the Python class `CellPool` described below. Class description: EmPOWER cell pool. This extends the list in order to add a few filtering and sorting methods Method signatures and docstrings: - def sort_by_rsrp(self, ue_id): Return list sorted by rsrp for the specified address. - def sort_by_rsrq(self, ue_id...
Implement the Python class `CellPool` described below. Class description: EmPOWER cell pool. This extends the list in order to add a few filtering and sorting methods Method signatures and docstrings: - def sort_by_rsrp(self, ue_id): Return list sorted by rsrp for the specified address. - def sort_by_rsrq(self, ue_id...
eda52649f855722fdec1d02e25a28c61a8fbda06
<|skeleton|> class CellPool: """EmPOWER cell pool. This extends the list in order to add a few filtering and sorting methods""" def sort_by_rsrp(self, ue_id): """Return list sorted by rsrp for the specified address.""" <|body_0|> def sort_by_rsrq(self, ue_id): """Return list sorted...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CellPool: """EmPOWER cell pool. This extends the list in order to add a few filtering and sorting methods""" def sort_by_rsrp(self, ue_id): """Return list sorted by rsrp for the specified address.""" filtered = [x for x in self if ue_id in x.ue_measurements] cells = sorted(filtere...
the_stack_v2_python_sparse
empower/core/cellpool.py
imec-idlab/sdn_wifi_manager
train
0
ff0079322c9c2cf6171813bc663a3b31c2aaa26c
[ "for entity in obj.entity_set.all():\n if user.has_perm('share_entity', entity):\n update_permission(entity, payload)\nfor data in obj.data.all():\n if user.has_perm('share_data', data):\n update_permission(data, payload)", "if not request.user.is_authenticated:\n raise exceptions.NotFound\...
<|body_start_0|> for entity in obj.entity_set.all(): if user.has_perm('share_entity', entity): update_permission(entity, payload) for data in obj.data.all(): if user.has_perm('share_data', data): update_permission(data, payload) <|end_body_0|> <|b...
Base API view for :class:`Collection` objects.
BaseCollectionViewSet
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseCollectionViewSet: """Base API view for :class:`Collection` objects.""" def set_content_permissions(self, user, obj, payload): """Apply permissions to data objects and entities in ``Collection``.""" <|body_0|> def create(self, request, *args, **kwargs): """On...
stack_v2_sparse_classes_36k_train_022555
3,589
permissive
[ { "docstring": "Apply permissions to data objects and entities in ``Collection``.", "name": "set_content_permissions", "signature": "def set_content_permissions(self, user, obj, payload)" }, { "docstring": "Only authenticated users can create new collections.", "name": "create", "signatu...
3
stack_v2_sparse_classes_30k_train_020515
Implement the Python class `BaseCollectionViewSet` described below. Class description: Base API view for :class:`Collection` objects. Method signatures and docstrings: - def set_content_permissions(self, user, obj, payload): Apply permissions to data objects and entities in ``Collection``. - def create(self, request,...
Implement the Python class `BaseCollectionViewSet` described below. Class description: Base API view for :class:`Collection` objects. Method signatures and docstrings: - def set_content_permissions(self, user, obj, payload): Apply permissions to data objects and entities in ``Collection``. - def create(self, request,...
11a06a9d741dcc999253246919a0abc12127fd2a
<|skeleton|> class BaseCollectionViewSet: """Base API view for :class:`Collection` objects.""" def set_content_permissions(self, user, obj, payload): """Apply permissions to data objects and entities in ``Collection``.""" <|body_0|> def create(self, request, *args, **kwargs): """On...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BaseCollectionViewSet: """Base API view for :class:`Collection` objects.""" def set_content_permissions(self, user, obj, payload): """Apply permissions to data objects and entities in ``Collection``.""" for entity in obj.entity_set.all(): if user.has_perm('share_entity', entit...
the_stack_v2_python_sparse
resolwe/flow/views/collection.py
romunov/resolwe
train
0
44e6c8601ed236699e42dfb54d278190afe77e2f
[ "super(TrafficStreamsBaseClass, self).__init__()\nself.p1_dst_start_mac = u'02:02:00:00:12:00'\nself.p2_dst_start_mac = u'02:02:00:00:02:00'\nself.p1_src_start_ip = u'10.0.0.1'\nself.p1_dst_start_ip = u'20.0.0.0'\nself.p1_dst_end_ip = u'20.0.0.3'\nself.p2_src_start_ip = u'20.0.0.1'\nself.p2_dst_start_ip = u'10.0.0....
<|body_start_0|> super(TrafficStreamsBaseClass, self).__init__() self.p1_dst_start_mac = u'02:02:00:00:12:00' self.p2_dst_start_mac = u'02:02:00:00:02:00' self.p1_src_start_ip = u'10.0.0.1' self.p1_dst_start_ip = u'20.0.0.0' self.p1_dst_end_ip = u'20.0.0.3' self.p...
Stream profile.
TrafficStreams
[ "GPL-2.0-only", "GPL-1.0-or-later", "CC-BY-4.0", "Apache-2.0", "LicenseRef-scancode-dco-1.1" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TrafficStreams: """Stream profile.""" def __init__(self): """Initialization and setting of streams' parameters.""" <|body_0|> def define_packets(self): """Defines the packets to be sent from the traffic generator. Packet definition: | ETH | IP | :returns: Packets...
stack_v2_sparse_classes_36k_train_022556
4,907
permissive
[ { "docstring": "Initialization and setting of streams' parameters.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Defines the packets to be sent from the traffic generator. Packet definition: | ETH | IP | :returns: Packets to be sent from the traffic generator. :rtype...
2
null
Implement the Python class `TrafficStreams` described below. Class description: Stream profile. Method signatures and docstrings: - def __init__(self): Initialization and setting of streams' parameters. - def define_packets(self): Defines the packets to be sent from the traffic generator. Packet definition: | ETH | I...
Implement the Python class `TrafficStreams` described below. Class description: Stream profile. Method signatures and docstrings: - def __init__(self): Initialization and setting of streams' parameters. - def define_packets(self): Defines the packets to be sent from the traffic generator. Packet definition: | ETH | I...
947057d7310cd1602119258c6b82fbb25fe1b79d
<|skeleton|> class TrafficStreams: """Stream profile.""" def __init__(self): """Initialization and setting of streams' parameters.""" <|body_0|> def define_packets(self): """Defines the packets to be sent from the traffic generator. Packet definition: | ETH | IP | :returns: Packets...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TrafficStreams: """Stream profile.""" def __init__(self): """Initialization and setting of streams' parameters.""" super(TrafficStreamsBaseClass, self).__init__() self.p1_dst_start_mac = u'02:02:00:00:12:00' self.p2_dst_start_mac = u'02:02:00:00:02:00' self.p1_src_...
the_stack_v2_python_sparse
GPL/traffic_profiles/trex/trex-stl-3n-ethip4-ip4dst4-2cnf.py
FDio/csit
train
28
dbb04c94750c152755d66a5a56a1f3fb7dc714bb
[ "super()._define_vars()\nself._transformer: Transformer = Transformer()\n'\\n Our lark->veredi tree transformer.\\n '\nself._variables: MutableMapping[lark.Token, tree.Node] = {}\n'\\n A collection to hold the name & value of any variables declared in the\\n tree.\\n '\nself._mili...
<|body_start_0|> super()._define_vars() self._transformer: Transformer = Transformer() '\n Our lark->veredi tree transformer.\n ' self._variables: MutableMapping[lark.Token, tree.Node] = {} '\n A collection to hold the name & value of any variables declared i...
MathParser interface implementation. Wraps up the lark parsing and tranformation operations for getting from a string to some valid d20 math tree.
D20Parser
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class D20Parser: """MathParser interface implementation. Wraps up the lark parsing and tranformation operations for getting from a string to some valid d20 math tree.""" def _define_vars(self) -> None: """Instance variable definitions, type hinting, doc strings, etc.""" <|body_0|> ...
stack_v2_sparse_classes_36k_train_022557
11,922
no_license
[ { "docstring": "Instance variable definitions, type hinting, doc strings, etc.", "name": "_define_vars", "signature": "def _define_vars(self) -> None" }, { "docstring": "Initialize/reset/clear/whatever our instance variables in prep for next parse & transform.", "name": "_set_up", "signa...
3
stack_v2_sparse_classes_30k_train_018290
Implement the Python class `D20Parser` described below. Class description: MathParser interface implementation. Wraps up the lark parsing and tranformation operations for getting from a string to some valid d20 math tree. Method signatures and docstrings: - def _define_vars(self) -> None: Instance variable definition...
Implement the Python class `D20Parser` described below. Class description: MathParser interface implementation. Wraps up the lark parsing and tranformation operations for getting from a string to some valid d20 math tree. Method signatures and docstrings: - def _define_vars(self) -> None: Instance variable definition...
8c9fc1170ceac335985686571568eebf08b0db7a
<|skeleton|> class D20Parser: """MathParser interface implementation. Wraps up the lark parsing and tranformation operations for getting from a string to some valid d20 math tree.""" def _define_vars(self) -> None: """Instance variable definitions, type hinting, doc strings, etc.""" <|body_0|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class D20Parser: """MathParser interface implementation. Wraps up the lark parsing and tranformation operations for getting from a string to some valid d20 math tree.""" def _define_vars(self) -> None: """Instance variable definitions, type hinting, doc strings, etc.""" super()._define_vars() ...
the_stack_v2_python_sparse
math/d20/parser.py
cole-brown/veredi-code
train
1
d2b337f57706b002e9b6442f6342d3996e2637c9
[ "super().__init__()\nif config and isinstance(config, dict):\n self.update(config)", "for key in dir(obj):\n if not key.isupper():\n continue\n self[key] = getattr(obj, key)", "for key, value in kw.items():\n if not key.isupper():\n continue\n self[key] = value", "fmt_js = json.lo...
<|body_start_0|> super().__init__() if config and isinstance(config, dict): self.update(config) <|end_body_0|> <|body_start_1|> for key in dir(obj): if not key.isupper(): continue self[key] = getattr(obj, key) <|end_body_1|> <|body_start_2|> ...
Extend origin dict class
Config
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Config: """Extend origin dict class""" def __init__(self, config: t.Optional[t.Dict]=None) -> None: """Initialize config instance""" <|body_0|> def from_object(self, obj: object) -> None: """Read config items from python object""" <|body_1|> def from...
stack_v2_sparse_classes_36k_train_022558
2,393
permissive
[ { "docstring": "Initialize config instance", "name": "__init__", "signature": "def __init__(self, config: t.Optional[t.Dict]=None) -> None" }, { "docstring": "Read config items from python object", "name": "from_object", "signature": "def from_object(self, obj: object) -> None" }, { ...
5
stack_v2_sparse_classes_30k_train_006238
Implement the Python class `Config` described below. Class description: Extend origin dict class Method signatures and docstrings: - def __init__(self, config: t.Optional[t.Dict]=None) -> None: Initialize config instance - def from_object(self, obj: object) -> None: Read config items from python object - def from_dic...
Implement the Python class `Config` described below. Class description: Extend origin dict class Method signatures and docstrings: - def __init__(self, config: t.Optional[t.Dict]=None) -> None: Initialize config instance - def from_object(self, obj: object) -> None: Read config items from python object - def from_dic...
6df8d6c26ec095e6c6c78101087c452e7bc713df
<|skeleton|> class Config: """Extend origin dict class""" def __init__(self, config: t.Optional[t.Dict]=None) -> None: """Initialize config instance""" <|body_0|> def from_object(self, obj: object) -> None: """Read config items from python object""" <|body_1|> def from...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Config: """Extend origin dict class""" def __init__(self, config: t.Optional[t.Dict]=None) -> None: """Initialize config instance""" super().__init__() if config and isinstance(config, dict): self.update(config) def from_object(self, obj: object) -> None: ...
the_stack_v2_python_sparse
mask/config.py
Eastwu5788/Mask
train
40
944d8ac6e854cc311959fd3e513e9bc8932e7ce9
[ "response = self.client.get(reverse('blog_post_list'))\nself.assertEqual(response.status_code, 200)\nresponse = self.client.get(reverse('blog_post_feed', args=('rss',)))\nself.assertEqual(response.status_code, 200)\nresponse = self.client.get(reverse('blog_post_feed', args=('atom',)))\nself.assertEqual(response.sta...
<|body_start_0|> response = self.client.get(reverse('blog_post_list')) self.assertEqual(response.status_code, 200) response = self.client.get(reverse('blog_post_feed', args=('rss',))) self.assertEqual(response.status_code, 200) response = self.client.get(reverse('blog_post_feed',...
BlogTests
[ "BSD-2-Clause", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BlogTests: def test_blog_views(self): """Basic status code test for blog views.""" <|body_0|> def test_login_protected_blog(self): """Test the blog is login protected if its page has login_required set to True.""" <|body_1|> <|end_skeleton|> <|body_start_0|...
stack_v2_sparse_classes_36k_train_022559
2,048
permissive
[ { "docstring": "Basic status code test for blog views.", "name": "test_blog_views", "signature": "def test_blog_views(self)" }, { "docstring": "Test the blog is login protected if its page has login_required set to True.", "name": "test_login_protected_blog", "signature": "def test_login...
2
stack_v2_sparse_classes_30k_train_010404
Implement the Python class `BlogTests` described below. Class description: Implement the BlogTests class. Method signatures and docstrings: - def test_blog_views(self): Basic status code test for blog views. - def test_login_protected_blog(self): Test the blog is login protected if its page has login_required set to ...
Implement the Python class `BlogTests` described below. Class description: Implement the BlogTests class. Method signatures and docstrings: - def test_blog_views(self): Basic status code test for blog views. - def test_login_protected_blog(self): Test the blog is login protected if its page has login_required set to ...
66b5a1089ed0ce2e615f889f35b5e39db91950ae
<|skeleton|> class BlogTests: def test_blog_views(self): """Basic status code test for blog views.""" <|body_0|> def test_login_protected_blog(self): """Test the blog is login protected if its page has login_required set to True.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BlogTests: def test_blog_views(self): """Basic status code test for blog views.""" response = self.client.get(reverse('blog_post_list')) self.assertEqual(response.status_code, 200) response = self.client.get(reverse('blog_post_feed', args=('rss',))) self.assertEqual(res...
the_stack_v2_python_sparse
mezzanine/blog/tests.py
yasakawa/mezzanine
train
4
b56e2e75fedbd56d73f2eba058a750e3349ad41f
[ "for k in dir(self.Default):\n if k[0] == '_':\n continue\n v = getattr(self.Default, k)\n if callable(v):\n continue\n self[k] = copy.copy(v)\nDict.__init__(self, *args, **kwargs)", "if cls.__components is None:\n cls.__components = {}\nreturn cls.__components", "def wrapper(target...
<|body_start_0|> for k in dir(self.Default): if k[0] == '_': continue v = getattr(self.Default, k) if callable(v): continue self[k] = copy.copy(v) Dict.__init__(self, *args, **kwargs) <|end_body_0|> <|body_start_1|> ...
デフォルトの辞書エントリを持つ `Dict` クラス; デフォルトの辞書エントリの値は :func:`copy.copy` によって浅いコピーが行われる。 TODO: components, register についての説明
AutoDict
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AutoDict: """デフォルトの辞書エントリを持つ `Dict` クラス; デフォルトの辞書エントリの値は :func:`copy.copy` によって浅いコピーが行われる。 TODO: components, register についての説明""" def __init__(self, *args, **kwargs): """デフォルトの辞書エントリで初期化した後に、与えられた引数で dictとして初期化する。""" <|body_0|> def components(cls): """この辞書の要素となりえる...
stack_v2_sparse_classes_36k_train_022560
22,736
permissive
[ { "docstring": "デフォルトの辞書エントリで初期化した後に、与えられた引数で dictとして初期化する。", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "この辞書の要素となりえる `AutoDict` のサブクラスの一覧を得る", "name": "components", "signature": "def components(cls)" }, { "docstring": "この辞書の要素となりえる ...
4
stack_v2_sparse_classes_30k_train_017081
Implement the Python class `AutoDict` described below. Class description: デフォルトの辞書エントリを持つ `Dict` クラス; デフォルトの辞書エントリの値は :func:`copy.copy` によって浅いコピーが行われる。 TODO: components, register についての説明 Method signatures and docstrings: - def __init__(self, *args, **kwargs): デフォルトの辞書エントリで初期化した後に、与えられた引数で dictとして初期化する。 - def componen...
Implement the Python class `AutoDict` described below. Class description: デフォルトの辞書エントリを持つ `Dict` クラス; デフォルトの辞書エントリの値は :func:`copy.copy` によって浅いコピーが行われる。 TODO: components, register についての説明 Method signatures and docstrings: - def __init__(self, *args, **kwargs): デフォルトの辞書エントリで初期化した後に、与えられた引数で dictとして初期化する。 - def componen...
ba9190524d7543347208e7ebf0618e2605dd4649
<|skeleton|> class AutoDict: """デフォルトの辞書エントリを持つ `Dict` クラス; デフォルトの辞書エントリの値は :func:`copy.copy` によって浅いコピーが行われる。 TODO: components, register についての説明""" def __init__(self, *args, **kwargs): """デフォルトの辞書エントリで初期化した後に、与えられた引数で dictとして初期化する。""" <|body_0|> def components(cls): """この辞書の要素となりえる...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AutoDict: """デフォルトの辞書エントリを持つ `Dict` クラス; デフォルトの辞書エントリの値は :func:`copy.copy` によって浅いコピーが行われる。 TODO: components, register についての説明""" def __init__(self, *args, **kwargs): """デフォルトの辞書エントリで初期化した後に、与えられた引数で dictとして初期化する。""" for k in dir(self.Default): if k[0] == '_': c...
the_stack_v2_python_sparse
amp/core/utils.py
nohomepand/amp
train
0
215f778e1a813fb3df4c494c0a9e8e05d639cd63
[ "left, right = divmod(n, 26)\nres = string.uppercase[right - 1]\nif right == 0:\n left -= 1\nwhile left:\n left, right = divmod(left, 26)\n res = string.uppercase[right - 1] + res\n if right == 0:\n left -= 1\nreturn res", "res = ''\nwhile n:\n n -= 1\n n, right = divmod(n, 26)\n res =...
<|body_start_0|> left, right = divmod(n, 26) res = string.uppercase[right - 1] if right == 0: left -= 1 while left: left, right = divmod(left, 26) res = string.uppercase[right - 1] + res if right == 0: left -= 1 retu...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def _convertToTitle(self, n): """:type n: int :rtype: str""" <|body_0|> def convertToTitle(self, n): """:type n: int :rtype: str""" <|body_1|> <|end_skeleton|> <|body_start_0|> left, right = divmod(n, 26) res = string.uppercase[rig...
stack_v2_sparse_classes_36k_train_022561
1,643
permissive
[ { "docstring": ":type n: int :rtype: str", "name": "_convertToTitle", "signature": "def _convertToTitle(self, n)" }, { "docstring": ":type n: int :rtype: str", "name": "convertToTitle", "signature": "def convertToTitle(self, n)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def _convertToTitle(self, n): :type n: int :rtype: str - def convertToTitle(self, n): :type n: int :rtype: str
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def _convertToTitle(self, n): :type n: int :rtype: str - def convertToTitle(self, n): :type n: int :rtype: str <|skeleton|> class Solution: def _convertToTitle(self, n): ...
0dd67edca4e0b0323cb5a7239f02ea46383cd15a
<|skeleton|> class Solution: def _convertToTitle(self, n): """:type n: int :rtype: str""" <|body_0|> def convertToTitle(self, n): """:type n: int :rtype: str""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def _convertToTitle(self, n): """:type n: int :rtype: str""" left, right = divmod(n, 26) res = string.uppercase[right - 1] if right == 0: left -= 1 while left: left, right = divmod(left, 26) res = string.uppercase[right - 1]...
the_stack_v2_python_sparse
168.excel-sheet-column-title.py
windard/leeeeee
train
0
88e9c16bb8871fb99e9b0fae3b8b4e3f02d4f5e1
[ "super(CheckMainPage, cls).setUpClass()\ncls.pagelogin = NCPLogin(cls.browserclass.get_driver())\ncls.pageindex = PageIndex(cls.browserclass.get_driver())", "self.log.info('--------- Start Login ---------')\nself.browserclass.get_driver().get(self.loginurl)\nself.pagelogin.NCPuserlogin('admin', '88888888')\ncheck...
<|body_start_0|> super(CheckMainPage, cls).setUpClass() cls.pagelogin = NCPLogin(cls.browserclass.get_driver()) cls.pageindex = PageIndex(cls.browserclass.get_driver()) <|end_body_0|> <|body_start_1|> self.log.info('--------- Start Login ---------') self.browserclass.get_driver(...
CheckMainPage
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CheckMainPage: def setUpClass(cls): """测试类中所有测试方法执行前执行的方法""" <|body_0|> def test_a_weblogin(self): """登录测试,并为后面的菜单页面check测试,提供登录后的系统操作 :return:""" <|body_1|> def test_b_pagecheck(self, menu1, menu2, menu3, check_a): """数据驱动,左侧菜单点击及页面显示check 三个参数依...
stack_v2_sparse_classes_36k_train_022562
6,726
no_license
[ { "docstring": "测试类中所有测试方法执行前执行的方法", "name": "setUpClass", "signature": "def setUpClass(cls)" }, { "docstring": "登录测试,并为后面的菜单页面check测试,提供登录后的系统操作 :return:", "name": "test_a_weblogin", "signature": "def test_a_weblogin(self)" }, { "docstring": "数据驱动,左侧菜单点击及页面显示check 三个参数依次是 一级菜单 二...
3
stack_v2_sparse_classes_30k_train_014200
Implement the Python class `CheckMainPage` described below. Class description: Implement the CheckMainPage class. Method signatures and docstrings: - def setUpClass(cls): 测试类中所有测试方法执行前执行的方法 - def test_a_weblogin(self): 登录测试,并为后面的菜单页面check测试,提供登录后的系统操作 :return: - def test_b_pagecheck(self, menu1, menu2, menu3, check_a...
Implement the Python class `CheckMainPage` described below. Class description: Implement the CheckMainPage class. Method signatures and docstrings: - def setUpClass(cls): 测试类中所有测试方法执行前执行的方法 - def test_a_weblogin(self): 登录测试,并为后面的菜单页面check测试,提供登录后的系统操作 :return: - def test_b_pagecheck(self, menu1, menu2, menu3, check_a...
08b98e08b76ed2a4984efb7f543ed63eabe30757
<|skeleton|> class CheckMainPage: def setUpClass(cls): """测试类中所有测试方法执行前执行的方法""" <|body_0|> def test_a_weblogin(self): """登录测试,并为后面的菜单页面check测试,提供登录后的系统操作 :return:""" <|body_1|> def test_b_pagecheck(self, menu1, menu2, menu3, check_a): """数据驱动,左侧菜单点击及页面显示check 三个参数依...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CheckMainPage: def setUpClass(cls): """测试类中所有测试方法执行前执行的方法""" super(CheckMainPage, cls).setUpClass() cls.pagelogin = NCPLogin(cls.browserclass.get_driver()) cls.pageindex = PageIndex(cls.browserclass.get_driver()) def test_a_weblogin(self): """登录测试,并为后面的菜单页面check测试,...
the_stack_v2_python_sparse
Sys_NCP/TestClass/checkMainPage.py
duozi/webUITestLight
train
0
a61acef0341ef1e902641da8ed0a0506f5334f30
[ "job_log = JobLog.get(job_id=job_id)\nif not job_log:\n job_log = JobLog(job_id=job_id)\njob_log.last_run = datetime.utcnow()\ncommit()", "job_log = JobLog.get(job_id=job_id)\nif not job_log:\n return False\nreturn job_log.last_run > datetime.utcnow() - timedelta(minutes=recent_minutes)" ]
<|body_start_0|> job_log = JobLog.get(job_id=job_id) if not job_log: job_log = JobLog(job_id=job_id) job_log.last_run = datetime.utcnow() commit() <|end_body_0|> <|body_start_1|> job_log = JobLog.get(job_id=job_id) if not job_log: return False ...
JobLogService
[ "LicenseRef-scancode-warranty-disclaimer" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JobLogService: def update_job_log(self, job_id): """Updates the last run datetime of a specific job""" <|body_0|> def has_run_recently(self, job_id, recent_minutes=5): """:returns True if specified job has been run in the last recent_minutes minutes, False if not""" ...
stack_v2_sparse_classes_36k_train_022563
923
no_license
[ { "docstring": "Updates the last run datetime of a specific job", "name": "update_job_log", "signature": "def update_job_log(self, job_id)" }, { "docstring": ":returns True if specified job has been run in the last recent_minutes minutes, False if not", "name": "has_run_recently", "signa...
2
stack_v2_sparse_classes_30k_train_001256
Implement the Python class `JobLogService` described below. Class description: Implement the JobLogService class. Method signatures and docstrings: - def update_job_log(self, job_id): Updates the last run datetime of a specific job - def has_run_recently(self, job_id, recent_minutes=5): :returns True if specified job...
Implement the Python class `JobLogService` described below. Class description: Implement the JobLogService class. Method signatures and docstrings: - def update_job_log(self, job_id): Updates the last run datetime of a specific job - def has_run_recently(self, job_id, recent_minutes=5): :returns True if specified job...
d1be650663224c24b41f675627fff37dfdbcde97
<|skeleton|> class JobLogService: def update_job_log(self, job_id): """Updates the last run datetime of a specific job""" <|body_0|> def has_run_recently(self, job_id, recent_minutes=5): """:returns True if specified job has been run in the last recent_minutes minutes, False if not""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class JobLogService: def update_job_log(self, job_id): """Updates the last run datetime of a specific job""" job_log = JobLog.get(job_id=job_id) if not job_log: job_log = JobLog(job_id=job_id) job_log.last_run = datetime.utcnow() commit() def has_run_recently...
the_stack_v2_python_sparse
components/core/job_log_service.py
jbinder/doforme-bot
train
7
e22c1450a935cdee39f03b1614daccdfea4f962b
[ "super().__init__(batch_size, **kwargs)\n_, num_classes, X_train, y_train, X_val, y_val = load_mnist_shard(shard_num=int(data_path), **kwargs)\nself.training_data_size = len(X_train)\nself.validation_data_size = len(X_val)\nself.num_classes = num_classes\nself.train_loader = self.create_loader(X=X_train, y=y_train,...
<|body_start_0|> super().__init__(batch_size, **kwargs) _, num_classes, X_train, y_train, X_val, y_val = load_mnist_shard(shard_num=int(data_path), **kwargs) self.training_data_size = len(X_train) self.validation_data_size = len(X_val) self.num_classes = num_classes self....
PyTorch data loader for MNIST dataset
PyTorchMNISTInMemory
[ "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-protobuf", "Apache-2.0", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PyTorchMNISTInMemory: """PyTorch data loader for MNIST dataset""" def __init__(self, data_path, batch_size, **kwargs): """Instantiate the data object Args: data_path: The file path to the data batch_size: The batch size of the data loader **kwargs: Additional arguments, passed to sup...
stack_v2_sparse_classes_36k_train_022564
5,563
permissive
[ { "docstring": "Instantiate the data object Args: data_path: The file path to the data batch_size: The batch size of the data loader **kwargs: Additional arguments, passed to super init and load_mnist_shard", "name": "__init__", "signature": "def __init__(self, data_path, batch_size, **kwargs)" }, {...
2
null
Implement the Python class `PyTorchMNISTInMemory` described below. Class description: PyTorch data loader for MNIST dataset Method signatures and docstrings: - def __init__(self, data_path, batch_size, **kwargs): Instantiate the data object Args: data_path: The file path to the data batch_size: The batch size of the ...
Implement the Python class `PyTorchMNISTInMemory` described below. Class description: PyTorch data loader for MNIST dataset Method signatures and docstrings: - def __init__(self, data_path, batch_size, **kwargs): Instantiate the data object Args: data_path: The file path to the data batch_size: The batch size of the ...
d8e2d22dfccfb8488f70f1fb5593d4e6ee1eca1f
<|skeleton|> class PyTorchMNISTInMemory: """PyTorch data loader for MNIST dataset""" def __init__(self, data_path, batch_size, **kwargs): """Instantiate the data object Args: data_path: The file path to the data batch_size: The batch size of the data loader **kwargs: Additional arguments, passed to sup...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PyTorchMNISTInMemory: """PyTorch data loader for MNIST dataset""" def __init__(self, data_path, batch_size, **kwargs): """Instantiate the data object Args: data_path: The file path to the data batch_size: The batch size of the data loader **kwargs: Additional arguments, passed to super init and l...
the_stack_v2_python_sparse
openfl/data/pytorch/ptmnist_inmemory.py
sbakas/OpenFederatedLearning-1
train
0
6d6094adc8bc950a34834930feb7cb148fffd8ce
[ "expected = '{\\n \"status\": \"created\"\\n}'\nfuture = event(EventType.PING)\nactual = future.result()\nself.assertEqual(actual, expected)", "duration_max = 0.001\nstart = time.time()\nevent(EventType.PING)\nduration_actual = time.time() - start\nself.assertLess(duration_actual, duration_max)", "expected =...
<|body_start_0|> expected = '{\n "status": "created"\n}' future = event(EventType.PING) actual = future.result() self.assertEqual(actual, expected) <|end_body_0|> <|body_start_1|> duration_max = 0.001 start = time.time() event(EventType.PING) duration_...
Tests for the telemetry module.
TelemetryTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TelemetryTest: """Tests for the telemetry module.""" def test_event(self) -> None: """Test if sending works against the actual API.""" <|body_0|> def test_not_blocking(self) -> None: """Test if the code is blocking. If the code does not block duration_actual shou...
stack_v2_sparse_classes_36k_train_022565
3,345
permissive
[ { "docstring": "Test if sending works against the actual API.", "name": "test_event", "signature": "def test_event(self) -> None" }, { "docstring": "Test if the code is blocking. If the code does not block duration_actual should be less than 0.001s.", "name": "test_not_blocking", "signat...
5
null
Implement the Python class `TelemetryTest` described below. Class description: Tests for the telemetry module. Method signatures and docstrings: - def test_event(self) -> None: Test if sending works against the actual API. - def test_not_blocking(self) -> None: Test if the code is blocking. If the code does not block...
Implement the Python class `TelemetryTest` described below. Class description: Tests for the telemetry module. Method signatures and docstrings: - def test_event(self) -> None: Test if sending works against the actual API. - def test_not_blocking(self) -> None: Test if the code is blocking. If the code does not block...
55be690535e5f3feb33c888c3e4a586b7bdbf489
<|skeleton|> class TelemetryTest: """Tests for the telemetry module.""" def test_event(self) -> None: """Test if sending works against the actual API.""" <|body_0|> def test_not_blocking(self) -> None: """Test if the code is blocking. If the code does not block duration_actual shou...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TelemetryTest: """Tests for the telemetry module.""" def test_event(self) -> None: """Test if sending works against the actual API.""" expected = '{\n "status": "created"\n}' future = event(EventType.PING) actual = future.result() self.assertEqual(actual, expect...
the_stack_v2_python_sparse
src/py/flwr/common/telemetry_test.py
adap/flower
train
2,999
bc948902a4877fcb219627d213bc93d6063e7b5f
[ "self.model_conf = model_conf\nself.inputs = inputs\nself.utils = utils\nself.layer = None", "with tf.keras.backend.name_scope('GRU'):\n mask = tf.keras.layers.Masking()(self.inputs)\n self.layer = tf.keras.layers.GRU(units=self.model_conf.units_num * 2, return_sequences=True, input_shape=mask.shape)\n o...
<|body_start_0|> self.model_conf = model_conf self.inputs = inputs self.utils = utils self.layer = None <|end_body_0|> <|body_start_1|> with tf.keras.backend.name_scope('GRU'): mask = tf.keras.layers.Masking()(self.inputs) self.layer = tf.keras.layers.GRU...
GRU
[ "Apache-2.0", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GRU: def __init__(self, model_conf: ModelConfig, inputs: tf.Tensor, utils: NetworkUtils): """:param model_conf: 配置 :param inputs: 网络上一层输入tf.keras.layers.Input/tf.Tensor类型 :param utils: 网络工具类""" <|body_0|> def build(self): """循环层构建参数 :return: 返回循环层的输出层""" <|bo...
stack_v2_sparse_classes_36k_train_022566
2,557
permissive
[ { "docstring": ":param model_conf: 配置 :param inputs: 网络上一层输入tf.keras.layers.Input/tf.Tensor类型 :param utils: 网络工具类", "name": "__init__", "signature": "def __init__(self, model_conf: ModelConfig, inputs: tf.Tensor, utils: NetworkUtils)" }, { "docstring": "循环层构建参数 :return: 返回循环层的输出层", "name": "...
2
stack_v2_sparse_classes_30k_train_002427
Implement the Python class `GRU` described below. Class description: Implement the GRU class. Method signatures and docstrings: - def __init__(self, model_conf: ModelConfig, inputs: tf.Tensor, utils: NetworkUtils): :param model_conf: 配置 :param inputs: 网络上一层输入tf.keras.layers.Input/tf.Tensor类型 :param utils: 网络工具类 - def...
Implement the Python class `GRU` described below. Class description: Implement the GRU class. Method signatures and docstrings: - def __init__(self, model_conf: ModelConfig, inputs: tf.Tensor, utils: NetworkUtils): :param model_conf: 配置 :param inputs: 网络上一层输入tf.keras.layers.Input/tf.Tensor类型 :param utils: 网络工具类 - def...
6fd35c0c789aaa43130de46d4c04622ec2948052
<|skeleton|> class GRU: def __init__(self, model_conf: ModelConfig, inputs: tf.Tensor, utils: NetworkUtils): """:param model_conf: 配置 :param inputs: 网络上一层输入tf.keras.layers.Input/tf.Tensor类型 :param utils: 网络工具类""" <|body_0|> def build(self): """循环层构建参数 :return: 返回循环层的输出层""" <|bo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GRU: def __init__(self, model_conf: ModelConfig, inputs: tf.Tensor, utils: NetworkUtils): """:param model_conf: 配置 :param inputs: 网络上一层输入tf.keras.layers.Input/tf.Tensor类型 :param utils: 网络工具类""" self.model_conf = model_conf self.inputs = inputs self.utils = utils self.la...
the_stack_v2_python_sparse
network/GRU.py
kerlomz/captcha_trainer
train
2,977
8e44b4f33e8737c96f56d1b20c70c8ba3488d83f
[ "y_pred_clipped = np.clip(y_pred, 1e-07, 1 - 1e-07)\nsample_losses = -(y_true * np.log(y_pred_clipped) + (1 - y_true) * np.log(1 - y_pred_clipped))\nsample_losses = np.mean(sample_losses, axis=-1)\nreturn sample_losses", "samples = len(derivated_values)\noutputs = len(derivated_values[0])\nclipped_derivated_value...
<|body_start_0|> y_pred_clipped = np.clip(y_pred, 1e-07, 1 - 1e-07) sample_losses = -(y_true * np.log(y_pred_clipped) + (1 - y_true) * np.log(1 - y_pred_clipped)) sample_losses = np.mean(sample_losses, axis=-1) return sample_losses <|end_body_0|> <|body_start_1|> samples = len(d...
The class computes the binary crossentropy by applying the formula. Sources: * Neural Networks from Scratch - Harrison Kinsley & Daniel Kukieła [pg.407-412]
BinaryCrossentropy
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BinaryCrossentropy: """The class computes the binary crossentropy by applying the formula. Sources: * Neural Networks from Scratch - Harrison Kinsley & Daniel Kukieła [pg.407-412]""" def forward(self, y_pred, y_true): """Performs the forward pass. Args : y_pred(np.array): Model predi...
stack_v2_sparse_classes_36k_train_022567
1,927
no_license
[ { "docstring": "Performs the forward pass. Args : y_pred(np.array): Model predictions y_true(np.array): Actual values Sources: * Neural Networks from Scratch - Harrison Kinsley & Daniel Kukieła [pg.112-116]", "name": "forward", "signature": "def forward(self, y_pred, y_true)" }, { "docstring": "...
2
stack_v2_sparse_classes_30k_val_000333
Implement the Python class `BinaryCrossentropy` described below. Class description: The class computes the binary crossentropy by applying the formula. Sources: * Neural Networks from Scratch - Harrison Kinsley & Daniel Kukieła [pg.407-412] Method signatures and docstrings: - def forward(self, y_pred, y_true): Perfor...
Implement the Python class `BinaryCrossentropy` described below. Class description: The class computes the binary crossentropy by applying the formula. Sources: * Neural Networks from Scratch - Harrison Kinsley & Daniel Kukieła [pg.407-412] Method signatures and docstrings: - def forward(self, y_pred, y_true): Perfor...
8ffd24971d8808e7c9caa722a7ff4df306b75b90
<|skeleton|> class BinaryCrossentropy: """The class computes the binary crossentropy by applying the formula. Sources: * Neural Networks from Scratch - Harrison Kinsley & Daniel Kukieła [pg.407-412]""" def forward(self, y_pred, y_true): """Performs the forward pass. Args : y_pred(np.array): Model predi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BinaryCrossentropy: """The class computes the binary crossentropy by applying the formula. Sources: * Neural Networks from Scratch - Harrison Kinsley & Daniel Kukieła [pg.407-412]""" def forward(self, y_pred, y_true): """Performs the forward pass. Args : y_pred(np.array): Model predictions y_true...
the_stack_v2_python_sparse
Music Recognizer/Metrics/BinaryCrossentropy.py
andutzu7/Lucrare-Licenta-MusicRecognizer
train
0
b601b0fd8c0a11b9cf0413e7f0c39a1a0f62453a
[ "print('\\nrunning test method:{}'.format(inspect.stack()[0][3]))\nreal_result = MathOperation(10, 2).division()\nexcept_result = 5\nmsg = '两个正数相除失败'\ntry:\n self.assertEqual(except_result, real_result, msg=msg)\nexcept AssertionError as e:\n print('具体异常为:{}'.format(e))\n file.write('{},执行结果为:{}\\n具体异常为:{}...
<|body_start_0|> print('\nrunning test method:{}'.format(inspect.stack()[0][3])) real_result = MathOperation(10, 2).division() except_result = 5 msg = '两个正数相除失败' try: self.assertEqual(except_result, real_result, msg=msg) except AssertionError as e: ...
测试两数相乘
TestDivide
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestDivide: """测试两数相乘""" def test_two_pos_divide(self): """1.两个正数相除 :return:""" <|body_0|> def test_two_neg_divide(self): """2.两个负数相除 :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> print('\nrunning test method:{}'.format(inspect.stack(...
stack_v2_sparse_classes_36k_train_022568
7,546
no_license
[ { "docstring": "1.两个正数相除 :return:", "name": "test_two_pos_divide", "signature": "def test_two_pos_divide(self)" }, { "docstring": "2.两个负数相除 :return:", "name": "test_two_neg_divide", "signature": "def test_two_neg_divide(self)" } ]
2
stack_v2_sparse_classes_30k_train_016804
Implement the Python class `TestDivide` described below. Class description: 测试两数相乘 Method signatures and docstrings: - def test_two_pos_divide(self): 1.两个正数相除 :return: - def test_two_neg_divide(self): 2.两个负数相除 :return:
Implement the Python class `TestDivide` described below. Class description: 测试两数相乘 Method signatures and docstrings: - def test_two_pos_divide(self): 1.两个正数相除 :return: - def test_two_neg_divide(self): 2.两个负数相除 :return: <|skeleton|> class TestDivide: """测试两数相乘""" def test_two_pos_divide(self): """1.两...
09d6bf79f46002b590289fdb94cbf1febe891184
<|skeleton|> class TestDivide: """测试两数相乘""" def test_two_pos_divide(self): """1.两个正数相除 :return:""" <|body_0|> def test_two_neg_divide(self): """2.两个负数相除 :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestDivide: """测试两数相乘""" def test_two_pos_divide(self): """1.两个正数相除 :return:""" print('\nrunning test method:{}'.format(inspect.stack()[0][3])) real_result = MathOperation(10, 2).division() except_result = 5 msg = '两个正数相除失败' try: self.assertEqua...
the_stack_v2_python_sparse
pythonbase_class_1/Class_11_Unittest_start_end_handle.py
2353501820/erp
train
0
f3b8b4b5ecc3204b58dfa5059fd88cfc957a9927
[ "if instance.pk and instance.name_changed:\n works = instance.digitizedwork_set.all()\n if works.exists():\n logger.debug('collection save, reindexing %d related works', works.count())\n DigitizedWork.index_items(works)", "logger.debug('collection delete')\ndigwork_ids = instance.digitizedwork...
<|body_start_0|> if instance.pk and instance.name_changed: works = instance.digitizedwork_set.all() if works.exists(): logger.debug('collection save, reindexing %d related works', works.count()) DigitizedWork.index_items(works) <|end_body_0|> <|body_start...
Signal handlers for indexing :class:`DigitizedWork` records when :class:`Collection` records are saved or deleted.
CollectionSignalHandlers
[ "Apache-2.0", "LicenseRef-scancode-free-unknown" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CollectionSignalHandlers: """Signal handlers for indexing :class:`DigitizedWork` records when :class:`Collection` records are saved or deleted.""" def save(sender, instance, **kwargs): """signal handler for collection save; reindex associated digitized works""" <|body_0|> ...
stack_v2_sparse_classes_36k_train_022569
46,514
permissive
[ { "docstring": "signal handler for collection save; reindex associated digitized works", "name": "save", "signature": "def save(sender, instance, **kwargs)" }, { "docstring": "signal handler for collection delete; clear associated digitized works and reindex", "name": "delete", "signatur...
2
null
Implement the Python class `CollectionSignalHandlers` described below. Class description: Signal handlers for indexing :class:`DigitizedWork` records when :class:`Collection` records are saved or deleted. Method signatures and docstrings: - def save(sender, instance, **kwargs): signal handler for collection save; rei...
Implement the Python class `CollectionSignalHandlers` described below. Class description: Signal handlers for indexing :class:`DigitizedWork` records when :class:`Collection` records are saved or deleted. Method signatures and docstrings: - def save(sender, instance, **kwargs): signal handler for collection save; rei...
99e751b0d656d0d28c7e995cc44c351622313593
<|skeleton|> class CollectionSignalHandlers: """Signal handlers for indexing :class:`DigitizedWork` records when :class:`Collection` records are saved or deleted.""" def save(sender, instance, **kwargs): """signal handler for collection save; reindex associated digitized works""" <|body_0|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CollectionSignalHandlers: """Signal handlers for indexing :class:`DigitizedWork` records when :class:`Collection` records are saved or deleted.""" def save(sender, instance, **kwargs): """signal handler for collection save; reindex associated digitized works""" if instance.pk and instance...
the_stack_v2_python_sparse
ppa/archive/models.py
Princeton-CDH/ppa-django
train
5
9f77000fba4809829eb5dd4e313488b10c14cf5f
[ "self.organisms = 0\nself.hyperparameters = hyperparameters\nself.grid_dim = self.hyperparameters['grid_dim']\nself.mutation_prob = self.hyperparameters['mutation_prob']\nself.replication_prob = self.hyperparameters['replication_prob']\nself.grid_range = list(range(self.grid_dim))\nself.grid = [None for _ in range(...
<|body_start_0|> self.organisms = 0 self.hyperparameters = hyperparameters self.grid_dim = self.hyperparameters['grid_dim'] self.mutation_prob = self.hyperparameters['mutation_prob'] self.replication_prob = self.hyperparameters['replication_prob'] self.grid_range = list(r...
1-Dimensional grid containing replicators -- the medium with which replication occurs
ReplicationGrid
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReplicationGrid: """1-Dimensional grid containing replicators -- the medium with which replication occurs""" def __init__(self, hyperparameters): """Initialize grid parameters :param hyperparameters: (dict) dictionary of hyperparameters""" <|body_0|> def step(self): ...
stack_v2_sparse_classes_36k_train_022570
8,990
permissive
[ { "docstring": "Initialize grid parameters :param hyperparameters: (dict) dictionary of hyperparameters", "name": "__init__", "signature": "def __init__(self, hyperparameters)" }, { "docstring": "Replicator's interaction with environment including replication, creation, and death :return: (list(...
4
stack_v2_sparse_classes_30k_train_014859
Implement the Python class `ReplicationGrid` described below. Class description: 1-Dimensional grid containing replicators -- the medium with which replication occurs Method signatures and docstrings: - def __init__(self, hyperparameters): Initialize grid parameters :param hyperparameters: (dict) dictionary of hyperp...
Implement the Python class `ReplicationGrid` described below. Class description: 1-Dimensional grid containing replicators -- the medium with which replication occurs Method signatures and docstrings: - def __init__(self, hyperparameters): Initialize grid parameters :param hyperparameters: (dict) dictionary of hyperp...
1a6f8225378b59423a97b439b56710bbed2754e9
<|skeleton|> class ReplicationGrid: """1-Dimensional grid containing replicators -- the medium with which replication occurs""" def __init__(self, hyperparameters): """Initialize grid parameters :param hyperparameters: (dict) dictionary of hyperparameters""" <|body_0|> def step(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ReplicationGrid: """1-Dimensional grid containing replicators -- the medium with which replication occurs""" def __init__(self, hyperparameters): """Initialize grid parameters :param hyperparameters: (dict) dictionary of hyperparameters""" self.organisms = 0 self.hyperparameters =...
the_stack_v2_python_sparse
evo_replicators/evolutionary_replicator.py
SamuelSchmidgall/EvolutionarySelfReplication
train
14
61848fc0e4c64324609b447cad36e68f3ba86a3f
[ "self._logger = None\nif need_log:\n self._logger = LoggerFactory.get_global_instance()", "if self._logger is None:\n return\nclass_name = '[{}]'.format(type(self).__name__.upper())\ncontent = class_name + ' ' + str(content)\nif level == constant.LogLevel.INFO:\n self._logger.info(content)\nelif level ==...
<|body_start_0|> self._logger = None if need_log: self._logger = LoggerFactory.get_global_instance() <|end_body_0|> <|body_start_1|> if self._logger is None: return class_name = '[{}]'.format(type(self).__name__.upper()) content = class_name + ' ' + str(c...
The operator base class
Operator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Operator: """The operator base class""" def __init__(self, need_log): """:param need_log: bool""" <|body_0|> def _log(self, content, level=constant.LogLevel.INFO): """:param content: str :param level: :return:""" <|body_1|> <|end_skeleton|> <|body_start...
stack_v2_sparse_classes_36k_train_022571
1,019
no_license
[ { "docstring": ":param need_log: bool", "name": "__init__", "signature": "def __init__(self, need_log)" }, { "docstring": ":param content: str :param level: :return:", "name": "_log", "signature": "def _log(self, content, level=constant.LogLevel.INFO)" } ]
2
null
Implement the Python class `Operator` described below. Class description: The operator base class Method signatures and docstrings: - def __init__(self, need_log): :param need_log: bool - def _log(self, content, level=constant.LogLevel.INFO): :param content: str :param level: :return:
Implement the Python class `Operator` described below. Class description: The operator base class Method signatures and docstrings: - def __init__(self, need_log): :param need_log: bool - def _log(self, content, level=constant.LogLevel.INFO): :param content: str :param level: :return: <|skeleton|> class Operator: ...
db959eef96f95fcdd92185f0cb728d1d0b99857b
<|skeleton|> class Operator: """The operator base class""" def __init__(self, need_log): """:param need_log: bool""" <|body_0|> def _log(self, content, level=constant.LogLevel.INFO): """:param content: str :param level: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Operator: """The operator base class""" def __init__(self, need_log): """:param need_log: bool""" self._logger = None if need_log: self._logger = LoggerFactory.get_global_instance() def _log(self, content, level=constant.LogLevel.INFO): """:param content: ...
the_stack_v2_python_sparse
fl/operator/operator.py
som-don/jeddak
train
0
9689eeca03569387815b68344597f6e1c00654f0
[ "super(InformationRatio, self).__init__()\nself.mtm = mtm\nself.benchmark = benchmark\npReturns = AnnualReturn(self.mtm)\nbReturns = AnnualReturn(self.benchmark)\nself.portfolioReturn = pReturns.getValue()\nself.benchmarkReturn = bReturns.getValue()\nvolatility = Volatility(self.mtm.shift() / self.mtm - self.benchm...
<|body_start_0|> super(InformationRatio, self).__init__() self.mtm = mtm self.benchmark = benchmark pReturns = AnnualReturn(self.mtm) bReturns = AnnualReturn(self.benchmark) self.portfolioReturn = pReturns.getValue() self.benchmarkReturn = bReturns.getValue() ...
Information ratio of the data.
InformationRatio
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InformationRatio: """Information ratio of the data.""" def __init__(self, mtm, benchmark): """Initialize a volatility calculator. Parameters ---------- mtm : pandas.Series daily mark-to-market indexed by trading date as strings in the format %Y%m%d. benchmark : pandas.Series benchmar...
stack_v2_sparse_classes_36k_train_022572
10,010
permissive
[ { "docstring": "Initialize a volatility calculator. Parameters ---------- mtm : pandas.Series daily mark-to-market indexed by trading date as strings in the format %Y%m%d. benchmark : pandas.Series benchmark daily mark-to-market indexed by trading date as strings in the format %Y%m%d.", "name": "__init__", ...
2
stack_v2_sparse_classes_30k_train_010988
Implement the Python class `InformationRatio` described below. Class description: Information ratio of the data. Method signatures and docstrings: - def __init__(self, mtm, benchmark): Initialize a volatility calculator. Parameters ---------- mtm : pandas.Series daily mark-to-market indexed by trading date as strings...
Implement the Python class `InformationRatio` described below. Class description: Information ratio of the data. Method signatures and docstrings: - def __init__(self, mtm, benchmark): Initialize a volatility calculator. Parameters ---------- mtm : pandas.Series daily mark-to-market indexed by trading date as strings...
139d604177da3855503643e0fcfa87711ba7e588
<|skeleton|> class InformationRatio: """Information ratio of the data.""" def __init__(self, mtm, benchmark): """Initialize a volatility calculator. Parameters ---------- mtm : pandas.Series daily mark-to-market indexed by trading date as strings in the format %Y%m%d. benchmark : pandas.Series benchmar...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InformationRatio: """Information ratio of the data.""" def __init__(self, mtm, benchmark): """Initialize a volatility calculator. Parameters ---------- mtm : pandas.Series daily mark-to-market indexed by trading date as strings in the format %Y%m%d. benchmark : pandas.Series benchmark daily mark-...
the_stack_v2_python_sparse
analytics/riskMeasurement/riskMetric.py
WinQuant/arsenal
train
0
972f50f66d68d56cd5f0aa063a2d86df62a83f5b
[ "self._data = data\nself._offset = offset\nself._limit = limit", "limit = self._limit\noffset = self._offset\nvalue = limit - offset >> 2\nreturn value", "index = index << 2\noffset = self._offset + index\nvalue = int.from_bytes(self._data[offset:offset + 4], 'big')\nreturn value", "data = self._data\noffset ...
<|body_start_0|> self._data = data self._offset = offset self._limit = limit <|end_body_0|> <|body_start_1|> limit = self._limit offset = self._offset value = limit - offset >> 2 return value <|end_body_1|> <|body_start_2|> index = index << 2 off...
Implements an uint32 array casted on bytes. Attributes ---------- _data : `bytes` The source `bytes` object. _offset : `int` The first byte what is inside of the array. _limit : `int` The first byte, what is not inside of the array after `._offset`.
Array_uint_32b
[ "LicenseRef-scancode-warranty-disclaimer" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Array_uint_32b: """Implements an uint32 array casted on bytes. Attributes ---------- _data : `bytes` The source `bytes` object. _offset : `int` The first byte what is inside of the array. _limit : `int` The first byte, what is not inside of the array after `._offset`.""" def __init__(self, d...
stack_v2_sparse_classes_36k_train_022573
11,434
permissive
[ { "docstring": "Creates a new uint32 array from the given parameters. Parameters ---------- data : `bytes` The source `bytes` object. offset : `int` The first byte what is inside of the array. limit : `int` The first byte, what is not inside of the array after `._offset`.", "name": "__init__", "signatur...
4
stack_v2_sparse_classes_30k_train_016615
Implement the Python class `Array_uint_32b` described below. Class description: Implements an uint32 array casted on bytes. Attributes ---------- _data : `bytes` The source `bytes` object. _offset : `int` The first byte what is inside of the array. _limit : `int` The first byte, what is not inside of the array after `...
Implement the Python class `Array_uint_32b` described below. Class description: Implements an uint32 array casted on bytes. Attributes ---------- _data : `bytes` The source `bytes` object. _offset : `int` The first byte what is inside of the array. _limit : `int` The first byte, what is not inside of the array after `...
53f24fdb38459dc5a4fd04f11bdbfee8295b76a4
<|skeleton|> class Array_uint_32b: """Implements an uint32 array casted on bytes. Attributes ---------- _data : `bytes` The source `bytes` object. _offset : `int` The first byte what is inside of the array. _limit : `int` The first byte, what is not inside of the array after `._offset`.""" def __init__(self, d...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Array_uint_32b: """Implements an uint32 array casted on bytes. Attributes ---------- _data : `bytes` The source `bytes` object. _offset : `int` The first byte what is inside of the array. _limit : `int` The first byte, what is not inside of the array after `._offset`.""" def __init__(self, data, offset, ...
the_stack_v2_python_sparse
hata/discord/voice/rtp_packet.py
HuyaneMatsu/hata
train
3
a67641ea4f1551885e3affc5f0d98ec102f5bff1
[ "self.max_age = max_age\nself.min_hits = min_hits\nself.iou_threshold = iou_threshold\nself.trackers = []\nself.frame_count = 0", "self.frame_count += 1\ntrks = np.zeros((len(self.trackers), 5))\nto_del = []\nret = []\nfor t, trk in enumerate(trks):\n pos = self.trackers[t].predict()[0]\n trk[:] = [pos[0], ...
<|body_start_0|> self.max_age = max_age self.min_hits = min_hits self.iou_threshold = iou_threshold self.trackers = [] self.frame_count = 0 <|end_body_0|> <|body_start_1|> self.frame_count += 1 trks = np.zeros((len(self.trackers), 5)) to_del = [] ...
Sort
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Sort: def __init__(self, max_age=1, min_hits=3, iou_threshold=0.3): """Sets key parameters for SORT""" <|body_0|> def update(self, dets=np.empty((0, 5))): """Params: dets - a numpy array of detections in the format [[x1,y1,x2,y2,score],[x1,y1,x2,y2,score],...] Requir...
stack_v2_sparse_classes_36k_train_022574
11,642
permissive
[ { "docstring": "Sets key parameters for SORT", "name": "__init__", "signature": "def __init__(self, max_age=1, min_hits=3, iou_threshold=0.3)" }, { "docstring": "Params: dets - a numpy array of detections in the format [[x1,y1,x2,y2,score],[x1,y1,x2,y2,score],...] Requires: this method must be c...
2
null
Implement the Python class `Sort` described below. Class description: Implement the Sort class. Method signatures and docstrings: - def __init__(self, max_age=1, min_hits=3, iou_threshold=0.3): Sets key parameters for SORT - def update(self, dets=np.empty((0, 5))): Params: dets - a numpy array of detections in the fo...
Implement the Python class `Sort` described below. Class description: Implement the Sort class. Method signatures and docstrings: - def __init__(self, max_age=1, min_hits=3, iou_threshold=0.3): Sets key parameters for SORT - def update(self, dets=np.empty((0, 5))): Params: dets - a numpy array of detections in the fo...
d6a135b098c3e1ee3b2a2f63b7dfeaa11f51fb30
<|skeleton|> class Sort: def __init__(self, max_age=1, min_hits=3, iou_threshold=0.3): """Sets key parameters for SORT""" <|body_0|> def update(self, dets=np.empty((0, 5))): """Params: dets - a numpy array of detections in the format [[x1,y1,x2,y2,score],[x1,y1,x2,y2,score],...] Requir...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Sort: def __init__(self, max_age=1, min_hits=3, iou_threshold=0.3): """Sets key parameters for SORT""" self.max_age = max_age self.min_hits = min_hits self.iou_threshold = iou_threshold self.trackers = [] self.frame_count = 0 def update(self, dets=np.empty(...
the_stack_v2_python_sparse
tracking/model/sort/sort.py
david8862/keras-YOLOv3-model-set
train
673
4b145d551c66638757662eacfdf533667286a83e
[ "is_prime = [True] * max(n, 2)\nis_prime[0], is_prime[1] = (False, False)\nx = 2\nwhile x * x < n:\n if is_prime[x]:\n p = x * x\n while p < n:\n is_prime[p] = False\n p += x\n x += 1\nreturn sum(is_prime)", "is_prime = [True] * max(n, 2)\nis_prime[0], is_prime[1] = (Fals...
<|body_start_0|> is_prime = [True] * max(n, 2) is_prime[0], is_prime[1] = (False, False) x = 2 while x * x < n: if is_prime[x]: p = x * x while p < n: is_prime[p] = False p += x x += 1 ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def countPrimes(self, n): """:type n: int :rtype: int""" <|body_0|> def countPrimes_v0(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> is_prime = [True] * max(n, 2) is_prime[0], is_prime[1] = (...
stack_v2_sparse_classes_36k_train_022575
2,525
no_license
[ { "docstring": ":type n: int :rtype: int", "name": "countPrimes", "signature": "def countPrimes(self, n)" }, { "docstring": ":type n: int :rtype: int", "name": "countPrimes_v0", "signature": "def countPrimes_v0(self, n)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countPrimes(self, n): :type n: int :rtype: int - def countPrimes_v0(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 countPrimes(self, n): :type n: int :rtype: int - def countPrimes_v0(self, n): :type n: int :rtype: int <|skeleton|> class Solution: def countPrimes(self, n): ""...
b5e09f24e8e96454dc99e20281e853fb9fcc85ed
<|skeleton|> class Solution: def countPrimes(self, n): """:type n: int :rtype: int""" <|body_0|> def countPrimes_v0(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def countPrimes(self, n): """:type n: int :rtype: int""" is_prime = [True] * max(n, 2) is_prime[0], is_prime[1] = (False, False) x = 2 while x * x < n: if is_prime[x]: p = x * x while p < n: is_pr...
the_stack_v2_python_sparse
python/204_Count_Primes.py
Moby5/myleetcode
train
2
36411adfecc59a959c1b034ba26157f728bf06a8
[ "self.fileHandle = fileHandle\nself.dagPath = dagPath\nself.light = OpenMaya.MFnPointLight(dagPath)", "color = self.light.color()\nintensity = self.light.intensity()\ncolorR = self.rgcAndClamp(color.r * intensity)\ncolorG = self.rgcAndClamp(color.g * intensity)\ncolorB = self.rgcAndClamp(color.b * intensity)\nsel...
<|body_start_0|> self.fileHandle = fileHandle self.dagPath = dagPath self.light = OpenMaya.MFnPointLight(dagPath) <|end_body_0|> <|body_start_1|> color = self.light.color() intensity = self.light.intensity() colorR = self.rgcAndClamp(color.r * intensity) colorG =...
Point light type.
PointLight
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PointLight: """Point light type.""" def __init__(self, fileHandle, dagPath): """Constructor. Sets up this object's data.""" <|body_0|> def getOutput(self): """Return lux LightSource "point" from the given pointlight node.""" <|body_1|> <|end_skeleton|> ...
stack_v2_sparse_classes_36k_train_022576
4,533
no_license
[ { "docstring": "Constructor. Sets up this object's data.", "name": "__init__", "signature": "def __init__(self, fileHandle, dagPath)" }, { "docstring": "Return lux LightSource \"point\" from the given pointlight node.", "name": "getOutput", "signature": "def getOutput(self)" } ]
2
null
Implement the Python class `PointLight` described below. Class description: Point light type. Method signatures and docstrings: - def __init__(self, fileHandle, dagPath): Constructor. Sets up this object's data. - def getOutput(self): Return lux LightSource "point" from the given pointlight node.
Implement the Python class `PointLight` described below. Class description: Point light type. Method signatures and docstrings: - def __init__(self, fileHandle, dagPath): Constructor. Sets up this object's data. - def getOutput(self): Return lux LightSource "point" from the given pointlight node. <|skeleton|> class ...
3891e40c3c4c3a054e5ff1ff16d051d4e690cc4a
<|skeleton|> class PointLight: """Point light type.""" def __init__(self, fileHandle, dagPath): """Constructor. Sets up this object's data.""" <|body_0|> def getOutput(self): """Return lux LightSource "point" from the given pointlight node.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PointLight: """Point light type.""" def __init__(self, fileHandle, dagPath): """Constructor. Sets up this object's data.""" self.fileHandle = fileHandle self.dagPath = dagPath self.light = OpenMaya.MFnPointLight(dagPath) def getOutput(self): """Return lux Ligh...
the_stack_v2_python_sparse
luxPlugin/Lux/LuxExportModules/Light.py
LuxRender/LuxMaya
train
0
d2bb2c890a0934bd0f1a7c378bcf8eb2832bcd7a
[ "data = {'aerodrome': airport_icao, 'aerodromeRole': 'DEPARTURE'}\nresponse = self.client.service.queryFlightsByAerodrome(**data)\nreturn response", "now = datetime.now()\ndata = {'sendTime': now.strftime('%Y-%m-%d %H:%M:%S'), 'dataset': {'type': 'OPERATIONAL'}, 'includeProposalFlights': False, 'includeForecastFl...
<|body_start_0|> data = {'aerodrome': airport_icao, 'aerodromeRole': 'DEPARTURE'} response = self.client.service.queryFlightsByAerodrome(**data) return response <|end_body_0|> <|body_start_1|> now = datetime.now() data = {'sendTime': now.strftime('%Y-%m-%d %H:%M:%S'), 'dataset':...
FlightManagementService
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FlightManagementService: def get_departures(self, airport_icao: str) -> List[str]: """:param airport_icao: :return:""" <|body_0|> def get_arrivals(self, airport_icao: str) -> List[str]: """:param airport_icao: :return:""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_36k_train_022577
3,070
permissive
[ { "docstring": ":param airport_icao: :return:", "name": "get_departures", "signature": "def get_departures(self, airport_icao: str) -> List[str]" }, { "docstring": ":param airport_icao: :return:", "name": "get_arrivals", "signature": "def get_arrivals(self, airport_icao: str) -> List[str...
2
stack_v2_sparse_classes_30k_train_007288
Implement the Python class `FlightManagementService` described below. Class description: Implement the FlightManagementService class. Method signatures and docstrings: - def get_departures(self, airport_icao: str) -> List[str]: :param airport_icao: :return: - def get_arrivals(self, airport_icao: str) -> List[str]: :p...
Implement the Python class `FlightManagementService` described below. Class description: Implement the FlightManagementService class. Method signatures and docstrings: - def get_departures(self, airport_icao: str) -> List[str]: :param airport_icao: :return: - def get_arrivals(self, airport_icao: str) -> List[str]: :p...
d1dd3ce9d4abd84a5d16a877a86b6daaed5e6b49
<|skeleton|> class FlightManagementService: def get_departures(self, airport_icao: str) -> List[str]: """:param airport_icao: :return:""" <|body_0|> def get_arrivals(self, airport_icao: str) -> List[str]: """:param airport_icao: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FlightManagementService: def get_departures(self, airport_icao: str) -> List[str]: """:param airport_icao: :return:""" data = {'aerodrome': airport_icao, 'aerodromeRole': 'DEPARTURE'} response = self.client.service.queryFlightsByAerodrome(**data) return response def get_ar...
the_stack_v2_python_sparse
swim_aim/network_manager/services/flight_management.py
eurocontrol-swim/swim-aim
train
0
e46ed043ea5a36b0f0974ddb8f084e6e813cd5e5
[ "logger.info('Overriding class: Optimizer -> SSA.')\nsuper(SSA, self).__init__()\nself.build(params)\nlogger.info('Class overrided.')", "c1 = 2 * np.exp(-(4 * iteration / n_iterations) ** 2)\nfor i, _ in enumerate(space.agents):\n if i == 0:\n for j, (lb, ub) in enumerate(zip(space.agents[i].lb, space.a...
<|body_start_0|> logger.info('Overriding class: Optimizer -> SSA.') super(SSA, self).__init__() self.build(params) logger.info('Class overrided.') <|end_body_0|> <|body_start_1|> c1 = 2 * np.exp(-(4 * iteration / n_iterations) ** 2) for i, _ in enumerate(space.agents): ...
A SSA class, inherited from Optimizer. This is the designed class to define SSA-related variables and methods. References: S. Mirjalili et al. Salp Swarm Algorithm: A bio-inspired optimizer for engineering design problems. Advances in Engineering Software (2017).
SSA
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SSA: """A SSA class, inherited from Optimizer. This is the designed class to define SSA-related variables and methods. References: S. Mirjalili et al. Salp Swarm Algorithm: A bio-inspired optimizer for engineering design problems. Advances in Engineering Software (2017).""" def __init__(self...
stack_v2_sparse_classes_36k_train_022578
2,550
permissive
[ { "docstring": "Initialization method. Args: params: Contains key-value parameters to the meta-heuristics.", "name": "__init__", "signature": "def __init__(self, params: Optional[Dict[str, Any]]=None) -> None" }, { "docstring": "Wraps Salp Swarm Algorithm over all agents and variables. Args: spa...
2
stack_v2_sparse_classes_30k_train_002590
Implement the Python class `SSA` described below. Class description: A SSA class, inherited from Optimizer. This is the designed class to define SSA-related variables and methods. References: S. Mirjalili et al. Salp Swarm Algorithm: A bio-inspired optimizer for engineering design problems. Advances in Engineering Sof...
Implement the Python class `SSA` described below. Class description: A SSA class, inherited from Optimizer. This is the designed class to define SSA-related variables and methods. References: S. Mirjalili et al. Salp Swarm Algorithm: A bio-inspired optimizer for engineering design problems. Advances in Engineering Sof...
7326a887ed8e3858bc99c8815048d56d02edf88c
<|skeleton|> class SSA: """A SSA class, inherited from Optimizer. This is the designed class to define SSA-related variables and methods. References: S. Mirjalili et al. Salp Swarm Algorithm: A bio-inspired optimizer for engineering design problems. Advances in Engineering Software (2017).""" def __init__(self...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SSA: """A SSA class, inherited from Optimizer. This is the designed class to define SSA-related variables and methods. References: S. Mirjalili et al. Salp Swarm Algorithm: A bio-inspired optimizer for engineering design problems. Advances in Engineering Software (2017).""" def __init__(self, params: Opt...
the_stack_v2_python_sparse
opytimizer/optimizers/swarm/ssa.py
gugarosa/opytimizer
train
602
d623b02e7b2d98227866e3cfc49467a30e2cd2fc
[ "permissions = [IsAuthenticated]\nif self.action in ['update', 'partial_update']:\n permissions.append(IsCircleAdmin)\nreturn [p() for p in permissions]", "queryset = Circle.objects.all()\nif self.action == 'list':\n queryset = Circle.objects.filter(is_public=True)\nreturn queryset", "user = self.request....
<|body_start_0|> permissions = [IsAuthenticated] if self.action in ['update', 'partial_update']: permissions.append(IsCircleAdmin) return [p() for p in permissions] <|end_body_0|> <|body_start_1|> queryset = Circle.objects.all() if self.action == 'list': ...
Circle viewset.
CircleViewSet
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CircleViewSet: """Circle viewset.""" def get_permissions(self): """Permissions based in actions.""" <|body_0|> def get_queryset(self): """Specify and limit queryset in list action.""" <|body_1|> def perform_create(self, serializer): """Create...
stack_v2_sparse_classes_36k_train_022579
1,656
permissive
[ { "docstring": "Permissions based in actions.", "name": "get_permissions", "signature": "def get_permissions(self)" }, { "docstring": "Specify and limit queryset in list action.", "name": "get_queryset", "signature": "def get_queryset(self)" }, { "docstring": "Create the relation...
3
stack_v2_sparse_classes_30k_train_011590
Implement the Python class `CircleViewSet` described below. Class description: Circle viewset. Method signatures and docstrings: - def get_permissions(self): Permissions based in actions. - def get_queryset(self): Specify and limit queryset in list action. - def perform_create(self, serializer): Create the relationsh...
Implement the Python class `CircleViewSet` described below. Class description: Circle viewset. Method signatures and docstrings: - def get_permissions(self): Permissions based in actions. - def get_queryset(self): Specify and limit queryset in list action. - def perform_create(self, serializer): Create the relationsh...
5c3b7e97400170c20864ad74af7f524bccf87cf9
<|skeleton|> class CircleViewSet: """Circle viewset.""" def get_permissions(self): """Permissions based in actions.""" <|body_0|> def get_queryset(self): """Specify and limit queryset in list action.""" <|body_1|> def perform_create(self, serializer): """Create...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CircleViewSet: """Circle viewset.""" def get_permissions(self): """Permissions based in actions.""" permissions = [IsAuthenticated] if self.action in ['update', 'partial_update']: permissions.append(IsCircleAdmin) return [p() for p in permissions] def get_...
the_stack_v2_python_sparse
bookshare/circles/views/circles.py
ezecavallo/bookshare
train
0
5128e83fb502b228cb40431be2f8594450d43ebe
[ "self.wb = openpyxl.load_workbook(file_name)\nself.sheet = self.wb[sheet_name]\nself.list = list1", "rows_data = list(self.sheet.rows)\ntitles = []\ntitles.append(rows_data[0][self.list[0] - 1].value)\ntitles.append(rows_data[0][self.list[1] - 1].value)\ncases = []\nfor i in range(2, self.sheet.max_row + 1):\n ...
<|body_start_0|> self.wb = openpyxl.load_workbook(file_name) self.sheet = self.wb[sheet_name] self.list = list1 <|end_body_0|> <|body_start_1|> rows_data = list(self.sheet.rows) titles = [] titles.append(rows_data[0][self.list[0] - 1].value) titles.append(rows_da...
读取Excel数据
ReadExcel_dict
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReadExcel_dict: """读取Excel数据""" def __init__(self, file_name, sheet_name, list): """初始化读取对象 :param file_name: 文件名称 --> str :param sheet_name: 表单名称 --> str :param list1: 指定列 --> list""" <|body_0|> def read_date(self): """执行读取数据 :return:""" <|body_1|> <|en...
stack_v2_sparse_classes_36k_train_022580
2,188
no_license
[ { "docstring": "初始化读取对象 :param file_name: 文件名称 --> str :param sheet_name: 表单名称 --> str :param list1: 指定列 --> list", "name": "__init__", "signature": "def __init__(self, file_name, sheet_name, list)" }, { "docstring": "执行读取数据 :return:", "name": "read_date", "signature": "def read_date(sel...
2
null
Implement the Python class `ReadExcel_dict` described below. Class description: 读取Excel数据 Method signatures and docstrings: - def __init__(self, file_name, sheet_name, list): 初始化读取对象 :param file_name: 文件名称 --> str :param sheet_name: 表单名称 --> str :param list1: 指定列 --> list - def read_date(self): 执行读取数据 :return:
Implement the Python class `ReadExcel_dict` described below. Class description: 读取Excel数据 Method signatures and docstrings: - def __init__(self, file_name, sheet_name, list): 初始化读取对象 :param file_name: 文件名称 --> str :param sheet_name: 表单名称 --> str :param list1: 指定列 --> list - def read_date(self): 执行读取数据 :return: <|ske...
f8a98389fa09f95e72914afa4935afc5c68eaccd
<|skeleton|> class ReadExcel_dict: """读取Excel数据""" def __init__(self, file_name, sheet_name, list): """初始化读取对象 :param file_name: 文件名称 --> str :param sheet_name: 表单名称 --> str :param list1: 指定列 --> list""" <|body_0|> def read_date(self): """执行读取数据 :return:""" <|body_1|> <|en...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ReadExcel_dict: """读取Excel数据""" def __init__(self, file_name, sheet_name, list): """初始化读取对象 :param file_name: 文件名称 --> str :param sheet_name: 表单名称 --> str :param list1: 指定列 --> list""" self.wb = openpyxl.load_workbook(file_name) self.sheet = self.wb[sheet_name] self.list =...
the_stack_v2_python_sparse
py_1816_readexcel/py_1816_excelclass_dict.py
2020668/python2019
train
0
5a4a2e05c4b732b0e74ddf0027af83494308d0ee
[ "ans = ''\nfor w in words:\n if any((not self.is_subseq(s, w), len(w) < len(ans), len(w) == len(ans) and w >= ans)):\n continue\n ans = w\nreturn ans", "m, n = (len(s), len(t))\ni = j = 0\nwhile i < m and j < n:\n if s[i] == t[j]:\n j += 1\n i += 1\nreturn j == n" ]
<|body_start_0|> ans = '' for w in words: if any((not self.is_subseq(s, w), len(w) < len(ans), len(w) == len(ans) and w >= ans)): continue ans = w return ans <|end_body_0|> <|body_start_1|> m, n = (len(s), len(t)) i = j = 0 while i...
1. to check the word in list is subsequence of given s 2. ignoring if the length less than current ans 3. ignoring if the length equal current ans but has larger lexicographical order
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: """1. to check the word in list is subsequence of given s 2. ignoring if the length less than current ans 3. ignoring if the length equal current ans but has larger lexicographical order""" def findLongestWord(self, s, words): """:type s: str :type words: List[str] :rtype: ...
stack_v2_sparse_classes_36k_train_022581
1,814
no_license
[ { "docstring": ":type s: str :type words: List[str] :rtype: str", "name": "findLongestWord", "signature": "def findLongestWord(self, s, words)" }, { "docstring": "return True if `t` is subsequence of `s`", "name": "is_subseq", "signature": "def is_subseq(self, s, t)" } ]
2
null
Implement the Python class `Solution` described below. Class description: 1. to check the word in list is subsequence of given s 2. ignoring if the length less than current ans 3. ignoring if the length equal current ans but has larger lexicographical order Method signatures and docstrings: - def findLongestWord(self...
Implement the Python class `Solution` described below. Class description: 1. to check the word in list is subsequence of given s 2. ignoring if the length less than current ans 3. ignoring if the length equal current ans but has larger lexicographical order Method signatures and docstrings: - def findLongestWord(self...
91892fd64281d96b8a9d5c0d57b938c314ae71be
<|skeleton|> class Solution: """1. to check the word in list is subsequence of given s 2. ignoring if the length less than current ans 3. ignoring if the length equal current ans but has larger lexicographical order""" def findLongestWord(self, s, words): """:type s: str :type words: List[str] :rtype: ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: """1. to check the word in list is subsequence of given s 2. ignoring if the length less than current ans 3. ignoring if the length equal current ans but has larger lexicographical order""" def findLongestWord(self, s, words): """:type s: str :type words: List[str] :rtype: str""" ...
the_stack_v2_python_sparse
leetcode/524_longest_word_in_dictionary_through_deleting.py
jaychsu/algorithm
train
143
ad141647a7c3bceeca57e8ebbbaeb62e6e2f1a45
[ "def PreOrder(root: TreeNode, Trace: [], TraceSet: set):\n if root.val in TraceSet:\n root.val = str(root.val) + '_' + str(random.randint(0, 99999))\n Trace.append(root.val)\n else:\n TraceSet.add(root.val)\n Trace.append(str(root.val))\n if root.left:\n PreOrder(root.lef...
<|body_start_0|> def PreOrder(root: TreeNode, Trace: [], TraceSet: set): if root.val in TraceSet: root.val = str(root.val) + '_' + str(random.randint(0, 99999)) Trace.append(root.val) else: TraceSet.add(root.val) Trace.appen...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data: str) -> TreeNode: """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|b...
stack_v2_sparse_classes_36k_train_022582
2,331
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root: TreeNode) -> str" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature"...
2
null
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data: str) -> TreeNode: Decodes your encoded dat...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data: str) -> TreeNode: Decodes your encoded dat...
45cabf05251711c6421c8c2ddbcc3fec9222f70a
<|skeleton|> class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data: str) -> TreeNode: """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|b...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" def PreOrder(root: TreeNode, Trace: [], TraceSet: set): if root.val in TraceSet: root.val = str(root.val) + '_' + str(random.randint(0, 99999...
the_stack_v2_python_sparse
Hard/297/297.py
GuoYunZheSE/Leetcode
train
1
64be43b9300501a54ff610bf9b52c471e37b7c6d
[ "values = self.getValues('SELECT max(c.coverage_anysense_pcovered) FROM \\n %(track)s_transcript_counts as c,\\n %(reference)s_transcript2gene as i\\n WHERE c.coverage_anysense_nval > %(min_...
<|body_start_0|> values = self.getValues('SELECT max(c.coverage_anysense_pcovered) FROM \n %(track)s_transcript_counts as c,\n %(reference)s_transcript2gene as i\n WHERE c.coverage_anyse...
status information on transcriptome building.
TranscriptStatus
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TranscriptStatus: """status information on transcriptome building.""" def testGeneCoverage(self, track): """test coverage of known protein coding transcript models with reads. PASS: >= 20% of expressed genes >90% covered WARN: <= 20% of expressed genes >90% covered FAIL: <= 10% of ex...
stack_v2_sparse_classes_36k_train_022583
3,919
permissive
[ { "docstring": "test coverage of known protein coding transcript models with reads. PASS: >= 20% of expressed genes >90% covered WARN: <= 20% of expressed genes >90% covered FAIL: <= 10% of expressed genes >90% covered Only genes with at least 5 reads mapping to them are used in order to only take into account ...
3
null
Implement the Python class `TranscriptStatus` described below. Class description: status information on transcriptome building. Method signatures and docstrings: - def testGeneCoverage(self, track): test coverage of known protein coding transcript models with reads. PASS: >= 20% of expressed genes >90% covered WARN: ...
Implement the Python class `TranscriptStatus` described below. Class description: status information on transcriptome building. Method signatures and docstrings: - def testGeneCoverage(self, track): test coverage of known protein coding transcript models with reads. PASS: >= 20% of expressed genes >90% covered WARN: ...
fe39fc42e1e919690426c9f34c68770f4f360d5a
<|skeleton|> class TranscriptStatus: """status information on transcriptome building.""" def testGeneCoverage(self, track): """test coverage of known protein coding transcript models with reads. PASS: >= 20% of expressed genes >90% covered WARN: <= 20% of expressed genes >90% covered FAIL: <= 10% of ex...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TranscriptStatus: """status information on transcriptome building.""" def testGeneCoverage(self, track): """test coverage of known protein coding transcript models with reads. PASS: >= 20% of expressed genes >90% covered WARN: <= 20% of expressed genes >90% covered FAIL: <= 10% of expressed genes...
the_stack_v2_python_sparse
CGATPipelines/pipeline_docs/pipeline_rnaseqtranscripts/trackers/Status.py
Acribbs/CGATPipelines
train
1
6445011fae0a63971ef3f22d24228138feb73828
[ "func_name = sys._getframe().f_code.co_name\nres = self.get_result(func_name)\nerrmsg = res[0].json()['errmsg']\ncouponrule_list = res[0].json()['data']\ngl.set_value('couponrule_list', couponrule_list)\nexpect_errmsg = self.get_expect_result(func_name)\nrow = self.get_case_row_index(func_name)\nself.update_result(...
<|body_start_0|> func_name = sys._getframe().f_code.co_name res = self.get_result(func_name) errmsg = res[0].json()['errmsg'] couponrule_list = res[0].json()['data'] gl.set_value('couponrule_list', couponrule_list) expect_errmsg = self.get_expect_result(func_name) ...
UserList
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserList: def test_urine_v2_couponManager_getAllCouponRules(self): """查询所有优惠券 :return:""" <|body_0|> def test_urine_v2_userInfo_getUserList(self): """查询用户列表 :return:""" <|body_1|> def test_urine_v2_userInfo_giftCoupons(self): """赠送优惠券 :return:"""...
stack_v2_sparse_classes_36k_train_022584
2,541
no_license
[ { "docstring": "查询所有优惠券 :return:", "name": "test_urine_v2_couponManager_getAllCouponRules", "signature": "def test_urine_v2_couponManager_getAllCouponRules(self)" }, { "docstring": "查询用户列表 :return:", "name": "test_urine_v2_userInfo_getUserList", "signature": "def test_urine_v2_userInfo_g...
3
null
Implement the Python class `UserList` described below. Class description: Implement the UserList class. Method signatures and docstrings: - def test_urine_v2_couponManager_getAllCouponRules(self): 查询所有优惠券 :return: - def test_urine_v2_userInfo_getUserList(self): 查询用户列表 :return: - def test_urine_v2_userInfo_giftCoupons...
Implement the Python class `UserList` described below. Class description: Implement the UserList class. Method signatures and docstrings: - def test_urine_v2_couponManager_getAllCouponRules(self): 查询所有优惠券 :return: - def test_urine_v2_userInfo_getUserList(self): 查询用户列表 :return: - def test_urine_v2_userInfo_giftCoupons...
6837a07ff200b610e7ba799a52543493848b6026
<|skeleton|> class UserList: def test_urine_v2_couponManager_getAllCouponRules(self): """查询所有优惠券 :return:""" <|body_0|> def test_urine_v2_userInfo_getUserList(self): """查询用户列表 :return:""" <|body_1|> def test_urine_v2_userInfo_giftCoupons(self): """赠送优惠券 :return:"""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserList: def test_urine_v2_couponManager_getAllCouponRules(self): """查询所有优惠券 :return:""" func_name = sys._getframe().f_code.co_name res = self.get_result(func_name) errmsg = res[0].json()['errmsg'] couponrule_list = res[0].json()['data'] gl.set_value('couponrul...
the_stack_v2_python_sparse
run/user_management/test_user_list.py
liwei123a/APITestFrame
train
0
e1234ffcaeecb11cc6b6beac88eb5414b5c6a852
[ "self.window = collections.deque(maxlen=size)\nself.sum = 0\nself.size = size", "if len(self.window) == self.size:\n self.sum -= self.window[0]\nself.sum += val\nself.window.append(val)\nreturn self.sum / float(len(self.window))" ]
<|body_start_0|> self.window = collections.deque(maxlen=size) self.sum = 0 self.size = size <|end_body_0|> <|body_start_1|> if len(self.window) == self.size: self.sum -= self.window[0] self.sum += val self.window.append(val) return self.sum / float(le...
MovingAverage
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MovingAverage: def __init__(self, size): """Initialize your data structure here. :type size: int""" <|body_0|> def next(self, val): """:type val: int :rtype: float""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.window = collections.deque(maxle...
stack_v2_sparse_classes_36k_train_022585
793
no_license
[ { "docstring": "Initialize your data structure here. :type size: int", "name": "__init__", "signature": "def __init__(self, size)" }, { "docstring": ":type val: int :rtype: float", "name": "next", "signature": "def next(self, val)" } ]
2
stack_v2_sparse_classes_30k_test_000262
Implement the Python class `MovingAverage` described below. Class description: Implement the MovingAverage class. Method signatures and docstrings: - def __init__(self, size): Initialize your data structure here. :type size: int - def next(self, val): :type val: int :rtype: float
Implement the Python class `MovingAverage` described below. Class description: Implement the MovingAverage class. Method signatures and docstrings: - def __init__(self, size): Initialize your data structure here. :type size: int - def next(self, val): :type val: int :rtype: float <|skeleton|> class MovingAverage: ...
94472f9b742571a4325b069a4c931610f1715542
<|skeleton|> class MovingAverage: def __init__(self, size): """Initialize your data structure here. :type size: int""" <|body_0|> def next(self, val): """:type val: int :rtype: float""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MovingAverage: def __init__(self, size): """Initialize your data structure here. :type size: int""" self.window = collections.deque(maxlen=size) self.sum = 0 self.size = size def next(self, val): """:type val: int :rtype: float""" if len(self.window) == sel...
the_stack_v2_python_sparse
leetcode-algorithms/346. Moving Average from Data Stream/MovingAverage.py
zzhyzzh/Leetcode
train
0
313840de514e25988a1b9083493f72b6e01afdcc
[ "json_dict = json.loads(request.body.decode())\nsku_id = json_dict.get('sku_id')\nfrom goods.models import SKU\ntry:\n SKU.objects.get(id=sku_id)\nexcept SKU.DoesNotExist:\n return http.HttpResponseForbidden('sku不存在')\nredis_conn = get_redis_connection('history')\npl = redis_conn.pipeline()\nuser_id = request...
<|body_start_0|> json_dict = json.loads(request.body.decode()) sku_id = json_dict.get('sku_id') from goods.models import SKU try: SKU.objects.get(id=sku_id) except SKU.DoesNotExist: return http.HttpResponseForbidden('sku不存在') redis_conn = get_redis...
用户浏览记录
UserBrowseHistory
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserBrowseHistory: """用户浏览记录""" def post(self, request): """保存用户浏览记录""" <|body_0|> def get(self, request): """获取用户浏览记录""" <|body_1|> <|end_skeleton|> <|body_start_0|> json_dict = json.loads(request.body.decode()) sku_id = json_dict.get('...
stack_v2_sparse_classes_36k_train_022586
24,646
permissive
[ { "docstring": "保存用户浏览记录", "name": "post", "signature": "def post(self, request)" }, { "docstring": "获取用户浏览记录", "name": "get", "signature": "def get(self, request)" } ]
2
null
Implement the Python class `UserBrowseHistory` described below. Class description: 用户浏览记录 Method signatures and docstrings: - def post(self, request): 保存用户浏览记录 - def get(self, request): 获取用户浏览记录
Implement the Python class `UserBrowseHistory` described below. Class description: 用户浏览记录 Method signatures and docstrings: - def post(self, request): 保存用户浏览记录 - def get(self, request): 获取用户浏览记录 <|skeleton|> class UserBrowseHistory: """用户浏览记录""" def post(self, request): """保存用户浏览记录""" <|body...
f89c80a22c5065b46900a20bd505614b5bcb2e6e
<|skeleton|> class UserBrowseHistory: """用户浏览记录""" def post(self, request): """保存用户浏览记录""" <|body_0|> def get(self, request): """获取用户浏览记录""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserBrowseHistory: """用户浏览记录""" def post(self, request): """保存用户浏览记录""" json_dict = json.loads(request.body.decode()) sku_id = json_dict.get('sku_id') from goods.models import SKU try: SKU.objects.get(id=sku_id) except SKU.DoesNotExist: ...
the_stack_v2_python_sparse
meiduo_mall/meiduo_mall/apps/users/views.py
ZHD165/Django_-
train
0
eda8de8ccada37bedd3845bd948fc30cfa7d0ad1
[ "cube1 = Cube('red', 6)\ncube2 = Cube('blue', 5)\nstacked_list = [cube1, cube2]\nself.assertEqual(calc_height(stacked_list), 'The maximum tower height is 11')", "cube1 = Cube('red', 5)\ncube2 = Cube('red', 5)\ncube_list = [cube1, cube2]\nwith self.assertRaises(ValueError):\n stack_cubes(cube_list)", "cube1 =...
<|body_start_0|> cube1 = Cube('red', 6) cube2 = Cube('blue', 5) stacked_list = [cube1, cube2] self.assertEqual(calc_height(stacked_list), 'The maximum tower height is 11') <|end_body_0|> <|body_start_1|> cube1 = Cube('red', 5) cube2 = Cube('red', 5) cube_list = [...
UnitTest
UnitTest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UnitTest: """UnitTest""" def test_calc_height(self): """test_calc_height: Testing calculate_height function""" <|body_0|> def test_failure(self): """test_failure: Make sure a ValueError is raised if you cannot stack the cubes""" <|body_1|> def test_w...
stack_v2_sparse_classes_36k_train_022587
1,393
no_license
[ { "docstring": "test_calc_height: Testing calculate_height function", "name": "test_calc_height", "signature": "def test_calc_height(self)" }, { "docstring": "test_failure: Make sure a ValueError is raised if you cannot stack the cubes", "name": "test_failure", "signature": "def test_fai...
3
stack_v2_sparse_classes_30k_train_014164
Implement the Python class `UnitTest` described below. Class description: UnitTest Method signatures and docstrings: - def test_calc_height(self): test_calc_height: Testing calculate_height function - def test_failure(self): test_failure: Make sure a ValueError is raised if you cannot stack the cubes - def test_wides...
Implement the Python class `UnitTest` described below. Class description: UnitTest Method signatures and docstrings: - def test_calc_height(self): test_calc_height: Testing calculate_height function - def test_failure(self): test_failure: Make sure a ValueError is raised if you cannot stack the cubes - def test_wides...
78f8f8d575e69da8d0c48929a562b0e9f64ab68d
<|skeleton|> class UnitTest: """UnitTest""" def test_calc_height(self): """test_calc_height: Testing calculate_height function""" <|body_0|> def test_failure(self): """test_failure: Make sure a ValueError is raised if you cannot stack the cubes""" <|body_1|> def test_w...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UnitTest: """UnitTest""" def test_calc_height(self): """test_calc_height: Testing calculate_height function""" cube1 = Cube('red', 6) cube2 = Cube('blue', 5) stacked_list = [cube1, cube2] self.assertEqual(calc_height(stacked_list), 'The maximum tower height is 11')...
the_stack_v2_python_sparse
task3/unit_test.py
jamesl33/210CT-Course-Work
train
0
436c414299ee28c6925d701acf6c3a137544a930
[ "ac = ActivityTypes.objects.filter(type_status=1)\npg = MyNumberPagination()\nret = ActiviyTypeSerializer(instance=ac, many=True)\nreturn Response(ret.data)", "ret = {'code': '1000', 'msg': None}\ntype_info = request.data\nprint(type_info)\nActivityTypes.objects.get(pk=2)\nActivityTypes.objects.create(type_name=t...
<|body_start_0|> ac = ActivityTypes.objects.filter(type_status=1) pg = MyNumberPagination() ret = ActiviyTypeSerializer(instance=ac, many=True) return Response(ret.data) <|end_body_0|> <|body_start_1|> ret = {'code': '1000', 'msg': None} type_info = request.data ...
ActivityType
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ActivityType: def get(self, request, *args, **kwargs): """获取所有活动类型""" <|body_0|> def post(self, request, *args, **kwargs): """添加活动类型""" <|body_1|> <|end_skeleton|> <|body_start_0|> ac = ActivityTypes.objects.filter(type_status=1) pg = MyNumb...
stack_v2_sparse_classes_36k_train_022588
33,770
no_license
[ { "docstring": "获取所有活动类型", "name": "get", "signature": "def get(self, request, *args, **kwargs)" }, { "docstring": "添加活动类型", "name": "post", "signature": "def post(self, request, *args, **kwargs)" } ]
2
stack_v2_sparse_classes_30k_train_014562
Implement the Python class `ActivityType` described below. Class description: Implement the ActivityType class. Method signatures and docstrings: - def get(self, request, *args, **kwargs): 获取所有活动类型 - def post(self, request, *args, **kwargs): 添加活动类型
Implement the Python class `ActivityType` described below. Class description: Implement the ActivityType class. Method signatures and docstrings: - def get(self, request, *args, **kwargs): 获取所有活动类型 - def post(self, request, *args, **kwargs): 添加活动类型 <|skeleton|> class ActivityType: def get(self, request, *args, ...
1d85ddac5c99094e943b6b736b6a2c873240b2d4
<|skeleton|> class ActivityType: def get(self, request, *args, **kwargs): """获取所有活动类型""" <|body_0|> def post(self, request, *args, **kwargs): """添加活动类型""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ActivityType: def get(self, request, *args, **kwargs): """获取所有活动类型""" ac = ActivityTypes.objects.filter(type_status=1) pg = MyNumberPagination() ret = ActiviyTypeSerializer(instance=ac, many=True) return Response(ret.data) def post(self, request, *args, **kwargs): ...
the_stack_v2_python_sparse
SecondClass/activities/views.py
akengakenga/myProjects
train
1
f5b32c67abb169fe308f80d1b337d293044c3b15
[ "self.scannr = env.nextScanID\nenv.nextScanID += 1\nu.verbose.set_level(3)\ndata = u.Param()\ndata.shape = 128\ndata.num_frames = 100\ndata.density = 0.2\ndata.min_frames = 1\ndata.label = None\ndata.psize = 0.000172\ndata.energy = 6.2\ndata.center = 'fftshift'\ndata.distance = 7\ndata.auto_center = True\ndata.orie...
<|body_start_0|> self.scannr = env.nextScanID env.nextScanID += 1 u.verbose.set_level(3) data = u.Param() data.shape = 128 data.num_frames = 100 data.density = 0.2 data.min_frames = 1 data.label = None data.psize = 0.000172 data.ene...
Dummy macro which produces data from ptypy's MoonFlowerScan. Does not use actual detectors or motors, but puts data in all active recorders.
Dummy_Ptycho
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Dummy_Ptycho: """Dummy macro which produces data from ptypy's MoonFlowerScan. Does not use actual detectors or motors, but puts data in all active recorders.""" def __init__(self): """The constructor should parse parameters.""" <|body_0|> def run(self): """This m...
stack_v2_sparse_classes_36k_train_022589
3,306
permissive
[ { "docstring": "The constructor should parse parameters.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "This method does all the serious interaction with motors, detectors, and data recorders.", "name": "run", "signature": "def run(self)" } ]
2
null
Implement the Python class `Dummy_Ptycho` described below. Class description: Dummy macro which produces data from ptypy's MoonFlowerScan. Does not use actual detectors or motors, but puts data in all active recorders. Method signatures and docstrings: - def __init__(self): The constructor should parse parameters. - ...
Implement the Python class `Dummy_Ptycho` described below. Class description: Dummy macro which produces data from ptypy's MoonFlowerScan. Does not use actual detectors or motors, but puts data in all active recorders. Method signatures and docstrings: - def __init__(self): The constructor should parse parameters. - ...
65a3b754068478fd518ab3b554397f0682c5d8ac
<|skeleton|> class Dummy_Ptycho: """Dummy macro which produces data from ptypy's MoonFlowerScan. Does not use actual detectors or motors, but puts data in all active recorders.""" def __init__(self): """The constructor should parse parameters.""" <|body_0|> def run(self): """This m...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Dummy_Ptycho: """Dummy macro which produces data from ptypy's MoonFlowerScan. Does not use actual detectors or motors, but puts data in all active recorders.""" def __init__(self): """The constructor should parse parameters.""" self.scannr = env.nextScanID env.nextScanID += 1 ...
the_stack_v2_python_sparse
contrast-master/beamlines/dummy/Ptycho_scan_v2.py
Lexelius/Contrast-ptycho
train
1
9495ccc6c21bd33d4569f3b40b22860e6fc2821b
[ "if not self.ITEM_MODEL:\n raise NotImplementedError(f'ITEM_MODEL attribute not defined for {__class__}')\nids = []\nfor k in [self.ITEM_KEY + x for x in ['', '[]', 's', 's[]']]:\n if (ids := self.request.query_params.getlist(k, [])):\n break\nvalid_ids = []\nfor id in ids:\n try:\n valid_ids...
<|body_start_0|> if not self.ITEM_MODEL: raise NotImplementedError(f'ITEM_MODEL attribute not defined for {__class__}') ids = [] for k in [self.ITEM_KEY + x for x in ['', '[]', 's', 's[]']]: if (ids := self.request.query_params.getlist(k, [])): break ...
Mixin for extracting multiple objects from query params. Each subclass *must* have an attribute called 'ITEM_KEY', which is used to determine what 'key' is used in the query parameters. This mixin defines a 'get_items' method which provides a generic implementation to return a list of matching database model instances
ReportFilterMixin
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReportFilterMixin: """Mixin for extracting multiple objects from query params. Each subclass *must* have an attribute called 'ITEM_KEY', which is used to determine what 'key' is used in the query parameters. This mixin defines a 'get_items' method which provides a generic implementation to return...
stack_v2_sparse_classes_36k_train_022590
19,444
permissive
[ { "docstring": "Return a list of database objects from query parameters", "name": "get_items", "signature": "def get_items(self)" }, { "docstring": "Filter the queryset based on the provided report ID values. As each 'report' instance may optionally define its own filters, the resulting queryset...
2
stack_v2_sparse_classes_30k_train_003591
Implement the Python class `ReportFilterMixin` described below. Class description: Mixin for extracting multiple objects from query params. Each subclass *must* have an attribute called 'ITEM_KEY', which is used to determine what 'key' is used in the query parameters. This mixin defines a 'get_items' method which prov...
Implement the Python class `ReportFilterMixin` described below. Class description: Mixin for extracting multiple objects from query params. Each subclass *must* have an attribute called 'ITEM_KEY', which is used to determine what 'key' is used in the query parameters. This mixin defines a 'get_items' method which prov...
e88a8e99a5f0b201c67a95cba097c729f090d5e2
<|skeleton|> class ReportFilterMixin: """Mixin for extracting multiple objects from query params. Each subclass *must* have an attribute called 'ITEM_KEY', which is used to determine what 'key' is used in the query parameters. This mixin defines a 'get_items' method which provides a generic implementation to return...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ReportFilterMixin: """Mixin for extracting multiple objects from query params. Each subclass *must* have an attribute called 'ITEM_KEY', which is used to determine what 'key' is used in the query parameters. This mixin defines a 'get_items' method which provides a generic implementation to return a list of ma...
the_stack_v2_python_sparse
InvenTree/report/api.py
inventree/InvenTree
train
3,077
4c308c06c751e5f143037c31c71b45ff8c37d022
[ "array = self.format_and_eval_string(self.target_array)\nif self.column_name:\n array = array[self.column_name]\nval = self.format_and_eval_string(self.value)\ntry:\n ind = np.where(np.abs(array - val) < 1e-12)[0][0]\nexcept IndexError as e:\n msg = 'Could not find {} in array {} ({})'\n raise ValueErro...
<|body_start_0|> array = self.format_and_eval_string(self.target_array) if self.column_name: array = array[self.column_name] val = self.format_and_eval_string(self.value) try: ind = np.where(np.abs(array - val) < 1e-12)[0][0] except IndexError as e: ...
Store the index of the first occurence of a value in an array. Wait for any parallel operation before execution.
ArrayFindValueTask
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ArrayFindValueTask: """Store the index of the first occurence of a value in an array. Wait for any parallel operation before execution.""" def perform(self): """Find index of value array and store index in database.""" <|body_0|> def check(self, *args, **kwargs): ...
stack_v2_sparse_classes_36k_train_022591
6,289
permissive
[ { "docstring": "Find index of value array and store index in database.", "name": "perform", "signature": "def perform(self)" }, { "docstring": "Check the target array can be found and has the right column.", "name": "check", "signature": "def check(self, *args, **kwargs)" } ]
2
stack_v2_sparse_classes_30k_train_009664
Implement the Python class `ArrayFindValueTask` described below. Class description: Store the index of the first occurence of a value in an array. Wait for any parallel operation before execution. Method signatures and docstrings: - def perform(self): Find index of value array and store index in database. - def check...
Implement the Python class `ArrayFindValueTask` described below. Class description: Store the index of the first occurence of a value in an array. Wait for any parallel operation before execution. Method signatures and docstrings: - def perform(self): Find index of value array and store index in database. - def check...
b6f1f5b236c7a4e28d9a3bc8da9820c52d789309
<|skeleton|> class ArrayFindValueTask: """Store the index of the first occurence of a value in an array. Wait for any parallel operation before execution.""" def perform(self): """Find index of value array and store index in database.""" <|body_0|> def check(self, *args, **kwargs): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ArrayFindValueTask: """Store the index of the first occurence of a value in an array. Wait for any parallel operation before execution.""" def perform(self): """Find index of value array and store index in database.""" array = self.format_and_eval_string(self.target_array) if self...
the_stack_v2_python_sparse
exopy_hqc_legacy/tasks/tasks/util/array_tasks.py
Exopy/exopy_hqc_legacy
train
0
0eeeee4084d8e99ceb462fc67f8ef41a15ef6f9b
[ "logger.info('Overriding class: PSO -> SAVPSO.')\nsuper(SAVPSO, self).__init__(params)\nlogger.info('Class overrided.')", "positions = np.zeros((space.agents[0].position.shape[0], space.agents[0].position.shape[1]))\nfor agent in space.agents:\n positions += agent.position\npositions /= len(space.agents)\nfor ...
<|body_start_0|> logger.info('Overriding class: PSO -> SAVPSO.') super(SAVPSO, self).__init__(params) logger.info('Class overrided.') <|end_body_0|> <|body_start_1|> positions = np.zeros((space.agents[0].position.shape[0], space.agents[0].position.shape[1])) for agent in space.a...
An SAVPSO class, inherited from Optimizer. This is the designed class to define SAVPSO-related variables and methods. References: H. Lu and W. Chen. Self-adaptive velocity particle swarm optimization for solving constrained optimization problems. Journal of global optimization (2008).
SAVPSO
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SAVPSO: """An SAVPSO class, inherited from Optimizer. This is the designed class to define SAVPSO-related variables and methods. References: H. Lu and W. Chen. Self-adaptive velocity particle swarm optimization for solving constrained optimization problems. Journal of global optimization (2008)."...
stack_v2_sparse_classes_36k_train_022592
15,941
permissive
[ { "docstring": "Initialization method. Args: params: Contains key-value parameters to the meta-heuristics.", "name": "__init__", "signature": "def __init__(self, params: Optional[Dict[str, Any]]=None) -> None" }, { "docstring": "Wraps Self-adaptive Velocity Particle Swarm Optimization over all a...
2
stack_v2_sparse_classes_30k_train_014871
Implement the Python class `SAVPSO` described below. Class description: An SAVPSO class, inherited from Optimizer. This is the designed class to define SAVPSO-related variables and methods. References: H. Lu and W. Chen. Self-adaptive velocity particle swarm optimization for solving constrained optimization problems. ...
Implement the Python class `SAVPSO` described below. Class description: An SAVPSO class, inherited from Optimizer. This is the designed class to define SAVPSO-related variables and methods. References: H. Lu and W. Chen. Self-adaptive velocity particle swarm optimization for solving constrained optimization problems. ...
7326a887ed8e3858bc99c8815048d56d02edf88c
<|skeleton|> class SAVPSO: """An SAVPSO class, inherited from Optimizer. This is the designed class to define SAVPSO-related variables and methods. References: H. Lu and W. Chen. Self-adaptive velocity particle swarm optimization for solving constrained optimization problems. Journal of global optimization (2008)."...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SAVPSO: """An SAVPSO class, inherited from Optimizer. This is the designed class to define SAVPSO-related variables and methods. References: H. Lu and W. Chen. Self-adaptive velocity particle swarm optimization for solving constrained optimization problems. Journal of global optimization (2008).""" def _...
the_stack_v2_python_sparse
opytimizer/optimizers/swarm/pso.py
gugarosa/opytimizer
train
602
0f05afc3dd0e3dbe5d069a74e1614d5bc86e7d56
[ "tableview.superview['search_field'].end_editing()\nif tableview.editing:\n tableview.superview['editbar']['delete'].enabled = True\n tableview.superview['editbar']['share'].enabled = True\nelse:\n item = vocab.tableview_cell_for_row(tableview, section, row)\n load_word_view(item.text_label.text)", "i...
<|body_start_0|> tableview.superview['search_field'].end_editing() if tableview.editing: tableview.superview['editbar']['delete'].enabled = True tableview.superview['editbar']['share'].enabled = True else: item = vocab.tableview_cell_for_row(tableview, section...
The delegate class to handle the vocabulary table.
TableViewDelegate
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TableViewDelegate: """The delegate class to handle the vocabulary table.""" def tableview_did_select(self, tableview, section, row): """Call when the user selects a table row. For some reason, setting the `action` attribute in the UI designer passes an empty ui.ListDataSource as the ...
stack_v2_sparse_classes_36k_train_022593
21,181
permissive
[ { "docstring": "Call when the user selects a table row. For some reason, setting the `action` attribute in the UI designer passes an empty ui.ListDataSource as the sender. This method fixes it.", "name": "tableview_did_select", "signature": "def tableview_did_select(self, tableview, section, row)" }, ...
2
stack_v2_sparse_classes_30k_train_004134
Implement the Python class `TableViewDelegate` described below. Class description: The delegate class to handle the vocabulary table. Method signatures and docstrings: - def tableview_did_select(self, tableview, section, row): Call when the user selects a table row. For some reason, setting the `action` attribute in ...
Implement the Python class `TableViewDelegate` described below. Class description: The delegate class to handle the vocabulary table. Method signatures and docstrings: - def tableview_did_select(self, tableview, section, row): Call when the user selects a table row. For some reason, setting the `action` attribute in ...
1d62f21c3492bfcf3e2ab360cfae52e5fc1b2853
<|skeleton|> class TableViewDelegate: """The delegate class to handle the vocabulary table.""" def tableview_did_select(self, tableview, section, row): """Call when the user selects a table row. For some reason, setting the `action` attribute in the UI designer passes an empty ui.ListDataSource as the ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TableViewDelegate: """The delegate class to handle the vocabulary table.""" def tableview_did_select(self, tableview, section, row): """Call when the user selects a table row. For some reason, setting the `action` attribute in the UI designer passes an empty ui.ListDataSource as the sender. This ...
the_stack_v2_python_sparse
WordRoom.py
johnridesabike/WordRoom
train
10
ce1f2b01c6c37c68e2892c96180f66f6fa7e013d
[ "value = bytes(json.dumps(message, cls=DjangoJSONEncoder), encoding='utf-8')\nif self.crypter:\n value = self.crypter.encrypt(value)\nrandom_prefix = random.getrandbits(8 * 12).to_bytes(12, 'big')\nreturn random_prefix + value", "message = message[12:]\nmessage = message.decode('utf-8')\nif self.crypter:\n ...
<|body_start_0|> value = bytes(json.dumps(message, cls=DjangoJSONEncoder), encoding='utf-8') if self.crypter: value = self.crypter.encrypt(value) random_prefix = random.getrandbits(8 * 12).to_bytes(12, 'big') return random_prefix + value <|end_body_0|> <|body_start_1|> ...
Use json to serialize and deserialize messages.
JsonRedisChannelLayer
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JsonRedisChannelLayer: """Use json to serialize and deserialize messages.""" def serialize(self, message): """Serializes message in json.""" <|body_0|> def deserialize(self, message): """Deserializes from a byte string.""" <|body_1|> <|end_skeleton|> <|...
stack_v2_sparse_classes_36k_train_022594
1,096
permissive
[ { "docstring": "Serializes message in json.", "name": "serialize", "signature": "def serialize(self, message)" }, { "docstring": "Deserializes from a byte string.", "name": "deserialize", "signature": "def deserialize(self, message)" } ]
2
stack_v2_sparse_classes_30k_train_017068
Implement the Python class `JsonRedisChannelLayer` described below. Class description: Use json to serialize and deserialize messages. Method signatures and docstrings: - def serialize(self, message): Serializes message in json. - def deserialize(self, message): Deserializes from a byte string.
Implement the Python class `JsonRedisChannelLayer` described below. Class description: Use json to serialize and deserialize messages. Method signatures and docstrings: - def serialize(self, message): Serializes message in json. - def deserialize(self, message): Deserializes from a byte string. <|skeleton|> class Js...
f767f1bdc12c9712f26ea17cb8b19f536389f0ed
<|skeleton|> class JsonRedisChannelLayer: """Use json to serialize and deserialize messages.""" def serialize(self, message): """Serializes message in json.""" <|body_0|> def deserialize(self, message): """Deserializes from a byte string.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class JsonRedisChannelLayer: """Use json to serialize and deserialize messages.""" def serialize(self, message): """Serializes message in json.""" value = bytes(json.dumps(message, cls=DjangoJSONEncoder), encoding='utf-8') if self.crypter: value = self.crypter.encrypt(value)...
the_stack_v2_python_sparse
src/backend/marsha/websocket/layers.py
openfun/marsha
train
92
09daefadd62d7cd18f007346ed627bd2468cc59c
[ "from ..misc import RelativePath\nsuper(CallProcess, self).__init__(maxtrials=maxtrials)\nself.functional = functional\n' Functional to execute. '\ntry:\n self.functional = self.functional\nexcept:\n pass\nself.outdir = RelativePath(outdir)\n' Execution directory of the folder. '\nself.outdir = RelativePath(o...
<|body_start_0|> from ..misc import RelativePath super(CallProcess, self).__init__(maxtrials=maxtrials) self.functional = functional ' Functional to execute. ' try: self.functional = self.functional except: pass self.outdir = RelativePath(o...
Calls functional in child python process. This process pickles_ a callable and its arguments and executes it in a child python process. .. _pickles: http://docs.python.org/library/pickle.html
CallProcess
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CallProcess: """Calls functional in child python process. This process pickles_ a callable and its arguments and executes it in a child python process. .. _pickles: http://docs.python.org/library/pickle.html""" def __init__(self, functional, outdir, stdout=None, stderr=None, maxtrials=1, dom...
stack_v2_sparse_classes_36k_train_022595
5,576
no_license
[ { "docstring": "Initializes a process. :param functional: A python callable. It should also be pickle-able. :param str outdir: Path where the python child process should be executed. :param str stdout: Optional path to an output file where the callable's output shall be streamed. :param str stderr: Optional pat...
6
null
Implement the Python class `CallProcess` described below. Class description: Calls functional in child python process. This process pickles_ a callable and its arguments and executes it in a child python process. .. _pickles: http://docs.python.org/library/pickle.html Method signatures and docstrings: - def __init__(...
Implement the Python class `CallProcess` described below. Class description: Calls functional in child python process. This process pickles_ a callable and its arguments and executes it in a child python process. .. _pickles: http://docs.python.org/library/pickle.html Method signatures and docstrings: - def __init__(...
9c0ab667f94dc4629404a8ec99cbeaa323f0c8b3
<|skeleton|> class CallProcess: """Calls functional in child python process. This process pickles_ a callable and its arguments and executes it in a child python process. .. _pickles: http://docs.python.org/library/pickle.html""" def __init__(self, functional, outdir, stdout=None, stderr=None, maxtrials=1, dom...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CallProcess: """Calls functional in child python process. This process pickles_ a callable and its arguments and executes it in a child python process. .. _pickles: http://docs.python.org/library/pickle.html""" def __init__(self, functional, outdir, stdout=None, stderr=None, maxtrials=1, dompi=False, **k...
the_stack_v2_python_sparse
process/call.py
Shibu778/LaDa
train
0
e40fbbeb90abfe8662eb148e1475bf7bc8542ee3
[ "self.Wh = np.random.normal(size=(i + h, h))\nself.Wy = np.random.normal(size=(h, o))\nself.bh = np.zeros((1, h))\nself.by = np.zeros((1, o))", "xh = np.concatenate((h_prev, x_t), axis=1)\na_next = np.tanh(np.dot(xh, self.Wh) + self.bh)\ny_pred = np.dot(a_next, self.Wy) + self.by\ny_pred = np.exp(y_pred) / np.sum...
<|body_start_0|> self.Wh = np.random.normal(size=(i + h, h)) self.Wy = np.random.normal(size=(h, o)) self.bh = np.zeros((1, h)) self.by = np.zeros((1, o)) <|end_body_0|> <|body_start_1|> xh = np.concatenate((h_prev, x_t), axis=1) a_next = np.tanh(np.dot(xh, self.Wh) + se...
RNN cell
RNNCell
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RNNCell: """RNN cell""" def __init__(self, i, h, o): """* The weights will be used on the right side for matrix multiplication * The biases should be initialized as zeros""" <|body_0|> def forward(self, h_prev, x_t): """Returns: h_next, y""" <|body_1|> <...
stack_v2_sparse_classes_36k_train_022596
818
no_license
[ { "docstring": "* The weights will be used on the right side for matrix multiplication * The biases should be initialized as zeros", "name": "__init__", "signature": "def __init__(self, i, h, o)" }, { "docstring": "Returns: h_next, y", "name": "forward", "signature": "def forward(self, h...
2
stack_v2_sparse_classes_30k_train_013975
Implement the Python class `RNNCell` described below. Class description: RNN cell Method signatures and docstrings: - def __init__(self, i, h, o): * The weights will be used on the right side for matrix multiplication * The biases should be initialized as zeros - def forward(self, h_prev, x_t): Returns: h_next, y
Implement the Python class `RNNCell` described below. Class description: RNN cell Method signatures and docstrings: - def __init__(self, i, h, o): * The weights will be used on the right side for matrix multiplication * The biases should be initialized as zeros - def forward(self, h_prev, x_t): Returns: h_next, y <|...
9ff78818c132d1233c11b8fc8fd469878b23b14e
<|skeleton|> class RNNCell: """RNN cell""" def __init__(self, i, h, o): """* The weights will be used on the right side for matrix multiplication * The biases should be initialized as zeros""" <|body_0|> def forward(self, h_prev, x_t): """Returns: h_next, y""" <|body_1|> <...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RNNCell: """RNN cell""" def __init__(self, i, h, o): """* The weights will be used on the right side for matrix multiplication * The biases should be initialized as zeros""" self.Wh = np.random.normal(size=(i + h, h)) self.Wy = np.random.normal(size=(h, o)) self.bh = np.ze...
the_stack_v2_python_sparse
supervised_learning/0x0D-RNNs/0-rnn_cell.py
Nzparra/holbertonschool-machine_learning
train
0
b5128df92e50f6c44c562ea1f21d955df952237b
[ "self.original_data = tmp_tuple\nself.original_data = sorted(self.original_data)\nself.target = target", "result = 'To find: %d' % self.target\nresult += '\\nIn the sequence: %s' % str(self.original_data)\nresult += '\\nRecursive result: %s' % self._isMemberR(self.original_data)\nresult += '\\nIterative result: %...
<|body_start_0|> self.original_data = tmp_tuple self.original_data = sorted(self.original_data) self.target = target <|end_body_0|> <|body_start_1|> result = 'To find: %d' % self.target result += '\nIn the sequence: %s' % str(self.original_data) result += '\nRecursive re...
database
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class database: def __init__(self, tmp_tuple, target): """(Tuple, number) -> None Effect: To initail the class, sorting the tuple and setting the target Input: Tuple needed to search and target No output at this moment""" <|body_0|> def __str__(self): """() -> None Effect:...
stack_v2_sparse_classes_36k_train_022597
6,575
no_license
[ { "docstring": "(Tuple, number) -> None Effect: To initail the class, sorting the tuple and setting the target Input: Tuple needed to search and target No output at this moment", "name": "__init__", "signature": "def __init__(self, tmp_tuple, target)" }, { "docstring": "() -> None Effect: Make t...
4
null
Implement the Python class `database` described below. Class description: Implement the database class. Method signatures and docstrings: - def __init__(self, tmp_tuple, target): (Tuple, number) -> None Effect: To initail the class, sorting the tuple and setting the target Input: Tuple needed to search and target No ...
Implement the Python class `database` described below. Class description: Implement the database class. Method signatures and docstrings: - def __init__(self, tmp_tuple, target): (Tuple, number) -> None Effect: To initail the class, sorting the tuple and setting the target Input: Tuple needed to search and target No ...
8dcc64c2746c908c4121b550ae839a5b75a3edaa
<|skeleton|> class database: def __init__(self, tmp_tuple, target): """(Tuple, number) -> None Effect: To initail the class, sorting the tuple and setting the target Input: Tuple needed to search and target No output at this moment""" <|body_0|> def __str__(self): """() -> None Effect:...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class database: def __init__(self, tmp_tuple, target): """(Tuple, number) -> None Effect: To initail the class, sorting the tuple and setting the target Input: Tuple needed to search and target No output at this moment""" self.original_data = tmp_tuple self.original_data = sorted(self.origin...
the_stack_v2_python_sparse
python/is_member.py
xzpjerry/learning
train
1
dd4e8dd9fe073747786f729ea5d57c32bbcb92ad
[ "super(ResourcesAPITestCase, cls).setUpTestData()\nfor name, _definition in utils.get_user_limit_templates():\n cls.localconfig.parameters.set_value('deflt_user_{0}_limit'.format(name), 2)\ncls.localconfig.save()\npopulate_database()\ncls.user = User.objects.get(username='admin@test.com')\ncls.da_token = Token.o...
<|body_start_0|> super(ResourcesAPITestCase, cls).setUpTestData() for name, _definition in utils.get_user_limit_templates(): cls.localconfig.parameters.set_value('deflt_user_{0}_limit'.format(name), 2) cls.localconfig.save() populate_database() cls.user = User.objects...
Check resources API.
ResourcesAPITestCase
[ "ISC" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ResourcesAPITestCase: """Check resources API.""" def setUpTestData(cls): """Create test data.""" <|body_0|> def test_get_admin_resources(self): """Retrieve admin resources.""" <|body_1|> def test_update_resources(self): """Update resources.""...
stack_v2_sparse_classes_36k_train_022598
13,614
permissive
[ { "docstring": "Create test data.", "name": "setUpTestData", "signature": "def setUpTestData(cls)" }, { "docstring": "Retrieve admin resources.", "name": "test_get_admin_resources", "signature": "def test_get_admin_resources(self)" }, { "docstring": "Update resources.", "name...
3
null
Implement the Python class `ResourcesAPITestCase` described below. Class description: Check resources API. Method signatures and docstrings: - def setUpTestData(cls): Create test data. - def test_get_admin_resources(self): Retrieve admin resources. - def test_update_resources(self): Update resources.
Implement the Python class `ResourcesAPITestCase` described below. Class description: Check resources API. Method signatures and docstrings: - def setUpTestData(cls): Create test data. - def test_get_admin_resources(self): Retrieve admin resources. - def test_update_resources(self): Update resources. <|skeleton|> cl...
df699aab0799ec1725b6b89be38e56285821c889
<|skeleton|> class ResourcesAPITestCase: """Check resources API.""" def setUpTestData(cls): """Create test data.""" <|body_0|> def test_get_admin_resources(self): """Retrieve admin resources.""" <|body_1|> def test_update_resources(self): """Update resources.""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ResourcesAPITestCase: """Check resources API.""" def setUpTestData(cls): """Create test data.""" super(ResourcesAPITestCase, cls).setUpTestData() for name, _definition in utils.get_user_limit_templates(): cls.localconfig.parameters.set_value('deflt_user_{0}_limit'.form...
the_stack_v2_python_sparse
modoboa/limits/api/v1/tests.py
modoboa/modoboa
train
2,201
dc8a6e7011c61f047f1c5224b7fb35e556324f34
[ "super(HighwayNet, self).__init__()\nself.idim = idim\nself.projection = torch.nn.Sequential(torch.nn.Linear(idim, idim), torch.nn.ReLU())\nself.gate = torch.nn.Sequential(torch.nn.Linear(idim, idim), torch.nn.Sigmoid())", "proj = self.projection(x)\ngate = self.gate(x)\nreturn proj * gate + x * (1.0 - gate)" ]
<|body_start_0|> super(HighwayNet, self).__init__() self.idim = idim self.projection = torch.nn.Sequential(torch.nn.Linear(idim, idim), torch.nn.ReLU()) self.gate = torch.nn.Sequential(torch.nn.Linear(idim, idim), torch.nn.Sigmoid()) <|end_body_0|> <|body_start_1|> proj = self.p...
Highway Network module. This is a module of Highway Network introduced in `Highway Networks`_. .. _`Highway Networks`: https://arxiv.org/abs/1505.00387
HighwayNet
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HighwayNet: """Highway Network module. This is a module of Highway Network introduced in `Highway Networks`_. .. _`Highway Networks`: https://arxiv.org/abs/1505.00387""" def __init__(self, idim): """Initialize Highway Network module. Args: idim (int): Dimension of the inputs.""" ...
stack_v2_sparse_classes_36k_train_022599
9,068
permissive
[ { "docstring": "Initialize Highway Network module. Args: idim (int): Dimension of the inputs.", "name": "__init__", "signature": "def __init__(self, idim)" }, { "docstring": "Calculate forward propagation. Args: x (Tensor): Batch of inputs (B, ..., idim). Returns: Tensor: Batch of outputs, which...
2
null
Implement the Python class `HighwayNet` described below. Class description: Highway Network module. This is a module of Highway Network introduced in `Highway Networks`_. .. _`Highway Networks`: https://arxiv.org/abs/1505.00387 Method signatures and docstrings: - def __init__(self, idim): Initialize Highway Network m...
Implement the Python class `HighwayNet` described below. Class description: Highway Network module. This is a module of Highway Network introduced in `Highway Networks`_. .. _`Highway Networks`: https://arxiv.org/abs/1505.00387 Method signatures and docstrings: - def __init__(self, idim): Initialize Highway Network m...
bcd20948db7846ee523443ef9fd78c7a1248c95e
<|skeleton|> class HighwayNet: """Highway Network module. This is a module of Highway Network introduced in `Highway Networks`_. .. _`Highway Networks`: https://arxiv.org/abs/1505.00387""" def __init__(self, idim): """Initialize Highway Network module. Args: idim (int): Dimension of the inputs.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HighwayNet: """Highway Network module. This is a module of Highway Network introduced in `Highway Networks`_. .. _`Highway Networks`: https://arxiv.org/abs/1505.00387""" def __init__(self, idim): """Initialize Highway Network module. Args: idim (int): Dimension of the inputs.""" super(Hig...
the_stack_v2_python_sparse
espnet/nets/pytorch_backend/tacotron2/cbhg.py
espnet/espnet
train
7,242